kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | 6c30136e2df6127e493355557b201ec15377a8b973a50db647515c47495dcd20 |
|---|---|
| Author | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 17:02 -07:00 |
| Committer | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-24 17:02 -07:00 |
| Parents | 97c937a181e7 |
9 files changed
modified llama_stack/apis/inference/inference.py +1 −1
| @@ -190,7 +190,7 @@ | ||
| 190 | 190 | messages: List[Message], |
| 191 | 191 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 192 | 192 | # zero-shot tool definitions as input to the model |
| 193 | - tools: Optional[List[ToolDefinition]] = list, | |
| 193 | + tools: Optional[List[ToolDefinition]] = None, | |
| 194 | 194 | tool_choice: Optional[ToolChoice] = ToolChoice.auto, |
| 195 | 195 | tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json, |
| 196 | 196 | stream: Optional[bool] = False, |
modified llama_stack/distribution/routers/routers.py +5 −2
| @@ -103,8 +103,7 @@ | ||
| 103 | 103 | stream: Optional[bool] = False, |
| 104 | 104 | logprobs: Optional[LogProbConfig] = None, |
| 105 | 105 | ) -> AsyncGenerator: |
| 106 | - # TODO: we need to fix streaming response to align provider implementations with Protocol. | |
| 107 | - async for chunk in self.routing_table.get_provider_impl(model).chat_completion( | |
| 106 | + params = dict( | |
| 108 | 107 | model=model, |
| 109 | 108 | messages=messages, |
| 110 | 109 | sampling_params=sampling_params, |
| @@ -113,6 +112,10 @@ | ||
| 113 | 112 | tool_prompt_format=tool_prompt_format, |
| 114 | 113 | stream=stream, |
| 115 | 114 | logprobs=logprobs, |
| 115 | + ) | |
| 116 | + # TODO: we need to fix streaming response to align provider implementations with Protocol. | |
| 117 | + async for chunk in self.routing_table.get_provider_impl(model).chat_completion( | |
| 118 | + **params | |
| 116 | 119 | ): |
| 117 | 120 | yield chunk |
| 118 | 121 |
modified llama_stack/distribution/routers/routing_tables.py +4 −2
| @@ -33,8 +33,10 @@ | ||
| 33 | 33 | for p in self.providers.values(): |
| 34 | 34 | await p.shutdown() |
| 35 | 35 | |
| 36 | - def get_provider_impl(self, routing_key: str) -> Optional[Any]: | |
| 37 | - return self.providers.get(routing_key) | |
| 36 | + def get_provider_impl(self, routing_key: str) -> Any: | |
| 37 | + if routing_key not in self.providers: | |
| 38 | + raise ValueError(f"Could not find provider for {routing_key}") | |
| 39 | + return self.providers[routing_key] | |
| 38 | 40 | |
| 39 | 41 | def get_routing_keys(self) -> List[str]: |
| 40 | 42 | return self.routing_keys |
modified llama_stack/distribution/server/server.py +3 −1
| @@ -368,17 +368,19 @@ | ||
| 368 | 368 | providers = all_providers[info.router_api] |
| 369 | 369 | |
| 370 | 370 | inner_specs = [] |
| 371 | + inner_deps = [] | |
| 371 | 372 | for rt_entry in routing_table: |
| 372 | 373 | if rt_entry.provider_id not in providers: |
| 373 | 374 | raise ValueError( |
| 374 | 375 | f"Unknown provider `{rt_entry.provider_id}` is not available for API `{api}`" |
| 375 | 376 | ) |
| 376 | 377 | inner_specs.append(providers[rt_entry.provider_id]) |
| 378 | + inner_deps.extend(providers[rt_entry.provider_id].api_dependencies) | |
| 377 | 379 | |
| 378 | 380 | specs[source_api] = RoutingTableProviderSpec( |
| 379 | 381 | api=source_api, |
| 380 | 382 | module="llama_stack.distribution.routers", |
| 381 | - api_dependencies=[], | |
| 383 | + api_dependencies=inner_deps, | |
| 382 | 384 | inner_specs=inner_specs, |
| 383 | 385 | ) |
| 384 | 386 | configs[source_api] = routing_table |
modified llama_stack/providers/adapters/inference/tgi/tgi.py +1 −1
| @@ -119,7 +119,7 @@ | ||
| 119 | 119 | ) |
| 120 | 120 | stop_reason = None |
| 121 | 121 | if response.details.finish_reason: |
| 122 | - if response.details.finish_reason == "stop": | |
| 122 | + if response.details.finish_reason in ["stop", "eos_token"]: | |
| 123 | 123 | stop_reason = StopReason.end_of_turn |
| 124 | 124 | elif response.details.finish_reason == "length": |
| 125 | 125 | stop_reason = StopReason.out_of_tokens |
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 | + | |
| 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 | + ) | |
| 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 +22 −56
| @@ -9,9 +9,8 @@ | ||
| 9 | 9 | from string import Template |
| 10 | 10 | from typing import List, Optional |
| 11 | 11 | |
| 12 | -import torch | |
| 13 | 12 | from llama_models.llama3.api.datatypes import Message, Role |
| 14 | -from transformers import AutoModelForCausalLM, AutoTokenizer | |
| 13 | +from llama_stack.apis.inference import * # noqa: F403 | |
| 15 | 14 | |
| 16 | 15 | from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse |
| 17 | 16 | |
| @@ -100,39 +99,17 @@ | ||
| 100 | 99 | |
| 101 | 100 | |
| 102 | 101 | 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 | 102 | def __init__( |
| 123 | 103 | self, |
| 124 | - on_violation_action: OnViolationAction = OnViolationAction.RAISE, | |
| 125 | - model_dir: str = None, | |
| 104 | + model: str, | |
| 105 | + inference_api: Inference, | |
| 126 | 106 | excluded_categories: List[str] = None, |
| 127 | 107 | disable_input_check: bool = False, |
| 128 | 108 | disable_output_check: bool = False, |
| 109 | + on_violation_action: OnViolationAction = OnViolationAction.RAISE, | |
| 129 | 110 | ): |
| 130 | 111 | super().__init__(on_violation_action) |
| 131 | 112 | |
| 132 | - dtype = torch.bfloat16 | |
| 133 | - | |
| 134 | - assert model_dir is not None, "Llama Guard model_dir is None" | |
| 135 | - | |
| 136 | 113 | if excluded_categories is None: |
| 137 | 114 | excluded_categories = [] |
| 138 | 115 | |
| @@ -140,18 +117,12 @@ | ||
| 140 | 117 | x in SAFETY_CATEGORIES_TO_CODE_MAP.values() for x in excluded_categories |
| 141 | 118 | ), "Invalid categories in excluded categories. Expected format is ['S1', 'S2', ..]" |
| 142 | 119 | |
| 143 | - self.device = "cuda" | |
| 120 | + self.model = model | |
| 121 | + self.inference_api = inference_api | |
| 144 | 122 | self.excluded_categories = excluded_categories |
| 145 | 123 | self.disable_input_check = disable_input_check |
| 146 | 124 | self.disable_output_check = disable_output_check |
| 147 | 125 | |
| 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 | 126 | def check_unsafe_response(self, response: str) -> Optional[str]: |
| 156 | 127 | match = re.match(r"^unsafe\n(.*)$", response) |
| 157 | 128 | if match: |
| @@ -212,26 +183,21 @@ | ||
| 212 | 183 | ) |
| 213 | 184 | else: |
| 214 | 185 | 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 | 186 | |
| 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) | |
| 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) | |
| 237 | 203 | return shield_response |
modified llama_stack/providers/registry/safety.py +4 −2
| @@ -15,13 +15,15 @@ | ||
| 15 | 15 | api=Api.safety, |
| 16 | 16 | provider_id="meta-reference", |
| 17 | 17 | pip_packages=[ |
| 18 | - "accelerate", | |
| 19 | 18 | "codeshield", |
| 20 | - "torch", | |
| 21 | 19 | "transformers", |
| 20 | + "torch --index-url https://download.pytorch.org/whl/cpu", | |
| 22 | 21 | ], |
| 23 | 22 | module="llama_stack.providers.impls.meta_reference.safety", |
| 24 | 23 | config_class="llama_stack.providers.impls.meta_reference.safety.SafetyConfig", |
| 24 | + api_dependencies=[ | |
| 25 | + Api.inference, | |
| 26 | + ], | |
| 25 | 27 | ), |
| 26 | 28 | remote_provider_spec( |
| 27 | 29 | api=Api.safety, |