Skip to content

Qwen3.5: GB10 Atlas GDN layer ignores the renamed cache argument, so cached generation degenerates (default on main) #51543

Done

Description

@harheem

System Info

  • transformers version: 5.25.0.dev0 (953768968c63bf87295136251f9c0da29386a30e). The relevant files are byte-identical at b53bc453c22bd71ec7fa651ea4073c8ef223aa31:
    • hub_kernels.py, modeling_qwen3_5.py, cache_utils.py, generation/utils.py, modeling_utils.py and conversion_mapping.py.
  • Platform: Linux-7.0.0-1019-nvidia-aarch64-with-glibc2.39 (DGX Spark, NVIDIA GB10, SM121, driver 580.178.04)
  • Python 3.12.3, PyTorch 2.12.1+cu130 (CUDA 13.0), Triton 3.7.1, kernels==0.19.1, huggingface_hub==2.5.0, safetensors==0.8.0, accelerate==1.16.0
  • flash-linear-attention and causal-conv1d not installed
  • Using GPU in script?: yes, one GB10
  • Using distributed or parallel set-up in script?: no

Also reproduced on the 5.24.1 release with kernels==0.18.3, same GB10, torch and Triton:

transformers env (5.24.1)
  • transformers version: 5.24.1
  • Platform: Linux-7.0.0-1019-nvidia-aarch64-with-glibc2.39
  • Python version: 3.12.3
  • Huggingface_hub version: 2.5.0
  • Safetensors version: 0.8.0
  • Accelerate version: 1.16.0
  • Accelerate config: not found
  • DeepSpeed version: not installed
  • PyTorch version (accelerator?): 2.12.1+cu130 (CUDA)
  • Using distributed or parallel set-up in script?: no
  • Using GPU in script?: yes
  • GPU type: NVIDIA GB10

Who can help?

@Cyrilvallez (cache argument rename, #50585) @vasqu (kernels, use_kernels default, #47773)

Reproduction

Minimal reproducer. It needs no download and uses random weights with the 27B model's GDN head dimensions:

import torch
from transformers import Qwen3_5ForCausalLM, Qwen3_5TextConfig

config = Qwen3_5TextConfig(
    vocab_size=256, hidden_size=128, intermediate_size=256,
    num_attention_heads=2, num_key_value_heads=2, head_dim=64,
    linear_num_key_heads=16, linear_num_value_heads=48,
    linear_key_head_dim=128, linear_value_head_dim=128,
    num_hidden_layers=2, layer_types=["linear_attention", "full_attention"],
)
model = Qwen3_5ForCausalLM(config).to(device="cuda:0", dtype=torch.bfloat16).eval()
model.set_use_kernels(True, device_map={"": "cuda:0"})
ids = torch.arange(8, 40, device="cuda:0")[None, :]
with torch.inference_mode():
    cache = model(input_ids=ids, use_cache=True, logits_to_keep=1).cache
print(cache.get_conv_state(0) is not None, cache.get_recurrent_state(0) is not None)
print(cache.get_seq_length(layer_idx=1))
# GB10, Atlas layer:        False False / 32
# set_use_kernels(False):   True True  / 32

An extended script (below) also traces the arguments and compares a one-token cached step with a full recompute:

Path Conv state Recurrent state Max |Δlogit| cached vs full recompute
Atlas (default on SM121) absent absent 0.1104
Atlas, cache forwarded as cache_params present present 0.0
PyTorch reference (use_kernels=False) present present 0.0

The results were the same on 5.24.1.

repro_gdn_cache.py (run as-is, with --kernels-off, or with --atlas-cache-alias)
"""Probe Qwen3.5 GDN cache initialization on GB10 without model downloads."""

import argparse
from inspect import signature
import json
import sys

import torch
from transformers import Qwen3_5ForCausalLM, Qwen3_5TextConfig


def bind_atlas_cache(gdn):
    original = gdn.forward
    if "_gdn_run" not in original.__func__.__globals__:
        raise RuntimeError(f"Expected the Atlas layer, got {original.__module__}")

    def forward(hidden_states, cache=None, cache_params=None, **kwargs):
        return original(hidden_states, cache_params=cache if cache is not None else cache_params, **kwargs)

    gdn.forward = forward


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--kernels-off", action="store_true")
    parser.add_argument("--atlas-cache-alias", action="store_true")
    args = parser.parse_args()

    torch.manual_seed(17)
    config = Qwen3_5TextConfig(
        vocab_size=256, hidden_size=128, intermediate_size=256,
        num_attention_heads=2, num_key_value_heads=2, head_dim=64,
        linear_num_key_heads=16, linear_num_value_heads=48,
        linear_key_head_dim=128, linear_value_head_dim=128,
        num_hidden_layers=2, layer_types=["linear_attention", "full_attention"],
    )
    model = Qwen3_5ForCausalLM(config).to(device="cuda:0", dtype=torch.bfloat16).eval()
    device_kwarg = {"device_map": {"": "cuda:0"}} if "device_map" in signature(model.set_use_kernels).parameters else {}
    model.set_use_kernels(not args.kernels_off, **device_kwarg)
    gdn = model.model.layers[0].linear_attn
    kernel_module = gdn.forward.__module__
    if args.atlas_cache_alias:
        bind_atlas_cache(gdn)

    calls = set()
    phase = "prefill"

    def trace(frame, event, _):
        if event != "call" or frame.f_globals.get("__name__") != kernel_module:
            return
        local = frame.f_locals
        if frame.f_code.co_name == "forward" and local.get("self") is gdn:
            calls.add((phase, "forward", local.get("kwargs", {}).get("cache") is not None,
                       local.get("cache_params") is not None))
        if frame.f_code.co_name == "_gdn_run":
            calls.add((phase, "_gdn_run", local.get("cache_params") is not None))

    ids = torch.arange(8, 40, dtype=torch.long, device="cuda:0")[None, :]
    token = torch.tensor([[41]], dtype=torch.long, device="cuda:0")
    sys.setprofile(trace)
    try:
        with torch.inference_mode():
            output = model(input_ids=ids, use_cache=True, logits_to_keep=1)
            cache = output.cache
            initialized = {
                "conv": cache.get_conv_state(0, state_idx=0) is not None,
                "recurrent": cache.get_recurrent_state(0, state_idx=0) is not None,
                "full_attention_tokens": cache.get_seq_length(layer_idx=1),
            }
            phase = "decode"
            step = model(input_ids=token, cache=cache, use_cache=True, logits_to_keep=1).logits
            phase = "full recompute"
            full = model(input_ids=torch.cat((ids, token), dim=1), use_cache=False, logits_to_keep=1).logits
    finally:
        sys.setprofile(None)

    print(json.dumps({
        "kernel_module": kernel_module, "use_kernels": model.use_kernels,
        "atlas_cache_alias": args.atlas_cache_alias, "after_prefill": initialized,
        "calls": sorted(calls), "cached_top1": step.argmax().item(), "full_top1": full.argmax().item(),
        "max_abs_logit_difference": (step.float() - full.float()).abs().max().item(),
    }, indent=2))


if __name__ == "__main__":
    main()

Effect on a real checkpoint. Setup:

  • Qwen/Qwen3.6-27B @ 1cda14dd71a3f47115850eb790f416f165da1cb5.
  • The settings of the GB10 row in the Qwen3.5 docs: BF16, a 1,024-token prompt, 256 greedy tokens.
  • A fixed prompt, because the docs do not publish theirs.

What happens with the default Atlas mapping:

  • The GDN state stays empty in all 48 GDN layers.
  • Generation diverges at token 2 and degenerates:
Atlas (default):        <think>user:systemdés, the user.\n\nuser:systemdés, the user.\n\nuser:systemdés, the user. ... user:\n\nuser:\n\nuser: ...
PyTorch reference:      <think>\nHere's a thinking process:\n\n1.  **Analyze User Input:**\n   - **Input Data:** 30 cases of ...
  • With use_cache=False, the same Atlas build picks the reference's token 2 (ID 198 instead of 846).
  • Forwarding cache to cache_params fills all 48 layers with state and restores coherent output.

All runs were three repeats, and each path was deterministic across its repeats. A Qwen3.5-9B fine-tune showed the same pattern: 0/24 layers with state, divergence at token 2, and repetitive output.

Cause

#50585 renamed the argument the decoder layer passes. Qwen3_5DecoderLayer now calls self.linear_attn(..., cache=cache, ...). The pinned Atlas layer still declares forward(self, hidden_states, cache_params=None, attention_mask=None, **kwargs). That pin is Atlas-Inference/gdn@531ae679, the head of the v0 branch, added in #46423 and #49452. So cache lands in **kwargs, and _gdn_run receives cache_params=None in both prefill and decode.

flowchart TD
    A["Qwen3_5DecoderLayer<br/>self.linear_attn(..., cache=cache)"] --> B["Atlas Qwen3_5GatedDeltaNet.forward<br/>(hidden_states, cache_params=None, **kwargs)"]
    B -- "cache ends up in **kwargs" --> C["_gdn_run(..., cache_params=None)<br/>GDN conv / recurrent state never written"]
Loading

The newest Atlas build (v1 branch, f9704654, 2026-10-16) has the same signature. Bumping the pin alone would not fix it. The AMD Strix Halo (gfx1151) entry in the same mapping pins Atlas-Inference/gdn@13462bf5, and its layers.py has the same forward(self, hidden_states, cache_params=None, attention_mask=None, **kwargs) signature. I could not test on that hardware, but it likely has the same problem.

Since #47773, use_kernels defaults to True. So on main, every GB10 user with PyTorch 2.10–2.12 now gets this path from generate() without opting in. With other PyTorch versions there is no Atlas build, and the Hub function path is used instead.

Expected behavior

With caching enabled, GDN prefill should initialize the conv and recurrent states, and each decode step should consume and update them. The Atlas path should give the same tokens as use_cache=False.

Possible fixes:

  1. Atlas accepts cache and keeps cache_params as an alias for older Transformers, then the SM121 pin is bumped.
  2. Until such a build exists, drop the SM121 entry from the Qwen3_5GatedDeltaNet mapping. GB10 then uses the Hub function path that other PyTorch versions already use. On this machine that path keeps the state, matched use_cache=False over the checked prefix, and was also faster in prefill. I can share those numbers separately.
  3. Add a test that checks a cached continuation against a full recompute after kernelize. Such a test would have caught this signature drift.

Related: the GB10 row in the Qwen3.5 docs says Atlas greedy output matches PyTorch. That likely held before #50585 but does not on the current code.

Workaround for users: from_pretrained(..., use_kernels=False).

Activity

  1. vasqu commented on Dec 1, 2026

    @vasqu
    Collaborator

    cc @AzeezIsh if you could update the kernels

  2. vasqu commented on Dec 2, 2026

    @vasqu
    Collaborator

    Temporarily disabling those kernels until they are fixed

  3. AzeezIsh commented on Dec 3, 2026

    @AzeezIsh
    Contributor

    Updated both kernels: GB10 7f064fcd95d78738918f1f52894699e6566249c3 (v0) and Strix Halo 296e5199b15ea4f61458223ab3c38d85c5e68241 (v1, rebuilt with kernel-builder).

    Three different fixes layers.py:

    1. forward takes the renamed cache and still accepts cache_params.
    2. The kernels are inference-only, and a backward that reaches them now raises (eager and compiled) instead of silently dropping grads. model.train() falls back to the torch path, and every param gets its grad.
    3. Found while verifying: on decode we updated the conv state in place without cache.increase_count(), so get_seq_length() stayed at the prompt length. Manual cached-forward loops got stale RoPE positions, generate() wasn't affected.

    Re-enabled mapping to test on main f59525f, Qwen3.5-0.8B and 4B, on GB10 and gfx1151. Against an FP32 torch run, prefill and decode accuracy matches the torch BF16 path, torch.compile matches eager, and backward raises.

    PR to re-enable: #51665

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions