kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | 4a1bbdac681264f11178bea13652f69410253a7fe8a3a16af0eb175c417ed8ea |
|---|---|
| Author | Lucain <lucainp@gmail.com> · 2024-09-25 23:08 +02:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-25 14:08 -07:00 |
| Parents | a4c3b576447a |
7 files changed
added llama_stack/distribution/templates/local-hf-endpoint-build.yaml +10 −0
| @@ -0,0 +1,10 @@ | ||
| 1 | +name: local-hf-endpoint | |
| 2 | +distribution_spec: | |
| 3 | + description: "Like local, but use Hugging Face Inference Endpoints for running LLM inference.\nSee https://hf.co/docs/api-endpoints." | |
| 4 | + providers: | |
| 5 | + inference: remote::hf::endpoint | |
| 6 | + memory: meta-reference | |
| 7 | + safety: meta-reference | |
| 8 | + agents: meta-reference | |
| 9 | + telemetry: meta-reference | |
| 10 | +image_type: conda |
added llama_stack/distribution/templates/local-hf-serverless-build.yaml +10 −0
| @@ -0,0 +1,10 @@ | ||
| 1 | +name: local-hf-serverless | |
| 2 | +distribution_spec: | |
| 3 | + description: "Like local, but use Hugging Face Inference API (serverless) for running LLM inference.\nSee https://hf.co/docs/api-inference." | |
| 4 | + providers: | |
| 5 | + inference: remote::hf::serverless | |
| 6 | + memory: meta-reference | |
| 7 | + safety: meta-reference | |
| 8 | + agents: meta-reference | |
| 9 | + telemetry: meta-reference | |
| 10 | +image_type: conda |
modified llama_stack/distribution/templates/local-tgi-build.yaml +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | name: local-tgi |
| 2 | 2 | distribution_spec: |
| 3 | - description: Use TGI (local or with Hugging Face Inference Endpoints for running LLM inference. When using HF Inference Endpoints, you must provide the name of the endpoint). | |
| 3 | + description: Like local, but use a TGI server for running LLM inference. | |
| 4 | 4 | providers: |
| 5 | 5 | inference: remote::tgi |
| 6 | 6 | memory: meta-reference |
modified llama_stack/providers/adapters/inference/tgi/__init__.py +18 −13
| @@ -4,21 +4,26 @@ | ||
| 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 .config import TGIImplConfig | |
| 8 | -from .tgi import InferenceEndpointAdapter, TGIAdapter | |
| 9 | - | |
| 10 | - | |
| 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) | |
| 7 | +from typing import Union | |
| 8 | + | |
| 9 | +from .config import InferenceAPIImplConfig, InferenceEndpointImplConfig, TGIImplConfig | |
| 10 | +from .tgi import InferenceAPIAdapter, InferenceEndpointAdapter, TGIAdapter | |
| 11 | + | |
| 12 | + | |
| 13 | +async def get_adapter_impl( | |
| 14 | + config: Union[InferenceAPIImplConfig, InferenceEndpointImplConfig, TGIImplConfig], | |
| 15 | + _deps, | |
| 16 | +): | |
| 17 | + if isinstance(config, TGIImplConfig): | |
| 18 | + impl = TGIAdapter() | |
| 19 | + elif isinstance(config, InferenceAPIImplConfig): | |
| 20 | + impl = InferenceAPIAdapter() | |
| 21 | + elif isinstance(config, InferenceEndpointImplConfig): | |
| 22 | + impl = InferenceEndpointAdapter() | |
| 18 | 23 | else: |
| 19 | 24 | raise ValueError( |
| 20 | - "Invalid configuration. Specify either an URL or HF Inference Endpoint details (namespace and endpoint name)." | |
| 25 | + f"Invalid configuration. Expected 'TGIAdapter', 'InferenceAPIImplConfig' or 'InferenceEndpointImplConfig'. Got {type(config)}." | |
| 21 | 26 | ) |
| 22 | 27 | |
| 23 | - await impl.initialize() | |
| 28 | + await impl.initialize(config) | |
| 24 | 29 | return impl |
modified llama_stack/providers/adapters/inference/tgi/config.py +22 −8
| @@ -12,18 +12,32 @@ | ||
| 12 | 12 | |
| 13 | 13 | @json_schema_type |
| 14 | 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)", | |
| 15 | + url: str = Field( | |
| 16 | + description="The URL for the TGI endpoint (e.g. 'http://localhost:8080')", | |
| 18 | 17 | ) |
| 19 | 18 | api_token: Optional[str] = Field( |
| 20 | 19 | default=None, |
| 21 | - description="The HF token for Hugging Face Inference Endpoints (will default to locally saved token if not provided)", | |
| 20 | + description="A bearer token if your TGI endpoint is protected.", | |
| 21 | + ) | |
| 22 | + | |
| 23 | + | |
| 24 | +@json_schema_type | |
| 25 | +class InferenceEndpointImplConfig(BaseModel): | |
| 26 | + endpoint_name: str = Field( | |
| 27 | + description="The name of the Hugging Face Inference Endpoint in the format of '{namespace}/{endpoint_name}' (e.g. 'my-cool-org/meta-llama-3-1-8b-instruct-rce'). Namespace is optional and will default to the user account if not provided.", | |
| 22 | 28 | ) |
| 23 | - hf_endpoint_name: Optional[str] = Field( | |
| 29 | + api_token: Optional[str] = Field( | |
| 24 | 30 | 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", | |
| 31 | + description="Your Hugging Face user access token (will default to locally saved token if not provided)", | |
| 26 | 32 | ) |
| 27 | 33 | |
| 28 | - def is_inference_endpoint(self) -> bool: | |
| 29 | - return self.hf_endpoint_name is not None | |
| 34 | + | |
| 35 | +@json_schema_type | |
| 36 | +class InferenceAPIImplConfig(BaseModel): | |
| 37 | + model_id: str = Field( | |
| 38 | + description="The model ID of the model on the Hugging Face Hub (e.g. 'meta-llama/Meta-Llama-3.1-70B-Instruct')", | |
| 39 | + ) | |
| 40 | + api_token: Optional[str] = Field( | |
| 41 | + default=None, | |
| 42 | + description="Your Hugging Face user access token (will default to locally saved token if not provided)", | |
| 43 | + ) |
modified llama_stack/providers/adapters/inference/tgi/tgi.py +46 −77
| @@ -5,54 +5,33 @@ | ||
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | 7 | |
| 8 | -from typing import Any, AsyncGenerator, Dict | |
| 8 | +import logging | |
| 9 | +from typing import AsyncGenerator | |
| 9 | 10 | |
| 10 | -import requests | |
| 11 | - | |
| 12 | -from huggingface_hub import HfApi, InferenceClient | |
| 11 | +from huggingface_hub import AsyncInferenceClient, HfApi | |
| 13 | 12 | from llama_models.llama3.api.chat_format import ChatFormat |
| 14 | 13 | from llama_models.llama3.api.datatypes import StopReason |
| 15 | 14 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 15 | + | |
| 16 | 16 | from llama_stack.apis.inference import * # noqa: F403 |
| 17 | 17 | from llama_stack.providers.utils.inference.augment_messages import ( |
| 18 | 18 | augment_messages_for_tools, |
| 19 | 19 | ) |
| 20 | 20 | |
| 21 | -from .config import TGIImplConfig | |
| 21 | +from .config import InferenceAPIImplConfig, InferenceEndpointImplConfig, TGIImplConfig | |
| 22 | + | |
| 23 | +logger = logging.getLogger(__name__) | |
| 24 | + | |
| 22 | 25 | |
| 26 | +class _HfAdapter(Inference): | |
| 27 | + client: AsyncInferenceClient | |
| 28 | + max_tokens: int | |
| 29 | + model_id: str | |
| 23 | 30 | |
| 24 | -class TGIAdapter(Inference): | |
| 25 | - def __init__(self, config: TGIImplConfig) -> None: | |
| 26 | - self.config = config | |
| 31 | + def __init__(self) -> None: | |
| 27 | 32 | self.tokenizer = Tokenizer.get_instance() |
| 28 | 33 | self.formatter = ChatFormat(self.tokenizer) |
| 29 | 34 | |
| 30 | - @property | |
| 31 | - def client(self) -> InferenceClient: | |
| 32 | - return InferenceClient(model=self.config.url, token=self.config.api_token) | |
| 33 | - | |
| 34 | - def _get_endpoint_info(self) -> Dict[str, Any]: | |
| 35 | - return { | |
| 36 | - **self.client.get_endpoint_info(), | |
| 37 | - "inference_url": self.config.url, | |
| 38 | - } | |
| 39 | - | |
| 40 | - async def initialize(self) -> None: | |
| 41 | - try: | |
| 42 | - info = self._get_endpoint_info() | |
| 43 | - if "model_id" not in info: | |
| 44 | - raise RuntimeError("Missing model_id in model info") | |
| 45 | - if "max_total_tokens" not in info: | |
| 46 | - raise RuntimeError("Missing max_total_tokens in model info") | |
| 47 | - self.max_tokens = info["max_total_tokens"] | |
| 48 | - | |
| 49 | - self.inference_url = info["inference_url"] | |
| 50 | - except Exception as e: | |
| 51 | - import traceback | |
| 52 | - | |
| 53 | - traceback.print_exc() | |
| 54 | - raise RuntimeError(f"Error initializing TGIAdapter: {e}") from e | |
| 55 | - | |
| 56 | 35 | async def shutdown(self) -> None: |
| 57 | 36 | pass |
| 58 | 37 | |
| @@ -111,7 +90,7 @@ | ||
| 111 | 90 | |
| 112 | 91 | options = self.get_chat_options(request) |
| 113 | 92 | if not request.stream: |
| 114 | - response = self.client.text_generation( | |
| 93 | + response = await self.client.text_generation( | |
| 115 | 94 | prompt=prompt, |
| 116 | 95 | stream=False, |
| 117 | 96 | details=True, |
| @@ -147,7 +126,7 @@ | ||
| 147 | 126 | stop_reason = None |
| 148 | 127 | tokens = [] |
| 149 | 128 | |
| 150 | - for response in self.client.text_generation( | |
| 129 | + async for response in await self.client.text_generation( | |
| 151 | 130 | prompt=prompt, |
| 152 | 131 | stream=True, |
| 153 | 132 | details=True, |
| @@ -239,46 +218,36 @@ | ||
| 239 | 218 | ) |
| 240 | 219 | |
| 241 | 220 | |
| 242 | -class InferenceEndpointAdapter(TGIAdapter): | |
| 243 | - def __init__(self, config: TGIImplConfig) -> None: | |
| 244 | - super().__init__(config) | |
| 245 | - self.config.url = self._construct_endpoint_url() | |
| 221 | +class TGIAdapter(_HfAdapter): | |
| 222 | + async def initialize(self, config: TGIImplConfig) -> None: | |
| 223 | + self.client = AsyncInferenceClient(model=config.url, token=config.api_token) | |
| 224 | + endpoint_info = await self.client.get_endpoint_info() | |
| 225 | + self.max_tokens = endpoint_info["max_total_tokens"] | |
| 226 | + self.model_id = endpoint_info["model_id"] | |
| 227 | + | |
| 246 | 228 | |
| 247 | - def _construct_endpoint_url(self) -> str: | |
| 248 | - hf_endpoint_name = self.config.hf_endpoint_name | |
| 249 | - assert hf_endpoint_name.count("/") <= 1, ( | |
| 250 | - "Endpoint name must be in the format of 'namespace/endpoint_name' " | |
| 251 | - "or 'endpoint_name'" | |
| 229 | +class InferenceAPIAdapter(_HfAdapter): | |
| 230 | + async def initialize(self, config: InferenceAPIImplConfig) -> None: | |
| 231 | + self.client = AsyncInferenceClient( | |
| 232 | + model=config.model_id, token=config.api_token | |
| 233 | + ) | |
| 234 | + endpoint_info = await self.client.get_endpoint_info() | |
| 235 | + self.max_tokens = endpoint_info["max_total_tokens"] | |
| 236 | + self.model_id = endpoint_info["model_id"] | |
| 237 | + | |
| 238 | + | |
| 239 | +class InferenceEndpointAdapter(_HfAdapter): | |
| 240 | + async def initialize(self, config: InferenceEndpointImplConfig) -> None: | |
| 241 | + # Get the inference endpoint details | |
| 242 | + api = HfApi(token=config.api_token) | |
| 243 | + endpoint = api.get_inference_endpoint(config.endpoint_name) | |
| 244 | + | |
| 245 | + # Wait for the endpoint to be ready (if not already) | |
| 246 | + endpoint.wait(timeout=60) | |
| 247 | + | |
| 248 | + # Initialize the adapter | |
| 249 | + self.client = endpoint.async_client | |
| 250 | + self.model_id = endpoint.repository | |
| 251 | + self.max_tokens = int( | |
| 252 | + endpoint.raw["model"]["image"]["custom"]["env"]["MAX_TOTAL_TOKENS"] | |
| 252 | 253 | ) |
| 253 | - if "/" not in hf_endpoint_name: | |
| 254 | - hf_namespace: str = self.get_namespace() | |
| 255 | - endpoint_path = f"{hf_namespace}/{hf_endpoint_name}" | |
| 256 | - else: | |
| 257 | - endpoint_path = hf_endpoint_name | |
| 258 | - return f"https://api.endpoints.huggingface.cloud/v2/endpoint/{endpoint_path}" | |
| 259 | - | |
| 260 | - def get_namespace(self) -> str: | |
| 261 | - return HfApi().whoami()["name"] | |
| 262 | - | |
| 263 | - @property | |
| 264 | - def client(self) -> InferenceClient: | |
| 265 | - return InferenceClient(model=self.inference_url, token=self.config.api_token) | |
| 266 | - | |
| 267 | - def _get_endpoint_info(self) -> Dict[str, Any]: | |
| 268 | - headers = { | |
| 269 | - "accept": "application/json", | |
| 270 | - "authorization": f"Bearer {self.config.api_token}", | |
| 271 | - } | |
| 272 | - response = requests.get(self.config.url, headers=headers) | |
| 273 | - response.raise_for_status() | |
| 274 | - endpoint_info = response.json() | |
| 275 | - return { | |
| 276 | - "inference_url": endpoint_info["status"]["url"], | |
| 277 | - "model_id": endpoint_info["model"]["repository"], | |
| 278 | - "max_total_tokens": int( | |
| 279 | - endpoint_info["model"]["image"]["custom"]["env"]["MAX_TOTAL_TOKENS"] | |
| 280 | - ), | |
| 281 | - } | |
| 282 | - | |
| 283 | - async def initialize(self) -> None: | |
| 284 | - await super().initialize() |
modified llama_stack/providers/registry/inference.py +19 −1
| @@ -48,11 +48,29 @@ | ||
| 48 | 48 | api=Api.inference, |
| 49 | 49 | adapter=AdapterSpec( |
| 50 | 50 | adapter_id="tgi", |
| 51 | - pip_packages=["huggingface_hub"], | |
| 51 | + pip_packages=["huggingface_hub", "aiohttp"], | |
| 52 | 52 | module="llama_stack.providers.adapters.inference.tgi", |
| 53 | 53 | config_class="llama_stack.providers.adapters.inference.tgi.TGIImplConfig", |
| 54 | 54 | ), |
| 55 | 55 | ), |
| 56 | + remote_provider_spec( | |
| 57 | + api=Api.inference, | |
| 58 | + adapter=AdapterSpec( | |
| 59 | + adapter_id="hf::serverless", | |
| 60 | + pip_packages=["huggingface_hub", "aiohttp"], | |
| 61 | + module="llama_stack.providers.adapters.inference.tgi", | |
| 62 | + config_class="llama_stack.providers.adapters.inference.tgi.InferenceAPIImplConfig", | |
| 63 | + ), | |
| 64 | + ), | |
| 65 | + remote_provider_spec( | |
| 66 | + api=Api.inference, | |
| 67 | + adapter=AdapterSpec( | |
| 68 | + adapter_id="hf::endpoint", | |
| 69 | + pip_packages=["huggingface_hub", "aiohttp"], | |
| 70 | + module="llama_stack.providers.adapters.inference.tgi", | |
| 71 | + config_class="llama_stack.providers.adapters.inference.tgi.InferenceEndpointImplConfig", | |
| 72 | + ), | |
| 73 | + ), | |
| 56 | 74 | remote_provider_spec( |
| 57 | 75 | api=Api.inference, |
| 58 | 76 | adapter=AdapterSpec( |