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