Skip to content

[Transformers backend] Give each pass of a looped model its own KV cache - #69836

Open
lucamotz wants to merge 1 commit into
vllm-project:mainfrom
lucamotz:tfb-looped-models
Open

lucamotz wants to merge 1 commit into
vllm-project:mainfrom
lucamotz:tfb-looped-models

Conversation

@lucamotz

@lucamotz lucamotz commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Looped models run their shared-weight layers more than once per forward pass, with a KV cache per pass: the attention module adds an offset argument to self.layer_idx for the cache layer it writes. The Transformers backend creates one vLLM attention layer per attention module, so all passes share one KV cache and the output is wrong from the second forward pass on, without an error. This PR creates one attention layer per cache layer and gives each call its own.

This affects the native Nanbeige4.2 class proposed in huggingface/transformers#50608, which is not merged yet. Today's path, the Hub remote code with trust_remote_code, is unaffected. No open PR or issue covers looped models in this backend.

Claims

  • With the native Nanbeige class, greedy output matches Transformers; on main it diverges at the first or second token.
  • Models whose attention forward does not add an argument to self.layer_idx take the same path as before.

Validation

On GB10 (bf16, Nanbeige4.2-3B), greedy output with the native class matches Transformers for 32/32 tokens on 3 prompts in eager, compiled + CUDA graph, prefix-cache and chunked-prefill runs, and GSM8K (first 200 questions) goes from 0.005 on main to 0.93 (0.91 with the Hub remote code). test_looped_model fails on main and passes with this PR; the rest of test_backend.py gives the same results with and without it.

The native class in these runs is my Nanbeige implementation, posted as suggestions in my review on huggingface/transformers#50608, not that PR's head aa124f9044. Both pass the same cache_offset argument to the attention.

Reproducer and parity (GB10, Nanbeige4.2-3B, bf16)

Reproducer: this PR's pytest tests/models/transformers/test_backend.py -k looped_model with main's backend and a Transformers that has my Nanbeige implementation. It stops at the layer count; the output divergence is in the table below.

>           assert counts == [num_layers * num_loops] * tp_size
E           assert [22] == [44]
FAILED tests/models/transformers/test_backend.py::test_looped_model

Runs, against Transformers native greedy (generate, bf16) on the same GPU:

llm = LLM("Nanbeige/Nanbeige4.2-3B", revision="b82e54bd60", model_impl="transformers", dtype="bfloat16",
          max_model_len=4096, enforce_eager=True)  # or False; chunked prefill: max_num_batched_tokens=32, max_num_seqs=8
llm.generate([{"prompt_token_ids": ids} for ids in prompts], SamplingParams(temperature=0, max_tokens=32, logprobs=1))
# prefix-cache hits: the same generate a second time on the same engine

Prompts: chat (47 tokens), code (20), and both with another chat turn (114). Transformers main ab014e21c5 with my Nanbeige implementation (models/nanbeige/ identical to the suggestions in my review). huggingface/transformers#50608 at aa124f9044 uses the same contract: its attention writes cache layer self.layer_idx + cache_offset, with cache_offset = loop_idx * num_layers. Not run yet with that head. vLLM a87e3a6554 with #66840, with main's Transformers backend package (b321d66fc8; no backend changes on main since) or this PR's (e331b330d), plus three files from main that the package needs on that base: transformers_utils/dynamic_module.py, multimodal/utils.py, and compilation/wrapper.py with d2da27e. The table gives the first differing token (0-based) of 32.

run attention layers chat code long
main, eager 22 1 1 1
main, compiled + CUDA graphs 22 1 1 1
main, second generate (prefix-cache hits) 22 1 1 0
main, chunked prefill (32-token budget) 22 0 1 0
this PR, each of the four runs above 44 32/32 identical 32/32 32/32
trust_remote_code (Hub code), compiled, main and this PR 44 32/32 32/32 32/32

Chat prompt, eager:

main:    "We're\nWe -  to� . . . . . ., it . ., sli . ., sli {,$9,$ \n HEL ., rac"
this PR: 'We are asked: "Which number is bigger, 9.11 or 9.8?" This seems straightforward, but we need to be careful about'

Max |Δ logprob| over the matched tokens with this PR: 0.153 (bf16). The compiled run also passes with VLLM_GPU_SYNC_CHECK=error (32/32 identical). The attention layers are named after their cache layer: model.layers.0.self_attn.attn, model.layers.22.self_attn.attn, ..., model.layers.43.self_attn.attn.

GSM8K (GB10, Nanbeige4.2-3B, bf16)

First 200 test questions of openai/gsm8k (revision 740312add8), zero-shot llm.chat with "Please reason step by step, and put your final answer within \boxed{}.", greedy, max_tokens=3072, compiled + CUDA graphs; scored on the last \boxed{} (else the last number).

run correct accuracy hit max_tokens
main, native class 1/200 0.005 8
this PR (e331b330d), native class 186/200 0.93 20
this PR, trust_remote_code (Hub code) 182/200 0.91 19

The native and Hub-code runs agree on 190 of the 200 verdicts. Summary lines:

# main
{"kwargs": {"dtype": "bfloat16", "gpu_memory_utilization": 0.4, "max_model_len": 4096, "seed": 0, "model_impl": "transformers", "enforce_eager": false}, "dataset_revision": "740312add88f781978c0658806c59bc2815b9866", "n": 200, "accuracy": 0.005, "correct": 1, "truncated": 8, "seconds": 275.2}
# this PR
{"kwargs": {"dtype": "bfloat16", "gpu_memory_utilization": 0.4, "max_model_len": 4096, "seed": 0, "model_impl": "transformers", "enforce_eager": false}, "dataset_revision": "740312add88f781978c0658806c59bc2815b9866", "n": 200, "accuracy": 0.93, "correct": 186, "truncated": 20, "seconds": 449.9}
# this PR, Hub code
{"kwargs": {"dtype": "bfloat16", "gpu_memory_utilization": 0.4, "max_model_len": 4096, "seed": 0, "model_impl": "transformers", "enforce_eager": false, "trust_remote_code": true}, "dataset_revision": "740312add88f781978c0658806c59bc2815b9866", "n": 200, "accuracy": 0.91, "correct": 182, "truncated": 19, "seconds": 450.3}
Tests

GB10, same environment as above.

pytest tests/models/transformers/test_backend.py -v --durations=0 -k looped_model    # main's backend
>           assert counts == [num_layers * num_loops] * tp_size
E           assert [22] == [44]
FAILED tests/models/transformers/test_backend.py::test_looped_model
================ 1 failed, 47 deselected, 2 warnings in 41.40s =================

pytest tests/models/transformers/test_backend.py -v --durations=0                    # this PR at e331b330d
tests/models/transformers/test_backend.py::test_looped_model PASSED [ 16%]
139.19s call     tests/models/transformers/test_backend.py::test_looped_model
====== 9 failed, 37 passed, 2 skipped, 63 warnings in 1398.22s (0:23:18) =======

pytest tests/models/transformers/test_backend.py -v --durations=0                    # main's backend
====== 10 failed, 36 passed, 2 skipped, 63 warnings in 1409.41s (0:23:29) ======

The 9 failing tests are the same with and without this PR and fail for environment reasons: gated meta-llama repos (2), no sentence_transformers (1), a vLLM core older than main (_mark_tower_model(auto_offload=...), MTP for multimodal models; 5), and a test subprocess that imports the unbuilt checkout (_C_stable_libtorch; 1). Multimodal models end to end with this PR: not run yet.

Details

Decisions for maintainers:

  1. This PR adds generic support (+133/−22 lines in the backend). The smaller alternative is a guard that raises for looped models until a released Transformers has one the backend can serve.
  2. The offsets are found by a one-token forward pass of a meta-device copy of the model at init, only for models whose attention forward adds an argument to self.layer_idx. The model's forward computes them. total_num_hidden_layers (my Nanbeige implementation, Inkling2-loop) gives the number of cache layers but not which module serves which, and Dory, HRM-Text and Add Nanbeige4.2-3B huggingface/transformers#50608 do not have it.
  3. test_looped_model skips until vLLM's Transformers pin has the native Nanbeige class, so CI covers this from then on. Merge now, or with that bump.
Design
  • The looped models in Transformers agree only on the attention side: an int argument added to self.layer_idx gives the call's cache layer. The name differs (cache_offset in Dory, Inkling2-loop and both Nanbeige implementations, cycle_offset in HRM-Text), and so does the layout. The backend finds the argument in the attention forward's source, and each module's offsets from the meta forward pass, with vLLM's attention interface, which builds no masks.
  • Each extra attention layer is named after its cache layer (the layer index replaced by the cache index), which is the virtual layer index the native Dory, LoopCoder and HRM-Text models use. A looped module holds its layers in a ModuleDict keyed by offset, and a forward pre-hook passes the call's layer to the attention interface in kwargs.
Limitations
  • Pipeline parallelism raises a ValueError for looped models. The PP ✅︎ in the Nanbeige row of the supported models table describes the Hub remote code path; I'll update the row with the pin bump that brings the native class.
  • Checkpoint KV-cache scales are not mapped to a looped module's attention layers: the scale names resolve to the ModuleDict, so the loader drops them and the layers keep a scale of 1.0.
  • Not run yet with a looped model: TP > 1, Eagle-3 and draft models, KV connectors.
  • Loops that read another pass's cache instead of writing their own (Dory's last_loop mode) are not handled. No model the backend can serve uses one.
  • The other looped Transformers models cannot be served with or without this PR. HRM-Text: on main its two stacks share layer indices (Layer 0 dispatches attention from more than one module); with this PR the offset pass raises a broadcast error, because its gate multiplies the attention output before the reshape. Dory and Inkling2-loop: vLLM loads its own config classes for them (DoryConfig, Inkling2LoopMMConfig), and loading fails the same way on main and with this PR.

Pull Request Checklist
  • I used vLLM's /pr-checklist skill. (Mandatory for agents, optional for humans).

  • AI assistance was used during the creation of this PR.

  • Design Fit: Minimizes impact on core components, reuses existing functionality, and justifies added complexity.

  • Testing and Validation: Validates the change and ensures any added tests are meaningful and reliable, with CI coverage or documented CI resource constraints and validation performed outside CI.

  • Code Quality and Style: Keeps code and comments clear and concise, and updates relevant documentation and examples.

  • Pull Request Contents: Includes a brief summary and relevant links, supports claims with evidence, explains root causes and implementation trade-offs, and follows the contributing guide.

I used Claude Code for parts of this implementation.

🤖 Generated with Claude Code

Looped models (e.g. Nanbeige4.2) run shared-weight layers more than once per
forward pass, and each pass writes its own cache layer: the attention module
adds an offset argument to `self.layer_idx`. The backend attached one vLLM
attention layer per module, so all passes shared one KV cache.

Find the offset argument in the attention forward and, only for models that
have one, each module's offsets with a one-token forward pass of a meta-device
copy of the model. Create one vLLM attention layer per cache layer, selected
per call by a forward pre-hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luca Motz <luca.motz@icloud.com>
@mergify

mergify Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Documentation preview: https://vllm--69836.org.readthedocs.build/en/69836/

@mergify mergify Bot added the documentation Improvements or additions to documentation label Nov 25, 2026
@lucamotz

Copy link
Copy Markdown
Contributor Author

fyi @hmellor

@lucamotz
lucamotz marked this pull request as ready for review November 25, 2026 07:43
@lucamotz
lucamotz requested a review from hmellor as a code owner November 25, 2026 07:43

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

Development

Successfully merging this pull request may close these issues.

1 participant