| 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 llama_models.llama3.api.datatypes import Message, Role |
| 14 | from transformers import AutoModelForCausalLM, AutoTokenizer |
| 15 | |
| 16 | from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse |
| 17 | from llama_stack.apis.safety import * # noqa: F403 |
| 18 | |
| 19 | SAFE_RESPONSE = "safe" |
| 20 | _INSTANCE = None |
| 21 | |
| 22 | CAT_VIOLENT_CRIMES = "Violent Crimes" |
| 23 | CAT_NON_VIOLENT_CRIMES = "Non-Violent Crimes" |
| 24 | CAT_SEX_CRIMES = "Sex Crimes" |
| 25 | CAT_CHILD_EXPLOITATION = "Child Exploitation" |
| 26 | CAT_DEFAMATION = "Defamation" |
| 27 | CAT_SPECIALIZED_ADVICE = "Specialized Advice" |
| 28 | CAT_PRIVACY = "Privacy" |
| 29 | CAT_INTELLECTUAL_PROPERTY = "Intellectual Property" |
| 30 | CAT_INDISCRIMINATE_WEAPONS = "Indiscriminate Weapons" |
| 31 | CAT_HATE = "Hate" |
| 32 | CAT_SELF_HARM = "Self-Harm" |
| 33 | CAT_SEXUAL_CONTENT = "Sexual Content" |
| 34 | CAT_ELECTIONS = "Elections" |
| 35 | CAT_CODE_INTERPRETER_ABUSE = "Code Interpreter Abuse" |
| 36 | |
| 37 | |
| 38 | SAFETY_CATEGORIES_TO_CODE_MAP = { |
| 39 | CAT_VIOLENT_CRIMES: "S1", |
| 40 | CAT_NON_VIOLENT_CRIMES: "S2", |
| 41 | CAT_SEX_CRIMES: "S3", |
| 42 | CAT_CHILD_EXPLOITATION: "S4", |
| 43 | CAT_DEFAMATION: "S5", |
| 44 | CAT_SPECIALIZED_ADVICE: "S6", |
| 45 | CAT_PRIVACY: "S7", |
| 46 | CAT_INTELLECTUAL_PROPERTY: "S8", |
| 47 | CAT_INDISCRIMINATE_WEAPONS: "S9", |
| 48 | CAT_HATE: "S10", |
| 49 | CAT_SELF_HARM: "S11", |
| 50 | CAT_SEXUAL_CONTENT: "S12", |
| 51 | CAT_ELECTIONS: "S13", |
| 52 | CAT_CODE_INTERPRETER_ABUSE: "S14", |
| 53 | } |
| 54 | |
| 55 | |
| 56 | DEFAULT_LG_V3_SAFETY_CATEGORIES = [ |
| 57 | CAT_VIOLENT_CRIMES, |
| 58 | CAT_NON_VIOLENT_CRIMES, |
| 59 | CAT_SEX_CRIMES, |
| 60 | CAT_CHILD_EXPLOITATION, |
| 61 | CAT_DEFAMATION, |
| 62 | CAT_SPECIALIZED_ADVICE, |
| 63 | CAT_PRIVACY, |
| 64 | CAT_INTELLECTUAL_PROPERTY, |
| 65 | CAT_INDISCRIMINATE_WEAPONS, |
| 66 | CAT_HATE, |
| 67 | CAT_SELF_HARM, |
| 68 | CAT_SEXUAL_CONTENT, |
| 69 | CAT_ELECTIONS, |
| 70 | CAT_CODE_INTERPRETER_ABUSE, |
| 71 | ] |
| 72 | |
| 73 | PROMPT_TASK = "Task: Check if there is unsafe content in '$agent_type' messages in conversations according our safety policy with the below categories." |
| 74 | |
| 75 | SAFETY_CATEGORIES = """ |
| 76 | |
| 77 | <BEGIN UNSAFE CONTENT CATEGORIES> |
| 78 | $categories |
| 79 | <END UNSAFE CONTENT CATEGORIES> |
| 80 | """ |
| 81 | |
| 82 | PROMPT_CONVERSATION = """ |
| 83 | <BEGIN CONVERSATION> |
| 84 | |
| 85 | $conversations |
| 86 | |
| 87 | <END CONVERSATION> |
| 88 | """ |
| 89 | |
| 90 | |
| 91 | PROMPT_INSTRUCTIONS = """ |
| 92 | Provide your safety assessment for ONLY THE LAST $agent_type message in the above conversation: |
| 93 | - First line must read 'safe' or 'unsafe'. |
| 94 | - If unsafe, a second line must include a comma-separated list of violated categories.""" |
| 95 | |
| 96 | |
| 97 | PROMPT_TEMPLATE = Template( |
| 98 | f"{PROMPT_TASK}{SAFETY_CATEGORIES}{PROMPT_CONVERSATION}{PROMPT_INSTRUCTIONS}" |
| 99 | ) |
| 100 | |
| 101 | |
| 102 | class LlamaGuardShield(ShieldBase): |
| 103 | @staticmethod |
| 104 | def instance( |
| 105 | on_violation_action=OnViolationAction.RAISE, |
| 106 | model_dir: str = None, |
| 107 | excluded_categories: List[str] = None, |
| 108 | disable_input_check: bool = False, |
| 109 | disable_output_check: bool = False, |
| 110 | ) -> "LlamaGuardShield": |
| 111 | global _INSTANCE |
| 112 | if _INSTANCE is None: |
| 113 | _INSTANCE = LlamaGuardShield( |
| 114 | on_violation_action, |
| 115 | model_dir, |
| 116 | excluded_categories, |
| 117 | disable_input_check, |
| 118 | disable_output_check, |
| 119 | ) |
| 120 | return _INSTANCE |
| 121 | |
| 122 | def __init__( |
| 123 | self, |
| 124 | on_violation_action: OnViolationAction = OnViolationAction.RAISE, |
| 125 | model_dir: str = None, |
| 126 | excluded_categories: List[str] = None, |
| 127 | disable_input_check: bool = False, |
| 128 | disable_output_check: bool = False, |
| 129 | ): |
| 130 | super().__init__(on_violation_action) |
| 131 | |
| 132 | dtype = torch.bfloat16 |
| 133 | |
| 134 | assert 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.device = "cuda" |
| 144 | self.excluded_categories = excluded_categories |
| 145 | self.disable_input_check = disable_input_check |
| 146 | self.disable_output_check = disable_output_check |
| 147 | |
| 148 | # load model |
| 149 | torch_dtype = torch.bfloat16 |
| 150 | self.tokenizer = AutoTokenizer.from_pretrained(model_dir) |
| 151 | self.model = AutoModelForCausalLM.from_pretrained( |
| 152 | model_dir, torch_dtype=torch_dtype, device_map=self.device |
| 153 | ) |
| 154 | |
| 155 | def get_shield_type(self) -> ShieldType: |
| 156 | return BuiltinShield.llama_guard |
| 157 | |
| 158 | def check_unsafe_response(self, response: str) -> Optional[str]: |
| 159 | match = re.match(r"^unsafe\n(.*)$", response) |
| 160 | if match: |
| 161 | # extracts the unsafe code |
| 162 | extracted = match.group(1) |
| 163 | return extracted |
| 164 | |
| 165 | return None |
| 166 | |
| 167 | def get_safety_categories(self) -> List[str]: |
| 168 | excluded_categories = self.excluded_categories |
| 169 | if set(excluded_categories) == set(SAFETY_CATEGORIES_TO_CODE_MAP.values()): |
| 170 | excluded_categories = [] |
| 171 | |
| 172 | categories = [] |
| 173 | for cat in DEFAULT_LG_V3_SAFETY_CATEGORIES: |
| 174 | cat_code = SAFETY_CATEGORIES_TO_CODE_MAP[cat] |
| 175 | if cat_code in excluded_categories: |
| 176 | continue |
| 177 | categories.append(f"{cat_code}: {cat}.") |
| 178 | |
| 179 | return categories |
| 180 | |
| 181 | def build_prompt(self, messages: List[Message]) -> str: |
| 182 | categories = self.get_safety_categories() |
| 183 | categories_str = "\n".join(categories) |
| 184 | conversations_str = "\n\n".join( |
| 185 | [f"{m.role.capitalize()}: {m.content}" for m in messages] |
| 186 | ) |
| 187 | return PROMPT_TEMPLATE.substitute( |
| 188 | agent_type=messages[-1].role.capitalize(), |
| 189 | categories=categories_str, |
| 190 | conversations=conversations_str, |
| 191 | ) |
| 192 | |
| 193 | def get_shield_response(self, response: str) -> ShieldResponse: |
| 194 | if response == SAFE_RESPONSE: |
| 195 | return ShieldResponse( |
| 196 | shield_type=BuiltinShield.llama_guard, is_violation=False |
| 197 | ) |
| 198 | unsafe_code = self.check_unsafe_response(response) |
| 199 | if unsafe_code: |
| 200 | unsafe_code_list = unsafe_code.split(",") |
| 201 | if set(unsafe_code_list).issubset(set(self.excluded_categories)): |
| 202 | return ShieldResponse( |
| 203 | shield_type=BuiltinShield.llama_guard, is_violation=False |
| 204 | ) |
| 205 | return ShieldResponse( |
| 206 | shield_type=BuiltinShield.llama_guard, |
| 207 | is_violation=True, |
| 208 | violation_type=unsafe_code, |
| 209 | violation_return_message=CANNED_RESPONSE_TEXT, |
| 210 | ) |
| 211 | |
| 212 | raise ValueError(f"Unexpected response: {response}") |
| 213 | |
| 214 | async def run(self, messages: List[Message]) -> ShieldResponse: |
| 215 | if self.disable_input_check and messages[-1].role == Role.user.value: |
| 216 | return ShieldResponse( |
| 217 | shield_type=BuiltinShield.llama_guard, is_violation=False |
| 218 | ) |
| 219 | elif self.disable_output_check and messages[-1].role == Role.assistant.value: |
| 220 | return ShieldResponse( |
| 221 | shield_type=BuiltinShield.llama_guard, |
| 222 | is_violation=False, |
| 223 | ) |
| 224 | else: |
| 225 | prompt = self.build_prompt(messages) |
| 226 | llama_guard_input = { |
| 227 | "role": "user", |
| 228 | "content": prompt, |
| 229 | } |
| 230 | input_ids = self.tokenizer.apply_chat_template( |
| 231 | [llama_guard_input], return_tensors="pt", tokenize=True |
| 232 | ).to(self.device) |
| 233 | prompt_len = input_ids.shape[1] |
| 234 | output = self.model.generate( |
| 235 | input_ids=input_ids, |
| 236 | max_new_tokens=20, |
| 237 | output_scores=True, |
| 238 | return_dict_in_generate=True, |
| 239 | pad_token_id=0, |
| 240 | ) |
| 241 | generated_tokens = output.sequences[:, prompt_len:] |
| 242 | |
| 243 | response = self.tokenizer.decode( |
| 244 | generated_tokens[0], skip_special_tokens=True |
| 245 | ) |
| 246 | response = response.strip() |
| 247 | shield_response = self.get_shield_response(response) |
| 248 | return shield_response |