kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | 3afa27c5b92668801d4e9b16cb878bfbdfc8184a7774413b1d2c3133d7222266 |
|---|---|
| Author | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 19:20 -07:00 |
| Committer | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 19:20 -07:00 |
| Parents | e7e47c3d00f8 |
4 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, deps) | |
| 15 | + impl = MetaReferenceSafetyImpl(config) | |
| 16 | 16 | await impl.initialize() |
| 17 | 17 | return impl |
modified llama_stack/providers/impls/meta_reference/safety/safety.py +14 −14
| @@ -7,10 +7,8 @@ | ||
| 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 | |
| 11 | 10 | from llama_stack.apis.safety import * # noqa: F403 |
| 12 | 11 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 13 | -from llama_stack.distribution.datatypes import Api | |
| 14 | 12 | |
| 15 | 13 | from llama_stack.providers.impls.meta_reference.safety.shields.base import ( |
| 16 | 14 | OnViolationAction, |
| @@ -36,11 +34,20 @@ | ||
| 36 | 34 | |
| 37 | 35 | |
| 38 | 36 | class MetaReferenceSafetyImpl(Safety): |
| 39 | - def __init__(self, config: SafetyConfig, deps) -> None: | |
| 37 | + def __init__(self, config: SafetyConfig) -> None: | |
| 40 | 38 | self.config = config |
| 41 | - self.inference_api = deps[Api.inference] | |
| 42 | 39 | |
| 43 | 40 | 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 | + | |
| 44 | 51 | shield_cfg = self.config.prompt_guard_shield |
| 45 | 52 | if shield_cfg is not None: |
| 46 | 53 | model_dir = resolve_and_get_path(shield_cfg.model) |
| @@ -84,18 +91,11 @@ | ||
| 84 | 91 | def get_shield_impl(self, typ: MetaReferenceShieldType) -> ShieldBase: |
| 85 | 92 | cfg = self.config |
| 86 | 93 | if typ == MetaReferenceShieldType.llama_guard: |
| 87 | - cfg = cfg.llama_guard_shield | |
| 88 | 94 | assert ( |
| 89 | - cfg is not None | |
| 95 | + cfg.llama_guard_shield is not None | |
| 90 | 96 | ), "Cannot use LlamaGuardShield since not present in config" |
| 91 | - | |
| 92 | - return LlamaGuardShield( | |
| 93 | - model=cfg.model, | |
| 94 | - inference_api=self.inference_api, | |
| 95 | - excluded_categories=cfg.excluded_categories, | |
| 96 | - disable_input_check=cfg.disable_input_check, | |
| 97 | - disable_output_check=cfg.disable_output_check, | |
| 98 | - ) | |
| 97 | + model_dir = resolve_and_get_path(cfg.llama_guard_shield.model) | |
| 98 | + return LlamaGuardShield.instance(model_dir=model_dir) | |
| 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 +56 −22
| @@ -9,8 +9,9 @@ | ||
| 9 | 9 | from string import Template |
| 10 | 10 | from typing import List, Optional |
| 11 | 11 | |
| 12 | +import torch | |
| 12 | 13 | from llama_models.llama3.api.datatypes import Message, Role |
| 13 | -from llama_stack.apis.inference import * # noqa: F403 | |
| 14 | +from transformers import AutoModelForCausalLM, AutoTokenizer | |
| 14 | 15 | |
| 15 | 16 | from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse |
| 16 | 17 | |
| @@ -99,17 +100,39 @@ | ||
| 99 | 100 | |
| 100 | 101 | |
| 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 | + | |
| 102 | 122 | def __init__( |
| 103 | 123 | self, |
| 104 | - model: str, | |
| 105 | - inference_api: Inference, | |
| 124 | + on_violation_action: OnViolationAction = OnViolationAction.RAISE, | |
| 125 | + model_dir: str = None, | |
| 106 | 126 | excluded_categories: List[str] = None, |
| 107 | 127 | disable_input_check: bool = False, |
| 108 | 128 | disable_output_check: bool = False, |
| 109 | - on_violation_action: OnViolationAction = OnViolationAction.RAISE, | |
| 110 | 129 | ): |
| 111 | 130 | super().__init__(on_violation_action) |
| 112 | 131 | |
| 132 | + dtype = torch.bfloat16 | |
| 133 | + | |
| 134 | + assert model_dir is not None, "Llama Guard model_dir is None" | |
| 135 | + | |
| 113 | 136 | if excluded_categories is None: |
| 114 | 137 | excluded_categories = [] |
| 115 | 138 | |
| @@ -117,12 +140,18 @@ | ||
| 117 | 140 | x in SAFETY_CATEGORIES_TO_CODE_MAP.values() for x in excluded_categories |
| 118 | 141 | ), "Invalid categories in excluded categories. Expected format is ['S1', 'S2', ..]" |
| 119 | 142 | |
| 120 | - self.model = model | |
| 121 | - self.inference_api = inference_api | |
| 143 | + self.device = "cuda" | |
| 122 | 144 | self.excluded_categories = excluded_categories |
| 123 | 145 | self.disable_input_check = disable_input_check |
| 124 | 146 | self.disable_output_check = disable_output_check |
| 125 | 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 | + | |
| 126 | 155 | def check_unsafe_response(self, response: str) -> Optional[str]: |
| 127 | 156 | match = re.match(r"^unsafe\n(.*)$", response) |
| 128 | 157 | if match: |
| @@ -183,21 +212,26 @@ | ||
| 183 | 212 | ) |
| 184 | 213 | else: |
| 185 | 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:] | |
| 186 | 231 | |
| 187 | - # TODO: llama-stack inference protocol has issues with non-streaming inference code | |
| 188 | - content = "" | |
| 189 | - async for chunk in self.inference_api.chat_completion( | |
| 190 | - model=self.model, | |
| 191 | - messages=[ | |
| 192 | - UserMessage(content=prompt), | |
| 193 | - ], | |
| 194 | - stream=True, | |
| 195 | - ): | |
| 196 | - event = chunk.event | |
| 197 | - if event.event_type == ChatCompletionResponseEventType.progress: | |
| 198 | - assert isinstance(event.delta, str) | |
| 199 | - content += event.delta | |
| 200 | - | |
| 201 | - content = content.strip() | |
| 202 | - shield_response = self.get_shield_response(content) | |
| 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) | |
| 203 | 237 | return shield_response |
modified llama_stack/providers/registry/safety.py +2 −4
| @@ -21,15 +21,13 @@ | ||
| 21 | 21 | api=Api.safety, |
| 22 | 22 | provider_id="meta-reference", |
| 23 | 23 | pip_packages=[ |
| 24 | + "accelerate", | |
| 24 | 25 | "codeshield", |
| 26 | + "torch", | |
| 25 | 27 | "transformers", |
| 26 | - "torch --index-url https://download.pytorch.org/whl/cpu", | |
| 27 | 28 | ], |
| 28 | 29 | module="llama_stack.providers.impls.meta_reference.safety", |
| 29 | 30 | config_class="llama_stack.providers.impls.meta_reference.safety.SafetyConfig", |
| 30 | - api_dependencies=[ | |
| 31 | - Api.inference, | |
| 32 | - ], | |
| 33 | 31 | ), |
| 34 | 32 | remote_provider_spec( |
| 35 | 33 | api=Api.safety, |