Elffuss BraidHub

kikocis/llama-stack public

174d429e7af6 · 11.4 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7import re
8
9from string import Template
10from typing import List, Optional
11
12import torch
13from transformers import (
14 AutoModelForCausalLM,
15 AutoTokenizer,
16 MllamaForConditionalGeneration,
17 MllamaProcessor,
18)
19
20from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse
21from llama_models.llama3.api.datatypes import Message, Role
22
23
24SAFE_RESPONSE = "safe"
25_INSTANCE = None
26
27CAT_VIOLENT_CRIMES = "Violent Crimes"
28CAT_NON_VIOLENT_CRIMES = "Non-Violent Crimes"
29CAT_SEX_CRIMES = "Sex Crimes"
30CAT_CHILD_EXPLOITATION = "Child Exploitation"
31CAT_DEFAMATION = "Defamation"
32CAT_SPECIALIZED_ADVICE = "Specialized Advice"
33CAT_PRIVACY = "Privacy"
34CAT_INTELLECTUAL_PROPERTY = "Intellectual Property"
35CAT_INDISCRIMINATE_WEAPONS = "Indiscriminate Weapons"
36CAT_HATE = "Hate"
37CAT_SELF_HARM = "Self-Harm"
38CAT_SEXUAL_CONTENT = "Sexual Content"
39CAT_ELECTIONS = "Elections"
40CAT_CODE_INTERPRETER_ABUSE = "Code Interpreter Abuse"
41
42
43SAFETY_CATEGORIES_TO_CODE_MAP = {
44 CAT_VIOLENT_CRIMES: "S1",
45 CAT_NON_VIOLENT_CRIMES: "S2",
46 CAT_SEX_CRIMES: "S3",
47 CAT_CHILD_EXPLOITATION: "S4",
48 CAT_DEFAMATION: "S5",
49 CAT_SPECIALIZED_ADVICE: "S6",
50 CAT_PRIVACY: "S7",
51 CAT_INTELLECTUAL_PROPERTY: "S8",
52 CAT_INDISCRIMINATE_WEAPONS: "S9",
53 CAT_HATE: "S10",
54 CAT_SELF_HARM: "S11",
55 CAT_SEXUAL_CONTENT: "S12",
56 CAT_ELECTIONS: "S13",
57 CAT_CODE_INTERPRETER_ABUSE: "S14",
58}
59
60
61DEFAULT_LG_V3_SAFETY_CATEGORIES = [
62 CAT_VIOLENT_CRIMES,
63 CAT_NON_VIOLENT_CRIMES,
64 CAT_SEX_CRIMES,
65 CAT_CHILD_EXPLOITATION,
66 CAT_DEFAMATION,
67 CAT_SPECIALIZED_ADVICE,
68 CAT_PRIVACY,
69 CAT_INTELLECTUAL_PROPERTY,
70 CAT_INDISCRIMINATE_WEAPONS,
71 CAT_HATE,
72 CAT_SELF_HARM,
73 CAT_SEXUAL_CONTENT,
74 CAT_ELECTIONS,
75]
76
77# model names
78LG_3_8B = "Llama-Guard-3-8B"
79LG_3_1B = "Llama-Guard-3-1B"
80LG_3_11B_VISION = "Llama-Guard-3-11B-Vision"
81
82
83MODEL_TO_SAFETY_CATEGORIES_MAP = {
84 LG_3_8B: DEFAULT_LG_V3_SAFETY_CATEGORIES + [CAT_CODE_INTERPRETER_ABUSE],
85 LG_3_1B: DEFAULT_LG_V3_SAFETY_CATEGORIES,
86 LG_3_11B_VISION: DEFAULT_LG_V3_SAFETY_CATEGORIES,
87}
88
89
90PROMPT_TASK = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nTask: Check if there is unsafe content in '$agent_type' messages in conversations according our safety policy with the below categories."
91
92SAFETY_CATEGORIES = """
93
94<BEGIN UNSAFE CONTENT CATEGORIES>
95$categories
96<END UNSAFE CONTENT CATEGORIES>
97"""
98
99PROMPT_CONVERSATION = """
100<BEGIN CONVERSATION>
101
102$conversations
103
104<END CONVERSATION>
105"""
106
107
108PROMPT_INSTRUCTIONS = """
109Provide your safety assessment for ONLY THE LAST $agent_type message in the above conversation:
110 - First line must read 'safe' or 'unsafe'.
111 - If unsafe, a second line must include a comma-separated list of violated categories. <|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
112
113
114PROMPT_TEMPLATE = Template(
115 f"{PROMPT_TASK}{SAFETY_CATEGORIES}{PROMPT_CONVERSATION}{PROMPT_INSTRUCTIONS}"
116)
117
118
119class LlamaGuardShield(ShieldBase):
120 def __init__(
121 self,
122 model_dir: str,
123 excluded_categories: List[str] = None,
124 disable_input_check: bool = False,
125 disable_output_check: bool = False,
126 on_violation_action: OnViolationAction = OnViolationAction.RAISE,
127 ):
128 super().__init__(on_violation_action)
129
130 dtype = torch.bfloat16
131 self.model_dir = model_dir
132 self.device = "cuda"
133
134 assert self.model_dir is not None, "Llama Guard model_dir is None"
135
136 if excluded_categories is None:
137 excluded_categories = []
138
139 assert len(excluded_categories) == 0 or all(
140 x in SAFETY_CATEGORIES_TO_CODE_MAP.values() for x in excluded_categories
141 ), "Invalid categories in excluded categories. Expected format is ['S1', 'S2', ..]"
142
143 self.excluded_categories = excluded_categories
144 self.disable_input_check = disable_input_check
145 self.disable_output_check = disable_output_check
146
147 torch_dtype = torch.bfloat16
148
149 if self.is_lg_vision():
150
151 self.model = MllamaForConditionalGeneration.from_pretrained(
152 self.model_dir, device_map=self.device, torch_dtype=torch_dtype
153 )
154 self.processor = MllamaProcessor.from_pretrained(self.model_dir)
155 else:
156
157 self.tokenizer = AutoTokenizer.from_pretrained(self.model_dir)
158 self.model = AutoModelForCausalLM.from_pretrained(
159 self.model_dir, torch_dtype=torch_dtype, device_map=self.device
160 )
161
162 def check_unsafe_response(self, response: str) -> Optional[str]:
163 match = re.match(r"^unsafe\n(.*)$", response)
164 if match:
165 # extracts the unsafe code
166 extracted = match.group(1)
167 return extracted
168
169 return None
170
171 def get_safety_categories(self) -> List[str]:
172 excluded_categories = self.excluded_categories
173 if set(excluded_categories) == set(SAFETY_CATEGORIES_TO_CODE_MAP.values()):
174 excluded_categories = []
175
176 final_categories = []
177 all_categories = MODEL_TO_SAFETY_CATEGORIES_MAP[self.get_model_name()]
178 for cat in all_categories:
179 cat_code = SAFETY_CATEGORIES_TO_CODE_MAP[cat]
180 if cat_code in excluded_categories:
181 continue
182 final_categories.append(f"{cat_code}: {cat}.")
183
184 return final_categories
185
186 def build_prompt(self, messages: List[Message]) -> str:
187 categories = self.get_safety_categories()
188 categories_str = "\n".join(categories)
189 conversations_str = "\n\n".join(
190 [f"{m.role.capitalize()}: {m.content}" for m in messages]
191 )
192 return PROMPT_TEMPLATE.substitute(
193 agent_type=messages[-1].role.capitalize(),
194 categories=categories_str,
195 conversations=conversations_str,
196 )
197
198 def get_shield_response(self, response: str) -> ShieldResponse:
199 response = response.strip()
200 if response == SAFE_RESPONSE:
201 return ShieldResponse(is_violation=False)
202 unsafe_code = self.check_unsafe_response(response)
203 if unsafe_code:
204 unsafe_code_list = unsafe_code.split(",")
205 if set(unsafe_code_list).issubset(set(self.excluded_categories)):
206 return ShieldResponse(is_violation=False)
207 return ShieldResponse(
208 is_violation=True,
209 violation_type=unsafe_code,
210 violation_return_message=CANNED_RESPONSE_TEXT,
211 )
212
213 raise ValueError(f"Unexpected response: {response}")
214
215 def build_mm_prompt(self, messages: List[Message]) -> str:
216 conversation = []
217 most_recent_img = None
218
219 for m in messages[::-1]:
220 if isinstance(m.content, str):
221 conversation.append(
222 {
223 "role": m.role,
224 "content": [{"type": "text", "text": m.content}],
225 }
226 )
227 elif isinstance(m.content, ImageMedia):
228 if most_recent_img is None and m.role == Role.user.value:
229 most_recent_img = m.content
230 conversation.append(
231 {
232 "role": m.role,
233 "content": [{"type": "image"}],
234 }
235 )
236
237 elif isinstance(m.content, list):
238 content = []
239 for c in m.content:
240 if isinstance(c, str):
241 content.append({"type": "text", "text": c})
242 elif isinstance(c, ImageMedia):
243 if most_recent_img is None and m.role == Role.user.value:
244 most_recent_img = c
245 content.append({"type": "image"})
246 else:
247 raise ValueError(f"Unknown content type: {c}")
248
249 conversation.append(
250 {
251 "role": m.role,
252 "content": content,
253 }
254 )
255 else:
256 raise ValueError(f"Unknown content type: {m.content}")
257
258 return conversation[::-1], most_recent_img
259
260 async def run_lg_mm(self, messages: List[Message]) -> ShieldResponse:
261 formatted_messages, most_recent_img = self.build_mm_prompt(messages)
262 raw_image = None
263 if most_recent_img:
264 raw_image = interleaved_text_media_localize(most_recent_img)
265 raw_image = raw_image.image
266 llama_guard_input_templ_applied = self.processor.apply_chat_template(
267 formatted_messages,
268 add_generation_prompt=True,
269 tokenize=False,
270 skip_special_tokens=False,
271 )
272 inputs = self.processor(
273 text=llama_guard_input_templ_applied, images=raw_image, return_tensors="pt"
274 ).to(self.device)
275 output = self.model.generate(**inputs, do_sample=False, max_new_tokens=50)
276 response = self.processor.decode(
277 output[0][len(inputs["input_ids"][0]) :], skip_special_tokens=True
278 )
279 shield_response = self.get_shield_response(response)
280 return shield_response
281
282 async def run_lg_text(self, messages: List[Message]):
283 prompt = self.build_prompt(messages)
284 input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
285 prompt_len = input_ids.shape[1]
286 output = self.model.generate(
287 input_ids=input_ids,
288 max_new_tokens=20,
289 output_scores=True,
290 return_dict_in_generate=True,
291 pad_token_id=0,
292 )
293 generated_tokens = output.sequences[:, prompt_len:]
294
295 response = self.tokenizer.decode(generated_tokens[0], skip_special_tokens=True)
296
297 shield_response = self.get_shield_response(response)
298 return shield_response
299
300 def get_model_name(self):
301 return self.model_dir.split("/")[-1]
302
303 def is_lg_vision(self):
304 model_name = self.get_model_name()
305 return model_name == LG_3_11B_VISION
306
307 def validate_messages(self, messages: List[Message]) -> None:
308 if len(messages) == 0:
309 raise ValueError("Messages must not be empty")
310 if messages[0].role != Role.user.value:
311 raise ValueError("Messages must start with user")
312
313 if len(messages) >= 2 and (
314 messages[0].role == Role.user.value and messages[1].role == Role.user.value
315 ):
316 messages = messages[1:]
317
318 for i in range(1, len(messages)):
319 if messages[i].role == messages[i - 1].role:
320 raise ValueError(
321 f"Messages must alternate between user and assistant. Message {i} has the same role as message {i-1}"
322 )
323 return messages
324
325 async def run(self, messages: List[Message]) -> ShieldResponse:
326
327 messages = self.validate_messages(messages)
328 if self.disable_input_check and messages[-1].role == Role.user.value:
329 return ShieldResponse(is_violation=False)
330 elif self.disable_output_check and messages[-1].role == Role.assistant.value:
331 return ShieldResponse(
332 is_violation=False,
333 )
334 else:
335
336 if self.is_lg_vision():
337
338 shield_response = await self.run_lg_mm(messages)
339
340 else:
341
342 shield_response = await self.run_lg_text(messages)
343
344 return shield_response