Pidoku

Adding a Model

Module 19 Lesson 19.g 45 min Difficulty 4/5

Prerequisites 18.a, 18.b, 18.c, 19.f


Before you start: words you need#

WordPlain meaning
Architecture stringThe architectures entry in a checkpoint’s config.json, such as "Qwen3ForCausalLM". vLLM uses it to choose the class to build.
Reference implementationThe model’s original PyTorch code, usually in Hugging Face Transformers.
Flat batchAll tokens of all requests in one step laid end to end in one dimension, with no padding (18.b).
Forward contextPer-step information (attention metadata, KV cache tensors) the model runner makes available to every layer without passing it as an argument.
ShardOne GPU’s slice of a weight matrix under tensor parallelism (14.c).
Greedy decodingAlways picking the most likely token (temperature 0), so output is deterministic and comparable.
Protocol / marker interfaceA 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:

  1. 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.
  2. An out-of-tree model registered by a plugin (19.f).
  3. 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#

Python
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 codeWhy it goesWho does it now
past_key_values threaded through every layerThe cache is not a Python object passed aroundBlock pool + attention backend
Attention masks, paddingThe batch is flat; nothing is paddedquery_start_loc, seq_lens
The scaled-dot-product attention itselfMust read a paged cacheThe attention backend
generate(), beam search, stopping criteriaOne step at a time, for many requestsScheduler + sampler
Logits processors, temperature, top-pBatched, in a fixed orderSampler (18.e)
Training branches, dropout, lossInference only—
Loading and device placementSharded and quantised at constructionModel loader (load_weights)

Tensor parallelism comes from the layers#

You do not write tensor-parallel code; you use the layers that implement it:

LayerSplitsCommunication
ColumnParallelLinearOutput features across GPUsNone; outputs stay split
RowParallelLinearInput features across GPUsAn all-reduce to sum partial results
QKVParallelLinearThe fused query/key/value projection, by headNone
MergedColumnParallelLinearFused gate and up projectionsNone
VocabParallelEmbeddingThe embedding tableAn 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):

Python
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:

InterfaceDeclares
SupportsLoRALayers can take adapters
SupportsMultiModalAccepts image, audio or video, with a processor
SupportsPPCan be split into pipeline stages
SupportsTranscriptionCan back the audio transcription API
SupportsEagle3, SupportsMRoPE, SupportsQuant and othersSpeculative-decoding hooks, multimodal rotary positions, quantisation hooks
IsHybrid, IsAttentionFreeMixes 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:

  1. 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.
  2. 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=1 makes results independent of batch composition if you need exact comparison.
  3. Chunked prefill. A prompt longer than max_num_batched_tokens. Wrong positions in the second chunk show up here.
  4. Prefix cache. The same prompt twice; the second must match the first.
  5. Tensor parallelism, if supported: -tp 2 against -tp 1.
  6. -O0 against -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.

Go
// 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: true

No 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. QKVParallelLinear and MergedColumnParallelLinear turn 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 CustomOp lets 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-code runs code from the checkpoint repository. Treat it as executing third-party code on your GPU hosts.

9. Common mistakes#

  1. Forgetting prefix on a submodule. Attention layers collide, or quantisation is applied to the wrong layers.
  2. Keeping a padding mask and a batch dimension in forward.
  3. Using nn.Linear instead of the parallel layers, so TP silently replicates the weight.
  4. Wrong load_weights name mapping for fused projections, leaving weights randomly initialised. Greedy comparison catches it at once.
  5. Declaring SupportsPP or SupportsLoRA without implementing what they require.
  6. Testing one request alone and never in a batch.

10. Hands-on exercise#

  1. Run rowparallel.go. Change tp to 2 and to 8. How many numbers does each rank hold? What constraint must dIn satisfy?
  2. 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.
  3. Pick a model you use, find its architectures string in config.json, then the line in vllm/model_executor/models/registry.py that maps it to a class.
  4. Load a model with --model-impl transformers and with the native implementation. Compare startup time and output tokens per second.

11. Interview questions#

  1. Why does a vLLM model’s forward have no attention-mask argument?
  2. What are the two uses of the prefix constructor argument?
  3. When would you choose the Transformers modeling backend over writing a native vLLM model?
  4. How does a model get tensor parallelism without any communication code of its own?
  5. 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.

↑↓ navigate↵ openesc close

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