File size: 17,398 Bytes
690e3c9
87e3a34
 
 
690e3c9
 
87e3a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79de16d
 
87e3a34
 
 
 
 
 
 
 
 
 
79de16d
 
 
87e3a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79de16d
 
87e3a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79de16d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87e3a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
690e3c9
 
 
87e3a34
 
 
 
 
 
 
 
aa09677
87e3a34
690e3c9
87e3a34
 
 
 
 
690e3c9
87e3a34
 
 
 
690e3c9
 
87e3a34
690e3c9
87e3a34
690e3c9
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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)