Skip to content

[serve] Refactor server and engine architecture - #50927

Merged
SunMarc merged 50 commits into
mainfrom
serve-model-process
Nov 27, 2026
Merged

SunMarc merged 50 commits into
mainfrom
serve-model-process

Conversation

@SunMarc

@SunMarc SunMarc commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

This PR refactors a bit how serve is designed so that we are not bottlenecked by the api server. I've tested this on H100 and on a mac laptop (M2). I tried to keep things as familiar as possible from the old arch. Some features like multiple API servers only work when there is one model (force-model) but could be added for multi-model if needed.

I've added only a few tests as we didn't really need a lot of new tests and made sure that existing tests were passing correctly !

Overall architecture

Before

Everything runs in one process. Python runs one thread at a time per process, so the GPU loop
waits whenever the server handles HTTP, and the reverse.

                         one process
 +-------------------------------------------------------+
 |  HTTP server -> handlers -> chat template, tokenize   |
 |                     |                                 |
 |                     v                                 |
 |  model.generate() thread / continuous batching (GPU)  |
 |                     |                                 |
 |                     v                                 |
 |  decode tokens -> SSE chunks -> client                |
 +-------------------------------------------------------+

Now

Two kinds of processes. The API server handles HTTP and text: chat template, tokenizing, decoding. The model process holds the model: it gets the prompt's tokens (with the image or audio features of a multimodal request, or the function to run for transcription and SystemOne), and sends back the new tokens.

        API server                                       model process
 +-----------------------------+                 +-----------------------------+
 | HTTP, handlers              |    requests     |                             |
 | chat template, tokenize  ---+---------------->|  model.generate()           |
 |                             |                 |  or continuous batching     |
 | decode tokens, SSE      <---+-----------------+  (GPU)                      |
 +-----------------------------+    results      +-----------------------------+
                               (new tokens, one message per step)

Major pros

  • The server no longer slows down the GPU. Python runs one thread at a time per process (the GIL). On main, the server's work and the generation loop share one process, so they take turns, and the GPU waits while the server works, most of all under heavy load. Now they run in separate processes, so neither waits for the other.
  • More CPU when needed. --api-server-count N adds API servers.
  • I also took the opportunity to clean a few things ;)

Behaviour changes

  • /v1/responses no longer streams by default: as in OpenAI's API, a request streams only with "stream": true.
  • A streamed answer sends its token usage only when the request asks for it, with stream_options={"include_usage": true}, in a last chunk of its own.
  • If the model's process dies, its requests fail, /health answers 503, and the server exits with an error, for whatever runs it to restart it.
  • Invalid values in a request (a seed that isn't a number, a setting generate rejects) give a 400 instead of a 500.
  • A server started with a model refuses transcriptions for another model (400), like the other endpoints.

Benchmark: server alone, ours vs vLLM

We only measure the server's own work. In both servers, the model is replaced by the same fake, which answers right away.

The load: 256 clients. Each sends a streamed chat request, and the next one as soon as it ends. The requests take
turns between four kinds:

Prompt Answer
short (73 tokens) short (32 tokens)
short (73 tokens) long (1,000 tokens)
long (10,000 tokens) short (32 tokens)
long (10,000 tokens) long (1,000 tokens)

Tokens streamed per second (higher is better):

API servers ours vLLM ours vs vLLM
1 58k 49k 1.2x
2 124k 90k 1.4x

Time until a client gets its first token, under this load (median, lower is better):

API servers ours vLLM
1 1.7 s 2.1 s
2 0.45 s 0.83 s
Further details

A request goes down through these classes, and its tokens come back up.

Going in: the request

 client
   |  POST /v1/chat/completions
   v
== API server ==========================================================
   FastAPI app               routes the request
   |
   v
   ChatCompletionHandler     applies the chat template, tokenizes
   |
   v
   ModelManager              finds the model's EngineClient
   |
   v
   EngineClient              sends ("generate", id, input_ids, settings)
   |
   |  requests queue
   v
== model process =======================================================
   run_engine                gives the request to the runner
   |
   v
   CBGenerateRunner          adds it to the batch on the GPU

Coming back: the tokens

== model process =======================================================
   CBGenerateRunner          each step: the new tokens of every request
   |
   |  results queue
   v
== API server ==========================================================
   EngineClient              gives each token to its request
   |
   v
   Detokenizer               turns the tokens into text
   |
   v
   ChatCompletionHandler     sends the text as an SSE chunk
   |
   v
 client

In the API server

Class What it does
Serve (serve.py) The CLI command. run() serves one API server; run_api_servers(n) starts the model process and n API servers.
build_server (server.py) Builds the FastAPI app: routes and middlewares. CancelOnDisconnect stops a request when its client leaves.
Handlers (BaseHandler and subclasses) One per endpoint. They check the request, apply the chat template and tokenize on the tokenizer thread (one per API server), then stream the answer as SSE.
ModelManager The models served: one EngineClient per model. Starts the model of the command line right away, others on their first request or /load_model.
EngineClient One model, as seen from the API server. The weights stay in the model process. It sends the requests, and a thread reads the results. It stops an idle model after --model-timeout seconds and notices a crash.
Detokenizer One per streamed request. It turns token ids into text and, with a response parser, into content, reasoning and tool calls.
ModelLoader How a model loads (dtype, quantization, attention, GGUF). The model process uses it for the weights, the API server for the config and processor.

Several API servers

With --api-server-count 3, three API servers share one model process. The model loads once.

Going in: the requests

 clients
   |
   v
 port 8000           one port for all the API servers:
   |                 each new connection goes to one of them
   +-------------------+-------------------+
   |                   |                   |
   v                   v                   v
== API servers =========================================================
   API server 0        API server 1        API server 2
   |                   |                   |
   +-------------------+-------------------+
                       |
                       |  requests queue (one, shared)
                       v
== model process =======================================================
                 CBGenerateRunner: one batch, with the requests
                 of all the API servers

Coming back: the tokens

== model process =======================================================
                 each step, every new token goes to the queue
                 of the API server that sent its request
   |                   |                   |
   | results queue 0   | results queue 1   | results queue 2
   v                   v                   v
== API servers =========================================================
   API server 0        API server 1        API server 2
  • To use it: transformers serve MODEL --api-server-count N. It needs a model on the command line.

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

@SunMarc
SunMarc requested a review from LysandreJik November 23, 2026 17:37
@SunMarc
SunMarc requested a review from ArthurZucker November 23, 2026 17:42

@tarekziade tarekziade left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work!

The description says invalid request values give a 400, and that the server exits when the model's process dies, but with --continuous-batching these two collides.

CBGenerateRunner.generate runs inline in the loop at the end of run_engine, which has no try/except, so a bad value like generation_config={"temperature": "hot"} ends the model's process instead of giving a 400, and the server exits for everyone.

I guess that's easy to fix with something like

while True:
    method, request_id, *args = requests.get()
    try:
        getattr(runner, method)(request_id, *args)
    except Exception as error:
        logger.exception(f"Request {request_id} failed")
        send_results([], [], [(request_id, error)])

@SunMarc

SunMarc commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Fixed the issue in the latest commit and added a test to cover that

@LysandreJik LysandreJik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Starts to look good! I haven't played with it yet, that's the next step for me.

Comment thread docs/source/en/serve-cli/serving.md Resolved
Comment thread docs/source/en/serve-cli/serving.md Resolved
Comment thread docs/source/en/serve-cli/serving.md Resolved
Comment thread src/transformers/cli/serving/utils.py Resolved
Comment thread src/transformers/cli/serving/utils.py Resolved

@LysandreJik LysandreJik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tried it out, works well! Thanks for shipping this @SunMarc !

@SunMarc
SunMarc added this pull request to the merge queue Nov 27, 2026
Merged via the queue into main with commit f6b7cbe Nov 27, 2026
126 checks passed
@SunMarc
SunMarc deleted the serve-model-process branch November 27, 2026 11:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants