Elffuss BraidHub

kikocis/llama-stack public

Make TGI adapter compatible with HF Inference API (#97)

Changeset4a1bbdac681264f11178bea13652f69410253a7fe8a3a16af0eb175c417ed8ea
AuthorLucain <lucainp@gmail.com> · 2024-09-25 23:08 +02:00
CommitterGitHub <noreply@github.com> · 2024-09-25 14:08 -07:00
Parentsa4c3b576447a

Browse the files at this changeset

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 @@
11 name: local-tgi
22 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.
44 providers:
55 inference: remote::tgi
66 memory: meta-reference
modified llama_stack/providers/adapters/inference/tgi/__init__.py +18 −13
@@ -4,21 +4,26 @@
44 # This source code is licensed under the terms described in the LICENSE file in
55 # the root directory of this source tree.
66
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()
1823 else:
1924 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)}."
2126 )
2227
23- await impl.initialize()
28+ await impl.initialize(config)
2429 return impl
modified llama_stack/providers/adapters/inference/tgi/config.py +22 −8
@@ -12,18 +12,32 @@
1212
1313 @json_schema_type
1414 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')",
1817 )
1918 api_token: Optional[str] = Field(
2019 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.",
2228 )
23- hf_endpoint_name: Optional[str] = Field(
29+ api_token: Optional[str] = Field(
2430 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)",
2632 )
2733
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 @@
55 # the root directory of this source tree.
66
77
8-from typing import Any, AsyncGenerator, Dict
8+import logging
9+from typing import AsyncGenerator
910
10-import requests
11-
12-from huggingface_hub import HfApi, InferenceClient
11+from huggingface_hub import AsyncInferenceClient, HfApi
1312 from llama_models.llama3.api.chat_format import ChatFormat
1413 from llama_models.llama3.api.datatypes import StopReason
1514 from llama_models.llama3.api.tokenizer import Tokenizer
15+
1616 from llama_stack.apis.inference import * # noqa: F403
1717 from llama_stack.providers.utils.inference.augment_messages import (
1818 augment_messages_for_tools,
1919 )
2020
21-from .config import TGIImplConfig
21+from .config import InferenceAPIImplConfig, InferenceEndpointImplConfig, TGIImplConfig
22+
23+logger = logging.getLogger(__name__)
24+
2225
26+class _HfAdapter(Inference):
27+ client: AsyncInferenceClient
28+ max_tokens: int
29+ model_id: str
2330
24-class TGIAdapter(Inference):
25- def __init__(self, config: TGIImplConfig) -> None:
26- self.config = config
31+ def __init__(self) -> None:
2732 self.tokenizer = Tokenizer.get_instance()
2833 self.formatter = ChatFormat(self.tokenizer)
2934
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-
5635 async def shutdown(self) -> None:
5736 pass
5837
@@ -111,7 +90,7 @@
11190
11291 options = self.get_chat_options(request)
11392 if not request.stream:
114- response = self.client.text_generation(
93+ response = await self.client.text_generation(
11594 prompt=prompt,
11695 stream=False,
11796 details=True,
@@ -147,7 +126,7 @@
147126 stop_reason = None
148127 tokens = []
149128
150- for response in self.client.text_generation(
129+ async for response in await self.client.text_generation(
151130 prompt=prompt,
152131 stream=True,
153132 details=True,
@@ -239,46 +218,36 @@
239218 )
240219
241220
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+
246228
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"]
252253 )
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 @@
4848 api=Api.inference,
4949 adapter=AdapterSpec(
5050 adapter_id="tgi",
51- pip_packages=["huggingface_hub"],
51+ pip_packages=["huggingface_hub", "aiohttp"],
5252 module="llama_stack.providers.adapters.inference.tgi",
5353 config_class="llama_stack.providers.adapters.inference.tgi.TGIImplConfig",
5454 ),
5555 ),
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+ ),
5674 remote_provider_spec(
5775 api=Api.inference,
5876 adapter=AdapterSpec(