Elffuss BraidHub

kikocis/llama-stack public

Add safety impl for llama guard vision
Changesetb889cb8543a11be4385a387c117e704912fd5a40222fc835141a4e66c2249b35
AuthorAshwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-25 11:06 -07:00
CommitterAshwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-25 11:07 -07:00
Parents6c6abf1d1b75

Browse the files at this changeset

3 files changed

modified llama_stack/providers/impls/meta_reference/safety/__init__.py +2 −2
@@ -7,11 +7,11 @@
77 from .config import SafetyConfig
88
99
10-async def get_provider_impl(config: SafetyConfig, _deps):
10+async def get_provider_impl(config: SafetyConfig, deps):
1111 from .safety import MetaReferenceSafetyImpl
1212
1313 assert isinstance(config, SafetyConfig), f"Unexpected config type: {type(config)}"
1414
15- impl = MetaReferenceSafetyImpl(config)
15+ impl = MetaReferenceSafetyImpl(config, deps)
1616 await impl.initialize()
1717 return impl
modified llama_stack/providers/impls/meta_reference/safety/safety.py +14 −14
@@ -7,8 +7,10 @@
77 from llama_models.sku_list import resolve_model
88
99 from llama_stack.distribution.utils.model_utils import model_local_dir
10+from llama_stack.apis.inference import * # noqa: F403
1011 from llama_stack.apis.safety import * # noqa: F403
1112 from llama_models.llama3.api.datatypes import * # noqa: F403
13+from llama_stack.distribution.datatypes import Api
1214
1315 from llama_stack.providers.impls.meta_reference.safety.shields.base import (
1416 OnViolationAction,
@@ -34,20 +36,11 @@
3436
3537
3638 class MetaReferenceSafetyImpl(Safety):
37- def __init__(self, config: SafetyConfig) -> None:
39+ def __init__(self, config: SafetyConfig, deps) -> None:
3840 self.config = config
41+ self.inference_api = deps[Api.inference]
3942
4043 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-
5144 shield_cfg = self.config.prompt_guard_shield
5245 if shield_cfg is not None:
5346 model_dir = resolve_and_get_path(shield_cfg.model)
@@ -91,11 +84,18 @@
9184 def get_shield_impl(self, typ: MetaReferenceShieldType) -> ShieldBase:
9285 cfg = self.config
9386 if typ == MetaReferenceShieldType.llama_guard:
87+ cfg = cfg.llama_guard_shield
9488 assert (
95- cfg.llama_guard_shield is not None
89+ cfg is not None
9690 ), "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+ )
9999 elif typ == MetaReferenceShieldType.jailbreak_shield:
100100 assert (
101101 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 @@
1010 from typing import List, Optional
1111
1212 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+)
1519
1620 from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse
1721
@@ -67,10 +71,22 @@
6771 CAT_SELF_HARM,
6872 CAT_SEXUAL_CONTENT,
6973 CAT_ELECTIONS,
70- CAT_CODE_INTERPRETER_ABUSE,
7174 ]
7275
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."
7490
7591 SAFETY_CATEGORIES = """
7692
@@ -91,7 +107,7 @@
91107 PROMPT_INSTRUCTIONS = """
92108 Provide your safety assessment for ONLY THE LAST $agent_type message in the above conversation:
93109 - 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|>"""
95111
96112
97113 PROMPT_TEMPLATE = Template(
@@ -100,38 +116,21 @@
100116
101117
102118 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-
122119 def __init__(
123120 self,
124- on_violation_action: OnViolationAction = OnViolationAction.RAISE,
125- model_dir: str = None,
121+ model_dir: str,
126122 excluded_categories: List[str] = None,
127123 disable_input_check: bool = False,
128124 disable_output_check: bool = False,
125+ on_violation_action: OnViolationAction = OnViolationAction.RAISE,
129126 ):
130127 super().__init__(on_violation_action)
131128
132129 dtype = torch.bfloat16
130+ self.model_dir = model_dir
131+ self.device = "cuda"
133132
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"
135134
136135 if excluded_categories is None:
137136 excluded_categories = []
@@ -140,17 +139,24 @@
140139 x in SAFETY_CATEGORIES_TO_CODE_MAP.values() for x in excluded_categories
141140 ), "Invalid categories in excluded categories. Expected format is ['S1', 'S2', ..]"
142141
143- self.device = "cuda"
144142 self.excluded_categories = excluded_categories
145143 self.disable_input_check = disable_input_check
146144 self.disable_output_check = disable_output_check
147145
148- # load model
149146 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+ )
154160
155161 def check_unsafe_response(self, response: str) -> Optional[str]:
156162 match = re.match(r"^unsafe\n(.*)$", response)
@@ -166,14 +172,15 @@
166172 if set(excluded_categories) == set(SAFETY_CATEGORIES_TO_CODE_MAP.values()):
167173 excluded_categories = []
168174
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:
171178 cat_code = SAFETY_CATEGORIES_TO_CODE_MAP[cat]
172179 if cat_code in excluded_categories:
173180 continue
174- categories.append(f"{cat_code}: {cat}.")
181+ final_categories.append(f"{cat_code}: {cat}.")
175182
176- return categories
183+ return final_categories
177184
178185 def build_prompt(self, messages: List[Message]) -> str:
179186 categories = self.get_safety_categories()
@@ -188,6 +195,7 @@
188195 )
189196
190197 def get_shield_response(self, response: str) -> ShieldResponse:
198+ response = response.strip()
191199 if response == SAFE_RESPONSE:
192200 return ShieldResponse(is_violation=False)
193201 unsafe_code = self.check_unsafe_response(response)
@@ -203,7 +211,119 @@
203211
204212 raise ValueError(f"Unexpected response: {response}")
205213
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+
206324 async def run(self, messages: List[Message]) -> ShieldResponse:
325+
326+ messages = self.validate_messages(messages)
207327 if self.disable_input_check and messages[-1].role == Role.user.value:
208328 return ShieldResponse(is_violation=False)
209329 elif self.disable_output_check and messages[-1].role == Role.assistant.value:
@@ -211,27 +331,13 @@
211331 is_violation=False,
212332 )
213333 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:]
231334
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