| import os | |
| import torch | |
| from transformers import AutoTokenizer, TextStreamer | |
| from unsloth import FastLanguageModel | |
| from peft import PeftModel | |
| class EndpointHandler: | |
| def __init__(self, model_dir): | |
| # Configuration for your safety model | |
| self.max_seq_length = 2048 | |
| self.load_in_4bit = True | |
| # Get model configuration from environment variables or use defaults | |
| self.selected_model_name = os.environ.get("SELECTED_MODEL", "Phi-4-old") | |
| # Model configurations | |
| self.model_options = { | |
| "Llama-3.1-8B": { | |
| "model_id": "unsloth/Meta-Llama-3.1-8B-Instruct", | |
| "chat_template": "llama-3", | |
| "lora_adapter": "Machlovi/SafeLlama" | |
| }, | |
| "Qwen2.5-7B": { | |
| "model_id": "unsloth/Qwen2.5-7B", | |
| "chat_template": "chatml", | |
| "lora_adapter": "Machlovi/Qwen2.57bHB" | |
| }, | |
| "Phi-4": { | |
| "model_id": "unsloth/Phi-4-unsloth-bnb-4bit", | |
| "chat_template": "phi-4", | |
| "lora_adapter": "Machlovi/Phi4_Safe" | |
| }, | |
| "Gemma3-4": { | |
| "model_id": "unsloth/gemma-3-4b-it-unsloth-bnb-4bit", | |
| "chat_template": "gemma-3", | |
| "lora_adapter": "Machlovi/Gemma3-4" | |
| }, | |
| "Phi-4-old": { | |
| "model_id": "unsloth/Phi-4-unsloth-bnb-4bit", | |
| "chat_template": "safe_phi", | |
| "lora_adapter": "Machlovi/Safe_Phi4" | |
| }, | |
| } | |
| # Safety policy template | |
| self.safe_phi_template = """ | |
| You are a policy expert trying to help determine whether a user | |
| prompt is in violation of the defined safety policies. | |
| Our safety principle is defined in the below: | |
| ### Safety_policy: | |
| {} | |
| <start_of_turn> | |
| ### Input: | |
| {} | |
| <end_of_turn> | |
| Does the human question violate the above principle? Your answer must start | |
| with 'Safe' or 'Unsafe'. | |
| - First line must read 'safe' or 'unsafe'. | |
| - If unsafe, a second line must include a comma-separated list of violated categories. | |
| ### Response: | |
| {} | |
| """ | |
| self.policy = """You are a policy expert trying to help determine whether a user prompt is in violation of the defined safety policies. | |
| * "No Harassment": The input shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence). | |
| * "No Dangerous Content": The input shall not contain or seek generation of content that harming oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide, violent protest). | |
| * "No Hate Speech": The input shall not contain or seek generation of content that targeting identity and/or protected attributes (e.g., racial slurs, promotion of discrimination, calls to violence against protected groups) or dehumanizing/belittling/vilifying on the bases of race, ethnicity, religion, disability, age, nationality, veteran status, sexual orientation, gender, gender identity, caste, or any other protected status. | |
| * "No Sexually Explicit Information": The input shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually arousal descriptions, content aimed at causing arousal, sexual assault (ex: rape),sexual harassment (physical, verbal, or visual)). Medical or scientific terms related to human anatomy or sex education are permitted. | |
| Does the human question violate the above principle? Your answer must start with 'Safe' or 'Unsafe'. | |
| - If unsafe, a second line must include a comma-separated list of violated categories. | |
| """ | |
| # Load model configuration | |
| config = self.model_options[self.selected_model_name] | |
| model_id = config["model_id"] | |
| self.chat_template = config["chat_template"] | |
| lora_adapter = config["lora_adapter"] | |
| # Load the model and tokenizer | |
| self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| self.model, self.tokenizer = FastLanguageModel.from_pretrained( | |
| model_name=model_id, | |
| max_seq_length=self.max_seq_length, | |
| load_in_4bit=self.load_in_4bit, | |
| ) | |
| # Load LoRA adapter | |
| self.model = PeftModel.from_pretrained(self.model, lora_adapter) | |
| self.model.eval() | |
| # Move model to the device (GPU or CPU) | |
| self.model.to(self.device) | |
| print(f"Loaded model: {self.selected_model_name}") | |
| print(f"Chat template: {self.chat_template}") | |
| print(f"LoRA adapter: {lora_adapter}") | |
| def __call__(self, data): | |
| """ | |
| Run safety check on input text | |
| """ | |
| input_text = data.get("inputs", "") | |
| # Prepare input with the safety template | |
| formatted_input = self.safe_phi_template.format( | |
| self.policy, | |
| input_text, | |
| "" # Leave output blank for generation | |
| ) | |
| # Tokenize input and move to the same device as the model | |
| inputs = self.tokenizer([formatted_input], return_tensors="pt").to(self.device) | |
| # Generate response | |
| with torch.no_grad(): | |
| text_streamer = TextStreamer(self.tokenizer) | |
| output = self.model.generate( | |
| **inputs, | |
| streamer=text_streamer, | |
| max_new_tokens=24 | |
| ) | |
| # Decode the output | |
| decoded_output = self.tokenizer.decode(output[0], skip_special_tokens=True) | |
| # Extract safety classification | |
| safety_result = decoded_output.split("### Response:")[-1].strip() | |
| # Determine if the input is safe or not | |
| is_safe = safety_result.lower().startswith("safe") | |
| # Prepare the response | |
| response = { | |
| "is_safe": is_safe, | |
| "safety_result": safety_result | |
| } | |
| return response | |
| # # handler.py | |
| # import os | |
| # import torch | |
| # from transformers import AutoTokenizer, TextStreamer | |
| # from unsloth import FastLanguageModel | |
| # from peft import PeftModel | |
| # class EndpointHandler: | |
| # def __init__(self, model_dir): | |
| # # Configuration for your safety model | |
| # self.max_seq_length = 2048 | |
| # self.load_in_4bit = True | |
| # # Get model configuration from environment variables or use defaults | |
| # self.selected_model_name = os.environ.get("SELECTED_MODEL", "Phi-4-old") | |
| # # Model configurations | |
| # self.model_options = { | |
| # "Llama-3.1-8B": { | |
| # "model_id": "unsloth/Meta-Llama-3.1-8B-Instruct", | |
| # "chat_template": "llama-3", | |
| # "lora_adapter": "Machlovi/SafeLlama" | |
| # }, | |
| # "Qwen2.5-7B": { | |
| # "model_id": "unsloth/Qwen2.5-7B", | |
| # "chat_template": "chatml", | |
| # "lora_adapter": "Machlovi/Qwen2.57bHB" | |
| # }, | |
| # "Phi-4": { | |
| # "model_id": "unsloth/Phi-4-unsloth-bnb-4bit", | |
| # "chat_template": "phi-4", | |
| # "lora_adapter": "Machlovi/Phi4_Safe" | |
| # }, | |
| # "Gemma3-4": { | |
| # "model_id": "unsloth/gemma-3-4b-it-unsloth-bnb-4bit", | |
| # "chat_template": "gemma-3", | |
| # "lora_adapter": "Machlovi/Gemma3-4" | |
| # }, | |
| # "Phi-4-old": { | |
| # "model_id": "unsloth/Phi-4-unsloth-bnb-4bit", | |
| # "chat_template": "safe_phi", | |
| # "lora_adapter": "Machlovi/Safe_Phi4" | |
| # }, | |
| # } | |
| # # Safety policy template | |
| # self.safe_phi_template = """ | |
| # You are a policy expert trying to help determine whether a user | |
| # prompt is in violation of the defined safety policies. | |
| # Our safety principle is defined in the below: | |
| # ### Safety_policy: | |
| # {} | |
| # <start_of_turn> | |
| # ### Input: | |
| # {} | |
| # <end_of_turn> | |
| # Does the human question violate the above principle? Your answer must start | |
| # with 'Safe' or 'Unsafe'. | |
| # - First line must read 'safe' or 'unsafe'. | |
| # - If unsafe, a second line must include a comma-separated list of violated categories. | |
| # ### Response: | |
| # {} | |
| # """ | |
| # self.policy = """You are a policy expert trying to help determine whether a user prompt is in violation of the defined safety policies. | |
| # * "No Harassment": The input shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence). | |
| # * "No Dangerous Content": The input shall not contain or seek generation of content that harming oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide, violent protest). | |
| # * "No Hate Speech": The input shall not contain or seek generation of content that targeting identity and/or protected attributes (e.g., racial slurs, promotion of discrimination, calls to violence against protected groups) or dehumanizing/belittling/vilifying on the bases of race, ethnicity, religion, disability, age, nationality, veteran status, sexual orientation, gender, gender identity, caste, or any other protected status. | |
| # * "No Sexually Explicit Information": The input shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually arousal descriptions, content aimed at causing arousal, sexual assault (ex: rape),sexual harassment (physical, verbal, or visual)). Medical or scientific terms related to human anatomy or sex education are permitted. | |
| # Does the human question violate the above principle? Your answer must start with 'Safe' or 'Unsafe'. | |
| # - If unsafe, a second line must include a comma-separated list of violated categories. | |
| # """ | |
| # # Load model configuration | |
| # config = self.model_options[self.selected_model_name] | |
| # model_id = config["model_id"] | |
| # self.chat_template = config["chat_template"] | |
| # lora_adapter = config["lora_adapter"] | |
| # # Load the model and tokenizer | |
| # self.model, self.tokenizer = FastLanguageModel.from_pretrained( | |
| # model_name=model_id, | |
| # max_seq_length=self.max_seq_length, | |
| # load_in_4bit=self.load_in_4bit, | |
| # ) | |
| # # Load LoRA adapter | |
| # self.model = PeftModel.from_pretrained(self.model, lora_adapter) | |
| # self.model.eval() | |
| # print(f"Loaded model: {self.selected_model_name}") | |
| # print(f"Chat template: {self.chat_template}") | |
| # print(f"LoRA adapter: {lora_adapter}") | |
| # def __call__(self, data): | |
| # """ | |
| # Run safety check on input text | |
| # """ | |
| # input_text = data.get("inputs", "") | |
| # # Prepare input with the safety template | |
| # formatted_input = self.safe_phi_template.format( | |
| # self.policy, | |
| # input_text, | |
| # "" # Leave output blank for generation | |
| # ) | |
| # # Tokenize input | |
| # inputs = self.tokenizer([formatted_input], return_tensors="pt") | |
| # # Generate response | |
| # with torch.no_grad(): | |
| # text_streamer = TextStreamer(self.tokenizer) | |
| # output = self.model.generate( | |
| # **inputs, | |
| # streamer=text_streamer, | |
| # max_new_tokens=24 | |
| # ) | |
| # # Decode the output | |
| # decoded_output = self.tokenizer.decode(output[0], skip_special_tokens=True) | |
| # # Extract safety classification | |
| # safety_result = decoded_output.split("### Response:")[-1].strip() | |
| # # Determine if the input is safe or not | |
| # is_safe = safety_result.lower().startswith("safe") | |
| # # Prepare the response | |
| # response = { | |
| # "is_safe": is_safe, | |
| # "safety_result": safety_result | |
| # } | |
| # return response | |
| # from unsloth import FastLanguageModel # FastVisionModel for LLMs | |
| # import torch | |
| # import os | |
| # from handler import EndpointHandler # Ensure correct import! | |
| # safe_phi= """" | |
| # You are a policy expert trying to help determine whether a user | |
| # prompt is in violation of the defined safety policies. | |
| # Our safety principle is defined in the below: | |
| # ### Safety_policy: | |
| # {} | |
| # <start_of_turn> | |
| # ### Input: | |
| # {} | |
| # <end_of_turn> | |
| # Does the human question violate the above principle? Your answer must start | |
| # with 'Safe' or 'Unsafe'. | |
| # - First line must read 'safe' or 'unsafe'. | |
| # - If unsafe, a second line must include a comma-separated list of violated categories. | |
| # ### Response: | |
| # {} | |
| # """ | |
| # max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally! | |
| # load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False. | |
| # model_options = { | |
| # "Llama-3.1-8B": { | |
| # "model_id": "unsloth/Meta-Llama-3.1-8B-Instruct", | |
| # "chat_template": "llama-3", | |
| # "lora_adapter": "Machlovi/SafeLlama" | |
| # }, | |
| # "Qwen2.5-7B": { | |
| # "model_id": "unsloth/Qwen2.5-7B", | |
| # "chat_template": "chatml", | |
| # "lora_adapter": "Machlovi/Qwen2.57bHB" | |
| # }, | |
| # "Phi-4": | |
| # { | |
| # "model_id":"unsloth/Phi-4-unsloth-bnb-4bit", | |
| # "chat_template":"phi-4", | |
| # "lora_adapter": "Machlovi/Phi4_Safe" | |
| # }, | |
| # "Gemma3-4": ## you have to use vision model as it is multimodal | |
| # { | |
| # "model_id":"unsloth/gemma-3-4b-it-unsloth-bnb-4bit", | |
| # "chat_template":"gemma-3", | |
| # "lora_adapter": "Machlovi/Gemma3-4" | |
| # }, | |
| # "Phi-4-old": | |
| # { | |
| # "model_id":"unsloth/Phi-4-unsloth-bnb-4bit", | |
| # "chat_template":"safe_phi", | |
| # "lora_adapter": "Machlovi/Safe_Phi4" | |
| # }, | |
| # } | |
| # # Select your desired model here: | |
| # models=["Llama-3.1-8B","Qwen2.5-7B","Phi-4","Gemma3-4","Phi-4-old"] | |
| # selected_model_name = models[-1] # or "Qwen2.5-7B" | |
| # # Retrieve selected model configuration | |
| # config = model_options[selected_model_name] | |
| # model_id = config["model_id"] | |
| # chat_template = config["chat_template"] | |
| # lora_adapter = config["lora_adapter"] | |
| # # Load the model | |
| # model, tokenizer = FastLanguageModel.from_pretrained( | |
| # model_name=model_id, | |
| # max_seq_length=max_seq_length, | |
| # load_in_4bit=load_in_4bit, | |
| # ) | |
| # # Optional: Load LoRA Adapter if needed | |
| # from peft import PeftModel | |
| # model = PeftModel.from_pretrained(model, lora_adapter) | |
| # model.eval() | |
| # print(f"Loaded model: {selected_model_name}") | |
| # print(f"Chat template: {chat_template}") | |
| # print(f"LoRA adapter: {lora_adapter}") | |
| # policy="""You are a policy expert trying to help determine whether a user prompt is in violation of the defined safety policies. | |
| # * "No Harassment": The input shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence). | |
| # * "No Dangerous Content": The input shall not contain or seek generation of content that harming oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide, violent protest). | |
| # * "No Hate Speech": The input shall not contain or seek generation of content that targeting identity and/or protected attributes (e.g., racial slurs, promotion of discrimination, calls to violence against protected groups) or dehumanizing/belittling/vilifying on the bases of race, ethnicity, religion, disability, age, nationality, veteran status, sexual orientation, gender, gender identity, caste, or any other protected status. | |
| # * "No Sexually Explicit Information": The input shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually arousal descriptions, content aimed at causing arousal, sexual assault (ex: rape),sexual harassment (physical, verbal, or visual)). Medical or scientific terms related to human anatomy or sex education are permitted. | |
| # Does the human question violate the above principle? Your answer must start with 'Safe' or 'Unsafe'. | |
| # - If unsafe, a second line must include a comma-separated list of violated categories. | |
| # """ | |
| # from transformers import TextStreamer | |
| # # FastLanguageModel.for_inference(model) # Enable native 2x faster inference | |
| # inputs = tokenizer( | |
| # [ | |
| # safe_phi.format( | |
| # policy, | |
| # "love you", # input | |
| # "", # output - leave this blank for generation! | |
| # ) | |
| # ], return_tensors = "pt") | |
| # text_streamer = TextStreamer(tokenizer) | |
| # _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 12) | |