Machlovi commited on
Commit
87e3a34
·
verified ·
1 Parent(s): 41db202

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +243 -107
handler.py CHANGED
@@ -1,121 +1,257 @@
1
- from unsloth import FastLanguageModel # FastVisionModel for LLMs
2
- import torch
3
  import os
4
- from handler import EndpointHandler # Ensure correct import!
5
-
6
-
7
- safe_phi= """"
8
- You are a policy expert trying to help determine whether a user
9
- prompt is in violation of the defined safety policies.
10
-
11
- Our safety principle is defined in the below:
12
- ### Safety_policy:
13
- {}
14
-
15
- <start_of_turn>
16
- ### Input:
17
- {}
18
- <end_of_turn>
19
-
20
- Does the human question violate the above principle? Your answer must start
21
- with 'Safe' or 'Unsafe'.
22
- - First line must read 'safe' or 'unsafe'.
23
- - If unsafe, a second line must include a comma-separated list of violated categories.
24
-
25
- ### Response:
26
- {}
27
-
28
- """
29
-
30
-
31
- max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
32
- load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
33
-
34
- model_options = {
35
- "Llama-3.1-8B": {
36
- "model_id": "unsloth/Meta-Llama-3.1-8B-Instruct",
37
- "chat_template": "llama-3",
38
- "lora_adapter": "Machlovi/SafeLlama"
39
- },
40
- "Qwen2.5-7B": {
41
- "model_id": "unsloth/Qwen2.5-7B",
42
- "chat_template": "chatml",
43
- "lora_adapter": "Machlovi/Qwen2.57bHB"
44
- },
45
- "Phi-4":
46
- {
47
- "model_id":"unsloth/Phi-4-unsloth-bnb-4bit",
48
- "chat_template":"phi-4",
49
- "lora_adapter": "Machlovi/Phi4_Safe"
50
- },
51
- "Gemma3-4": ## you have to use vision model as it is multimodal
52
- {
53
- "model_id":"unsloth/gemma-3-4b-it-unsloth-bnb-4bit",
54
- "chat_template":"gemma-3",
55
- "lora_adapter": "Machlovi/Gemma3-4"
56
- },
57
-
58
- "Phi-4-old":
59
- {
60
- "model_id":"unsloth/Phi-4-unsloth-bnb-4bit",
61
- "chat_template":"safe_phi",
62
- "lora_adapter": "Machlovi/Safe_Phi4"
63
- },
64
- }
65
-
66
- # Select your desired model here:
67
- models=["Llama-3.1-8B","Qwen2.5-7B","Phi-4","Gemma3-4","Phi-4-old"]
68
- selected_model_name = models[-1] # or "Qwen2.5-7B"
69
-
70
- # Retrieve selected model configuration
71
- config = model_options[selected_model_name]
72
- model_id = config["model_id"]
73
- chat_template = config["chat_template"]
74
- lora_adapter = config["lora_adapter"]
75
-
76
- # Load the model
77
- model, tokenizer = FastLanguageModel.from_pretrained(
78
- model_name=model_id,
79
- max_seq_length=max_seq_length,
80
- load_in_4bit=load_in_4bit,
81
- )
82
-
83
- # Optional: Load LoRA Adapter if needed
84
  from peft import PeftModel
85
- model = PeftModel.from_pretrained(model, lora_adapter)
86
- model.eval()
87
 
88
- print(f"Loaded model: {selected_model_name}")
89
- print(f"Chat template: {chat_template}")
90
- print(f"LoRA adapter: {lora_adapter}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
 
93
 
94
- policy="""You are a policy expert trying to help determine whether a user prompt is in violation of the defined safety policies.
95
- * "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).
96
- * "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).
97
- * "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.
98
- * "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.
99
- Does the human question violate the above principle? Your answer must start with 'Safe' or 'Unsafe'.
100
- - If unsafe, a second line must include a comma-separated list of violated categories.
101
- """
102
 
103
- from transformers import TextStreamer
104
 
105
- # FastLanguageModel.for_inference(model) # Enable native 2x faster inference
106
- inputs = tokenizer(
107
- [
108
- safe_phi.format(
109
- policy,
110
 
111
- "love you", # input
112
- "", # output - leave this blank for generation!
113
- )
114
- ], return_tensors = "pt")
115
 
116
 
117
- text_streamer = TextStreamer(tokenizer)
118
 
119
- _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 12)
120
 
121
 
 
1
+
2
+ # handler.py
3
  import os
4
+ import torch
5
+ from transformers import AutoTokenizer, TextStreamer
6
+ from unsloth import FastLanguageModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  from peft import PeftModel
 
 
8
 
9
+ class EndpointHandler:
10
+ def __init__(self, model_dir):
11
+ # Configuration for your safety model
12
+ self.max_seq_length = 2048
13
+ self.load_in_4bit = True
14
+
15
+ # Get model configuration from environment variables or use defaults
16
+ self.selected_model_name = os.environ.get("SELECTED_MODEL", "Phi-4-old")
17
+
18
+ # Model configurations
19
+ self.model_options = {
20
+ "Llama-3.1-8B": {
21
+ "model_id": "unsloth/Meta-Llama-3.1-8B-Instruct",
22
+ "chat_template": "llama-3",
23
+ "lora_adapter": "Machlovi/SafeLlama"
24
+ },
25
+ "Qwen2.5-7B": {
26
+ "model_id": "unsloth/Qwen2.5-7B",
27
+ "chat_template": "chatml",
28
+ "lora_adapter": "Machlovi/Qwen2.57bHB"
29
+ },
30
+ "Phi-4": {
31
+ "model_id": "unsloth/Phi-4-unsloth-bnb-4bit",
32
+ "chat_template": "phi-4",
33
+ "lora_adapter": "Machlovi/Phi4_Safe"
34
+ },
35
+ "Gemma3-4": {
36
+ "model_id": "unsloth/gemma-3-4b-it-unsloth-bnb-4bit",
37
+ "chat_template": "gemma-3",
38
+ "lora_adapter": "Machlovi/Gemma3-4"
39
+ },
40
+ "Phi-4-old": {
41
+ "model_id": "unsloth/Phi-4-unsloth-bnb-4bit",
42
+ "chat_template": "safe_phi",
43
+ "lora_adapter": "Machlovi/Safe_Phi4"
44
+ },
45
+ }
46
+
47
+ # Safety policy template
48
+ self.safe_phi_template = """
49
+ You are a policy expert trying to help determine whether a user
50
+ prompt is in violation of the defined safety policies.
51
+ Our safety principle is defined in the below:
52
+ ### Safety_policy:
53
+ {}
54
+ <start_of_turn>
55
+ ### Input:
56
+ {}
57
+ <end_of_turn>
58
+ Does the human question violate the above principle? Your answer must start
59
+ with 'Safe' or 'Unsafe'.
60
+ - First line must read 'safe' or 'unsafe'.
61
+ - If unsafe, a second line must include a comma-separated list of violated categories.
62
+ ### Response:
63
+ {}
64
+ """
65
+
66
+ self.policy = """You are a policy expert trying to help determine whether a user prompt is in violation of the defined safety policies.
67
+ * "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).
68
+ * "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).
69
+ * "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.
70
+ * "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.
71
+ Does the human question violate the above principle? Your answer must start with 'Safe' or 'Unsafe'.
72
+ - If unsafe, a second line must include a comma-separated list of violated categories.
73
+ """
74
+
75
+ # Load model configuration
76
+ config = self.model_options[self.selected_model_name]
77
+ model_id = config["model_id"]
78
+ self.chat_template = config["chat_template"]
79
+ lora_adapter = config["lora_adapter"]
80
+
81
+ # Load the model and tokenizer
82
+ self.model, self.tokenizer = FastLanguageModel.from_pretrained(
83
+ model_name=model_id,
84
+ max_seq_length=self.max_seq_length,
85
+ load_in_4bit=self.load_in_4bit,
86
+ )
87
+
88
+ # Load LoRA adapter
89
+ self.model = PeftModel.from_pretrained(self.model, lora_adapter)
90
+ self.model.eval()
91
+
92
+ print(f"Loaded model: {self.selected_model_name}")
93
+ print(f"Chat template: {self.chat_template}")
94
+ print(f"LoRA adapter: {lora_adapter}")
95
+
96
+ def __call__(self, data):
97
+ """
98
+ Run safety check on input text
99
+ """
100
+ input_text = data.get("inputs", "")
101
+
102
+ # Prepare input with the safety template
103
+ formatted_input = self.safe_phi_template.format(
104
+ self.policy,
105
+ input_text,
106
+ "" # Leave output blank for generation
107
+ )
108
+
109
+ # Tokenize input
110
+ inputs = self.tokenizer([formatted_input], return_tensors="pt")
111
+
112
+ # Generate response
113
+ with torch.no_grad():
114
+ text_streamer = TextStreamer(self.tokenizer)
115
+ output = self.model.generate(
116
+ **inputs,
117
+ streamer=text_streamer,
118
+ max_new_tokens=24
119
+ )
120
+
121
+ # Decode the output
122
+ decoded_output = self.tokenizer.decode(output[0], skip_special_tokens=True)
123
+
124
+ # Extract safety classification
125
+ safety_result = decoded_output.split("### Response:")[-1].strip()
126
+
127
+ # Determine if the input is safe or not
128
+ is_safe = safety_result.lower().startswith("safe")
129
+
130
+ # Prepare the response
131
+ response = {
132
+ "is_safe": is_safe,
133
+ "safety_result": safety_result
134
+ }
135
+
136
+ return response
137
+ # from unsloth import FastLanguageModel # FastVisionModel for LLMs
138
+ # import torch
139
+ # import os
140
+ # from handler import EndpointHandler # Ensure correct import!
141
+
142
+
143
+ # safe_phi= """"
144
+ # You are a policy expert trying to help determine whether a user
145
+ # prompt is in violation of the defined safety policies.
146
+
147
+ # Our safety principle is defined in the below:
148
+ # ### Safety_policy:
149
+ # {}
150
+
151
+ # <start_of_turn>
152
+ # ### Input:
153
+ # {}
154
+ # <end_of_turn>
155
+
156
+ # Does the human question violate the above principle? Your answer must start
157
+ # with 'Safe' or 'Unsafe'.
158
+ # - First line must read 'safe' or 'unsafe'.
159
+ # - If unsafe, a second line must include a comma-separated list of violated categories.
160
+
161
+ # ### Response:
162
+ # {}
163
+
164
+ # """
165
+
166
+
167
+ # max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
168
+ # load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
169
+
170
+ # model_options = {
171
+ # "Llama-3.1-8B": {
172
+ # "model_id": "unsloth/Meta-Llama-3.1-8B-Instruct",
173
+ # "chat_template": "llama-3",
174
+ # "lora_adapter": "Machlovi/SafeLlama"
175
+ # },
176
+ # "Qwen2.5-7B": {
177
+ # "model_id": "unsloth/Qwen2.5-7B",
178
+ # "chat_template": "chatml",
179
+ # "lora_adapter": "Machlovi/Qwen2.57bHB"
180
+ # },
181
+ # "Phi-4":
182
+ # {
183
+ # "model_id":"unsloth/Phi-4-unsloth-bnb-4bit",
184
+ # "chat_template":"phi-4",
185
+ # "lora_adapter": "Machlovi/Phi4_Safe"
186
+ # },
187
+ # "Gemma3-4": ## you have to use vision model as it is multimodal
188
+ # {
189
+ # "model_id":"unsloth/gemma-3-4b-it-unsloth-bnb-4bit",
190
+ # "chat_template":"gemma-3",
191
+ # "lora_adapter": "Machlovi/Gemma3-4"
192
+ # },
193
+
194
+ # "Phi-4-old":
195
+ # {
196
+ # "model_id":"unsloth/Phi-4-unsloth-bnb-4bit",
197
+ # "chat_template":"safe_phi",
198
+ # "lora_adapter": "Machlovi/Safe_Phi4"
199
+ # },
200
+ # }
201
+
202
+ # # Select your desired model here:
203
+ # models=["Llama-3.1-8B","Qwen2.5-7B","Phi-4","Gemma3-4","Phi-4-old"]
204
+ # selected_model_name = models[-1] # or "Qwen2.5-7B"
205
+
206
+ # # Retrieve selected model configuration
207
+ # config = model_options[selected_model_name]
208
+ # model_id = config["model_id"]
209
+ # chat_template = config["chat_template"]
210
+ # lora_adapter = config["lora_adapter"]
211
+
212
+ # # Load the model
213
+ # model, tokenizer = FastLanguageModel.from_pretrained(
214
+ # model_name=model_id,
215
+ # max_seq_length=max_seq_length,
216
+ # load_in_4bit=load_in_4bit,
217
+ # )
218
+
219
+ # # Optional: Load LoRA Adapter if needed
220
+ # from peft import PeftModel
221
+ # model = PeftModel.from_pretrained(model, lora_adapter)
222
+ # model.eval()
223
+
224
+ # print(f"Loaded model: {selected_model_name}")
225
+ # print(f"Chat template: {chat_template}")
226
+ # print(f"LoRA adapter: {lora_adapter}")
227
 
228
 
229
 
230
+ # policy="""You are a policy expert trying to help determine whether a user prompt is in violation of the defined safety policies.
231
+ # * "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).
232
+ # * "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).
233
+ # * "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.
234
+ # * "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.
235
+ # Does the human question violate the above principle? Your answer must start with 'Safe' or 'Unsafe'.
236
+ # - If unsafe, a second line must include a comma-separated list of violated categories.
237
+ # """
238
 
239
+ # from transformers import TextStreamer
240
 
241
+ # # FastLanguageModel.for_inference(model) # Enable native 2x faster inference
242
+ # inputs = tokenizer(
243
+ # [
244
+ # safe_phi.format(
245
+ # policy,
246
 
247
+ # "love you", # input
248
+ # "", # output - leave this blank for generation!
249
+ # )
250
+ # ], return_tensors = "pt")
251
 
252
 
253
+ # text_streamer = TextStreamer(tokenizer)
254
 
255
+ # _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 12)
256
 
257