kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | b889cb8543a11be4385a387c117e704912fd5a40222fc835141a4e66c2249b35 |
|---|---|
| Author | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-25 11:06 -07:00 |
| Committer | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-25 11:07 -07:00 |
| Parents | 6c6abf1d1b75 |
3 files changed
modified llama_stack/providers/impls/meta_reference/safety/__init__.py +2 −2
| @@ -7,11 +7,11 @@ | ||
| 7 | 7 | from .config import SafetyConfig |
| 8 | 8 | |
| 9 | 9 | |
| 10 | -async def get_provider_impl(config: SafetyConfig, _deps): | |
| 10 | +async def get_provider_impl(config: SafetyConfig, deps): | |
| 11 | 11 | from .safety import MetaReferenceSafetyImpl |
| 12 | 12 | |
| 13 | 13 | assert isinstance(config, SafetyConfig), f"Unexpected config type: {type(config)}" |
| 14 | 14 | |
| 15 | - impl = MetaReferenceSafetyImpl(config) | |
| 15 | + impl = MetaReferenceSafetyImpl(config, deps) | |
| 16 | 16 | await impl.initialize() |
| 17 | 17 | return impl |
modified llama_stack/providers/impls/meta_reference/safety/safety.py +14 −14
| @@ -7,8 +7,10 @@ | ||
| 7 | 7 | from llama_models.sku_list import resolve_model |
| 8 | 8 | |
| 9 | 9 | from llama_stack.distribution.utils.model_utils import model_local_dir |
| 10 | +from llama_stack.apis.inference import * # noqa: F403 | |
| 10 | 11 | from llama_stack.apis.safety import * # noqa: F403 |
| 11 | 12 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 13 | +from llama_stack.distribution.datatypes import Api | |
| 12 | 14 | |
| 13 | 15 | from llama_stack.providers.impls.meta_reference.safety.shields.base import ( |
| 14 | 16 | OnViolationAction, |
| @@ -34,20 +36,11 @@ | ||
| 34 | 36 | |
| 35 | 37 | |
| 36 | 38 | class MetaReferenceSafetyImpl(Safety): |
| 37 | - def __init__(self, config: SafetyConfig) -> None: | |
| 39 | + def __init__(self, config: SafetyConfig, deps) -> None: | |
| 38 | 40 | self.config = config |
| 41 | + self.inference_api = deps[Api.inference] | |
| 39 | 42 | |
| 40 | 43 | async def initialize(self) -> None: |
| 41 | - shield_cfg = self.config.llama_guard_shield | |
| 42 | - if shield_cfg is not None: | |
| 43 | - model_dir = resolve_and_get_path(shield_cfg.model) | |
| 44 | - _ = LlamaGuardShield.instance( | |
| 45 | - model_dir=model_dir, | |
| 46 | - excluded_categories=shield_cfg.excluded_categories, | |
| 47 | - disable_input_check=shield_cfg.disable_input_check, | |
| 48 | - disable_output_check=shield_cfg.disable_output_check, | |
| 49 | - ) | |
| 50 | - | |
| 51 | 44 | shield_cfg = self.config.prompt_guard_shield |
| 52 | 45 | if shield_cfg is not None: |
| 53 | 46 | model_dir = resolve_and_get_path(shield_cfg.model) |
| @@ -91,11 +84,18 @@ | ||
| 91 | 84 | def get_shield_impl(self, typ: MetaReferenceShieldType) -> ShieldBase: |
| 92 | 85 | cfg = self.config |
| 93 | 86 | if typ == MetaReferenceShieldType.llama_guard: |
| 87 | + cfg = cfg.llama_guard_shield | |
| 94 | 88 | assert ( |
| 95 | - cfg.llama_guard_shield is not None | |
| 89 | + cfg is not None | |
| 96 | 90 | ), "Cannot use LlamaGuardShield since not present in config" |
| 97 | - model_dir = resolve_and_get_path(cfg.llama_guard_shield.model) | |
| 98 | - return LlamaGuardShield.instance(model_dir=model_dir) | |
| 91 | + model_dir = resolve_and_get_path(cfg.model) | |
| 92 | + | |
| 93 | + return LlamaGuardShield( | |
| 94 | + model_dir=model_dir, | |
| 95 | + excluded_categories=cfg.excluded_categories, | |
| 96 | + disable_input_check=cfg.disable_input_check, | |
| 97 | + disable_output_check=cfg.disable_output_check, | |
| 98 | + ) | |
| 99 | 99 | elif typ == MetaReferenceShieldType.jailbreak_shield: |
| 100 | 100 | assert ( |
| 101 | 101 | cfg.prompt_guard_shield is not None |
modified llama_stack/providers/impls/meta_reference/safety/shields/llama_guard.py +166 −60
| @@ -10,8 +10,12 @@ | ||
| 10 | 10 | from typing import List, Optional |
| 11 | 11 | |
| 12 | 12 | import torch |
| 13 | -from llama_models.llama3.api.datatypes import Message, Role | |
| 14 | -from transformers import AutoModelForCausalLM, AutoTokenizer | |
| 13 | +from transformers import ( | |
| 14 | + AutoModelForCausalLM, | |
| 15 | + AutoTokenizer, | |
| 16 | + MllamaForConditionalGeneration, | |
| 17 | + MllamaProcessor, | |
| 18 | +) | |
| 15 | 19 | |
| 16 | 20 | from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse |
| 17 | 21 | |
| @@ -67,10 +71,22 @@ | ||
| 67 | 71 | CAT_SELF_HARM, |
| 68 | 72 | CAT_SEXUAL_CONTENT, |
| 69 | 73 | CAT_ELECTIONS, |
| 70 | - CAT_CODE_INTERPRETER_ABUSE, | |
| 71 | 74 | ] |
| 72 | 75 | |
| 73 | -PROMPT_TASK = "Task: Check if there is unsafe content in '$agent_type' messages in conversations according our safety policy with the below categories." | |
| 76 | +# model names | |
| 77 | +LG_3_8B = "Llama-Guard-3-8B" | |
| 78 | +LG_3_1B = "Llama-Guard-3-1B" | |
| 79 | +LG_3_11B_VISION = "Llama-Guard-3-11B-Vision" | |
| 80 | + | |
| 81 | + | |
| 82 | +MODEL_TO_SAFETY_CATEGORIES_MAP = { | |
| 83 | + LG_3_8B: DEFAULT_LG_V3_SAFETY_CATEGORIES + [CAT_CODE_INTERPRETER_ABUSE], | |
| 84 | + LG_3_1B: DEFAULT_LG_V3_SAFETY_CATEGORIES, | |
| 85 | + LG_3_11B_VISION: DEFAULT_LG_V3_SAFETY_CATEGORIES, | |
| 86 | +} | |
| 87 | + | |
| 88 | + | |
| 89 | +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." | |
| 74 | 90 | |
| 75 | 91 | SAFETY_CATEGORIES = """ |
| 76 | 92 | |
| @@ -91,7 +107,7 @@ | ||
| 91 | 107 | PROMPT_INSTRUCTIONS = """ |
| 92 | 108 | Provide your safety assessment for ONLY THE LAST $agent_type message in the above conversation: |
| 93 | 109 | - First line must read 'safe' or 'unsafe'. |
| 94 | - - If unsafe, a second line must include a comma-separated list of violated categories.""" | |
| 110 | + - If unsafe, a second line must include a comma-separated list of violated categories. <|eot_id|><|start_header_id|>assistant<|end_header_id|>""" | |
| 95 | 111 | |
| 96 | 112 | |
| 97 | 113 | PROMPT_TEMPLATE = Template( |
| @@ -100,38 +116,21 @@ | ||
| 100 | 116 | |
| 101 | 117 | |
| 102 | 118 | 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 | 119 | def __init__( |
| 123 | 120 | self, |
| 124 | - on_violation_action: OnViolationAction = OnViolationAction.RAISE, | |
| 125 | - model_dir: str = None, | |
| 121 | + model_dir: str, | |
| 126 | 122 | excluded_categories: List[str] = None, |
| 127 | 123 | disable_input_check: bool = False, |
| 128 | 124 | disable_output_check: bool = False, |
| 125 | + on_violation_action: OnViolationAction = OnViolationAction.RAISE, | |
| 129 | 126 | ): |
| 130 | 127 | super().__init__(on_violation_action) |
| 131 | 128 | |
| 132 | 129 | dtype = torch.bfloat16 |
| 130 | + self.model_dir = model_dir | |
| 131 | + self.device = "cuda" | |
| 133 | 132 | |
| 134 | - assert model_dir is not None, "Llama Guard model_dir is None" | |
| 133 | + assert self.model_dir is not None, "Llama Guard model_dir is None" | |
| 135 | 134 | |
| 136 | 135 | if excluded_categories is None: |
| 137 | 136 | excluded_categories = [] |
| @@ -140,17 +139,24 @@ | ||
| 140 | 139 | x in SAFETY_CATEGORIES_TO_CODE_MAP.values() for x in excluded_categories |
| 141 | 140 | ), "Invalid categories in excluded categories. Expected format is ['S1', 'S2', ..]" |
| 142 | 141 | |
| 143 | - self.device = "cuda" | |
| 144 | 142 | self.excluded_categories = excluded_categories |
| 145 | 143 | self.disable_input_check = disable_input_check |
| 146 | 144 | self.disable_output_check = disable_output_check |
| 147 | 145 | |
| 148 | - # load model | |
| 149 | 146 | 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 | - ) | |
| 147 | + | |
| 148 | + if self.is_lg_vision(): | |
| 149 | + | |
| 150 | + self.model = MllamaForConditionalGeneration.from_pretrained( | |
| 151 | + self.model_dir, device_map=self.device, torch_dtype=torch_dtype | |
| 152 | + ) | |
| 153 | + self.processor = MllamaProcessor.from_pretrained(self.model_dir) | |
| 154 | + else: | |
| 155 | + | |
| 156 | + self.tokenizer = AutoTokenizer.from_pretrained(self.model_dir) | |
| 157 | + self.model = AutoModelForCausalLM.from_pretrained( | |
| 158 | + self.model_dir, torch_dtype=torch_dtype, device_map=self.device | |
| 159 | + ) | |
| 154 | 160 | |
| 155 | 161 | def check_unsafe_response(self, response: str) -> Optional[str]: |
| 156 | 162 | match = re.match(r"^unsafe\n(.*)$", response) |
| @@ -166,14 +172,15 @@ | ||
| 166 | 172 | if set(excluded_categories) == set(SAFETY_CATEGORIES_TO_CODE_MAP.values()): |
| 167 | 173 | excluded_categories = [] |
| 168 | 174 | |
| 169 | - categories = [] | |
| 170 | - for cat in DEFAULT_LG_V3_SAFETY_CATEGORIES: | |
| 175 | + final_categories = [] | |
| 176 | + all_categories = MODEL_TO_SAFETY_CATEGORIES_MAP[self.get_model_name()] | |
| 177 | + for cat in all_categories: | |
| 171 | 178 | cat_code = SAFETY_CATEGORIES_TO_CODE_MAP[cat] |
| 172 | 179 | if cat_code in excluded_categories: |
| 173 | 180 | continue |
| 174 | - categories.append(f"{cat_code}: {cat}.") | |
| 181 | + final_categories.append(f"{cat_code}: {cat}.") | |
| 175 | 182 | |
| 176 | - return categories | |
| 183 | + return final_categories | |
| 177 | 184 | |
| 178 | 185 | def build_prompt(self, messages: List[Message]) -> str: |
| 179 | 186 | categories = self.get_safety_categories() |
| @@ -188,6 +195,7 @@ | ||
| 188 | 195 | ) |
| 189 | 196 | |
| 190 | 197 | def get_shield_response(self, response: str) -> ShieldResponse: |
| 198 | + response = response.strip() | |
| 191 | 199 | if response == SAFE_RESPONSE: |
| 192 | 200 | return ShieldResponse(is_violation=False) |
| 193 | 201 | unsafe_code = self.check_unsafe_response(response) |
| @@ -203,7 +211,119 @@ | ||
| 203 | 211 | |
| 204 | 212 | raise ValueError(f"Unexpected response: {response}") |
| 205 | 213 | |
| 214 | + def build_mm_prompt(self, messages: List[Message]) -> str: | |
| 215 | + conversation = [] | |
| 216 | + most_recent_img = None | |
| 217 | + | |
| 218 | + for m in messages[::-1]: | |
| 219 | + if isinstance(m.content, str): | |
| 220 | + conversation.append( | |
| 221 | + { | |
| 222 | + "role": m.role, | |
| 223 | + "content": [{"type": "text", "text": m.content}], | |
| 224 | + } | |
| 225 | + ) | |
| 226 | + elif isinstance(m.content, ImageMedia): | |
| 227 | + if most_recent_img is None and m.role == Role.user.value: | |
| 228 | + most_recent_img = m.content | |
| 229 | + conversation.append( | |
| 230 | + { | |
| 231 | + "role": m.role, | |
| 232 | + "content": [{"type": "image"}], | |
| 233 | + } | |
| 234 | + ) | |
| 235 | + | |
| 236 | + elif isinstance(m.content, list): | |
| 237 | + content = [] | |
| 238 | + for c in m.content: | |
| 239 | + if isinstance(c, str): | |
| 240 | + content.append({"type": "text", "text": c}) | |
| 241 | + elif isinstance(c, ImageMedia): | |
| 242 | + if most_recent_img is None and m.role == Role.user.value: | |
| 243 | + most_recent_img = c | |
| 244 | + content.append({"type": "image"}) | |
| 245 | + else: | |
| 246 | + raise ValueError(f"Unknown content type: {c}") | |
| 247 | + | |
| 248 | + conversation.append( | |
| 249 | + { | |
| 250 | + "role": m.role, | |
| 251 | + "content": content, | |
| 252 | + } | |
| 253 | + ) | |
| 254 | + else: | |
| 255 | + raise ValueError(f"Unknown content type: {m.content}") | |
| 256 | + | |
| 257 | + return conversation[::-1], most_recent_img | |
| 258 | + | |
| 259 | + async def run_lg_mm(self, messages: List[Message]) -> ShieldResponse: | |
| 260 | + formatted_messages, most_recent_img = self.build_mm_prompt(messages) | |
| 261 | + raw_image = None | |
| 262 | + if most_recent_img: | |
| 263 | + raw_image = interleaved_text_media_localize(most_recent_img) | |
| 264 | + raw_image = raw_image.image | |
| 265 | + llama_guard_input_templ_applied = self.processor.apply_chat_template( | |
| 266 | + formatted_messages, | |
| 267 | + add_generation_prompt=True, | |
| 268 | + tokenize=False, | |
| 269 | + skip_special_tokens=False, | |
| 270 | + ) | |
| 271 | + inputs = self.processor( | |
| 272 | + text=llama_guard_input_templ_applied, images=raw_image, return_tensors="pt" | |
| 273 | + ).to(self.device) | |
| 274 | + output = self.model.generate(**inputs, do_sample=False, max_new_tokens=50) | |
| 275 | + response = self.processor.decode( | |
| 276 | + output[0][len(inputs["input_ids"][0]) :], skip_special_tokens=True | |
| 277 | + ) | |
| 278 | + shield_response = self.get_shield_response(response) | |
| 279 | + return shield_response | |
| 280 | + | |
| 281 | + async def run_lg_text(self, messages: List[Message]): | |
| 282 | + prompt = self.build_prompt(messages) | |
| 283 | + input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device) | |
| 284 | + prompt_len = input_ids.shape[1] | |
| 285 | + output = self.model.generate( | |
| 286 | + input_ids=input_ids, | |
| 287 | + max_new_tokens=20, | |
| 288 | + output_scores=True, | |
| 289 | + return_dict_in_generate=True, | |
| 290 | + pad_token_id=0, | |
| 291 | + ) | |
| 292 | + generated_tokens = output.sequences[:, prompt_len:] | |
| 293 | + | |
| 294 | + response = self.tokenizer.decode(generated_tokens[0], skip_special_tokens=True) | |
| 295 | + | |
| 296 | + shield_response = self.get_shield_response(response) | |
| 297 | + return shield_response | |
| 298 | + | |
| 299 | + def get_model_name(self): | |
| 300 | + return self.model_dir.split("/")[-1] | |
| 301 | + | |
| 302 | + def is_lg_vision(self): | |
| 303 | + model_name = self.get_model_name() | |
| 304 | + return model_name == LG_3_11B_VISION | |
| 305 | + | |
| 306 | + def validate_messages(self, messages: List[Message]) -> None: | |
| 307 | + if len(messages) == 0: | |
| 308 | + raise ValueError("Messages must not be empty") | |
| 309 | + if messages[0].role != Role.user.value: | |
| 310 | + raise ValueError("Messages must start with user") | |
| 311 | + | |
| 312 | + if len(messages) >= 2 and ( | |
| 313 | + messages[0].role == Role.user.value and messages[1].role == Role.user.value | |
| 314 | + ): | |
| 315 | + messages = messages[1:] | |
| 316 | + | |
| 317 | + for i in range(1, len(messages)): | |
| 318 | + if messages[i].role == messages[i - 1].role: | |
| 319 | + raise ValueError( | |
| 320 | + f"Messages must alternate between user and assistant. Message {i} has the same role as message {i-1}" | |
| 321 | + ) | |
| 322 | + return messages | |
| 323 | + | |
| 206 | 324 | async def run(self, messages: List[Message]) -> ShieldResponse: |
| 325 | + | |
| 326 | + messages = self.validate_messages(messages) | |
| 207 | 327 | if self.disable_input_check and messages[-1].role == Role.user.value: |
| 208 | 328 | return ShieldResponse(is_violation=False) |
| 209 | 329 | elif self.disable_output_check and messages[-1].role == Role.assistant.value: |
| @@ -211,27 +331,13 @@ | ||
| 211 | 331 | is_violation=False, |
| 212 | 332 | ) |
| 213 | 333 | 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 | 334 | |
| 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 | |
| 335 | + if self.is_lg_vision(): | |
| 336 | + | |
| 337 | + shield_response = await self.run_lg_mm(messages) | |
| 338 | + | |
| 339 | + else: | |
| 340 | + | |
| 341 | + shield_response = await self.run_lg_text(messages) | |
| 342 | + | |
| 343 | + return shield_response |