朗之文 文章首页

Inference Engines (Part 2): vLLM / Xinference and your voice stack

Part 2: Inference Engines

Audience: you've read Part 1 (or already know PyTorch well) and now have to decide "which engine should this model run on, why, and where do I look when it's slow." Scope of this part: starts from the model already loads. PyTorch itself (tensors, VRAM, nn.Module, state_dict, model file formats) is in Part 1. One criterion for the whole document: is there autoregressive decoding + a KV cache that grows with the sequence? Every selection, tuning and troubleshooting decision in this part follows from it. Test environment: source references and measured numbers correspond to vLLM V1, Xinference 1.x, transformers 5.x; the transformers / vLLM internals in §8 are the fastest-expiring part of the whole set — treat this as the baseline when re-verifying later.

Recap: ten takeaways from Part 1

If you don't want to go back and flip through it, this page is enough to pick up the thread. Each item cites where it came from in Part 1.

① A tensor = a flat block of memory + a way of reading it (Part 1 §1) A tensor is a Storage (the flat buffer that actually holds the numbers) + metadata (shape, stride, offset, dtype). Several tensors can be different views over the same Storage — transpose only swaps strides, broadcasting sets one dimension's stride to 0, only contiguous() really copies. The price of zero-copy is "non-contiguous," and many CUDA kernels (attention included) require contiguous input — that's where view size is not compatible in a traceback comes from.

② Two separate rules for shape alignment — don't mix them (Part 1 §1, Appendix Two)

And PyTorch's foundation is features always in the last dimension: nn.Linear eats [*, in] and emits [*, out], with any number of leading dims ([B,in], [B,seq,in], [B,heads,seq,in] all work), because matmul broadcasts the leading dims away uniformly. That foundation is what forces the x @ W.T in the code.

③ The batch dimension is only "how many are in the shape" (Part 1 Appendix Two) The B in [B, seq, hidden] means one thing: this forward processed B samples at once. Where those B came from — cut from a training set (mini-batch), passed by you in one call, or bundled by the server — the model neither knows nor cares. And the samples in a batch are independent of each other, exchanging no information; computed separately the results are identical.

These two items are the entire premise of Chapter 4: because samples are independent, a server can freely bundle and unbundle requests; and because one forward reads the weights once and shares them across B samples, batching speeds things up.

④ VRAM = weights + KV cache + activations + overhead (Part 1 §2, §3) The weights are mental arithmetic: param_count × bytes_per_param (bf16=2, fp8/int8=1, int4≈0.5); for sharded models read total_size from index.json. The KV cache grows linearly with context length × concurrency and can rival the weights at long context and high concurrency — Part 1 gave the formula, this part covers how engines manage it (§5, §10). What nvidia-smi shows is reserved + CUDA context + non-PyTorch allocations; larger than allocated is normal, not a leak.

⑤ bf16 is the modern inference default (Part 1 §3) Same 2 bytes as fp16 but the exponent range of fp32, so far less prone to NaN/inf. Quantization (AWQ/GPTQ/FP8) changes only "bytes per parameter"; it doesn't touch the tokenizer, the vocab or the model structure.

⑥ Inference = model.eval() + inference_mode() (Part 1 §4) The former changes layer behavior (Dropout off, BatchNorm uses running statistics), the latter builds no computation graph. What's saved is the graph and the intermediate activations — the entire reason inference needs less VRAM than training. Real engines run in this mode throughout. The criterion is "does this step update weights": prompt engineering is pure inference; LoRA fine-tuning brings all of autograd back.

⑦ Model = structure + weights + tokenizer (Part 1 §7) config.json (the structure spec, including the architectures field that decides "which code loads this") + safetensors (the weights, i.e. the state_dict) + vocab / tokenizer_config (the tokenizer). Stored separately, aligned via vocab_size. .pt is a container (holds any Python object, optimizer state included, so training checkpoints have no other option); safetensors is a data format (only a flat "name → tensor" map, but mmap-able, executes no code, and its header is the manifest).

⑧ state_dict keys are attribute paths (Part 1 §5, Appendix One) From the root module to this tensor, joined with . — so fc1.weight and model.layers.0.self_attn.q_proj.weight follow one rule, and so stripping one prefix promotes a submodule into a standalone model (Chapter 8 of this part shows the real use). state_dict holds parameters + persistent buffers, not just "learnable parameters." Registration has four tiers, and the last one bites:

What you write Learnable In state_dict Moved by .to()
nn.Parameter(t) ✓ ✓ ✓
register_buffer("m", t) ✗ ✓ ✓
register_buffer("m", t, persistent=False) ✗ ✗ ✓
self.m = torch.zeros(...) ✗ ✗ ✗

⑨ transformers doesn't replace PyTorch; it lifts it to the "model" level (Part 1 §8) PreTrainedModel is literally a subclass of nn.Module; the few dozen extra methods (from_pretrained, device/dtype, tie_weights, can_generate, set_attn_implementation…) are the layer it adds. PyTorch provides the foundation; transformers supplies "structure + weights + tokenizer." — This part goes on to ask: what does vLLM change on top of that? What does Xinference add?

⑩ from_pretrained doesn't error by default (Part 1 §5) load_state_dict defaults to strict=True and errors on a key mismatch; from_pretrained does not — weights missing from the file are filled with random initialization, extra keys are dropped, and all you get is one log line, Some weights ... are newly initialized. The model loads, runs, and produces nonsense — a major source of that. §9 of this part lists three causes of "silent garbage"; this is the most common.

0. What this part answers

Three questions, and read in order they form one line:

  1. Which engine should my model run on? — One criterion: is there autoregressive decoding + a growing KV cache? Where your LLM, ASR and TTS each land is cut through one by one in Chapters 5–6.
  2. What do engines actually do on top of PyTorch? — Two answers in opposite directions: vLLM changes things downward (replacing memory management and attention kernels so that one model runs fast); Xinference adds things upward (touches not one line of compute; adds process management, batch scheduling and a unified API so that a pile of models is easy to use).
  3. Where do I look when it's slow or wrong? — Loading problems: the PyTorch/HF layer. VRAM and throughput problems: engine scheduling. Garbage output with no error: look at architectures first.

Reading map

Chapter What question it answers
§1 Two meanings of embedding What is embed_tokens when I dump an LLM? Is it the same thing as a BGE-style "text embedding model"? How does multimodal input plug in? required
§2 tokenize How does text become something the model can eat? Why doesn't vocab_size match len(tokenizer)? required
§3 tokenizer_config What is a chat_template and why can't I invent my own format? What's the difference between /v1/completions and /v1/chat/completions? required
§4 Batching ⭐ How do concurrent requests become one forward? Why must some workloads "wait" and others not? read this
§5 vLLM ⭐ What does it replace on top of PyTorch? Which stages of my LLM / ASR / TTS can go on it, and which can't? read this
§6 Xinference What do embedding / rerank workloads look like? What does Xinference add on top of PyTorch? required
§7 Scaling out Are model parallelism and load balancing the same thing? What does multi-machine actually buy? required
§8 transformers Why does vLLM depend on both pytorch and transformers? Who provides the serving-layer engine? recommended
§9 Engineering traps What goes wrong when a model directory is handed to an engine? Why is the output sometimes garbage with no error? lookup
§10 Troubleshooting table What to check first when the engine layer misbehaves lookup
§11 Mental model One page to take away wrap-up
Appendix Why is the transformer ecosystem almost entirely on PyTorch? Where does ONNX fit? optional

§4 and §5 are the core of this part; §5 and §6 are each other's mirror image (change downward vs add upward). Skip the appendix on a first read.

1. The two meanings of "embedding": even LLMs have an embedding table

"embedding" is an overloaded word — distinguishing the two uses is key:

embedding table (nn.Embedding) embedding model (bge)
what it is lookup table: token id → vector the whole model's purpose: text → one vector
where the input of every transformer a type of model
is it the output? no, internal component yes, the model's output IS an embedding
who has it both LLM and bge only embedding models

Key names per family: bge → embeddings.word_embeddings.weight; Qwen3 → model.embed_tokens.weight; GPT-2 → transformer.wte.weight.

LLM and bge share the entire front half

token id
  → embed_tokens table (lookup → vector)   ← identical step for LLM and bge
  → transformer layers (N layers)
  → one hidden vector per token [N, D]
  → ┬─ LLM:  LM head → next-token logits → sample → loop (generation)
    └─ bge:  Pooler  → sentence vector (see §6 pooling)

They differ only in the final head — which ties into §6 "why they're called pooling models."

What that "sample → loop (generation)" is: the autoregressive LLM decoder

The "sample → loop (generation)" at the LLM branch above is the core of the criterion that recurs in §5/§6/§11. Let's unpack it. Three words:

auto (self) + regression = each step's output regresses on its own previous outputs. The model doesn't spit out an entire sentence at once; it predicts one token at a time, appends it to the input, and predicts the next, looping until it emits eos. Mathematically, the joint probability of the whole sentence factors into a chain of conditionals:

P(y₁…yₙ | prompt) = ∏ₜ P(yₜ | y₁…yₜ₋₁, prompt)
                         └─ each step conditioned on "prompt + all tokens generated so far"

The key property is inherent seriality: you can't compute token t+1 without first having token t — because t+1's input includes t. That's the fundamental reason LLM decoding is slow and latency-bound, and the source of §4.1's "weight reloading saturates the bandwidth" (each step produces just one token, compute is nearly idle, the bottleneck is reading through all the weights once).

"Decoder" refers to the structure: a decoder uses causal attention (a causal mask) — each position can only attend to tokens to its left, never to the right. This "see only the past" property is what makes the factorization above valid, and it directly gives rise to the KV cache: because past tokens' K and V don't depend on the future and never change, they can be computed once and cached; each new token only needs Q/K/V for its one new position, attended against the cached history. Without the cache you'd recompute the whole prefix's K/V every step (O(n²) redundancy); with the cache each step is O(n), but the cache grows token by token with the sequence — exactly what §5's PagedAttention manages.

So "autoregressive LLM decoder" = causal-attention structure + one-token-at-a-time serial generation + a KV cache that grows with sequence length — this trio. vLLM's entire machinery is built for exactly this trio — commit this sentence to memory; in §5/§6, who can use vLLM and who can't is decided by it alone.

A single autoregressive decode has two phases: prefill and decode (engine-independent — any autoregressive generation has them). The "serial loop" above actually starts with a parallel beginning:

This naturally yields two latency metrics: TTFT (time to first token, determined by prefill) and TPOT (time per output token, determined by decode). This split is engine-independent — transformers' generate, any autoregressive decode has prefill/decode phases; vLLM didn't invent it, it just schedules them specifically (§5). Even LLM-based ASR (Fun-ASR-Nano prefilling the sequence spliced from audio_embeds + prompt, then decoding the transcript) has these same two phases.

Counterexample (confirming the criterion): Paraformer-style ASR is non-autoregressive — it predicts all output tokens in parallel in one forward, with no "previous feeds into next" dependency chain, no loop, no KV cache. So it's fast, but precisely because it lacks the trio, vLLM has nothing to optimize. ASR can afford non-autoregressive because output length/alignment is predictable; open-ended generation can't, which is why it must be autoregressive. (This comes up again in §6's embedding/rerank and §5's two FunASR generations.)

Weight tying: why lm_head and embed_tokens can share weights

Look at shapes first — this is the precondition for sharing: embed_tokens is [vocab, hidden] (token id t → grab row t, input); lm_head is Linear(hidden, vocab) with weight [vocab, hidden] (final hidden → vocab logits, output). Both are [vocab, hidden] — same shape.

Why sharing makes sense (the intuition): lm_head computes token t's logit = hidden · lm_head[t] (final hidden dotted with row t of lm_head). If lm_head = embed_tokens, then token t's logit = hidden · embed_tokens[t] = "how aligned the final hidden state is with token t's embedding." Elegant: "predict the next token = find the token whose embedding is most similar (highest dot product) to the current hidden state" — the input representation space and the output prediction space are the same space; a token's "meaning vector" serves double duty, representing it on input and scoring it on output. Mathematically input indexes rows while output projects via the same rows (a transpose relationship), so you can literally set lm_head.weight = embed_tokens.weight to share one tensor.

Benefits and tradeoff:

So if you dump keys and see no standalone lm_head.weight, it's been tied — there's only embed_tokens.weight and lm_head reuses it. And "why can the file hold only one copy" has a hard reason at the format level too: safetensors doesn't allow two keys pointing at the same storage — see Part 1 §7.

How multimodal inputs plug in: "cutting the line" at the embedding table (EmbedsPrompt)

The embedding table above is exactly where multimodal (audio/image) inputs plug into the LLM. Recall the standard input path:

token_id ──embed_tokens lookup──▶ text vectors [seq, hidden] ──▶ transformer layers

Normally the engine receives token_id and does the lookup internally. But audio has no token_id — it's not a discrete symbol and can't be looked up in a vocabulary. Using FunASR's LLM-based ASR (see §5) as an example, the approach is:

  1. Text parts go through the normal lookup: prefix/suffix text → embed_tokens → text vectors;
  2. Audio part: fbank → audio encoder → adaptor, directly producing vectors that live in the LLM's input embedding space, with the same hidden dimension (the adaptor's job is to project/align the encoder output into this space);
  3. The two are concatenated along the sequence dimension: [prefix_emb | audio_emb | suffix_emb];
  4. This already-looked-up vector sequence is fed to the engine as prompt_embeds (vLLM calls it EmbedsPrompt), bypassing its own lookup step, starting from transformer layer 0.

A side glance at the front half of this chain — it's the cleanest example on your stack of Part 1 §0.5's three-tier criterion.

What fbank is: a spectrogram plus two steps. The PCM waveform is cut into frames and put through a short-time Fourier transform to get each frame's spectrum; the frequency axis is merged into 80 bands on a perceptual scale (fine at low frequencies, coarse at high — the scale is called mel), taking each band's energy; finally take the log. The product is a [frames, 80] matrix, one frame every 10 ms. Not a single learnable parameter in the whole process — it's Tier 1 (a fixed transform people decided on); SenseVoice, Paraformer and Whisper (128 bands) all take it as input. From the encoder onward it's Tier 3 (representations the network learned itself):

audio → [ fbank: human-designed, fixed ] → [ encoder: learned by the network ] → [ adaptor ] → LLM
               gradient stops here           gradient flows through here

One pipeline with Tier 1 and Tier 3 joined end to end, cleanly divided. It also shows that "hand-crafted features" weren't eliminated — on the ASR line fbank is cheap and good enough and mainstream models still use it; models that learn the front end directly from the waveform do exist (self-supervised models like wav2vec 2.0 and HuBERT, whose front end is a learned 1-D convolution), they just aren't on your stack. What was replaced is "hand-crafted features followed directly by a classifier."

Verify it yourself: after loading Fun-ASR-Nano, sum(p.numel() for p in model.frontend.parameters()) should be 0 (FunASR's WavFrontend wraps torchaudio.compliance.kaldi.fbank).

One-liner: EmbedsPrompt = "I'm handing you the post-embedding-layer tensors directly — don't tokenize, don't look up, just run from here." This completes the diagram from this section into its multimodal version — the essence of multimodal is splicing other modalities' vectors into the same sequence at the embedding-table layer; the audio/image encoder's job is turning non-text into vectors of the same dimension and space as token embeddings. This is the direct low-level picture behind end-to-end audio models (like Qwen-Omni): what end-to-end eliminates is exactly "audio → text → re-tokenize," letting audio embeddings enter the LLM sequence directly. (Why the encoder stage can only stay in PyTorch while the decoder goes to vLLM — see §5.)

The cost: on this path there are no token IDs — and some things go with them. The engine side has to explicitly enable enable_prompt_embeds=True, and the most immediate loss once it's on is that repetition_penalty can't be used: the penalty's algorithm is "take the prompt's and the generated token IDs, index into the logits, and lower those positions." In prompt-embeds mode there are no IDs to index → out-of-range index → CUDA device-side assert (not a friendly error; the whole engine goes down).

To be precise, this is a limitation of vLLM's implementation, not something inherent to prompt-embeds mode: the penalty indexes "prompt tokens + generated tokens"; the prompt has no IDs, but the generated tokens do — penalizing only the generated part is entirely feasible in principle, and transformers' generate(inputs_embeds=...) does exactly that (input_ids is empty; the penalty acts only on the generated part). vLLM indexes both halves together, so in prompt-embeds mode it goes out of range. So on vLLM's path, what you can do is fall back to output-side post-processing (e.g. detect repeated n-grams and truncate). Remember this, and §5's "why LLM-based ASR needs dedicated anti-repetition" has its complete answer: not only does autoregressive sampling naturally fall into repetition attractors, the standard remedy happens to be unavailable in this engine's this mode.

2. From text to tensor: tokenize, token id, vocab

Before text enters the model it travels a "text → integers → vectors" pipeline. Tokenization is really two small steps:

  1. text → token pieces: the string is split into subwords ("unhappiness" → ["un","happiness"]); the output is strings.
  2. token pieces → token ids: each piece is looked up in the vocabulary and turned into an integer. Those integers are the token ids.

The actual product of tokenization is a list of integers (input_ids in HF), which then gets wrapped into a tensor:

tok("Hello world")
# {'input_ids': [9906, 1917], 'attention_mask': [1, 1]}   ← Python list

tok("Hello world", return_tensors="pt")
# {'input_ids': tensor([[9906, 1917]]), ...}   ← tensor, shape [1,2], dtype int64

Key: a token id is an integer index, not a vector, dtype int64. It's just the "row number" into the embedding table — telling the model to grab the vector at row 9906. So this integer tensor isn't the compute input yet; it first passes through the §1 embedding table to become float vectors before entering the transformer. (attention_mask is a separate array marking real tokens vs padding.)

vocab.json: the same vocab as in Part 1 §3 and §1 here

vocab.json is the "token string ↔︎ id" map:

{ "!": 0, ..., "Hello": 9906, "Ġworld": 1917, ... }

(In BPE, the Ġ is a space marker meaning "this word has a leading space.")

Hard constraint: number of entries in vocab.json = vocab_size in config = number of rows in the embedding table. All three must align — the tokenizer emits id=k, and row k of the embedding table must be that token's vector. So "wrong tokenizer for a model" produces garbage and doesn't error.

Vocab file names vary by algorithm

The vocab belongs to the tokenizer, not in safetensors, but it must agree with the embedding table on vocab_size.

Two traps that only show up when you run it (invisible in the config)

The "entries in vocab.json = config vocab_size" above is a simplification; reality has two subtleties:

  1. config.vocab_size is often padded, ≠ len(tokenizer). vocab_size is the number of rows in the embed_tokens matrix, frequently padded up to a multiple of 128 for GPU/tensor-core alignment (e.g. Qwen3-8B's config says 151936 = 128×1187, but len(tokenizer) is only 151669; the 267-row gap is padding rows the tokenizer never emits). So don't subtract two configs' vocab_size values to infer "how many tokens differ" — compare len(tokenizer) instead.

  2. add_special_tokens makes "the same text" produce different id sequences. tokenizer(s) adds special tokens by default, and different models add them differently (e.g. some embedding tokenizers append <|endoftext|> as a last-token-pooling anchor). So "the same plain text tokenizes to different ids under two tokenizers" may be just a wrapping difference, not a segmentation difference — diagnostic: compare tok(s, add_special_tokens=False) for the core text. (§6 has a full Qwen3-Embedding vs Qwen3-8B worked example.)

Note: the specific numbers in this section and §6 (151936 / len(tokenizer)=151669, etc.) are local measured snapshots; padding amounts and special-token counts will vary with model version — don't memorize the numbers, remember the method: "config.vocab_size is padded; to compare, compare len(tokenizer)." Reproduce it yourself: from transformers import AutoConfig, AutoTokenizer; AutoConfig.from_pretrained(p).vocab_size; len(AutoTokenizer.from_pretrained(p)).

3. tokenizer_config.json and special tokens

tokenizer_config.json is the tokenizer's "config.json" — it holds settings/metadata, not the vocab data. The parallel: a model has config.json (structure) + safetensors (weights); a tokenizer has tokenizer_config.json (settings) + vocab (data).

Main fields:

chat_template (directly relevant to your work)

It's a Jinja2 template defining "how a list of {role, content} messages becomes the final prompt" (in older model directories it's a field of tokenizer_config.json; from transformers 5 it's stored as a standalone chat_template.jinja, and loaders accept both). Qwen uses ChatML, rendering to <|im_start|>role\n...<|im_end|>. vLLM reads this at serve time, turning your OpenAI-style messages into the real prompt. So the model actually sees the rendered string, not your messages. When debugging DST (dialogue state tracking) / step drift, print it out:

print(tok.chat_template)
print(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True))
# prints the full prompt the model actually receives (with all <|im_start|> markers)

added_tokens_decoder: per-token attributes of special tokens

"151644": { "content": "<|im_start|>", "special": true,
            "normalized": false, "single_word": false,
            "lstrip": false, "rstrip": false }

(151644/151645 are Qwen's ChatML delimiters; their ids sit at the top of the vocab — appended after the base vocab.) Field meanings:

field meaning why this value
content the literal token string matched as one atom → single id, never split by BPE
special is it a control token true: registered as special; dropped under skip_special_tokens=True; atomic match
normalized normalize before matching false: matched byte-for-byte exactly, never altered
single_word only match at word boundaries false
lstrip/rstrip absorb adjacent left/right whitespace false: leave whitespace alone; spacing/newlines are controlled explicitly by the template

Why control tokens use this combo: special:true + normalized:false → recognized atomically and exactly as one id. The model learned message boundaries from this single token; once it's split into multiple BPE pieces, the model can't recognize the boundary.

The prompt-engineering footgun

Because these are registered added tokens, as long as the string in your prompt matches content exactly, it maps to that single id. But if you have an extra space, a missing bar, or wrong case (<| im_start |>), it won't match — it gets shattered into a string of BPE pieces, the model loses the turn structure, and you get rambling / off-topic / state-drift behavior, while the prompt looks nearly identical to the eye. Triage trick: encode with tok(prompt)["input_ids"] and confirm 151644/151645 appear as single integers at the expected positions.

Why chat_template exists (you can't just invent your own format)

Key realization: the model never sees {role, content}. It's a next-token predictor over a flat token sequence, with no concept of "role" or "message." {role, content} is a developer abstraction that must be serialized into one flat string before reaching the model — and chat_template is that serialization rule.

You do define the message content (what goes in system/user is yours), but you can't freely invent the serialization format: the model was fine-tuned on one specific format (Qwen's ChatML: <|im_start|>role\n...<|im_end|>, down to the exact special tokens and newlines). That format is what it learned a conversation looks like. Deviate → out of distribution → worse instruction-following (a likely root cause of step drift / state errors). So chat_template is a contract the model author ships: it travels with the model, and vLLM / transformers render it to the same string whoever reads it, so you needn't memorize each family's format (ChatML / Llama's [INST] / Gemma's <start_of_turn>...).

Not all LLMs have a chat_template: Base/pretrained models don't (and shouldn't — they're raw continuators with no chat notion); Instruct/Chat models should (it's their format contract). But it's a convention standardized only in 2023 — older or poorly-packaged models may lack it or ship a wrong one, needing a --chat-template override. For your voice system: use the Instruct variant, go through the chat API or apply_chat_template, don't hand-roll full ChatML; put your survey state inside the role content, and don't alter the <|im_start|> delimiters.

The other solution: the framework maintains its own format table. The "may lack it or ship a wrong one" above is a real pain point, and chat_template isn't the only answer. Xinference (§6) early on took the opposite route — it stores a prompt format in its own model-metadata JSON:

"prompt_style": {
  "style_name": "LLAMA3",
  "system_prompt": "You are a helpful assistant.",
  "roles": ["user", "assistant"],
  "stop_token_ids": [128001, 128009],
  "stop": ["<|end_of_text|>", "<|eot_id|>"]
}

The same job (serializing {role, content} into a string), two ways of shipping it:

chat_template framework-maintained prompt_style
who maintains it the model author, ships with the model the serving framework, in its own config
adding a new model no framework change append a metadata entry
upside always consistent with the model covers old models that have no chat_template
risk old models may lack it or have it wrong can lag model updates; may differ from the official rendering

Knowing both routes exist gives you one more suspect when "the same model behaves differently under two frameworks": it may not be the model at all — the two sides rendered the messages into different strings. The diagnostic is the same as before: print the final prompt and compare.

Two endpoints: /v1/completions vs /v1/chat/completions

They are not two models or two capabilities — they're two formatting front-ends over the same next-token engine. Same forward pass; they differ only in the layer in front:

/v1/completions /v1/chat/completions
you send prompt: a raw string messages: [{role, content}]
server does tokenize → run render via chat_template → tokenize → run
chat_template not applied applied automatically
also handles nothing auto-appends `<
returns choices[].text (raw continuation) choices[].message (assistant message object)

In one line: chat = completions + auto chat_template rendering + structured I/O + auto "your turn" cue + auto stops. Both converge to one flat token sequence.

When to use which: default to chat (Instruct models, roles/multi-turn, staying on the training distribution, 95% of cases). Switch to completions when you need full prompt control: serving a Base model, prefilling the assistant's opening to force a format (useful for structured output / DST), hand-crafted few-shot, reproducible eval, or bypassing a model's template bug. The cost: you must assemble ChatML correctly yourself — back to the footgun above, so always self-check with tok(prompt)["input_ids"] after hand-rolling.

4. Batching: how concurrent requests become one forward

This chapter is the second main line of this part, and the foundation that §5 and §6 keep coming back to when they discuss engines. It's about one thing: how multiple requests become one forward on the GPU, and why sometimes they can't.

4.1 Why batch: the weights are read once

Recall two points from Part 1 (recap ③): the B samples in the batch dimension are independent, and within one forward the weights are read from VRAM once and shared by all samples. The latter is the entire value of batching.

From this follows a point that must be nailed down, and is counterintuitive: "concurrency" and "batching" are not the same thing.

The real dividing line isn't "memory-bound vs compute-bound" — it's what saturates the bandwidth, and whether that traffic can be amortized across requests:

One sentence to nail it: merged into the same forward, the weights are read once; each in its own forward, they're fighting over the same memory bus.

This also explains a common misjudgment: measuring "a single concurrent request already saturates VRAM bandwidth, more concurrency gains little" proves less that "this model is memory-bound so concurrency is useless" than that "this deployment never batched at all." With the same memory-bound property, whether requests are merged into one forward or not gives completely opposite outcomes.

4.2 A third-party comparison

Not our own measurement. The Xinference paper (EMNLP 2024 Demo), Appendix A.3, compares four engines on Llama 3 8B on an A800, concurrency from 10 to 50:

Engine concurrency 10 (token/s) concurrency 50 (token/s) ratio
PyTorch (bare transformers) 36.69 37.10 1.01×
vLLM 487.94 1276.29 2.6×
SGLang 627.83 2087.81 3.3×
llama.cpp 77.68 77.99 1.00×

The bare transformers backend's concurrency rises 5×, throughput doesn't move (36.69 → 37.10); llama.cpp likewise (1.00×). That's the clean sample of "no batching" — requests each run their own forward, none amortizing any other. vLLM / SGLang, by merging requests into one forward, reap the concurrency dividend.

But the two 1.0× rows have different causes, worth separating: the transformers backend at the time had no continuous-batching mechanism at all; llama.cpp proper does — in common/common.h, cont_batching = true is the default, with n_parallel defaulting to 1, so with llama-server the mechanism is there but the slots aren't open — one startup flag away. However, what Xinference wrapped back then was llama-cpp-python's Llama class, a path with no cross-request concurrency at all (it later switched to xllamacpp), so that row is more likely "the entry point lacks the capability" than "the slots aren't open" — the paper's appendix doesn't say which entry point, and we won't conclude on its behalf. What it means for the reader: when you see "throughput doesn't rise with concurrency," first ask is the mechanism absent, or just not turned on — the former means changing engines, the latter means changing a parameter.

Note: that's 2024 data, when Xinference's transformers backend had no continuous batching yet (added later, see §6). So that 1.01× happens to be a clean "no batching" control; it does not represent today's Xinference. Cite this table for the mechanism, not the current state.

4.3 Two ailments of the naive approach: padding waste and head-of-line blocking

GPUs need large batches to be well-utilized. But autoregressive generation has two heterogeneities that make "pack multiple requests into one batch" awkward: ① different requests have different prompt lengths; ② different requests produce different output lengths, and you don't know in advance how many tokens each will generate (until it emits eos).

The naive approach: static batch + manual padding. To pack N requests into one rectangular tensor [N, seq_len] for a single compute, unequal-length sequences must be padded to the longest with pad tokens, plus an attention_mask telling the model "these are filler, ignore." The cost is two layers:

static batch: batch locked, waits for the slowest, new requests blocked
  step→   1   2   3   4   5   6   7   8
  R1     ■   ■  eos  ·   ·   ·   ·   ·      ← R1 done at step 3, but slot locked until step 8
  R2     ■   ■   ■   ■   ■   ■   ■  eos
  R3     ■   ■   ■  eos  ·   ·   ·   ·
  R4(new) wait wait wait wait wait wait wait wait → can only start after the whole batch finishes

(This isn't saying HF generate can't batch — it can, but it does exactly the static padding above, with the waste and head-of-line blocking baked in.)

4.4 The decision point: when can the batch's composition still be rewritten

Whether those two ailments can be fixed depends on one thing. The mechanism is one sentence:

One model.forward(batch) is atomic — the tensor shapes are fixed at the moment of the call, and once the kernels are running you cannot add a row to the input. So the composition of a batch can be decided only in the instant before a forward begins.

Call that instant the decision point; the entire difference between the two classes of workload is how many decision points there are:

single forward (embedding / rerank / encoder) — exactly one decision point, ever
   R1 arrives ──┐
   R2 arrives ──┼─ wait one window ─→ [form batch] ─→ one forward ─→ all leave
   R3 arrives ──┘                  ↑
                          the only decision point; miss it and you wait for the next batch

autoregressive decode (LLM) — a decision point at every step, and the steps are happening anyway
   step:   1      2      3      4      5
   R1     ■      ■      ■      ■     eos
   R2            ■      ■      ■      ■      ← R2 arrives at step 2, goes straight in
   R3                   ■      ■      ■      ← R3 arrives at step 3, goes straight in
          ↑      ↑      ↑      ↑      ↑
        every step is a decision point; no need to wait specially

So a "wait window" isn't an optimization choice; it compensates for the defect of "only one decision point." Don't wait and you get a handful of stragglers; wait and you can form a batch. Autoregressive decode has no such defect — it has a decision point at every step, and those decision points weren't designed in; the autoregressive structure gives them away for free. Putting a wait window on a batch that reorganizes every step would be pointless.

This is explicit in the vLLM V1 scheduler source: there is no delay_factor / batch_timeout or any other waiting mechanism anywhere; every call to schedule() is "scan the running requests first, then pull from the waiting queue until max_num_batched_tokens or max_num_seqs is used up." Its comment even states the abstraction outright:

"There's no 'decoding phase' nor 'prefill phase' in the scheduler. Each request just has the num_computed_tokens and num_tokens_with_spec. At each step, the scheduler tries to assign tokens to the requests so that each request's num_computed_tokens can catch up its num_tokens_with_spec."

The scheduler sees no prefill/decode distinction, only "how many tokens does this request still owe" — and the same abstraction covers chunked prefill, prefix caching and speculative decoding along the way.

Then could a single forward be split into layer-by-layer execution, with decision points between layers? No — the layers don't line up: when R1 is at layer 8 and R2 just arrived, R2 has to start at layer 0, and layer 0 and layer 8 use different weight matrices. The entire benefit of batching is multiple requests sharing one weight read (§4.1); different layer = different weights = nothing to share — you've just split one big matmul into two small ones, which is worse.

To batch, they must leave layer 0 together; to leave together, someone has to wait. That's an inherent constraint of single-forward workloads, not anyone's clumsy implementation.

Contrast with autoregressive: at every step every request is doing the same thing — computing its next token, each running the full network once. So a request joining at any moment is naturally aligned with the existing ones at the next step.

4.5 The three-rung ladder: who actually forms the batch

With the mechanism clear, "batching" turns out to be three different things, differing in who forms the batch:

Who forms it Example What the server has to do
① In-request batch The client: one call carries N items one /v1/embeddings call with 100 texts nothing; the batch is already in hand
② Request-level
dynamic batching
The server: N clients send 1 each, the server waits a window and bundles them Xinference's BatchMixin queue, wait, form the batch, compute, split and return
③ Iteration-level
continuous batching
The server, redone at every token step vLLM reassemble every step; evict the finished, insert the waiting

②③ aren't two parallel options; it's a containment relationship: ③ has ②'s batching capability, just implemented by other means, and eliminates head-of-line blocking as a bonus.

Note that ① is often overlooked, but it's the easiest — the batch is already inside the request; the server forms nothing and so bypasses the wait window and scheduling overhead entirely. Offline jobs like index building and bulk transcription are faster on ① than on ② or ③.

4.6 Two instances

vLLM's continuous batching (③). The core in one line: scheduling granularity drops from "request level" to "each token-step level" — the batch is reassembled every step. Any request that emits eos is evicted immediately and its result returned at once, and the freed slot is filled right away by a queued request.

How it makes "unequal lengths" disappear: no padding needed. PagedAttention stores each sequence's KV cache as non-contiguous fixed-size blocks (pages), each taking only what it needs, and the attention kernel gathers per sequence — no rectangular tensor has to be formed.

Continuous batching: slots reclaimed every step, new requests fill in immediately
  step→   1   2   3   4   5   6   7   8
  slotA  R1  R1 eos→R4 R4  R4 eos→R6 ...   ← R1 finishes, R4 fills in immediately
  slotB  R2  R2  R2  R2  R2  R2  R2 eos
  slotC  R3  R3 eos→R5 R5 eos→R7 R7  ...
                  ↑ the GPU is always full of useful tokens — no idling, no padding

What this means for the two kinds of scenario:

Xinference's BatchMixin (②). A request-level batcher for embedding / rerank; the implementation is an asyncio queue plus a short window:

(first_args, first_kwargs), first_future = await self._queue.get()   # the first one: block indefinitely

while size < self.batch_size:                                        # for every subsequent one
    try:
        (args, kwargs), future = await asyncio.wait_for(
            self._queue.get(), timeout=self.batch_interval)           # ← returns IMMEDIATELY if the queue has items
    except asyncio.TimeoutError:
        break                                                        # only gives up once it's empty; ships the batch as is

Defaults are XINFERENCE_BATCH_SIZE=32 and XINFERENCE_BATCH_INTERVAL=0.003 (3 milliseconds); both are tunable via environment variables.

That 3 ms is smarter than it looks. It's easily misread as "every batch adds a fixed 3 ms of latency," but it isn't — wait_for returns immediately when the queue already has requests; it never actually waits out the window. So the value is "the maximum idle gap allowed":

No waiting when busy, waiting only when idle, and waiting when idle costs nothing — it's already load-adaptive.

4.7 A counterintuitive corollary

What decides the kind of batching is the workload, not the engine.

vLLM supports pooling models too (start of §6), and an embedding request is done in one step — there is no "next step" for a new request to slip into, so continuous batching here automatically degrades to ②.

That also explains why Xinference, even with vLLM as its embedding backend, still wraps its own BatchMixin around it: it merges requests at the HTTP layer, regardless of which engine sits underneath.

Back to this part's criterion: autoregressive decoding is what creates "steps," and steps are what make iteration-level scheduling possible; a single forward has no steps, so all that's possible is request-level batching. The next two chapters on vLLM and Xinference are two expansions of this one sentence.

↑