kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | 401d6bad2f7e7d2be64a57fb6314ac9437fb270d48ff91959ffa89472c0f27fc |
|---|---|
| Author | Celina Hanouti <hanouticelina@gmail.com> · 2024-09-12 18:11 +02:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-12 09:11 -07:00 |
| Parents | b2b1c7375a99 |
6 files changed
modified docs/cli_reference.md +7 −0
| @@ -286,6 +286,13 @@ | ||
| 286 | 286 | | | "memory": "meta-reference-faiss" | | |
| 287 | 287 | | | } | | |
| 288 | 288 | +--------------------------------+---------------------------------------+----------------------------------------------------------------------+ |
| 289 | +| local-plus-tgi-inference | { | Use TGI (local or with [Hugging Face Inference Endpoints](https:// | | |
| 290 | +| | "inference": "remote::tgi", | huggingface.co/inference-endpoints/dedicated)) for running LLM | | |
| 291 | +| | "safety": "meta-reference", | inference. When using HF Inference Endpoints, you must provide the | | |
| 292 | +| | "agentic_system": "meta-reference", | name of the endpoint. | | |
| 293 | +| | "memory": "meta-reference-faiss" | | | |
| 294 | +| | } | | | |
| 295 | ++--------------------------------+---------------------------------------+----------------------------------------------------------------------+ | |
| 289 | 296 | </pre> |
| 290 | 297 | |
| 291 | 298 | As you can see above, each “distribution” details the “providers” it is composed of. For example, `local` uses the “meta-reference” provider for inference while local-ollama relies on a different provider (Ollama) for inference. Similarly, you can use Fireworks or Together.AI for running inference as well. |
modified llama_toolchain/core/distribution_registry.py +13 −1
| @@ -65,11 +65,23 @@ | ||
| 65 | 65 | Api.telemetry: "console", |
| 66 | 66 | }, |
| 67 | 67 | ), |
| 68 | + DistributionSpec( | |
| 69 | + distribution_type="local-plus-tgi-inference", | |
| 70 | + description="Use TGI for running LLM inference", | |
| 71 | + providers={ | |
| 72 | + Api.inference: remote_provider_type("tgi"), | |
| 73 | + Api.safety: "meta-reference", | |
| 74 | + Api.agentic_system: "meta-reference", | |
| 75 | + Api.memory: "meta-reference-faiss", | |
| 76 | + }, | |
| 77 | + ), | |
| 68 | 78 | ] |
| 69 | 79 | |
| 70 | 80 | |
| 71 | 81 | @lru_cache() |
| 72 | -def resolve_distribution_spec(distribution_type: str) -> Optional[DistributionSpec]: | |
| 82 | +def resolve_distribution_spec( | |
| 83 | + distribution_type: str, | |
| 84 | +) -> Optional[DistributionSpec]: | |
| 73 | 85 | for spec in available_distribution_specs(): |
| 74 | 86 | if spec.distribution_type == distribution_type: |
| 75 | 87 | return spec |
modified llama_toolchain/inference/adapters/tgi/__init__.py +13 −4
| @@ -4,12 +4,21 @@ | ||
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | -from llama_toolchain.core.datatypes import RemoteProviderConfig | |
| 7 | +from .config import TGIImplConfig | |
| 8 | +from .tgi import InferenceEndpointAdapter, TGIAdapter | |
| 8 | 9 | |
| 9 | 10 | |
| 10 | -async def get_adapter_impl(config: RemoteProviderConfig, _deps): | |
| 11 | - from .tgi import TGIInferenceAdapter | |
| 11 | +async def get_adapter_impl(config: TGIImplConfig, _deps): | |
| 12 | + assert isinstance(config, TGIImplConfig), f"Unexpected config type: {type(config)}" | |
| 13 | + | |
| 14 | + if config.url is not None: | |
| 15 | + impl = TGIAdapter(config) | |
| 16 | + elif config.is_inference_endpoint(): | |
| 17 | + impl = InferenceEndpointAdapter(config) | |
| 18 | + else: | |
| 19 | + raise ValueError( | |
| 20 | + "Invalid configuration. Specify either an URL or HF Inference Endpoint details (namespace and endpoint name)." | |
| 21 | + ) | |
| 12 | 22 | |
| 13 | - impl = TGIInferenceAdapter(config.url) | |
| 14 | 23 | await impl.initialize() |
| 15 | 24 | return impl |
added llama_toolchain/inference/adapters/tgi/config.py +29 −0
| @@ -0,0 +1,29 @@ | ||
| 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 | + | |
| 7 | +from typing import Optional | |
| 8 | + | |
| 9 | +from llama_models.schema_utils import json_schema_type | |
| 10 | +from pydantic import BaseModel, Field | |
| 11 | + | |
| 12 | + | |
| 13 | +@json_schema_type | |
| 14 | +class TGIImplConfig(BaseModel): | |
| 15 | + url: Optional[str] = Field( | |
| 16 | + default=None, | |
| 17 | + description="The URL for the local TGI endpoint (e.g., http://localhost:8080)", | |
| 18 | + ) | |
| 19 | + api_token: Optional[str] = Field( | |
| 20 | + default=None, | |
| 21 | + description="The HF token for Hugging Face Inference Endpoints (will default to locally saved token if not provided)", | |
| 22 | + ) | |
| 23 | + hf_endpoint_name: Optional[str] = Field( | |
| 24 | + default=None, | |
| 25 | + description="The name of the Hugging Face Inference Endpoint : can be either in the format of '{namespace}/{endpoint_name}' (namespace can be the username or organization name) or just '{endpoint_name}' if logged into the same account as the namespace", | |
| 26 | + ) | |
| 27 | + | |
| 28 | + def is_inference_endpoint(self) -> bool: | |
| 29 | + return self.hf_endpoint_name is not None |
modified llama_toolchain/inference/adapters/tgi/tgi.py +108 −67
| @@ -4,63 +4,68 @@ | ||
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | -from typing import AsyncGenerator, List | |
| 8 | 7 | |
| 9 | -import httpx | |
| 8 | +from typing import Any, AsyncGenerator, Dict | |
| 10 | 9 | |
| 11 | -from llama_models.llama3.api.chat_format import ChatFormat | |
| 10 | +import requests | |
| 12 | 11 | |
| 13 | -from llama_models.llama3.api.datatypes import Message, StopReason | |
| 12 | +from huggingface_hub import HfApi, InferenceClient | |
| 13 | +from llama_models.llama3.api.chat_format import ChatFormat | |
| 14 | +from llama_models.llama3.api.datatypes import StopReason | |
| 14 | 15 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 15 | - | |
| 16 | -from text_generation import Client | |
| 17 | - | |
| 18 | 16 | from llama_toolchain.inference.api import * # noqa: F403 |
| 19 | 17 | from llama_toolchain.inference.prepare_messages import prepare_messages |
| 20 | 18 | |
| 19 | +from .config import TGIImplConfig | |
| 21 | 20 | |
| 22 | -SUPPORTED_MODELS = { | |
| 21 | +HF_SUPPORTED_MODELS = { | |
| 23 | 22 | "Meta-Llama3.1-8B-Instruct": "meta-llama/Meta-Llama-3.1-8B-Instruct", |
| 24 | 23 | "Meta-Llama3.1-70B-Instruct": "meta-llama/Meta-Llama-3.1-70B-Instruct", |
| 25 | 24 | "Meta-Llama3.1-405B-Instruct": "meta-llama/Meta-Llama-3.1-405B-Instruct", |
| 26 | 25 | } |
| 27 | 26 | |
| 28 | 27 | |
| 29 | -class TGIInferenceAdapter(Inference): | |
| 30 | - def __init__(self, url: str) -> None: | |
| 31 | - self.url = url.rstrip("/") | |
| 28 | +class TGIAdapter(Inference): | |
| 29 | + def __init__(self, config: TGIImplConfig) -> None: | |
| 30 | + self.config = config | |
| 32 | 31 | self.tokenizer = Tokenizer.get_instance() |
| 33 | 32 | self.formatter = ChatFormat(self.tokenizer) |
| 34 | - self.model = None | |
| 35 | - self.max_tokens = None | |
| 36 | 33 | |
| 37 | - async def initialize(self) -> None: | |
| 38 | - hf_models = {v: k for k, v in SUPPORTED_MODELS.items()} | |
| 34 | + @property | |
| 35 | + def client(self) -> InferenceClient: | |
| 36 | + return InferenceClient(model=self.config.url, token=self.config.api_token) | |
| 39 | 37 | |
| 40 | - try: | |
| 41 | - print(f"Connecting to TGI server at: {self.url}") | |
| 42 | - async with httpx.AsyncClient() as client: | |
| 43 | - response = await client.get(f"{self.url}/info") | |
| 44 | - response.raise_for_status() | |
| 45 | - info = response.json() | |
| 46 | - if "model_id" not in info: | |
| 47 | - raise RuntimeError("Missing model_id in model info") | |
| 48 | - if "max_total_tokens" not in info: | |
| 49 | - raise RuntimeError("Missing max_total_tokens in model info") | |
| 50 | - self.max_tokens = info["max_total_tokens"] | |
| 51 | - | |
| 52 | - model_id = info["model_id"] | |
| 53 | - if model_id not in hf_models: | |
| 54 | - raise RuntimeError( | |
| 55 | - f"TGI is serving model: {model_id}, use one of the supported models: {','.join(hf_models.keys())}" | |
| 56 | - ) | |
| 38 | + def _get_endpoint_info(self) -> Dict[str, Any]: | |
| 39 | + return { | |
| 40 | + **self.client.get_endpoint_info(), | |
| 41 | + "inference_url": self.config.url, | |
| 42 | + } | |
| 57 | 43 | |
| 58 | - self.model = hf_models[model_id] | |
| 44 | + async def initialize(self) -> None: | |
| 45 | + try: | |
| 46 | + info = self._get_endpoint_info() | |
| 47 | + if "model_id" not in info: | |
| 48 | + raise RuntimeError("Missing model_id in model info") | |
| 49 | + if "max_total_tokens" not in info: | |
| 50 | + raise RuntimeError("Missing max_total_tokens in model info") | |
| 51 | + self.max_tokens = info["max_total_tokens"] | |
| 52 | + | |
| 53 | + model_id = info["model_id"] | |
| 54 | + model_name = next( | |
| 55 | + (name for name, id in HF_SUPPORTED_MODELS.items() if id == model_id), | |
| 56 | + None, | |
| 57 | + ) | |
| 58 | + if model_name is None: | |
| 59 | + raise RuntimeError( | |
| 60 | + f"TGI is serving model: {model_id}, use one of the supported models: {', '.join(HF_SUPPORTED_MODELS.values())}" | |
| 61 | + ) | |
| 62 | + self.model_name = model_name | |
| 63 | + self.inference_url = info["inference_url"] | |
| 59 | 64 | except Exception as e: |
| 60 | 65 | import traceback |
| 61 | 66 | |
| 62 | 67 | traceback.print_exc() |
| 63 | - raise RuntimeError("Could not connect to TGI server") from e | |
| 68 | + raise RuntimeError(f"Error initializing TGIAdapter: {e}") from e | |
| 64 | 69 | |
| 65 | 70 | async def shutdown(self) -> None: |
| 66 | 71 | pass |
| @@ -68,16 +73,6 @@ | ||
| 68 | 73 | async def completion(self, request: CompletionRequest) -> AsyncGenerator: |
| 69 | 74 | raise NotImplementedError() |
| 70 | 75 | |
| 71 | - def _convert_messages(self, messages: List[Message]) -> List[Message]: | |
| 72 | - ret = [] | |
| 73 | - for message in messages: | |
| 74 | - if message.role == "ipython": | |
| 75 | - role = "tool" | |
| 76 | - else: | |
| 77 | - role = message.role | |
| 78 | - ret.append({"role": role, "content": message.content}) | |
| 79 | - return ret | |
| 80 | - | |
| 81 | 76 | def get_chat_options(self, request: ChatCompletionRequest) -> dict: |
| 82 | 77 | options = {} |
| 83 | 78 | if request.sampling_params is not None: |
| @@ -89,47 +84,47 @@ | ||
| 89 | 84 | |
| 90 | 85 | async def chat_completion(self, request: ChatCompletionRequest) -> AsyncGenerator: |
| 91 | 86 | messages = prepare_messages(request) |
| 92 | - | |
| 93 | 87 | model_input = self.formatter.encode_dialog_prompt(messages) |
| 94 | 88 | prompt = self.tokenizer.decode(model_input.tokens) |
| 89 | + | |
| 90 | + input_tokens = len(model_input.tokens) | |
| 95 | 91 | max_new_tokens = min( |
| 96 | - request.sampling_params.max_tokens or self.max_tokens, | |
| 97 | - self.max_tokens - len(model_input.tokens) - 1, | |
| 92 | + request.sampling_params.max_tokens or (self.max_tokens - input_tokens), | |
| 93 | + self.max_tokens - input_tokens - 1, | |
| 98 | 94 | ) |
| 99 | 95 | |
| 100 | - if request.model != self.model: | |
| 101 | - raise ValueError( | |
| 102 | - f"Model mismatch, expected: {self.model}, got: {request.model}" | |
| 103 | - ) | |
| 96 | + print(f"Calculated max_new_tokens: {max_new_tokens}") | |
| 104 | 97 | |
| 105 | - options = self.get_chat_options(request) | |
| 98 | + assert ( | |
| 99 | + request.model == self.model_name | |
| 100 | + ), f"Model mismatch, expected {self.model_name}, got {request.model}" | |
| 106 | 101 | |
| 107 | - client = Client(base_url=self.url) | |
| 102 | + options = self.get_chat_options(request) | |
| 108 | 103 | if not request.stream: |
| 109 | - r = client.generate( | |
| 110 | - prompt, | |
| 104 | + response = self.client.text_generation( | |
| 105 | + prompt=prompt, | |
| 106 | + stream=False, | |
| 107 | + details=True, | |
| 111 | 108 | max_new_tokens=max_new_tokens, |
| 112 | 109 | stop_sequences=["<|eom_id|>", "<|eot_id|>"], |
| 113 | 110 | **options, |
| 114 | 111 | ) |
| 115 | - | |
| 116 | - if r.details.finish_reason: | |
| 117 | - if r.details.finish_reason == "stop": | |
| 112 | + stop_reason = None | |
| 113 | + if response.details.finish_reason: | |
| 114 | + if response.details.finish_reason == "stop": | |
| 118 | 115 | stop_reason = StopReason.end_of_turn |
| 119 | - elif r.details.finish_reason == "length": | |
| 116 | + elif response.details.finish_reason == "length": | |
| 120 | 117 | stop_reason = StopReason.out_of_tokens |
| 121 | - else: | |
| 122 | - stop_reason = StopReason.end_of_message | |
| 123 | - else: | |
| 124 | - stop_reason = StopReason.out_of_tokens | |
| 125 | 118 | |
| 126 | 119 | completion_message = self.formatter.decode_assistant_message_from_content( |
| 127 | - r.generated_text, stop_reason | |
| 120 | + response.generated_text, | |
| 121 | + stop_reason, | |
| 128 | 122 | ) |
| 129 | 123 | yield ChatCompletionResponse( |
| 130 | 124 | completion_message=completion_message, |
| 131 | 125 | logprobs=None, |
| 132 | 126 | ) |
| 127 | + | |
| 133 | 128 | else: |
| 134 | 129 | yield ChatCompletionResponseStreamChunk( |
| 135 | 130 | event=ChatCompletionResponseEvent( |
| @@ -137,14 +132,15 @@ | ||
| 137 | 132 | delta="", |
| 138 | 133 | ) |
| 139 | 134 | ) |
| 140 | - | |
| 141 | 135 | buffer = "" |
| 142 | 136 | ipython = False |
| 143 | 137 | stop_reason = None |
| 144 | 138 | tokens = [] |
| 145 | 139 | |
| 146 | - for response in client.generate_stream( | |
| 147 | - prompt, | |
| 140 | + for response in self.client.text_generation( | |
| 141 | + prompt=prompt, | |
| 142 | + stream=True, | |
| 143 | + details=True, | |
| 148 | 144 | max_new_tokens=max_new_tokens, |
| 149 | 145 | stop_sequences=["<|eom_id|>", "<|eot_id|>"], |
| 150 | 146 | **options, |
| @@ -231,3 +227,48 @@ | ||
| 231 | 227 | stop_reason=stop_reason, |
| 232 | 228 | ) |
| 233 | 229 | ) |
| 230 | + | |
| 231 | + | |
| 232 | +class InferenceEndpointAdapter(TGIAdapter): | |
| 233 | + def __init__(self, config: TGIImplConfig) -> None: | |
| 234 | + super().__init__(config) | |
| 235 | + self.config.url = self._construct_endpoint_url() | |
| 236 | + | |
| 237 | + def _construct_endpoint_url(self) -> str: | |
| 238 | + hf_endpoint_name = self.config.hf_endpoint_name | |
| 239 | + assert hf_endpoint_name.count("/") <= 1, ( | |
| 240 | + "Endpoint name must be in the format of 'namespace/endpoint_name' " | |
| 241 | + "or 'endpoint_name'" | |
| 242 | + ) | |
| 243 | + if "/" not in hf_endpoint_name: | |
| 244 | + hf_namespace: str = self.get_namespace() | |
| 245 | + endpoint_path = f"{hf_namespace}/{hf_endpoint_name}" | |
| 246 | + else: | |
| 247 | + endpoint_path = hf_endpoint_name | |
| 248 | + return f"https://api.endpoints.huggingface.cloud/v2/endpoint/{endpoint_path}" | |
| 249 | + | |
| 250 | + def get_namespace(self) -> str: | |
| 251 | + return HfApi().whoami()["name"] | |
| 252 | + | |
| 253 | + @property | |
| 254 | + def client(self) -> InferenceClient: | |
| 255 | + return InferenceClient(model=self.inference_url, token=self.config.api_token) | |
| 256 | + | |
| 257 | + def _get_endpoint_info(self) -> Dict[str, Any]: | |
| 258 | + headers = { | |
| 259 | + "accept": "application/json", | |
| 260 | + "authorization": f"Bearer {self.config.api_token}", | |
| 261 | + } | |
| 262 | + response = requests.get(self.config.url, headers=headers) | |
| 263 | + response.raise_for_status() | |
| 264 | + endpoint_info = response.json() | |
| 265 | + return { | |
| 266 | + "inference_url": endpoint_info["status"]["url"], | |
| 267 | + "model_id": endpoint_info["model"]["repository"], | |
| 268 | + "max_total_tokens": int( | |
| 269 | + endpoint_info["model"]["image"]["custom"]["env"]["MAX_TOTAL_TOKENS"] | |
| 270 | + ), | |
| 271 | + } | |
| 272 | + | |
| 273 | + async def initialize(self) -> None: | |
| 274 | + await super().initialize() |
modified llama_toolchain/inference/providers.py +2 −1
| @@ -39,8 +39,9 @@ | ||
| 39 | 39 | api=Api.inference, |
| 40 | 40 | adapter=AdapterSpec( |
| 41 | 41 | adapter_id="tgi", |
| 42 | - pip_packages=["text-generation"], | |
| 42 | + pip_packages=["huggingface_hub"], | |
| 43 | 43 | module="llama_toolchain.inference.adapters.tgi", |
| 44 | + config_class="llama_toolchain.inference.adapters.tgi.TGIImplConfig", | |
| 44 | 45 | ), |
| 45 | 46 | ), |
| 46 | 47 | remote_provider_spec( |