Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Architecture string | The architectures entry in a checkpoint’s config.json, such as "Qwen3ForCausalLM". vLLM uses it to choose the class to build. |
| Reference implementation | The model’s original PyTorch code, usually in Hugging Face Transformers. |
| Flat batch | All tokens of all requests in one step laid end to end in one dimension, with no padding (18.b). |
| Forward context | Per-step information (attention metadata, KV cache tensors) the model runner makes available to every layer without passing it as an argument. |
| Shard | One GPU’s slice of a weight matrix under tensor parallelism (14.c). |
| Greedy decoding | Always picking the most likely token (temperature 0), so output is deterministic and comparable. |
| Protocol / marker interface | A class a model inherits to declare a capability, such as “supports LoRA”. |
1. What is it?#
Making vLLM serve a model architecture it does not yet support. There are three routes, lightest first:
- The Transformers modeling backend. If the model’s Transformers code follows that library’s
conventions, vLLM can run it directly (
--model-impl transformers, chosen automatically when no native implementation exists). No new code at all. - An out-of-tree model registered by a plugin (19.f).
- An in-tree model contributed to
vllm/model_executor/models/.
Routes 2 and 3 are mostly subtraction. You start from the reference PyTorch code and remove everything the engine now owns: the batch dimension, the attention implementation, the KV cache, the generation loop, sampling. What remains is the model’s layers, wired to vLLM’s shared building blocks and written against a flat batch. Seeing what a model must not do is a good summary of what the engine does. Facts checked on 12 November 2026 against vLLM v0.32.0.
flowchart LR HF[":huggingface: <b>Reference model code</b><br/><small>batch × seq tensors, own attention,<br/>own cache, generate()</small>"] --> STRIP[":i-wrench: <b>Remove</b><br/><small>padding and masks, cache handling,<br/>generation loop, training code</small>"] STRIP --> ADAPT[":i-code: <b>Adapt</b><br/><small>flat input_ids + positions,<br/>vLLM Attention and linear layers,<br/>prefix on every module</small>"] ADAPT --> REG[":i-list-checks: <b>Register</b><br/><small>in-tree, or via a plugin</small>"] REG --> RUN[":vllm: <b>The engine does the rest</b><br/><small>scheduling, paging, batching,<br/>sampling, streaming</small>"] class HF neutral class STRIP warn class ADAPT compute class REG queue class RUN compute
2. Why does it exist?#
New open-weight models arrive every week, often with a new attention variant or layer type. Teams also run private fine-tuned or research architectures that will never be upstream. If the only way to serve them were a fork of vLLM, every release would mean a rebase. A small, stable model interface lets the engine’s scheduling, paging and kernels apply to any model that follows it.
3. Simple analogy#
Adapting a recipe written for one home cook so a restaurant kitchen can produce it. You keep the ingredients and steps (the layers). You throw away “preheat your oven”, “set the table” and “serve one plate at a time” (cache handling, the generation loop, batching), because the restaurant already has ovens, waiters and a ticket system. And you write each step so that any station can do its share of it (tensor-parallel layers).
4. Tiny example: the constructor and forward signature#
class MyModelForCausalLM(nn.Module):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
self.model = MyModel(vllm_config, prefix=f"{prefix}.model")
def forward(
self,
input_ids: torch.Tensor | None,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor:
...No attention_mask, no past_key_values, no batch dimension. Two requests of 5 and 3 tokens
arrive as input_ids of shape [8] and positions such as [0 1 2 3 4 0 1 2].
5. Technical explanation#
What vLLM’s model interface looks like#
The contributor guide lists the requirements; each one corresponds to something from an earlier lesson.
1. A uniform constructor, with a prefix on every module. The guide gives two reasons.
Runtime support: “vLLM’s attention operators are registered in a model’s state by their full
names. Each attention operator must have a unique prefix as its layer name to avoid conflicts.”
This is how each layer finds its own KV cache tensor and how layers are grouped (17.i).
Non-uniform quantization: a checkpoint may quantise some layers and not others, and the prefix
is how a layer looks up its own treatment (18.j).
2. A forward function over a flat batch. The guide: “treat input_ids and positions as
flattened tensors with a single batch size dimension, without a max-sequence length dimension.”
Request boundaries are the attention backend’s business, through query_start_loc and
seq_lens (18.b). intermediate_tensors exists for pipeline parallelism: a later stage receives
the previous stage’s activations instead of token IDs. inputs_embeds is the door through which
image and audio embeddings arrive (18.h).
3. An embed_input_ids method, so the engine can get text embeddings separately and
overwrite placeholder positions with media embeddings before the layers run.
4. vLLM’s layers instead of your own. Attention becomes
vllm.model_executor.layers.attention.Attention, which holds no mathematics of its own: it looks
up the selected backend, the layer’s cache tensor and this step’s metadata from the forward
context, and calls the backend (18.c). Linear layers become vLLM’s parallel linear layers, which
create only this GPU’s slice of each weight and know how to be quantised. MoE layers use the
shared fused-MoE layer, which brings expert parallelism (19.a) with it.
What you delete#
| In the reference code | Why it goes | Who does it now |
|---|---|---|
past_key_values threaded through every layer | The cache is not a Python object passed around | Block pool + attention backend |
| Attention masks, padding | The batch is flat; nothing is padded | query_start_loc, seq_lens |
| The scaled-dot-product attention itself | Must read a paged cache | The attention backend |
generate(), beam search, stopping criteria | One step at a time, for many requests | Scheduler + sampler |
| Logits processors, temperature, top-p | Batched, in a fixed order | Sampler (18.e) |
| Training branches, dropout, loss | Inference only | — |
| Loading and device placement | Sharded and quantised at construction | Model loader (load_weights) |
Tensor parallelism comes from the layers#
You do not write tensor-parallel code; you use the layers that implement it:
| Layer | Splits | Communication |
|---|---|---|
ColumnParallelLinear | Output features across GPUs | None; outputs stay split |
RowParallelLinear | Input features across GPUs | An all-reduce to sum partial results |
QKVParallelLinear | The fused query/key/value projection, by head | None |
MergedColumnParallelLinear | Fused gate and up projections | None |
VocabParallelEmbedding | The embedding table | An all-reduce |
An attention block is a column-parallel projection followed by a row-parallel one; an MLP is the same pair. Each pair costs one all-reduce: the “two collectives per layer” of 19.a. Because these layers build only their own shard, the model never exists in full on any one GPU (18.a).
Registering it#
In-tree: add the class under vllm/model_executor/models/ and an entry in
vllm/model_executor/models/registry.py mapping the architecture string to a module and class,
for example "OPTForCausalLM": ("opt", "OPTForCausalLM"). Add an example repository to
tests/models/registry.py; the guide makes that, and the dummy-weight loading test it enables,
required for a pull request.
Out-of-tree: a general plugin (19.f):
def register():
from vllm import ModelRegistry
if "MyModelForCausalLM" not in ModelRegistry.get_supported_archs():
ModelRegistry.register_model(
"MyModelForCausalLM", "my_package.my_model:MyModelForCausalLM"
)Either way the key is the architectures string.
Through Transformers: if a model’s Transformers code follows that library’s “custom model”
conventions (attention through its attention interface, base_model_tp_plan and
base_model_pp_plan in the config for TP and PP), vLLM runs it through the Transformers modeling
backend, including remote code with --trust-remote-code. The documentation says its performance
“should be identical to a dedicated vLLM model implementation”; that is the project’s claim, so
benchmark your model both ways where both exist. v0.32.0 moved several architectures (GPT-NeoX,
Phi, Seed-OSS and others) onto this backend.
Capabilities are interfaces#
Optional features are declared by inheriting protocols in
vllm/model_executor/models/interfaces.py, which the engine checks:
| Interface | Declares |
|---|---|
SupportsLoRA | Layers can take adapters |
SupportsMultiModal | Accepts image, audio or video, with a processor |
SupportsPP | Can be split into pipeline stages |
SupportsTranscription | Can back the audio transcription API |
SupportsEagle3, SupportsMRoPE, SupportsQuant and others | Speculative-decoding hooks, multimodal rotary positions, quantisation hooks |
IsHybrid, IsAttentionFree | Mixes state-space (Mamba-like) layers with attention, or has no attention at all |
A multimodal model also supplies the processor that computes placeholder counts and a method that turns media into embeddings; the separate multimodal guide covers it, and it is most of the work for a vision-language model.
When the model is not a plain transformer#
Layers that keep state differently — a sliding window, a state-space block, a new compressed or
sparse attention — need more than a model class: a KV cache spec saying how much each layer
stores, possibly a new single-type cache manager (17.i), and an attention backend that understands
the layout. Hybrid models declare IsHybrid and implement get_mamba_state_shape_from_config and
get_mamba_state_dtype_from_config. This is why a brand-new architecture often arrives first as
“runs, but slowly” and gets efficient a release or two later.
Testing it#
The testing guide asks for, at minimum, the model-loading test, and recommends correctness tests against Hugging Face Transformers. A practical sequence:
- Greedy equivalence. Same prompt, temperature 0, compare token IDs with Transformers
generate(). Small numerical differences are expected at 16 bits; vLLM’s own tests compare log-probabilities of the top few tokens rather than demanding identical text. - Batch independence. One request alone versus the same request among thirty others.
Different kernels per batch size can cause tiny differences; a large divergence means request
boundaries are leaking.
VLLM_BATCH_INVARIANT=1makes results independent of batch composition if you need exact comparison. - Chunked prefill. A prompt longer than
max_num_batched_tokens. Wrong positions in the second chunk show up here. - Prefix cache. The same prompt twice; the second must match the first.
- Tensor parallelism, if supported:
-tp 2against-tp 1. -O0against-O2. A difference points at compilation or CUDA graph capture, not at your model.
Each test isolates one of the engine’s assumptions about a model.
6. Under the hood: the row-parallel contract#
Each rank holds a slice of the weight, computes a partial result, and the sum over ranks equals the full layer.
// rowparallel.go — a row-parallel linear layer: shards plus an all-reduce equal the full layer.
package main
import "fmt"
// matVec computes W.x for W given as rows.
func matVec(w [][]float64, x []float64) []float64 {
out := make([]float64, len(w))
for i, row := range w {
for j, v := range row {
out[i] += v * x[j]
}
}
return out
}
func main() {
const (
dOut = 3
dIn = 8
tp = 4
)
// The full weight, as it exists in the checkpoint: dOut x dIn.
w := make([][]float64, dOut)
for i := range w {
w[i] = make([]float64, dIn)
for j := range w[i] {
w[i][j] = float64((i+1)*(j+2)%7) - 3
}
}
x := []float64{1, -2, 0.5, 3, -1, 2, 0.25, -0.5}
full := matVec(w, x)
// Row-parallel: the INPUT dimension is split. Rank r is built with only its own
// columns of W and receives only its own slice of x (the output of the preceding
// column-parallel layer, which is already split the same way).
shard := dIn / tp
sum := make([]float64, dOut)
fmt.Printf("full weight %dx%d = %d numbers; each of %d ranks holds %dx%d = %d\n\n",
dOut, dIn, dOut*dIn, tp, dOut, shard, dOut*shard)
for r := 0; r < tp; r++ {
lo, hi := r*shard, (r+1)*shard
wr := make([][]float64, dOut)
for i := range wr {
wr[i] = w[i][lo:hi] // only this slice is ever loaded on rank r
}
partial := matVec(wr, x[lo:hi])
fmt.Printf("rank %d: columns %d-%d partial = %v\n", r, lo, hi-1, partial)
for i := range sum {
sum[i] += partial[i] // the all-reduce
}
}
fmt.Printf("\nall-reduce (sum over ranks): %v\n", sum)
fmt.Printf("single-GPU result: %v\n", full)
fmt.Println("equal:", fmt.Sprint(sum) == fmt.Sprint(full))
}Output:
full weight 3x8 = 24 numbers; each of 4 ranks holds 3x2 = 6
rank 0: columns 0-1 partial = [-1 -5 5]
rank 1: columns 2-3 partial = [6.5 -1 -5]
rank 2: columns 4-5 partial = [-9 -8 -7]
rank 3: columns 6-7 partial = [0 -0.75 -1.5]
all-reduce (sum over ranks): [-3.5 -14.75 -8.5]
single-GPU result: [-3.5 -14.75 -8.5]
equal: trueNo rank ever holds the whole matrix, and none needs to. That is sharding at construction: the checkpoint’s full tensor is read once by the loader, and each process keeps only its columns.
7. Performance implications#
- Use the fused layers.
QKVParallelLinearandMergedColumnParallelLinearturn three or two matrix multiplies into one, and the fused-MoE layer picks tuned kernels per GPU. - Avoid Python in
forward. It is compiled and captured into CUDA graphs (18.d). Data-dependent Python branches,.item()calls and shape changes break compilation or force fallbacks. - Custom ops for new layers. A new normalisation or activation written in plain PyTorch runs,
but registering it as a
CustomOplets platforms swap in fast kernels. - Transformers backend vs native. Usually close; a native implementation can still win where it uses vLLM-specific fusions.
8. Production implications#
- Pin the vLLM version for out-of-tree models; layer and loader signatures change.
- Check feature support before launch: LoRA, PP, speculative decoding and quantised checkpoints each need the model to opt in.
- Watch the supported-models page for your architecture: an upstream implementation may make your private one unnecessary after an upgrade.
--trust-remote-coderuns code from the checkpoint repository. Treat it as executing third-party code on your GPU hosts.
9. Common mistakes#
- Forgetting
prefixon a submodule. Attention layers collide, or quantisation is applied to the wrong layers. - Keeping a padding mask and a batch dimension in
forward. - Using
nn.Linearinstead of the parallel layers, so TP silently replicates the weight. - Wrong
load_weightsname mapping for fused projections, leaving weights randomly initialised. Greedy comparison catches it at once. - Declaring
SupportsPPorSupportsLoRAwithout implementing what they require. - Testing one request alone and never in a batch.
10. Hands-on exercise#
- Run
rowparallel.go. Changetpto 2 and to 8. How many numbers does each rank hold? What constraint mustdInsatisfy? - Open
vllm/model_executor/models/opt.py, one of the smallest models in the tree, beside Transformers’modeling_opt.py. List five things present in the second and absent from the first. - Pick a model you use, find its
architecturesstring inconfig.json, then the line invllm/model_executor/models/registry.pythat maps it to a class. - Load a model with
--model-impl transformersand with the native implementation. Compare startup time and output tokens per second.
11. Interview questions#
- Why does a vLLM model’s
forwardhave no attention-mask argument? - What are the two uses of the
prefixconstructor argument? - When would you choose the Transformers modeling backend over writing a native vLLM model?
- How does a model get tensor parallelism without any communication code of its own?
- A new model gives correct output alone but wrong output in a batch. Which assumption is most likely violated?
12. Further reading#
Checked on 12 November 2026 against vLLM v0.32.0.
- Adding a new model: basic model
- Registering a model
- Multi-modal support
- Unit testing a model
- Supported models: the Transformers modeling backend
- Integration with Hugging Face
vllm/model_executor/layers/linear.py— the parallel linear layersvllm/model_executor/models/interfaces.py— capability protocolsvllm/model_executor/models/registry.py— architecture string to class