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