Elffuss BraidHub

kikocis/llama-stack public

[Inference] Use huggingface_hub inference client for TGI adapter (#53)

* Use huggingface_hub inference client for TGI inference

* Update the default value for TGI URL

* Use InferenceClient.text_generation for TGI inference

* Fixes post-review and split TGI adapter into local and Inference Endpoints ones

* Update CLI reference and add typing

* Rename TGI Adapter class

* Use HfApi to get the namespace when not provide in the hf endpoint name

* Remove unecessary method argument

* Improve TGI adapter initialization condition

* Move helper into impl file + fix merging conflicts
Changeset401d6bad2f7e7d2be64a57fb6314ac9437fb270d48ff91959ffa89472c0f27fc
AuthorCelina Hanouti <hanouticelina@gmail.com> · 2024-09-12 18:11 +02:00
CommitterGitHub <noreply@github.com> · 2024-09-12 09:11 -07:00
Parentsb2b1c7375a99

Browse the files at this changeset

6 files changed

modified docs/cli_reference.md +7 −0
@@ -286,6 +286,13 @@
286286 | | "memory": "meta-reference-faiss" | |
287287 | | } | |
288288 +--------------------------------+---------------------------------------+----------------------------------------------------------------------+
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++--------------------------------+---------------------------------------+----------------------------------------------------------------------+
289296 </pre>
290297
291298 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 @@
6565 Api.telemetry: "console",
6666 },
6767 ),
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+ ),
6878 ]
6979
7080
7181 @lru_cache()
72-def resolve_distribution_spec(distribution_type: str) -> Optional[DistributionSpec]:
82+def resolve_distribution_spec(
83+ distribution_type: str,
84+) -> Optional[DistributionSpec]:
7385 for spec in available_distribution_specs():
7486 if spec.distribution_type == distribution_type:
7587 return spec
modified llama_toolchain/inference/adapters/tgi/__init__.py +13 −4
@@ -4,12 +4,21 @@
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 llama_toolchain.core.datatypes import RemoteProviderConfig
7+from .config import TGIImplConfig
8+from .tgi import InferenceEndpointAdapter, TGIAdapter
89
910
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+ )
1222
13- impl = TGIInferenceAdapter(config.url)
1423 await impl.initialize()
1524 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 @@
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 typing import AsyncGenerator, List
87
9-import httpx
8+from typing import Any, AsyncGenerator, Dict
109
11-from llama_models.llama3.api.chat_format import ChatFormat
10+import requests
1211
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
1415 from llama_models.llama3.api.tokenizer import Tokenizer
15-
16-from text_generation import Client
17-
1816 from llama_toolchain.inference.api import * # noqa: F403
1917 from llama_toolchain.inference.prepare_messages import prepare_messages
2018
19+from .config import TGIImplConfig
2120
22-SUPPORTED_MODELS = {
21+HF_SUPPORTED_MODELS = {
2322 "Meta-Llama3.1-8B-Instruct": "meta-llama/Meta-Llama-3.1-8B-Instruct",
2423 "Meta-Llama3.1-70B-Instruct": "meta-llama/Meta-Llama-3.1-70B-Instruct",
2524 "Meta-Llama3.1-405B-Instruct": "meta-llama/Meta-Llama-3.1-405B-Instruct",
2625 }
2726
2827
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
3231 self.tokenizer = Tokenizer.get_instance()
3332 self.formatter = ChatFormat(self.tokenizer)
34- self.model = None
35- self.max_tokens = None
3633
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)
3937
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+ }
5743
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"]
5964 except Exception as e:
6065 import traceback
6166
6267 traceback.print_exc()
63- raise RuntimeError("Could not connect to TGI server") from e
68+ raise RuntimeError(f"Error initializing TGIAdapter: {e}") from e
6469
6570 async def shutdown(self) -> None:
6671 pass
@@ -68,16 +73,6 @@
6873 async def completion(self, request: CompletionRequest) -> AsyncGenerator:
6974 raise NotImplementedError()
7075
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-
8176 def get_chat_options(self, request: ChatCompletionRequest) -> dict:
8277 options = {}
8378 if request.sampling_params is not None:
@@ -89,47 +84,47 @@
8984
9085 async def chat_completion(self, request: ChatCompletionRequest) -> AsyncGenerator:
9186 messages = prepare_messages(request)
92-
9387 model_input = self.formatter.encode_dialog_prompt(messages)
9488 prompt = self.tokenizer.decode(model_input.tokens)
89+
90+ input_tokens = len(model_input.tokens)
9591 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,
9894 )
9995
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}")
10497
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}"
106101
107- client = Client(base_url=self.url)
102+ options = self.get_chat_options(request)
108103 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,
111108 max_new_tokens=max_new_tokens,
112109 stop_sequences=["<|eom_id|>", "<|eot_id|>"],
113110 **options,
114111 )
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":
118115 stop_reason = StopReason.end_of_turn
119- elif r.details.finish_reason == "length":
116+ elif response.details.finish_reason == "length":
120117 stop_reason = StopReason.out_of_tokens
121- else:
122- stop_reason = StopReason.end_of_message
123- else:
124- stop_reason = StopReason.out_of_tokens
125118
126119 completion_message = self.formatter.decode_assistant_message_from_content(
127- r.generated_text, stop_reason
120+ response.generated_text,
121+ stop_reason,
128122 )
129123 yield ChatCompletionResponse(
130124 completion_message=completion_message,
131125 logprobs=None,
132126 )
127+
133128 else:
134129 yield ChatCompletionResponseStreamChunk(
135130 event=ChatCompletionResponseEvent(
@@ -137,14 +132,15 @@
137132 delta="",
138133 )
139134 )
140-
141135 buffer = ""
142136 ipython = False
143137 stop_reason = None
144138 tokens = []
145139
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,
148144 max_new_tokens=max_new_tokens,
149145 stop_sequences=["<|eom_id|>", "<|eot_id|>"],
150146 **options,
@@ -231,3 +227,48 @@
231227 stop_reason=stop_reason,
232228 )
233229 )
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 @@
3939 api=Api.inference,
4040 adapter=AdapterSpec(
4141 adapter_id="tgi",
42- pip_packages=["text-generation"],
42+ pip_packages=["huggingface_hub"],
4343 module="llama_toolchain.inference.adapters.tgi",
44+ config_class="llama_toolchain.inference.adapters.tgi.TGIImplConfig",
4445 ),
4546 ),
4647 remote_provider_spec(