serving.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  1. # Copyright 2025 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. import base64
  16. import copy
  17. import datetime
  18. import enum
  19. import functools
  20. import gc
  21. import io
  22. import json
  23. import re
  24. import tempfile
  25. import threading
  26. import time
  27. import uuid
  28. from argparse import ArgumentParser, Namespace
  29. from collections.abc import AsyncGenerator, Generator, Iterable
  30. from contextlib import asynccontextmanager
  31. from dataclasses import dataclass, field
  32. from io import BytesIO
  33. from threading import Thread
  34. from typing import Optional, TypedDict, Union
  35. from huggingface_hub import model_info
  36. from huggingface_hub.constants import HF_HUB_OFFLINE
  37. from tokenizers.decoders import DecodeStream
  38. import transformers
  39. from transformers.models.auto.modeling_auto import (
  40. MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
  41. MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES,
  42. )
  43. from transformers.utils.import_utils import (
  44. is_fastapi_available,
  45. is_librosa_available,
  46. is_openai_available,
  47. is_pydantic_available,
  48. is_uvicorn_available,
  49. is_vision_available,
  50. )
  51. from .. import (
  52. AutoConfig,
  53. LogitsProcessorList,
  54. PreTrainedTokenizerFast,
  55. ProcessorMixin,
  56. TextIteratorStreamer,
  57. )
  58. from ..utils import is_torch_available, logging
  59. from . import BaseTransformersCLICommand
  60. if is_torch_available():
  61. import torch
  62. from transformers import (
  63. AutoProcessor,
  64. BitsAndBytesConfig,
  65. GenerationConfig,
  66. PreTrainedModel,
  67. )
  68. from ..generation.continuous_batching import ContinuousBatchingManager, RequestStatus
  69. if is_librosa_available():
  70. import librosa
  71. if is_vision_available():
  72. from PIL import Image
  73. serve_dependencies_available = (
  74. is_pydantic_available() and is_fastapi_available() and is_uvicorn_available() and is_openai_available()
  75. )
  76. if serve_dependencies_available:
  77. import uvicorn
  78. from fastapi import FastAPI, HTTPException
  79. from fastapi.middleware.cors import CORSMiddleware
  80. from fastapi.responses import JSONResponse, StreamingResponse
  81. from openai.types.audio.transcription import Transcription
  82. from openai.types.audio.transcription_create_params import TranscriptionCreateParamsBase
  83. from openai.types.chat import ChatCompletionMessageParam
  84. from openai.types.chat.chat_completion_chunk import (
  85. ChatCompletionChunk,
  86. Choice,
  87. ChoiceDelta,
  88. ChoiceDeltaToolCall,
  89. ChoiceDeltaToolCallFunction,
  90. )
  91. from openai.types.chat.completion_create_params import CompletionCreateParamsStreaming
  92. from openai.types.responses import (
  93. Response,
  94. ResponseCompletedEvent,
  95. ResponseContentPartAddedEvent,
  96. ResponseContentPartDoneEvent,
  97. ResponseCreatedEvent,
  98. ResponseError,
  99. ResponseErrorEvent,
  100. ResponseFailedEvent,
  101. ResponseInProgressEvent,
  102. ResponseOutputItemAddedEvent,
  103. ResponseOutputItemDoneEvent,
  104. ResponseOutputMessage,
  105. ResponseOutputText,
  106. ResponseTextDeltaEvent,
  107. ResponseTextDoneEvent,
  108. )
  109. from openai.types.responses.response_create_params import ResponseCreateParamsStreaming
  110. from pydantic import BaseModel, TypeAdapter, ValidationError
  111. # Expand OpenAI's request input types with an optional `generation_config` field
  112. class TransformersResponseCreateParamsStreaming(ResponseCreateParamsStreaming, total=False):
  113. """
  114. OpenAI's ResponseCreateParamsStreaming with an additional field for the generation config (as a json string).
  115. """
  116. generation_config: str
  117. class TransformersCompletionCreateParamsStreaming(CompletionCreateParamsStreaming, total=False):
  118. """
  119. OpenAI's CompletionCreateParamsStreaming with additional fields for the generation config (as a json string) and passing the request_id
  120. """
  121. generation_config: str
  122. class TransformersTranscriptionCreateParams(TranscriptionCreateParamsBase, total=False):
  123. """
  124. OpenAI's TranscriptionCreateParamsBase with an additional field for the generation config (as a json string).
  125. """
  126. file: bytes # Overwritten -- pydantic isn't happy with `typing.IO[bytes]`, present in the original type
  127. generation_config: str
  128. stream: bool = False
  129. # Contrarily to OpenAI's output types, input types are `TypedDict`, which don't have built-in validation.
  130. response_validator = TypeAdapter(TransformersResponseCreateParamsStreaming)
  131. completion_validator = TypeAdapter(TransformersCompletionCreateParamsStreaming)
  132. transcription_validator = TypeAdapter(TransformersTranscriptionCreateParams)
  133. # Define request fields that are not yet used in `transformers serve`. Receiving these fields will raise an
  134. # HTTPException.
  135. UNUSED_RESPONSE_FIELDS = {
  136. "background",
  137. "include",
  138. "max_tool_calls",
  139. "previous_response_id",
  140. "prompt",
  141. "reasoning",
  142. "service_tier",
  143. "store",
  144. "text",
  145. "tool_choice",
  146. "top_logprobs",
  147. "truncation",
  148. "user",
  149. }
  150. UNUSED_CHAT_COMPLETION_FIELDS = {
  151. "audio",
  152. "function_call",
  153. "functions",
  154. "logprobs",
  155. "max_completion_tokens",
  156. "metadata",
  157. "modalities",
  158. "n",
  159. "parallel_tool_calls",
  160. "prediction",
  161. "presence_penalty",
  162. "reasoning_effort",
  163. "response_format",
  164. "service_tier",
  165. "stop",
  166. "store",
  167. "stream_options",
  168. "tool_choice",
  169. "top_logprobs",
  170. "user",
  171. "web_search_options",
  172. }
  173. UNUSED_TRANSCRIPTION_FIELDS = {
  174. "chunking_strategy",
  175. "include",
  176. "language",
  177. "prompt",
  178. "response_format",
  179. "timestamp_granularities",
  180. }
  181. logger = logging.get_logger(__name__)
  182. # Possible tokens that indicate the start/end of a tool call
  183. # TODO (joao, matt): streamline tool token detection logic
  184. _TOOL_CALL_TOKENS = {
  185. "qwen": {
  186. "start": "<tool_call>",
  187. "end": "</tool_call>",
  188. },
  189. }
  190. _MODELS_WITH_TOOL_SUPPORT = list(_TOOL_CALL_TOKENS.keys())
  191. X_REQUEST_ID = "x-request-id"
  192. class Modality(enum.Enum):
  193. LLM = "LLM"
  194. VLM = "VLM"
  195. STT = "STT"
  196. TTS = "TTS"
  197. def serve_command_factory(args: Namespace):
  198. """
  199. Factory function used to instantiate serving server from provided command line arguments.
  200. Returns: ServeCommand
  201. """
  202. return ServeCommand(args)
  203. def create_generation_config_from_req(
  204. req: dict,
  205. model_generation_config: "GenerationConfig",
  206. **kwargs,
  207. ) -> "GenerationConfig":
  208. """
  209. Creates a generation config from the parameters of the request. If a generation config is passed in the request,
  210. it will be used as a baseline for parameterization. Otherwise, we will use the model's default generation config.
  211. Other parameters in the request will be applied on top of the baseline.
  212. Args:
  213. req (`dict`):
  214. The request which may optionally contain generation parameters.
  215. model_generation_config (`GenerationConfig`):
  216. The model's default generation config.
  217. kwargs (`dict`):
  218. Additional parameters to set in the generation config.
  219. Returns:
  220. The prepared `GenerationConfig` object.
  221. """
  222. # If there is a generation config in the request, it is a json string serialization from a `GenerationConfig`
  223. # object. For simplicity, flags set here take precedence over all other flags.
  224. if req.get("generation_config") is not None:
  225. generation_config = GenerationConfig(**json.loads(req["generation_config"]))
  226. else:
  227. generation_config = copy.deepcopy(model_generation_config)
  228. non_standard_kwargs = generation_config.update(**kwargs)
  229. # Set extra kwargs that are not in the `GenerationConfig` class (e.g. continuous batching flags)
  230. for k, v in non_standard_kwargs.items():
  231. if v is not None:
  232. setattr(generation_config, k, v)
  233. # Response-specific parameters
  234. if req.get("max_output_tokens") is not None:
  235. generation_config.max_new_tokens = int(req["max_output_tokens"])
  236. # Completion-specific parameters
  237. if req.get("max_tokens") is not None:
  238. generation_config.max_new_tokens = int(req["max_tokens"])
  239. if req.get("frequency_penalty") is not None:
  240. generation_config.repetition_penalty = float(req["frequency_penalty"])
  241. if req.get("logit_bias") is not None:
  242. generation_config.sequence_bias = req["logit_bias"]
  243. if req.get("stop") is not None:
  244. generation_config.stop_strings = req["stop"]
  245. if req.get("temperature") is not None:
  246. generation_config.temperature = float(req["temperature"])
  247. if float(req["temperature"]) == 0.0:
  248. generation_config.do_sample = False
  249. if req.get("top_p") is not None:
  250. generation_config.top_p = float(req["top_p"])
  251. if req.get("seed") is not None:
  252. torch.manual_seed(req["seed"])
  253. return generation_config
  254. class ToolState:
  255. """Lightweight class to keep track of the tool call state."""
  256. def __init__(self):
  257. self.reset()
  258. def reset(self):
  259. """Reset the tool call state (assumes we're outside a tool call)."""
  260. self.inside_tool_call = False
  261. self.has_tool_name_defined = False
  262. self.arg_nesting_level = 0
  263. self.buffer = ""
  264. class TimedModel:
  265. """
  266. A class that holds a PreTrainedModel instance and its associated processor.
  267. Automatically deletes the instances after a specified timeout.
  268. """
  269. def __init__(
  270. self,
  271. model: "PreTrainedModel",
  272. timeout_seconds: int,
  273. processor: Optional[Union["ProcessorMixin", "PreTrainedTokenizerFast"]] = None,
  274. ):
  275. self.model = model
  276. self._name_or_path = str(model.name_or_path)
  277. self.processor = processor
  278. self.timeout_seconds = timeout_seconds
  279. self._timer = threading.Timer(self.timeout_seconds, self.timeout_reached)
  280. self._timer.start()
  281. def reset_timer(self):
  282. """Reset the timer for the deletion of the instances."""
  283. self._timer.cancel()
  284. self._timer = threading.Timer(self.timeout_seconds, self.timeout_reached)
  285. self._timer.start()
  286. def delete_model(self):
  287. """Delete the wrapped model and processor and clean up resources."""
  288. if hasattr(self, "model") and self.model is not None:
  289. del self.model
  290. del self.processor
  291. self.model = None
  292. self.processor = None
  293. gc.collect()
  294. # Clear CUDA cache if available
  295. if torch.cuda.is_available():
  296. torch.cuda.empty_cache()
  297. # XXX: in case we manually delete the model, like on server shutdown
  298. self._timer.cancel()
  299. def timeout_reached(self):
  300. self.delete_model()
  301. logger.info(f"{self._name_or_path} was removed from memory after {self.timeout_seconds} seconds of inactivity")
  302. def is_deleted(self):
  303. """Check if the instances have been deleted."""
  304. return not hasattr(self, "model") or self.model is None
  305. @dataclass
  306. class ServeArguments:
  307. r"""
  308. Arguments for the serve CLI.
  309. See the metadata arg for each argument's description -- the metadata will be printed with
  310. `transformers serve --help`
  311. """
  312. continuous_batching: bool = field(
  313. default=False,
  314. metadata={"help": "Whether to use continuous batching for chat completions."},
  315. )
  316. device: str = field(
  317. default="auto",
  318. metadata={
  319. "help": "Device to use for inference; will default to `auto` and"
  320. "place the model on an accelerator if available."
  321. },
  322. )
  323. torch_dtype: Optional[str] = field(
  324. default=None,
  325. metadata={
  326. "help": "`torch_dtype` is deprecated! Please use `dtype` argument instead.",
  327. "choices": ["auto", "bfloat16", "float16", "float32"],
  328. },
  329. )
  330. dtype: Optional[str] = field(
  331. default="auto",
  332. metadata={
  333. "help": "Override the default `torch.dtype` and load the model under this dtype. If `'auto'` is passed, "
  334. "the dtype will be automatically derived from the model's weights.",
  335. "choices": ["auto", "bfloat16", "float16", "float32"],
  336. },
  337. )
  338. trust_remote_code: bool = field(
  339. default=False, metadata={"help": "Whether to trust remote code when loading a model."}
  340. )
  341. attn_implementation: Optional[str] = field(
  342. default=None,
  343. metadata={
  344. "help": "Which attention implementation to use; you can run --attn_implementation=flash_attention_2, in "
  345. "which case you must install this manually by running `pip install flash-attn --no-build-isolation`."
  346. },
  347. )
  348. load_in_8bit: bool = field(
  349. default=False,
  350. metadata={"help": "Whether to use 8 bit precision for the base model - works only with LoRA."},
  351. )
  352. load_in_4bit: bool = field(
  353. default=False,
  354. metadata={"help": "Whether to use 4 bit precision for the base model - works only with LoRA."},
  355. )
  356. bnb_4bit_quant_type: str = field(default="nf4", metadata={"help": "Quantization type.", "choices": ["fp4", "nf4"]})
  357. use_bnb_nested_quant: bool = field(default=False, metadata={"help": "Whether to use nested quantization."})
  358. # Serving settings
  359. host: str = field(default="localhost", metadata={"help": "Interface the server will listen to."})
  360. port: int = field(default=8000, metadata={"help": "Port the server will listen to."})
  361. model_timeout: int = field(
  362. default=300,
  363. metadata={"help": "Time in seconds after which a model will be removed from memory."},
  364. )
  365. # Other settings
  366. log_level: str = field(
  367. default="info", metadata={"help": "Logging level as a string. Example: 'info' or 'warning'."}
  368. )
  369. default_seed: Optional[int] = field(
  370. default=None, metadata={"help": "The default seed for torch, should be an integer."}
  371. )
  372. enable_cors: bool = field(
  373. default=False,
  374. metadata={
  375. "help": (
  376. "Whether to enable CORS. Some apps that make requests from external domains (e.g. Cursor) require "
  377. "CORS to be enabled."
  378. ),
  379. },
  380. )
  381. # TODO
  382. # Testing
  383. # As of 2025-07-11, testing on https://github.com/openai/openai-responses-starter-app/, validation on the
  384. # Response input is failing. The app works well without validation. Enable at some point in the future.
  385. input_validation: bool = field(
  386. default=False,
  387. metadata={
  388. "help": ("Whether to turn on strict input validation."),
  389. },
  390. )
  391. force_model: Optional[str] = field(
  392. default=None,
  393. metadata={
  394. "help": (
  395. "Name of the model to be forced on all requests. This is useful for testing Apps that don't allow "
  396. "changing models in the request."
  397. ),
  398. },
  399. )
  400. def __post_init__(self):
  401. """Only used for BC `torch_dtype` argument."""
  402. # In this case only the BC torch_dtype was given
  403. if self.torch_dtype is not None:
  404. if self.dtype is None:
  405. self.dtype = self.torch_dtype
  406. elif self.torch_dtype != self.dtype:
  407. raise ValueError(
  408. f"`torch_dtype` {self.torch_dtype} and `dtype` {self.dtype} have different values. `torch_dtype` is deprecated and "
  409. "will be removed in 4.59.0, please set `dtype` instead."
  410. )
  411. class ServeCommand(BaseTransformersCLICommand):
  412. @staticmethod
  413. def register_subcommand(parser: ArgumentParser):
  414. """
  415. Register this command to argparse so it's available for the transformer-cli
  416. Args:
  417. parser: Root parser to register command-specific arguments
  418. """
  419. dataclass_types = (ServeArguments,)
  420. serve_parser = parser.add_parser("serve", dataclass_types=dataclass_types)
  421. serve_parser.set_defaults(func=serve_command_factory)
  422. def __init__(self, args: ServeArguments):
  423. if not serve_dependencies_available:
  424. raise ImportError(
  425. "Missing dependencies for the serving CLI. Please install with `pip install transformers[serving]`"
  426. )
  427. # Store and process input arguments
  428. self.args = args
  429. self.use_continuous_batching = self.args.continuous_batching
  430. if self.use_continuous_batching:
  431. default_attn_impl = ContinuousBatchingManager.default_attention_implementation()
  432. # checking if attn_implementation is supported by continuous batching
  433. if self.args.attn_implementation is None:
  434. self.args.attn_implementation = default_attn_impl # default to sdpa_paged
  435. logger.info(f"No attn_implementation passed, defaulting to {default_attn_impl}")
  436. supported_attn_impl = ContinuousBatchingManager.supported_attention_implementations()
  437. if self.args.attn_implementation not in supported_attn_impl:
  438. raise ValueError(
  439. f"Continuous batching only supports {supported_attn_impl} as attn_implementation, got "
  440. f"{self.args.attn_implementation}"
  441. f"Try setting `--attn_implementation={default_attn_impl}`"
  442. )
  443. self.enable_cors = self.args.enable_cors
  444. if self.args.default_seed is not None:
  445. torch.manual_seed(self.args.default_seed)
  446. # Set up logging
  447. transformers_logger = logging.get_logger("transformers")
  448. transformers_logger.setLevel(logging.log_levels[self.args.log_level.lower()])
  449. cb_logger = logging.get_logger("transformers.generation.continuous_batching")
  450. cb_logger.setLevel(logging.log_levels[self.args.log_level.lower()])
  451. # Internal state:
  452. # 1. Tracks models in memory, to prevent reloading the model unnecessarily
  453. self.loaded_models: dict[str, TimedModel] = {}
  454. self.running_continuous_batching_manager: Optional[ContinuousBatchingManager] = None
  455. # 2. preserves information about the last call and last KV cache, to determine whether we can reuse the KV
  456. # cache and avoid re-running prefil
  457. self.last_messages = None
  458. self.last_kv_cache = None
  459. self.last_model = None
  460. def _validate_request(
  461. self,
  462. request: dict,
  463. schema: TypedDict,
  464. validator: "TypeAdapter",
  465. unused_fields: set,
  466. ):
  467. """
  468. Validates the request against the schema, and checks for unexpected keys.
  469. Args:
  470. request (`dict`):
  471. The request to validate.
  472. schema (`TypedDict`):
  473. The schema of the request to validate. It is a `TypedDict` definition.
  474. validator (`TypeAdapter`):
  475. The validator to use to validate the request. Built from `schema`.
  476. unused_fields (`set`):
  477. Fields accepted by `schema`, but not used in `transformers serve`.
  478. Raises:
  479. HTTPException: If the request is invalid or contains unexpected or unused fields.
  480. """
  481. logger.debug(f"Validating request: {request}")
  482. # Validate unexpected keys -- Pydantic doesn't validate extra keys in the request.
  483. input_keys = set(request.keys())
  484. possible_keys = schema.__mutable_keys__
  485. unexpected_keys = input_keys - possible_keys
  486. if unexpected_keys:
  487. logger.error(f"Unexpected keys in the request: {unexpected_keys}")
  488. raise HTTPException(status_code=422, detail=f"Unexpected keys in the request: {unexpected_keys}")
  489. if self.args.input_validation:
  490. # Validate expected keys
  491. try:
  492. validator.validate_python(request)
  493. except ValidationError as e:
  494. logger.error(f"Validation error: {e.errors()}")
  495. raise HTTPException(status_code=422, detail=e.errors())
  496. # Validate unused fields
  497. unused_fields_in_request = input_keys & unused_fields
  498. if unused_fields_in_request:
  499. logger.error(f"Unused fields in the request: {unused_fields_in_request}")
  500. raise HTTPException(
  501. status_code=422, detail=f"Unused fields in the request: {unused_fields_in_request}"
  502. )
  503. def validate_response_request(self, request: dict):
  504. self._validate_request(
  505. request=request,
  506. schema=TransformersResponseCreateParamsStreaming,
  507. validator=response_validator,
  508. unused_fields=UNUSED_RESPONSE_FIELDS,
  509. )
  510. def validate_chat_completion_request(self, request: dict):
  511. self._validate_request(
  512. request=request,
  513. schema=TransformersCompletionCreateParamsStreaming,
  514. validator=completion_validator,
  515. unused_fields=UNUSED_CHAT_COMPLETION_FIELDS,
  516. )
  517. def validate_transcription_request(self, request: dict):
  518. self._validate_request(
  519. request=request,
  520. schema=TransformersTranscriptionCreateParams,
  521. validator=transcription_validator,
  522. unused_fields=UNUSED_TRANSCRIPTION_FIELDS,
  523. )
  524. def build_chat_completion_chunk(
  525. self,
  526. request_id: str = "",
  527. content: Optional[int] = None,
  528. model: Optional[str] = None,
  529. role: Optional[str] = None,
  530. finish_reason: Optional[str] = None,
  531. tool_calls: Optional[list["ChoiceDeltaToolCall"]] = None,
  532. decode_stream: Optional[DecodeStream] = None,
  533. tokenizer: Optional[PreTrainedTokenizerFast] = None,
  534. ) -> str:
  535. """
  536. Builds a chunk of a streaming OpenAI Chat Completion response.
  537. IMPORTANT: The serialized chunk won't contain empty fields (fields with `None`). Some downstream apps,
  538. like Cursor, assume that when the field exists, it has data.
  539. Args:
  540. request_id (`str`):
  541. The request ID.
  542. content (`str`, *optional*):
  543. Content of the response from the model.
  544. model (`str`, *optional*):
  545. The model that generated the content.
  546. role (`str`, *optional*):
  547. The role of the next content, until a new role is defined.
  548. finish_reason (`str`, *optional*):
  549. The reason the generation by the model has finished.
  550. tool_calls (`list[ChoiceDeltaToolCall]`, *optional*):
  551. Data about the tool calls, when they are triggered.
  552. Returns:
  553. `str`: The built chunk, a string containing a JSON string with the payload.
  554. """
  555. if decode_stream is not None and content is not None and tokenizer is not None:
  556. content = decode_stream.step(tokenizer._tokenizer, content)
  557. chunk = ChatCompletionChunk(
  558. id=request_id,
  559. created=int(time.time()),
  560. model=model,
  561. choices=[
  562. Choice(
  563. delta=ChoiceDelta(
  564. content=content,
  565. role=role,
  566. tool_calls=tool_calls,
  567. ),
  568. index=0,
  569. finish_reason=finish_reason,
  570. )
  571. ],
  572. system_fingerprint="",
  573. object="chat.completion.chunk",
  574. )
  575. return f"data: {chunk.model_dump_json(exclude_none=True)}\n\n"
  576. def build_response_event(self, response: "BaseModel") -> str:
  577. """
  578. Builds a event of a streaming OpenAI Response response.
  579. IMPORTANT: The serialized chunk won't contain empty fields (fields with `None`). Some downstream apps,
  580. like Cursor, assume that when the field exists, it has data.
  581. Args:
  582. response (`BaseModel`):
  583. The response to build an event from. One of the multiple OpenAI Response output types
  584. Returns:
  585. `str`: The built chunk, a string containing a JSON string with the payload.
  586. """
  587. return f"data: {response.model_dump_json(exclude_none=True)}\n\n"
  588. def run(self):
  589. """
  590. Setup and run the FastAPI server for transformers serve.
  591. Models will be loaded and unloaded automatically based on usage and a timeout.
  592. The server will expose the following endpoints:
  593. - POST /v1/chat/completions: Generates chat completions.
  594. - POST /v1/responses: Generates responses.
  595. - POST /v1/audio/transcriptions: Generates transcriptions from audio.
  596. - GET /v1/models: Lists available models for 3rd party tools.
  597. Requires FastAPI and Uvicorn to be installed.
  598. """
  599. @asynccontextmanager
  600. async def lifespan(app: FastAPI):
  601. yield
  602. for model in self.loaded_models.values():
  603. model.delete_model()
  604. if self.running_continuous_batching_manager is not None:
  605. self.running_continuous_batching_manager.stop(block=True, timeout=5)
  606. app = FastAPI(lifespan=lifespan)
  607. # Some apps that make requests from external domains (e.g. Cursor) require CORS to be enabled. However, for
  608. # security purposes, it's disabled by default
  609. if self.enable_cors:
  610. app.add_middleware(
  611. CORSMiddleware,
  612. allow_origins=["*"],
  613. allow_credentials=True,
  614. allow_methods=["*"],
  615. allow_headers=["*"],
  616. )
  617. logger.warning_once(
  618. "CORS allow origin is set to `*`. This is not recommended for production environments."
  619. )
  620. from fastapi import Request
  621. @app.post("/v1/chat/completions")
  622. def chat_completion(request: Request, body: dict):
  623. self.validate_chat_completion_request(request=body)
  624. if self.use_continuous_batching:
  625. output = self.continuous_batching_chat_completion(body, request.state.request_id)
  626. else:
  627. output = self.generate_chat_completion(body)
  628. return StreamingResponse(output, media_type="text/event-stream")
  629. @app.post("/v1/responses")
  630. def responses(request: dict):
  631. self.validate_response_request(request=request)
  632. output = self.generate_response(request)
  633. return StreamingResponse(output, media_type="text/event-stream")
  634. @app.post("/v1/audio/transcriptions")
  635. async def audio_transcriptions(request: Request):
  636. # Parses the multipart/form-data request into the request format used by other endpoints
  637. async with request.form() as form:
  638. parsed_request = TransformersTranscriptionCreateParams(
  639. file=await form["file"].read(),
  640. model=form["model"],
  641. # TODO: add other fields
  642. )
  643. logger.debug(
  644. f"Received file: {form['file'].filename}; MIME type: {form['file'].content_type}; "
  645. f"size: {form['file'].size / 1024:.2f} KiB"
  646. )
  647. self.validate_transcription_request(request=parsed_request)
  648. output = self.generate_transcription(parsed_request)
  649. return StreamingResponse(output, media_type="text/event-stream")
  650. @app.options("/v1/models")
  651. @app.get("/v1/models")
  652. def get_all_models():
  653. return JSONResponse({"object": "list", "data": self.get_gen_models()})
  654. @app.get("/health")
  655. def healthcheck():
  656. return JSONResponse({"status": "ok"})
  657. @app.middleware("http")
  658. async def get_or_set_request_id(request: Request, call_next):
  659. request_id = request.headers.get(X_REQUEST_ID) or str(uuid.uuid4())
  660. request.state.request_id = request_id
  661. response = await call_next(request)
  662. response.headers[X_REQUEST_ID] = request_id
  663. return response
  664. uvicorn.run(app, host=self.args.host, port=self.args.port, log_level=self.args.log_level)
  665. @functools.cache
  666. def get_gen_models(self) -> list[dict[str, any]]:
  667. """
  668. This is by no means a limit to which models may be instantiated with `transformers serve`: any chat-based
  669. model working with generate can work.
  670. This is a limited list of models to ensure we have a discoverable /v1/models endpoint for third-party
  671. integrations.
  672. """
  673. models = [
  674. "Menlo/Jan-nano",
  675. "Menlo/Jan-nano-128k",
  676. "Qwen/Qwen2.5-0.5B-Instruct",
  677. "Qwen/Qwen2.5-3B-Instruct",
  678. "Qwen/Qwen2.5-7B-Instruct",
  679. "Qwen/Qwen2.5-14B-Instruct",
  680. "meta-llama/Llama-3.1-8B-Instruct",
  681. "meta-llama/Llama-3.2-1B-Instruct",
  682. "meta-llama/Llama-3.3-70B-Instruct",
  683. "HuggingFaceTB/SmolVLM-Instruct",
  684. "ibm-granite/granite-vision-3.2-2b",
  685. "Qwen/Qwen2.5-VL-7B-Instruct",
  686. ]
  687. if HF_HUB_OFFLINE:
  688. return [
  689. {
  690. "id": model,
  691. "object": "model",
  692. "created": datetime.datetime.now().timestamp(),
  693. "owned_by": model.split("/")[0],
  694. }
  695. for model in models
  696. ]
  697. else:
  698. model_infos = [model_info(model) for model in models]
  699. return [
  700. {
  701. "id": model.id,
  702. "object": "model",
  703. "created": model.created_at.timestamp(),
  704. "owned_by": model.author,
  705. }
  706. for model in model_infos
  707. ]
  708. def continuous_batching_chat_completion(self, req: dict, request_id: str) -> AsyncGenerator[str, None]:
  709. """
  710. Generates an OpenAI Chat Completion using continuous batching.
  711. Args:
  712. req (`dict`): The request to generate an OpenAI Chat Completion for.
  713. Returns:
  714. `Generator[str, None, None]`: A generator that yields the OpenAI Chat Completion chunks.
  715. """
  716. model_id_and_revision = self.process_model_name(req["model"])
  717. must_discard_cache = model_id_and_revision != self.last_model
  718. self.last_model = model_id_and_revision
  719. if must_discard_cache:
  720. # When switching models, terminate a continuous batching manager if it is running.
  721. if self.running_continuous_batching_manager is not None:
  722. self.running_continuous_batching_manager.stop(block=True, timeout=2)
  723. self.running_continuous_batching_manager = None
  724. model, processor = self.load_model_and_processor(model_id_and_revision)
  725. tokenizer = processor.tokenizer if hasattr(processor, "tokenizer") else processor
  726. generation_config = create_generation_config_from_req(
  727. req,
  728. model_generation_config=model.generation_config,
  729. eos_token_id=tokenizer.eos_token_id,
  730. pad_token_id=tokenizer.pad_token_id,
  731. use_cache=False,
  732. do_sample=False,
  733. scheduler="fifo",
  734. )
  735. if self.running_continuous_batching_manager is None:
  736. self.running_continuous_batching_manager = model.init_continuous_batching(
  737. generation_config=generation_config, streaming=True
  738. )
  739. # TODO (Joao, Lysandre): the logits processors should be fixed in continuous batching
  740. # and correctly applied in non-cb
  741. self.running_continuous_batching_manager.logit_processor = LogitsProcessorList()
  742. self.running_continuous_batching_manager.start()
  743. # TODO (Joao, Lysandre): this should also work with tool support
  744. inputs = processor.apply_chat_template(req["messages"], return_tensors="pt", add_generation_prompt=True).to(
  745. model.device
  746. )
  747. def stream_chat_completion(request_id, decode_stream):
  748. try:
  749. # Emit the assistant role to start the stream. Other chunks won't have a role, as it is implicit
  750. # they come from the assistant.
  751. yield self.build_chat_completion_chunk(request_id, role="assistant", model=model_id_and_revision)
  752. for result in self.running_continuous_batching_manager.request_id_iter(request_id):
  753. if result.status == RequestStatus.FINISHED:
  754. yield self.build_chat_completion_chunk(
  755. request_id,
  756. finish_reason="stop",
  757. model=model_id_and_revision,
  758. )
  759. break
  760. else:
  761. yield self.build_chat_completion_chunk(
  762. request_id=request_id,
  763. content=result.generated_tokens[-1],
  764. model=model_id_and_revision,
  765. decode_stream=decode_stream,
  766. tokenizer=tokenizer,
  767. )
  768. except Exception as e:
  769. logger.error(str(e))
  770. self.running_continuous_batching_manager.cancel_request(request_id)
  771. yield f'data: {{"error": "{str(e)}"}}'
  772. async def cancellation_wrapper(_inputs, request_id):
  773. try:
  774. decode_stream = DecodeStream(_inputs.tolist(), False)
  775. # XXX: using returned request_id as safety in case it is None
  776. request_id = self.running_continuous_batching_manager.add_request(
  777. _inputs, request_id=request_id, max_new_tokens=generation_config.max_new_tokens
  778. )
  779. for chunk in stream_chat_completion(request_id, decode_stream):
  780. yield chunk
  781. await asyncio.sleep(0) # Yield control to the event loop to check for cancellations
  782. except asyncio.CancelledError:
  783. self.running_continuous_batching_manager.cancel_request(request_id)
  784. logger.warning(f"Request {request_id} was cancelled.")
  785. return cancellation_wrapper(inputs[0], request_id)
  786. @staticmethod
  787. def get_model_modality(model: "PreTrainedModel") -> Modality:
  788. model_classname = model.__class__.__name__
  789. if model_classname in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.values():
  790. modality = Modality.VLM
  791. elif model_classname in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values():
  792. modality = Modality.LLM
  793. else:
  794. raise ValueError(f"Unknown modality: {model_classname}")
  795. return modality
  796. @staticmethod
  797. def get_processor_inputs_from_inbound_messages(messages, modality: Modality):
  798. processor_inputs = []
  799. for message in messages:
  800. parsed_message = {"role": message["role"], "content": []}
  801. if modality == Modality.LLM:
  802. # Input: `content` is a string or a list of dictionaries with a "text" key.
  803. # Output: `content` is a string.
  804. if isinstance(message["content"], str):
  805. parsed_content = message["content"]
  806. elif isinstance(message["content"], list):
  807. parsed_content = []
  808. for content in message["content"]:
  809. if content["type"] == "text":
  810. parsed_content.append(content["text"])
  811. parsed_content = " ".join(parsed_content)
  812. parsed_message["content"] = parsed_content
  813. elif modality == Modality.VLM:
  814. # Input: `content` is a string or a list of dictionaries with a "type" key (possible types: "text",
  815. # "image_url").
  816. # Output: `content` is a list of dictionaries with a "type" key
  817. if isinstance(message["content"], str):
  818. parsed_message["content"].append({"type": "text", "text": message["content"]})
  819. else:
  820. for content in message["content"]:
  821. if content["type"] == "text":
  822. parsed_message["content"].append(content)
  823. elif content["type"] == "image_url":
  824. if "base64" in content["image_url"]["url"]:
  825. image_data = re.sub("^data:image/.+;base64,", "", content["image_url"]["url"])
  826. image = Image.open(BytesIO(base64.b64decode(image_data)))
  827. file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
  828. url = file.name
  829. image.save(file.name)
  830. else:
  831. url = content["image_url"]["url"]
  832. parsed_message["content"].append({"type": "image", "url": url})
  833. processor_inputs.append(parsed_message)
  834. return processor_inputs
  835. def generate_chat_completion(self, req: dict) -> Generator[str, None, None]:
  836. """
  837. Generates an OpenAI Chat Completion using `generate`.
  838. Args:
  839. req (`dict`): The request to generate an OpenAI Chat Completion for.
  840. Returns:
  841. `Generator[str, None, None]`: A generator that yields the OpenAI Chat Completion chunks.
  842. """
  843. if self.args.force_model is not None:
  844. req["model"] = self.args.force_model
  845. messages: Iterable[ChatCompletionMessageParam] = req["messages"]
  846. # HACK for tiny-agents: it sends a request after the assistant message (???). Let's assume we can't have a
  847. # request whose last message is from the assistant.
  848. if messages[-1]["role"] == "assistant":
  849. return
  850. model_id_and_revision = self.process_model_name(req["model"])
  851. must_discard_cache = model_id_and_revision != self.last_model
  852. self.last_model = model_id_and_revision
  853. model, processor = self.load_model_and_processor(model_id_and_revision)
  854. modality = self.get_model_modality(model)
  855. processor_inputs = self.get_processor_inputs_from_inbound_messages(messages, modality)
  856. # ====== TOOL PREPROCESSING LOGIC ======
  857. tool_model_family = None
  858. for supported_model_families in _MODELS_WITH_TOOL_SUPPORT:
  859. if supported_model_families in model.config.architectures[0].lower():
  860. tool_model_family = supported_model_families
  861. break
  862. # TODO: trigger 2 constrained generations after the tool call start token is emitted:
  863. # 1. force generation to pick from the tool names
  864. # 2. force generation to pick from that tool's arguments
  865. # ====== END OF TOOL PREPROCESSING LOGIC ======
  866. inputs = processor.apply_chat_template(
  867. processor_inputs,
  868. add_generation_prompt=True,
  869. tools=req.get("tools"),
  870. return_tensors="pt",
  871. return_dict=True,
  872. tokenize=True,
  873. )
  874. inputs = inputs.to(model.device)
  875. request_id = req.get("request_id", "req_0")
  876. # Temporary hack for GPTOSS 1: don't filter special tokens
  877. skip_special_tokens = True
  878. if "gptoss" in model.config.architectures[0].lower():
  879. skip_special_tokens = False
  880. generation_streamer = TextIteratorStreamer(
  881. processor,
  882. skip_special_tokens=skip_special_tokens,
  883. skip_prompt=True,
  884. )
  885. generation_config = create_generation_config_from_req(req, model_generation_config=model.generation_config)
  886. last_kv_cache = None
  887. if self.is_continuation(req) and not must_discard_cache:
  888. seq_len = self.last_kv_cache.get_seq_length()
  889. if inputs["input_ids"].shape[-1] > seq_len:
  890. last_kv_cache = self.last_kv_cache
  891. generation_kwargs = {
  892. **inputs,
  893. "streamer": generation_streamer,
  894. "generation_config": generation_config,
  895. "return_dict_in_generate": True,
  896. "past_key_values": last_kv_cache,
  897. }
  898. def stream_chat_completion(streamer, _request_id):
  899. # Temporary hack for GPTOS 2: filter out the CoT tokens. Full solution here implies defining new output
  900. # classes and piping the reasoning trace into a new field
  901. filter_cot = False
  902. cot_trace_end = None
  903. if "gptoss" in model.config.architectures[0].lower():
  904. filter_cot = True
  905. cot_trace_end = "<|channel|>final<|message|>"
  906. # Thin wrapper to save the KV cache after generation
  907. def generate_with_cache(**kwargs):
  908. generate_output = model.generate(**kwargs)
  909. self.last_kv_cache = generate_output.past_key_values
  910. thread = Thread(target=generate_with_cache, kwargs=generation_kwargs)
  911. results = ""
  912. try:
  913. thread.start()
  914. tool_state = ToolState()
  915. # Emit the assistant role to start the stream. Other chunks won't have a role, as it is implicit
  916. # they come from the assistant.
  917. yield self.build_chat_completion_chunk(request_id, role="assistant", model=model_id_and_revision)
  918. for result in streamer:
  919. # Temporary hack for GPTOS 3: don't emit the final "<|return|>"
  920. if "gptoss" in model.config.architectures[0].lower():
  921. result = result.removesuffix("<|return|>")
  922. results += result
  923. # (related to temporary hack 2)
  924. if filter_cot:
  925. if cot_trace_end in results: # end of reasoning trace observed -> stop filtering
  926. filter_cot = False
  927. continue
  928. else:
  929. continue
  930. # ====== TOOL CALL LOGIC ======
  931. if tool_model_family is not None:
  932. # Start of a tool call: reset state variables, set `inside_tool_call`
  933. if result.strip() == _TOOL_CALL_TOKENS[tool_model_family]["start"]:
  934. tool_state.inside_tool_call = True
  935. continue
  936. # End of tool call: reset `inside_tool_call`, emit a `finish_reason`
  937. if result.strip() == _TOOL_CALL_TOKENS[tool_model_family]["end"]:
  938. tool_state.reset()
  939. yield self.build_chat_completion_chunk(
  940. request_id=_request_id,
  941. role=None,
  942. finish_reason="tool_calls",
  943. model=model_id_and_revision,
  944. )
  945. continue
  946. # Inside a tool call
  947. if tool_state.inside_tool_call:
  948. tool_state.buffer += result
  949. # First step: extract the tool name (may need several tokens, and we can't emit a delta
  950. # until we have the full name)
  951. if not tool_state.has_tool_name_defined:
  952. tool_name = re.search(r"\"name\": \"(.*?)\"", tool_state.buffer)
  953. if tool_name is None:
  954. continue
  955. else:
  956. tool_name = tool_name.group(1)
  957. tool_state.has_tool_name_defined = True
  958. tool = ChoiceDeltaToolCall(
  959. function=ChoiceDeltaToolCallFunction(name=tool_name),
  960. index=0,
  961. type="function",
  962. id=_request_id + "_tool_call", # Only the first tool call delta has an id
  963. )
  964. # Second step: extract tool arguments. The tool arguments can be seen as a json string
  965. # within the tool json string. We emit a delta for the arguments.
  966. else:
  967. # Empty text: skip
  968. if result == "":
  969. continue
  970. # Until we see the `"arguments": {` in the buffer, we skip
  971. # TODO: other models will likely need more elaborate processing here
  972. if '"arguments": {' not in tool_state.buffer:
  973. continue
  974. # Handle nesting. We want to exclude the last } from the emitted arguments (it's
  975. # closing the outermost nesting level, outside the arguments block)
  976. tool_state.arg_nesting_level += result.count("{")
  977. tool_state.arg_nesting_level -= result.count("}")
  978. if tool_state.arg_nesting_level < 0:
  979. result = "".join(result.split("}")[:-2]) + "}" # e.g. "4}}\n" -> "4}"
  980. tool = ChoiceDeltaToolCall(
  981. function=ChoiceDeltaToolCallFunction(arguments=result),
  982. index=0,
  983. type="function",
  984. )
  985. yield self.build_chat_completion_chunk(
  986. request_id=_request_id, role=None, tool_calls=[tool], model=model_id_and_revision
  987. )
  988. continue
  989. # ====== END OF TOOL CALL LOGIC ======
  990. # All non-tool related tokens are emitted as assistant messages. Empty text is skipped.
  991. if result != "":
  992. yield self.build_chat_completion_chunk(
  993. _request_id, content=result, model=model_id_and_revision
  994. )
  995. yield self.build_chat_completion_chunk(_request_id, finish_reason="stop", model=model_id_and_revision)
  996. thread.join()
  997. except Exception as e:
  998. logger.error(str(e))
  999. yield f'data: {{"error": "{str(e)}"}}'
  1000. finally:
  1001. thread.join()
  1002. return stream_chat_completion(generation_streamer, request_id)
  1003. def generate_response(self, req: dict) -> Generator[str, None, None]:
  1004. """
  1005. Generates an OpenAI Response using `generate`.
  1006. Args:
  1007. req (`dict`): The request to generate an OpenAI Response for.
  1008. Returns:
  1009. `Generator[str, None, None]`: A generator that yields the OpenAI Response events.
  1010. """
  1011. # TODO -- Implement non-streaming mode
  1012. model_id_and_revision = self.process_model_name(req["model"])
  1013. must_discard_cache = model_id_and_revision != self.last_model
  1014. self.last_model = model_id_and_revision
  1015. model, processor = self.load_model_and_processor(model_id_and_revision)
  1016. if isinstance(req["input"], str):
  1017. inputs = [{"role": "system", "content": req["instructions"]}] if "instructions" in req else []
  1018. inputs.append({"role": "user", "content": req["input"]})
  1019. elif isinstance(req["input"], list):
  1020. if "instructions" in req:
  1021. if req["input"][0]["role"] != "system":
  1022. inputs = [{"role": "system", "content": req["instructions"]}, *req["input"]]
  1023. else:
  1024. inputs = req["input"]
  1025. inputs[0]["content"] = req["instructions"]
  1026. else:
  1027. inputs = req["input"]
  1028. elif isinstance(req["input"], dict):
  1029. inputs = [{"role": "system", "content": req["instructions"]}] if "instructions" in req else []
  1030. inputs.append(req["input"])
  1031. else:
  1032. raise ValueError("inputs should be a list, dict, or str")
  1033. inputs = processor.apply_chat_template(inputs, add_generation_prompt=True, return_tensors="pt")
  1034. inputs = inputs.to(model.device)
  1035. request_id = req.get("previous_response_id", "req_0")
  1036. # Temporary hack for GPTOSS 1: don't filter special tokens
  1037. skip_special_tokens = True
  1038. if "gptoss" in model.config.architectures[0].lower():
  1039. skip_special_tokens = False
  1040. generation_streamer = TextIteratorStreamer(
  1041. processor,
  1042. skip_special_tokens=skip_special_tokens,
  1043. skip_prompt=True,
  1044. )
  1045. generation_config = create_generation_config_from_req(req, model_generation_config=model.generation_config)
  1046. last_kv_cache = None
  1047. if self.is_continuation(req) and not must_discard_cache:
  1048. seq_len = self.last_kv_cache.get_seq_length()
  1049. if inputs["input_ids"].shape[-1] > seq_len:
  1050. last_kv_cache = self.last_kv_cache
  1051. generation_kwargs = {
  1052. "inputs": inputs,
  1053. "attention_mask": torch.ones_like(inputs),
  1054. "streamer": generation_streamer,
  1055. "generation_config": generation_config,
  1056. "return_dict_in_generate": True,
  1057. "past_key_values": last_kv_cache,
  1058. }
  1059. def stream_response(streamer, _request_id):
  1060. # Temporary hack for GPTOS 2: filter out the CoT tokens. Full solution here implies defining new output
  1061. # classes and piping the reasoning trace into a new field
  1062. filter_cot = False
  1063. cot_trace_end = None
  1064. if "gptoss" in model.config.architectures[0].lower():
  1065. filter_cot = True
  1066. cot_trace_end = "<|channel|>final<|message|>"
  1067. # Thin wrapper to save the KV cache after generation
  1068. def generate_with_cache(**kwargs):
  1069. generate_output = model.generate(**kwargs)
  1070. self.last_kv_cache = generate_output.past_key_values
  1071. thread = Thread(target=generate_with_cache, kwargs=generation_kwargs)
  1072. sequence_number = 0
  1073. output_index = 0
  1074. content_index = 0
  1075. try:
  1076. thread.start()
  1077. created_at = time.time() # the spec expects a unix timestamp in seconds
  1078. # We start by acknowledging the request (the request has `status="queued"`), and then by moving it to
  1079. # in progress (`status="in_progress"`)
  1080. response_created = ResponseCreatedEvent(
  1081. type="response.created",
  1082. sequence_number=sequence_number,
  1083. response=Response(
  1084. id=f"resp_{request_id}",
  1085. created_at=created_at,
  1086. status="queued",
  1087. model=model_id_and_revision,
  1088. instructions=req.get("instructions"),
  1089. text={"format": {"type": "text"}},
  1090. object="response",
  1091. tools=[],
  1092. output=[],
  1093. parallel_tool_calls=req.get("parallel_tool_calls", False),
  1094. tool_choice="auto",
  1095. metadata=req.get("metadata"),
  1096. ),
  1097. )
  1098. sequence_number += 1
  1099. yield self.build_response_event(response_created)
  1100. response_in_progress = ResponseInProgressEvent(
  1101. type="response.in_progress",
  1102. sequence_number=sequence_number,
  1103. response=Response(
  1104. id=f"resp_{request_id}",
  1105. created_at=created_at,
  1106. status="in_progress",
  1107. model=model_id_and_revision,
  1108. instructions=req.get("instructions"),
  1109. text={"format": {"type": "text"}},
  1110. object="response",
  1111. tools=[],
  1112. output=[],
  1113. parallel_tool_calls=req.get("parallel_tool_calls", False),
  1114. tool_choice="auto",
  1115. metadata=req.get("metadata"),
  1116. ),
  1117. )
  1118. sequence_number += 1
  1119. yield self.build_response_event(response_in_progress)
  1120. # Start the output item. Emit the assistant role to start the stream. Other chunks won't have a role,
  1121. # as it is implicit
  1122. response_output_item_added = ResponseOutputItemAddedEvent(
  1123. type="response.output_item.added",
  1124. sequence_number=sequence_number,
  1125. output_index=output_index,
  1126. item=ResponseOutputMessage(
  1127. id=f"msg_{request_id}", type="message", status="in_progress", role="assistant", content=[]
  1128. ),
  1129. )
  1130. sequence_number += 1
  1131. yield self.build_response_event(response_output_item_added)
  1132. # Start the content part of the event
  1133. response_content_part_added = ResponseContentPartAddedEvent(
  1134. type="response.content_part.added",
  1135. item_id=f"msg_{request_id}",
  1136. sequence_number=sequence_number,
  1137. output_index=output_index,
  1138. content_index=content_index,
  1139. part=ResponseOutputText(type="output_text", text="", annotations=[]),
  1140. )
  1141. sequence_number += 1
  1142. yield self.build_response_event(response_content_part_added)
  1143. # Stream the actual generated text
  1144. results = ""
  1145. for result in streamer:
  1146. # Temporary hack for GPTOS 3: don't emit the final "<|return|>"
  1147. if "gptoss" in model.config.architectures[0].lower():
  1148. result = result.removesuffix("<|return|>")
  1149. results += result
  1150. # (related to temporary hack 2)
  1151. if filter_cot:
  1152. if cot_trace_end in results: # end of reasoning trace observed -> stop filtering
  1153. filter_cot = False
  1154. results = "" # reset the results -> results will now track the final response
  1155. continue
  1156. else:
  1157. continue
  1158. response_output_text_delta = ResponseTextDeltaEvent(
  1159. type="response.output_text.delta",
  1160. item_id=f"msg_{request_id}",
  1161. sequence_number=sequence_number,
  1162. output_index=output_index,
  1163. content_index=content_index,
  1164. delta=result,
  1165. logprobs=[{"token": "", "logprob": 99.9}], # TODO: add actual logprobs
  1166. )
  1167. sequence_number += 1
  1168. yield self.build_response_event(response_output_text_delta)
  1169. # Signal the end of the text generation
  1170. response_output_text_done = ResponseTextDoneEvent(
  1171. type="response.output_text.done",
  1172. item_id=f"msg_{request_id}",
  1173. sequence_number=sequence_number,
  1174. output_index=output_index,
  1175. content_index=0,
  1176. text=results,
  1177. logprobs=[{"token": "", "logprob": 99.9}], # TODO: add actual logprobs
  1178. )
  1179. sequence_number += 1
  1180. yield self.build_response_event(response_output_text_done)
  1181. # Complete the content part
  1182. response_content_part_done = ResponseContentPartDoneEvent(
  1183. type="response.content_part.done",
  1184. item_id=f"msg_{request_id}",
  1185. sequence_number=sequence_number,
  1186. output_index=output_index,
  1187. content_index=content_index,
  1188. part=ResponseOutputText(type="output_text", text=response_output_text_done.text, annotations=[]),
  1189. )
  1190. sequence_number += 1
  1191. content_index += 1
  1192. yield self.build_response_event(response_content_part_done)
  1193. # Complete the output item
  1194. response_output_item_done = ResponseOutputItemDoneEvent(
  1195. type="response.output_item.done",
  1196. sequence_number=sequence_number,
  1197. output_index=output_index,
  1198. item=ResponseOutputMessage(
  1199. id=f"msg_{request_id}",
  1200. type="message",
  1201. status="completed",
  1202. role="assistant",
  1203. content=[response_content_part_done.part],
  1204. annotations=[],
  1205. ),
  1206. )
  1207. sequence_number += 1
  1208. output_index += 1
  1209. yield self.build_response_event(response_output_item_done)
  1210. # Finally, Complete the event
  1211. response_completed = ResponseCompletedEvent(
  1212. type="response.completed",
  1213. sequence_number=sequence_number,
  1214. response=Response(
  1215. id=f"resp_{request_id}",
  1216. created_at=created_at,
  1217. status="completed",
  1218. model=model_id_and_revision,
  1219. instructions=req.get("instructions"),
  1220. text={"format": {"type": "text"}},
  1221. output=[response_output_item_done.item],
  1222. object="response",
  1223. tools=[],
  1224. parallel_tool_calls=req.get("parallel_tool_calls", False),
  1225. tool_choice="auto",
  1226. metadata=req.get("metadata"),
  1227. ),
  1228. )
  1229. sequence_number += 1
  1230. yield self.build_response_event(response_completed)
  1231. thread.join()
  1232. except Exception as e:
  1233. logger.error(f"Exception in response generation: {str(e)}")
  1234. error_event = ResponseErrorEvent(
  1235. type="error",
  1236. sequence_number=sequence_number,
  1237. message=str(e),
  1238. )
  1239. sequence_number += 1
  1240. yield self.build_response_event(error_event)
  1241. response_failed = ResponseFailedEvent(
  1242. type="response.failed",
  1243. sequence_number=sequence_number,
  1244. response=Response(
  1245. id=f"resp_{request_id}",
  1246. created_at=created_at,
  1247. status="failed",
  1248. model=model_id_and_revision,
  1249. instructions=req.get("instructions"),
  1250. text={"format": {"type": "text"}},
  1251. output=[],
  1252. object="response",
  1253. tools=[],
  1254. parallel_tool_calls=False,
  1255. tool_choice="auto",
  1256. metadata=req.get("metadata"),
  1257. error=ResponseError(
  1258. code="server_error",
  1259. message=str(e),
  1260. ),
  1261. ),
  1262. )
  1263. sequence_number += 1
  1264. yield self.build_response_event(response_failed)
  1265. finally:
  1266. thread.join()
  1267. return stream_response(generation_streamer, request_id)
  1268. def generate_transcription(self, req: dict) -> Generator[str, None, None]:
  1269. """
  1270. Generates an OpenAI Transcription using the audio file.
  1271. Args:
  1272. req (`dict`): The request containing the audio file and model information.
  1273. Returns:
  1274. `Generator[str, None, None]`: A generator that yields the transcription result.
  1275. """
  1276. # TODO: implement streaming transcription (currently, it's not streaming)
  1277. if not is_librosa_available():
  1278. raise ImportError(
  1279. "Missing librosa dependency for audio transcription. Please install with `pip install librosa`"
  1280. )
  1281. model_id_and_revision = self.process_model_name(req["model"])
  1282. audio_model, audio_processor = self.load_audio_model_and_processor(model_id_and_revision)
  1283. generation_streamer = TextIteratorStreamer(
  1284. audio_processor.tokenizer, skip_special_tokens=True, skip_prompt=True
  1285. )
  1286. generation_config = create_generation_config_from_req(
  1287. req, model_generation_config=audio_model.generation_config
  1288. )
  1289. # Read the binary audio file using librosa
  1290. model_sampling_rate = audio_processor.feature_extractor.sampling_rate
  1291. audio_bytes = io.BytesIO(req["file"])
  1292. audio_array, _ = librosa.load(audio_bytes, sr=model_sampling_rate, mono=True)
  1293. audio_inputs = audio_processor(audio_array, sampling_rate=model_sampling_rate, return_tensors="pt").to(
  1294. audio_model.device
  1295. )
  1296. audio_inputs["input_features"] = audio_inputs["input_features"].to(audio_model.dtype)
  1297. generation_kwargs = {
  1298. "streamer": generation_streamer,
  1299. "generation_config": generation_config,
  1300. "return_dict_in_generate": True,
  1301. }
  1302. def _generate_transcription():
  1303. generated_ids = audio_model.generate(**audio_inputs, **generation_kwargs)
  1304. transcription_text = audio_processor.batch_decode(generated_ids.sequences, skip_special_tokens=True)[0]
  1305. transcription = Transcription(text=transcription_text)
  1306. yield f"{transcription.model_dump_json(exclude_none=True)}"
  1307. return _generate_transcription()
  1308. def is_continuation(self, req: dict) -> bool:
  1309. """
  1310. Determines whether the current request is a continuation of the last request. In other words, if it is the
  1311. same chat session.
  1312. Args:
  1313. req (`dict`): The request to check.
  1314. Returns:
  1315. `True` if the request is a continuation of the last request, `False` otherwise.
  1316. """
  1317. messages = req.get("messages") or req.get("input") # ChatCompletion and Response have different fields
  1318. req_continues_last_messages = True
  1319. # No cached messages: this is a new request
  1320. if self.last_messages is None:
  1321. req_continues_last_messages = False
  1322. # The new request has no new rounds of conversation: this is a new request
  1323. elif len(self.last_messages) >= len(messages):
  1324. req_continues_last_messages = False
  1325. # Otherwise, check that the last messages are a subset of the new request
  1326. else:
  1327. for i in range(len(self.last_messages)):
  1328. if self.last_messages[i] != messages[i]:
  1329. req_continues_last_messages = False
  1330. break
  1331. self.last_messages = messages
  1332. return req_continues_last_messages
  1333. @staticmethod
  1334. def get_quantization_config(args: ServeArguments) -> Optional["BitsAndBytesConfig"]:
  1335. """
  1336. Returns the quantization config for the given CLI arguments.
  1337. Args:
  1338. args (`ServeArguments`): The serve arguments. May contain quantization settings, device, etc.
  1339. Returns:
  1340. `Optional[BitsAndBytesConfig]`: The quantization config.
  1341. """
  1342. if args.load_in_4bit:
  1343. quantization_config = BitsAndBytesConfig(
  1344. load_in_4bit=True,
  1345. # For consistency with model weights, we use the same value as `dtype`
  1346. bnb_4bit_compute_dtype=args.dtype,
  1347. bnb_4bit_quant_type=args.bnb_4bit_quant_type,
  1348. bnb_4bit_use_double_quant=args.use_bnb_nested_quant,
  1349. bnb_4bit_quant_storage=args.dtype,
  1350. )
  1351. elif args.load_in_8bit:
  1352. quantization_config = BitsAndBytesConfig(
  1353. load_in_8bit=True,
  1354. )
  1355. else:
  1356. quantization_config = None
  1357. return quantization_config
  1358. def process_model_name(self, model_id: str) -> str:
  1359. """
  1360. Applies the `force_model` CLI argument and canonicalizes the model name to the format "model_id@revision".
  1361. If the model_id DOESN'T contain an @, it defaults to "model_id@main".
  1362. Args:
  1363. model_id (`str`): The model ID.
  1364. Returns:
  1365. `str`: The canonicalized model name to be used
  1366. """
  1367. if self.args.force_model is not None:
  1368. model_id = self.args.force_model
  1369. if "@" in model_id:
  1370. return model_id
  1371. return f"{model_id}@main"
  1372. def _load_model_and_data_processor(self, model_id_and_revision: str):
  1373. """
  1374. Generic method to load a model and a data processor from a model ID and revision, making use of the serve CLI
  1375. arguments.
  1376. Args:
  1377. model_id_and_revision (`str`):
  1378. The model ID and revision to load.
  1379. model_cls (`type[PreTrainedModel]`):
  1380. The model class to load.
  1381. Returns:
  1382. `tuple[PreTrainedModel, Union[ProcessorMixin, PreTrainedTokenizerFast]]`: The loaded model and
  1383. data processor (tokenizer, audio processor, etc.).
  1384. """
  1385. args = self.args
  1386. logger.info(f"Loading {model_id_and_revision}")
  1387. if "@" in model_id_and_revision:
  1388. model_id, revision = model_id_and_revision.split("@", 1)
  1389. else:
  1390. model_id, revision = model_id_and_revision, "main"
  1391. data_processor = AutoProcessor.from_pretrained(
  1392. model_id,
  1393. revision=revision,
  1394. trust_remote_code=args.trust_remote_code,
  1395. )
  1396. dtype = args.dtype if args.dtype in ["auto", None] else getattr(torch, args.dtype)
  1397. quantization_config = self.get_quantization_config(args)
  1398. model_kwargs = {
  1399. "revision": revision,
  1400. "attn_implementation": args.attn_implementation,
  1401. "dtype": dtype,
  1402. "device_map": "auto",
  1403. "trust_remote_code": args.trust_remote_code,
  1404. }
  1405. if quantization_config is not None:
  1406. model_kwargs["quantization_config"] = quantization_config
  1407. config = AutoConfig.from_pretrained(model_id, **model_kwargs)
  1408. architecture = getattr(transformers, config.architectures[0])
  1409. model = architecture.from_pretrained(model_id, **model_kwargs)
  1410. if getattr(model, "hf_device_map", None) is None:
  1411. model = model.to(args.device)
  1412. has_default_max_length = (
  1413. model.generation_config.max_new_tokens is None and model.generation_config.max_length == 20
  1414. )
  1415. has_short_max_new_tokens = (
  1416. model.generation_config.max_new_tokens is not None and model.generation_config.max_new_tokens < 1024
  1417. )
  1418. if has_default_max_length or has_short_max_new_tokens:
  1419. model.generation_config.max_new_tokens = 1024
  1420. logger.info(f"Loaded model {model_id_and_revision}")
  1421. return model, data_processor
  1422. def load_model_and_processor(
  1423. self, model_id_and_revision: str
  1424. ) -> tuple["PreTrainedModel", PreTrainedTokenizerFast]:
  1425. """
  1426. Loads the text model and processor from the given model ID and revision into the ServeCommand instance.
  1427. Args:
  1428. model_id_and_revision (`str`):
  1429. The model ID and revision to load.
  1430. Returns:
  1431. `tuple[PreTrainedModel, PreTrainedTokenizerFast]`: The loaded text model and processor.
  1432. """
  1433. if model_id_and_revision not in self.loaded_models or self.loaded_models[model_id_and_revision].is_deleted():
  1434. model, processor = self._load_model_and_data_processor(model_id_and_revision)
  1435. self.loaded_models[model_id_and_revision] = TimedModel(
  1436. model,
  1437. timeout_seconds=self.args.model_timeout,
  1438. processor=processor,
  1439. )
  1440. else:
  1441. self.loaded_models[model_id_and_revision].reset_timer()
  1442. model = self.loaded_models[model_id_and_revision].model
  1443. processor = self.loaded_models[model_id_and_revision].processor
  1444. return model, processor
  1445. def load_audio_model_and_processor(self, model_id_and_revision: str) -> tuple["PreTrainedModel", ProcessorMixin]:
  1446. """
  1447. Loads the audio model and processor from the given model ID and revision into the ServeCommand instance.
  1448. Args:
  1449. model_id_and_revision (`str`):
  1450. The model ID and revision to load.
  1451. Returns:
  1452. `tuple[PreTrainedModel, ProcessorMixin]`: The loaded audio model and processor.
  1453. """
  1454. if model_id_and_revision not in self.loaded_models or self.loaded_models[model_id_and_revision].is_deleted():
  1455. audio_model, audio_processor = self._load_model_and_data_processor(model_id_and_revision)
  1456. self.loaded_models[model_id_and_revision] = TimedModel(
  1457. audio_model,
  1458. timeout_seconds=self.args.model_timeout,
  1459. processor=audio_processor,
  1460. )
  1461. else:
  1462. self.loaded_models[model_id_and_revision].reset_timer()
  1463. audio_model = self.loaded_models[model_id_and_revision].model
  1464. audio_processor = self.loaded_models[model_id_and_revision].processor
  1465. return audio_model, audio_processor
  1466. if __name__ == "__main__":
  1467. serve = ServeCommand()
  1468. serve.run()