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