Pidoku

AsyncLLM and the Way Back: Tokens to Text

Module 16 Lesson 16.f 50 min Difficulty 3/5

Prerequisites 16.e


Before you start: words you need#

WordPlain meaning
asyncio taskOne coroutine scheduled on the event loop. Every HTTP request in vLLM’s API server is one task.
awaitPause this task until something is ready, letting other tasks run meanwhile.
DetokeniserCode that turns token IDs back into text.
IncrementalDone a little at a time, keeping state between steps, instead of redoing everything from the start.
Stop stringText the client says should end the answer, such as "\n\nUser:".
DeltaOnly what is new since the last message, as opposed to everything so far.
Unicode replacement character�, what you get when you decode half of a multi-byte character.

1. What is it?#

The way back: how the integers the engine core returns become the text a client sees.

For each request that made progress in a step, the engine core returns a short list of new token IDs (16.d). Turning those into streamed text is harder than it sounds. One token is not one character (an emoji or a Chinese character can be split across several tokens), so text can only be released when it is complete. Stop strings must be found even when they straddle two tokens, and text that might be the start of a stop string must be held back. All of it has to be done for hundreds of requests on one event loop without stalling any of them.

The class that connects an HTTP handler to this machinery is AsyncLLM (vllm/v1/engine/async_llm.py); the class that does the conversion is OutputProcessor (vllm/v1/engine/output_processor.py). Read from the v0.32.0 source; facts checked on 13 November 2026.

flowchart LR
  E[":vllm: <b>Engine core</b><br/><small>EngineCoreOutputs per step</small>"] -->|"PULL socket"| OT[":i-activity: <b>Socket task</b><br/><small>decode msgpack</small>"]
  OT --> OQ[("outputs_queue")]
  OQ --> OH[":i-recycle: <b>output_handler</b><br/><small>one task for all requests</small>"]
  OH --> OP[":i-message-square: <b>OutputProcessor</b><br/><small>detokenise, stop, logprobs</small>"]
  OP --> C1[("collector A")]
  OP --> C2[("collector B")]
  OP --> C3[("collector C")]
  C1 --> G1[":i-globe: <b>generate() A</b><br/><small>SSE to client A</small>"]
  C2 --> G2[":i-globe: <b>generate() B</b>"]
  C3 --> G3[":i-globe: <b>generate() C</b>"]
  OP -.->|"stop string hit: abort"| E
  class E io
  class OT,OH queue
  class OQ,C1,C2,C3 memory
  class OP compute
  class G1,G2,G3 io

2. Why does it exist?#

The naive version is easy to write and wrong in three ways:

  1. Decode everything every step. tokenizer.decode(all_ids) each step costs time proportional to the answer so far, on every token: quadratic overall. It also emits � mid-stream when a token ends in the middle of a character.
  2. Each request reads the socket itself. A thousand tasks competing for one socket, each decoding messages meant for others.
  3. Stream every character as soon as it exists. The client sees the first half of a stop string that should never have been shown.

AsyncLLM and OutputProcessor are the fixes: one reader, incremental detokenisers, and a hold-back buffer.


3. Simple analogy#

A post room. One clerk (the output handler) empties the single mail sack from head office (the engine core) every few minutes and sorts letters into pigeonholes, one per person (collectors). If someone has not collected yesterday’s letter, today’s is clipped to it rather than starting a pile. Letters written in a code the recipient cannot read are translated a page at a time (incremental detokenising), and the last line of each page is held until the next page arrives, in case it is the start of “END OF MESSAGE” (stop-string hold-back).


4. Tiny example: streaming with a stop string#

An incremental detokeniser with a stop-string hold-back buffer. The “tokens” are short strings so the logic is visible; the algorithm is the one vLLM uses.

Go
package main

import (
	"fmt"
	"strings"
)

type detok struct {
	stops     []string
	holdBack  int    // longest stop string minus one
	text      string // everything decoded so far
	sent      int    // how much of text has been released to the client
	stoppedBy string
}

func newDetok(stops ...string) *detok {
	d := &detok{stops: stops}
	for _, s := range stops {
		if len(s)-1 > d.holdBack {
			d.holdBack = len(s) - 1
		}
	}
	return d
}

// update appends one decoded piece and returns the text that is safe to stream.
func (d *detok) update(piece string, finished bool) string {
	searchFrom := len(d.text) - d.holdBack // a stop string may straddle the boundary
	if searchFrom < 0 {
		searchFrom = 0
	}
	d.text += piece

	for _, s := range d.stops {
		if i := strings.Index(d.text[searchFrom:], s); i >= 0 {
			d.text = d.text[:searchFrom+i] // truncate at the stop string
			d.stoppedBy = s
			finished = true
		}
	}

	limit := len(d.text)
	if !finished {
		limit -= d.holdBack // might still turn out to be the start of a stop string
	}
	if limit <= d.sent {
		return ""
	}
	out := d.text[d.sent:limit]
	d.sent = limit
	return out
}

func main() {
	pieces := []string{"The", " answer", " is", " 42", ".", "\n", "\n", "User", ":", " thanks"}
	d := newDetok("\n\nUser:")
	fmt.Printf("hold back %d characters\n\n", d.holdBack)

	for i, p := range pieces {
		out := d.update(p, false)
		fmt.Printf("token %-2d %-10q -> stream %q\n", i+1, p, out)
		if d.stoppedBy != "" {
			fmt.Printf("\nstop string %q found: abort sent to the engine core\n", d.stoppedBy)
			fmt.Printf("tokens generated after this one are discarded\n")
			break
		}
	}
	fmt.Printf("\nclient received: %q\n", d.text[:d.sent])
}

Output:

hold back 6 characters

token 1  "The"      -> stream ""
token 2  " answer"  -> stream "The "
token 3  " is"      -> stream "ans"
token 4  " 42"      -> stream "wer"
token 5  "."        -> stream " "
token 6  "\n"       -> stream "i"
token 7  "\n"       -> stream "s"
token 8  "User"     -> stream " 42."
token 9  ":"        -> stream ""

stop string "\n\nUser:" found: abort sent to the engine core
tokens generated after this one are discarded

client received: "The answer is 42."

The stream stays six characters behind generation the whole way, the stop string is found on the token that completes it (":"), and the client never sees any part of it.


5. Technical explanation#

One reader, many writers#

Every HTTP request is its own asyncio task running AsyncLLM.generate(). There could be a thousand of them. They do not each read from the engine socket. Exactly one background task, the output handler (started by _run_output_handler), reads the engine’s output and distributes it. Abridged from v0.32.0:

Python
async def output_handler():
    try:
        while True:
            # 1) Pull EngineCoreOutputs from the EngineCore.
            outputs = await engine_core.get_output_async()
            ...
            for start in range(0, num_outputs, chunk_size):
                end = start + chunk_size
                outputs_slice = engine_core_outputs[start:end]
                # 2) Process EngineCoreOutputs.
                processed_outputs = output_processor.process_outputs(
                    outputs_slice, outputs.timestamp, iteration_stats, ...
                )
                # Allow other asyncio tasks to run between chunks
                if end < num_outputs:
                    await asyncio.sleep(0)
                # 3) Abort any reqs that finished due to stop strings.
                if processed_outputs.reqs_to_abort:
                    await engine_core.abort_requests_async(processed_outputs.reqs_to_abort)
            # 4) Logging.
            if logger_ref[0]:
                logger_ref[0].record(...)
    except Exception as e:
        output_processor.propagate_error(e)

Three design points are visible in those lines.

Chunks of 128. One engine step can return outputs for hundreds of requests. Detokenising all of them without a pause would block the event loop (no new connection accepted, no byte written to any client) for the whole batch. So the handler processes VLLM_V1_OUTPUT_PROC_CHUNK_SIZE (default 128) outputs, yields with asyncio.sleep(0) so other tasks can run, and continues.

One loop over the batch. The docstring of process_outputs carries a rule for contributors: “vLLM V1 minimizes the number of python loops over the full batch to ensure system overheads are minimized. This is the only function that should loop over EngineCoreOutputs.” At 500 requests a step, a second Python loop over the batch is measurable.

Metrics are recorded here, in the API server, from timestamps the engine attached. The engine core never touches Prometheus (19.c).

generate(): the consumer side#

Python
q = await self.add_request(...)

# The output_handler task pushes items into the queue.
# This task pulls from the queue and yields to caller.
finished = False
while not finished:
    # Note: drain queue without await if possible (avoids
    # task switching under load which helps performance).
    out = q.get_nowait() or await q.get()
    finished = out.finished
    if out is not STREAM_FINISHED:
        yield out

q is a RequestOutputCollector, a one-slot mailbox rather than a queue. If the output handler deposits a second output before the client task has taken the first, the two are merged: in streaming (delta) mode the new token IDs and text are appended to the waiting output. A slow client therefore gets larger, less frequent chunks instead of an ever-growing backlog, and the server’s memory use does not depend on how slowly clients read.

get_nowait() or await get() is a small optimisation with a large effect under load: if an output is already waiting, the task takes it without suspending, which avoids a round trip through the event loop’s scheduler.

Cancellation is automatic#

When a client disconnects, the web server cancels that request’s task. generate() catches the cancellation and sends an abort to the engine:

Python
# If the request is disconnected by the client, generate()
# is cancelled or the generator is garbage collected. So,
# we abort the request if we end up here.
except (asyncio.CancelledError, GeneratorExit):
    if q is not None:
        await self.abort(q.request_id, internal=True)
    raise

The abort travels as an ABORT message, lands on the engine core’s fast aborts_queue (16.d), and the scheduler frees that request’s KV blocks right after the step in progress. Closing the connection is the correct way for a client to stop generation; no separate cancel call is needed.

Incremental detokenisation#

Each request owns an incremental detokeniser (vllm/v1/engine/detokenizer.py) that keeps state between steps and emits only text that is known to be complete:

ClassUsed whenHow
FastIncrementalDetokenizerThe tokenizer is a Hugging Face “fast” (Rust) tokenizer, which is almost alwaysThe tokenizers library’s DecodeStream: feed one token, get back finished text or nothing
SlowIncrementalDetokenizerPython-only tokenizersRe-decodes a short trailing window of tokens each step and emits the difference

“Nothing” is a normal result. When a token ends in the middle of a character, the stream returns no text and the piece appears with the next token. Clients see this as an occasional event with an empty content.

Stop strings, and why text is held back#

There are two different kinds of stop:

  • Stop token IDs (including end-of-sequence) are checked in the engine core, right after sampling, by check_stop() in vllm/v1/core/sched/utils.py. They cost nothing extra.
  • Stop strings can only be checked on text, and the engine core has no tokenizer. They are checked in the API server, inside the detokeniser’s update().

That split has two consequences.

The engine finds out late. When the API server finds a stop string, the engine core is still generating. So process_outputs adds the request to reqs_to_abort, and the output handler sends an abort. The engine may compute a token or two past the stop before the abort arrives; they are discarded. (When one step returns several tokens, as with speculative decoding, the detokeniser also drops the tokens after the one that completed the stop string.) This is the dotted arrow in the picture.

Text must be withheld. Suppose the stop string is "\n\nUser:" and the text so far ends with "\n\nUs". That might be the start of the stop string, or the start of “Usually”. If it were streamed and turned out to be the stop string, the client would already have text it should never have seen. The detokeniser therefore holds back the last few characters:

Python
# Number of chars to hold back when stop strings are to be excluded
# from streamed output.
if self.stop and not self.include_stop_str_in_output:
    self.stop_buffer_length = max(len(s) for s in self.stop) - 1
else:
    self.stop_buffer_length = 0

With stop strings set, the stream always trails generation by longest_stop - 1 characters, and the held-back text is flushed when the request finishes.

min_tokens interacts here too: until min_tokens tokens have been produced, stop strings are not evaluated, and afterwards the search starts only from the text after the min_tokens-th token, so a stop string cannot fire early.


6. Under the hood#

Three shapes of output#

SamplingParams.output_kind (RequestOutputKind) decides what make_request_output returns each step:

KindEach output containsUsed by
DELTAOnly the new text and tokens since the last outputStreaming HTTP responses
CUMULATIVEEverything so farLegacy callers
FINAL_ONLYNothing until the request finishes, then everythingNon-streaming HTTP responses, offline LLM

FINAL_ONLY matters for throughput: a non-streaming request creates no intermediate output objects, so a server handling only non-streaming traffic does far less Python work per token.

Trading smoothness for throughput: --stream-interval#

By default every token becomes one output and one server-sent event. For small models that generate thousands of tokens per second across all requests, the per-event cost (building objects, serialising JSON, a system call per write) becomes a real fraction of total CPU.

--stream-interval N (default 1) releases output only when the request has finished, or this is its first token, or N tokens have accumulated since the last release:

Python
# Send output request only when
# 1. It has finished, or
# 2. It is the first token, or
# 3. It has reached the stream interval number of tokens
if not (
    finished
    or self.sent_tokens_offset == 0
    or self.detokenizer.num_output_tokens() - self.sent_tokens_offset
    >= self.stream_interval
):
    return None

The first token is always sent immediately, so time to first token is unaffected. Only the cadence afterwards changes. A request may also set its own stream_interval in its sampling parameters; it can raise the server’s value but not lower it.

When the engine dies#

If the socket task receives the ENGINE_CORE_DEAD marker (16.d), it raises EngineDeadError; the output handler’s except calls output_processor.propagate_error(e), which delivers the error to every waiting collector. All in-flight requests fail at once, and /health returns 503. No request is left hanging.


7. Performance implications#

  • Per-token work lives here. Detokenising, stop-string search, logprob formatting and JSON serialisation run in the API server for every token of every streaming request. Under many concurrent short streams, the API server’s CPU is often the limit before the GPU.
  • Long stop strings add latency of a few characters to every stream, not to generation.
  • Logprobs are expensive on this path: each requested top-k alternative is detokenised too.
  • --stream-interval and non-streaming requests (FINAL_ONLY) both cut Python work per token. More API server processes (--api-server-count) spread the work across cores.

8. Production implications#

  • Clients should stop generation by closing the connection; the server aborts and frees memory. Proxies that buffer responses or ignore client disconnects defeat this, and the GPU keeps generating for nobody.
  • A load test that measures only non-streaming requests underestimates API-server CPU for streaming traffic.
  • When /health fails, every in-flight request has already failed with EngineDeadError; retry logic belongs in the client or gateway.
  • Empty content deltas are normal. Client code must not treat them as the end of the stream.

9. Common mistakes#

  1. Decoding the whole output every step in custom serving code: quadratic cost and � characters mid-stream.
  2. Expecting stop strings to stop the GPU instantly. One or two extra tokens are computed and thrown away.
  3. Assuming streamed text is generated text. With stop strings set, the stream lags by longest_stop - 1 characters.
  4. Treating an empty delta as end-of-stream. The end is finish_reason or data: [DONE].
  5. Adding a second loop over the batch in a plugin or patch to OutputProcessor; at large batch sizes it shows up in step time.

10. Hands-on exercise#

  1. In the program, add a second stop string ".". What is the hold-back now, and when does generation stop? Which stop string determines the hold-back, the first to match or the longest?
  2. Change main to call update(p, true) for the final piece of a run that never hits a stop string. Confirm that the held-back characters are flushed.
  3. Against a real server, send the same streaming request with and without "stop": ["zzzzzzzzzzzzzzzzzzzz"] (a 20-character string that will never occur). Compare how the chunks arrive.
  4. Start a server with --stream-interval 8 and run the Go client from 16.b. Does time to first token change? Count the SSE events.

11. Interview questions#

  1. Why does one task read all engine output instead of each request reading its own?
  2. Why does process_outputs exist as a single loop, and what would a second loop cost?
  3. Why can a stop string not be detected in the engine core?
  4. What happens to tokens the engine generates between a stop string appearing and the abort arriving?
  5. How does RequestOutputCollector keep a slow client from using unbounded memory?
  6. Why does --stream-interval leave time to first token unchanged?

12. Further reading#

Checked on 13 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in