Elffuss BraidHub

kikocis/llama-stack public

fdd93e9c02dc · 8.2 KiBRawPermalink
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
7import asyncio
8
9from typing import AsyncIterator, Union
10
11from llama_models.llama3.api.datatypes import StopReason
12from llama_models.sku_list import resolve_model
13
14from llama_stack.apis.inference import (
15 ChatCompletionRequest,
16 ChatCompletionResponse,
17 ChatCompletionResponseEvent,
18 ChatCompletionResponseEventType,
19 ChatCompletionResponseStreamChunk,
20 Inference,
21 ToolCallDelta,
22 ToolCallParseStatus,
23)
24from llama_stack.providers.utils.inference.augment_messages import (
25 augment_messages_for_tools,
26)
27
28from .config import MetaReferenceImplConfig
29from .model_parallel import LlamaModelParallelGenerator
30
31from llama_models.llama3.api.datatypes import * # noqa: F403
32from llama_stack.apis.inference import * # noqa: F403
33
34# there's a single model parallel process running serving the model. for now,
35# we don't support multiple concurrent requests to this process.
36SEMAPHORE = asyncio.Semaphore(1)
37
38
39class MetaReferenceInferenceImpl(Inference):
40 def __init__(self, config: MetaReferenceImplConfig) -> None:
41 self.config = config
42 model = resolve_model(config.model)
43 if model is None:
44 raise RuntimeError(f"Unknown model: {config.model}, Run `llama model list`")
45 self.model = model
46 # verify that the checkpoint actually is for this model lol
47
48 async def initialize(self) -> None:
49 self.generator = LlamaModelParallelGenerator(self.config)
50 self.generator.start()
51
52 async def shutdown(self) -> None:
53 self.generator.stop()
54
55 # hm, when stream=False, we should not be doing SSE :/ which is what the
56 # top-level server is going to do. make the typing more specific here
57 async def chat_completion(
58 self,
59 model: str,
60 messages: List[Message],
61 sampling_params: Optional[SamplingParams] = SamplingParams(),
62 tools: Optional[List[ToolDefinition]] = None,
63 tool_choice: Optional[ToolChoice] = ToolChoice.auto,
64 tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json,
65 stream: Optional[bool] = False,
66 logprobs: Optional[LogProbConfig] = None,
67 ) -> AsyncIterator[
68 Union[ChatCompletionResponseStreamChunk, ChatCompletionResponse]
69 ]:
70 # wrapper request to make it easier to pass around (internal only, not exposed to API)
71 request = ChatCompletionRequest(
72 model=model,
73 messages=messages,
74 sampling_params=sampling_params,
75 tools=tools or [],
76 tool_choice=tool_choice,
77 tool_prompt_format=tool_prompt_format,
78 stream=stream,
79 logprobs=logprobs,
80 )
81
82 messages = augment_messages_for_tools(request)
83 model = resolve_model(request.model)
84 if model is None:
85 raise RuntimeError(
86 f"Unknown model: {request.model}, Run `llama model list`"
87 )
88 elif model.descriptor() != self.model.descriptor():
89 raise RuntimeError(
90 f"Model mismatch: {request.model} != {self.model.descriptor()}"
91 )
92
93 if SEMAPHORE.locked():
94 raise RuntimeError("Only one concurrent request is supported")
95
96 async with SEMAPHORE:
97 if request.stream:
98 yield ChatCompletionResponseStreamChunk(
99 event=ChatCompletionResponseEvent(
100 event_type=ChatCompletionResponseEventType.start,
101 delta="",
102 )
103 )
104
105 tokens = []
106 logprobs = []
107
108 stop_reason = None
109
110 buffer = ""
111 ipython = False
112
113 for token_result in self.generator.chat_completion(
114 messages=messages,
115 temperature=request.sampling_params.temperature,
116 top_p=request.sampling_params.top_p,
117 max_gen_len=request.sampling_params.max_tokens,
118 logprobs=request.logprobs,
119 tool_prompt_format=request.tool_prompt_format,
120 ):
121 buffer += token_result.text
122 tokens.append(token_result.token)
123
124 if not ipython and buffer.startswith("<|python_tag|>"):
125 ipython = True
126 yield ChatCompletionResponseStreamChunk(
127 event=ChatCompletionResponseEvent(
128 event_type=ChatCompletionResponseEventType.progress,
129 delta=ToolCallDelta(
130 content="",
131 parse_status=ToolCallParseStatus.started,
132 ),
133 )
134 )
135 buffer = buffer[len("<|python_tag|>") :]
136 continue
137
138 if not request.stream:
139 if request.logprobs:
140 logprobs.append(token_result.logprob)
141
142 continue
143
144 if token_result.text == "<|eot_id|>":
145 stop_reason = StopReason.end_of_turn
146 text = ""
147 elif token_result.text == "<|eom_id|>":
148 stop_reason = StopReason.end_of_message
149 text = ""
150 else:
151 text = token_result.text
152
153 if ipython:
154 delta = ToolCallDelta(
155 content=text,
156 parse_status=ToolCallParseStatus.in_progress,
157 )
158 else:
159 delta = text
160
161 if stop_reason is None:
162 yield ChatCompletionResponseStreamChunk(
163 event=ChatCompletionResponseEvent(
164 event_type=ChatCompletionResponseEventType.progress,
165 delta=delta,
166 stop_reason=stop_reason,
167 )
168 )
169
170 if stop_reason is None:
171 stop_reason = StopReason.out_of_tokens
172
173 # TODO(ashwin): parse tool calls separately here and report errors?
174 # if someone breaks the iteration before coming here we are toast
175 message = self.generator.formatter.decode_assistant_message(
176 tokens, stop_reason
177 )
178 if request.stream:
179 parsed_tool_calls = len(message.tool_calls) > 0
180 if ipython and not parsed_tool_calls:
181 yield ChatCompletionResponseStreamChunk(
182 event=ChatCompletionResponseEvent(
183 event_type=ChatCompletionResponseEventType.progress,
184 delta=ToolCallDelta(
185 content="",
186 parse_status=ToolCallParseStatus.failure,
187 ),
188 stop_reason=stop_reason,
189 )
190 )
191
192 for tool_call in message.tool_calls:
193 yield ChatCompletionResponseStreamChunk(
194 event=ChatCompletionResponseEvent(
195 event_type=ChatCompletionResponseEventType.progress,
196 delta=ToolCallDelta(
197 content=tool_call,
198 parse_status=ToolCallParseStatus.success,
199 ),
200 stop_reason=stop_reason,
201 )
202 )
203
204 yield ChatCompletionResponseStreamChunk(
205 event=ChatCompletionResponseEvent(
206 event_type=ChatCompletionResponseEventType.complete,
207 delta="",
208 stop_reason=stop_reason,
209 )
210 )
211
212 # TODO(ashwin): what else do we need to send out here when everything finishes?
213 else:
214 yield ChatCompletionResponse(
215 completion_message=message,
216 logprobs=logprobs if request.logprobs else None,
217 )