Elffuss BraidHub

kikocis/llama-stack public

842c3e3bbdd0 · 7.6 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 llama_models.llama3.api.datatypes import Message, Role
14from transformers import AutoModelForCausalLM, AutoTokenizer
15
16from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse
17
18
19SAFE_RESPONSE = "safe"
20_INSTANCE = None
21
22CAT_VIOLENT_CRIMES = "Violent Crimes"
23CAT_NON_VIOLENT_CRIMES = "Non-Violent Crimes"
24CAT_SEX_CRIMES = "Sex Crimes"
25CAT_CHILD_EXPLOITATION = "Child Exploitation"
26CAT_DEFAMATION = "Defamation"
27CAT_SPECIALIZED_ADVICE = "Specialized Advice"
28CAT_PRIVACY = "Privacy"
29CAT_INTELLECTUAL_PROPERTY = "Intellectual Property"
30CAT_INDISCRIMINATE_WEAPONS = "Indiscriminate Weapons"
31CAT_HATE = "Hate"
32CAT_SELF_HARM = "Self-Harm"
33CAT_SEXUAL_CONTENT = "Sexual Content"
34CAT_ELECTIONS = "Elections"
35CAT_CODE_INTERPRETER_ABUSE = "Code Interpreter Abuse"
36
37
38SAFETY_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
56DEFAULT_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
73PROMPT_TASK = "Task: Check if there is unsafe content in '$agent_type' messages in conversations according our safety policy with the below categories."
74
75SAFETY_CATEGORIES = """
76
77<BEGIN UNSAFE CONTENT CATEGORIES>
78$categories
79<END UNSAFE CONTENT CATEGORIES>
80"""
81
82PROMPT_CONVERSATION = """
83<BEGIN CONVERSATION>
84
85$conversations
86
87<END CONVERSATION>
88"""
89
90
91PROMPT_INSTRUCTIONS = """
92Provide 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
97PROMPT_TEMPLATE = Template(
98 f"{PROMPT_TASK}{SAFETY_CATEGORIES}{PROMPT_CONVERSATION}{PROMPT_INSTRUCTIONS}"
99)
100
101
102class 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 check_unsafe_response(self, response: str) -> Optional[str]:
156 match = re.match(r"^unsafe\n(.*)$", response)
157 if match:
158 # extracts the unsafe code
159 extracted = match.group(1)
160 return extracted
161
162 return None
163
164 def get_safety_categories(self) -> List[str]:
165 excluded_categories = self.excluded_categories
166 if set(excluded_categories) == set(SAFETY_CATEGORIES_TO_CODE_MAP.values()):
167 excluded_categories = []
168
169 categories = []
170 for cat in DEFAULT_LG_V3_SAFETY_CATEGORIES:
171 cat_code = SAFETY_CATEGORIES_TO_CODE_MAP[cat]
172 if cat_code in excluded_categories:
173 continue
174 categories.append(f"{cat_code}: {cat}.")
175
176 return categories
177
178 def build_prompt(self, messages: List[Message]) -> str:
179 categories = self.get_safety_categories()
180 categories_str = "\n".join(categories)
181 conversations_str = "\n\n".join(
182 [f"{m.role.capitalize()}: {m.content}" for m in messages]
183 )
184 return PROMPT_TEMPLATE.substitute(
185 agent_type=messages[-1].role.capitalize(),
186 categories=categories_str,
187 conversations=conversations_str,
188 )
189
190 def get_shield_response(self, response: str) -> ShieldResponse:
191 if response == SAFE_RESPONSE:
192 return ShieldResponse(is_violation=False)
193 unsafe_code = self.check_unsafe_response(response)
194 if unsafe_code:
195 unsafe_code_list = unsafe_code.split(",")
196 if set(unsafe_code_list).issubset(set(self.excluded_categories)):
197 return ShieldResponse(is_violation=False)
198 return ShieldResponse(
199 is_violation=True,
200 violation_type=unsafe_code,
201 violation_return_message=CANNED_RESPONSE_TEXT,
202 )
203
204 raise ValueError(f"Unexpected response: {response}")
205
206 async def run(self, messages: List[Message]) -> ShieldResponse:
207 if self.disable_input_check and messages[-1].role == Role.user.value:
208 return ShieldResponse(is_violation=False)
209 elif self.disable_output_check and messages[-1].role == Role.assistant.value:
210 return ShieldResponse(
211 is_violation=False,
212 )
213 else:
214 prompt = self.build_prompt(messages)
215 llama_guard_input = {
216 "role": "user",
217 "content": prompt,
218 }
219 input_ids = self.tokenizer.apply_chat_template(
220 [llama_guard_input], return_tensors="pt", tokenize=True
221 ).to(self.device)
222 prompt_len = input_ids.shape[1]
223 output = self.model.generate(
224 input_ids=input_ids,
225 max_new_tokens=20,
226 output_scores=True,
227 return_dict_in_generate=True,
228 pad_token_id=0,
229 )
230 generated_tokens = output.sequences[:, prompt_len:]
231
232 response = self.tokenizer.decode(
233 generated_tokens[0], skip_special_tokens=True
234 )
235 response = response.strip()
236 shield_response = self.get_shield_response(response)
237 return shield_response