Gated attention

Key cache

×

state · kept between calls

The keys of every key–value head and position so far, kept between forward calls.

shape
kk k [B batch, 4 kv heads, 1001 cached positions, 256 d_h]

This call makes the new token’s keys and hands them to the cache, which returns all 1,001 positions for the scores. With the value cache, a layer keeps 4 heads of 256 key and 256 value features per position, 2,048 values, before the heads are repeated to the 64 query heads, and grows by that much with every token. A Gated DeltaNet layer keeps 2,179,072 values whatever the length: from 1,065 positions on, this layer’s cache holds more values. The cache has no fixed size; the slider stops at the configuration’s 262,144 positions (max_position_embeddings), which the code does not enforce.

Sources

In codepast_key_values.update(key_states, value_states, self.layer_idx) · 789–790; self.keys · cache_utils.py

Open pinned code ↗

Contextual evidence

A linear-attention layer’s cache keeps a convolution state of the last kernel inputs and a recurrent state, both of fixed size, updated in place.

cache_utils.py 1046–1134 ↗ · huggingface/transformers @ 18329f106538

Excerpt
class LinearAttentionLayer(LinearAttentionCacheLayerMixin):
    def lazy_initialization(
        self,
        conv_states: torch.Tensor | None = None,
        recurrent_states: torch.Tensor | None = None,
        state_idx: int = 0,
        conv_kernel_size: int | None = None,
    ) -> None:
        if conv_states is not None:
            if self.device is None:
                self.dtype, self.device = conv_states.dtype, conv_states.device
            # Even if prefill is larger/shorter than the conv_size, the tensor is usually either padded or truncated, except if
            # self.record_past is true and conv_kernel_size is provided explicitly
            conv_kernel_size = conv_states.shape[-1] if conv_kernel_size is None else conv_kernel_size
            self.conv_kernel_size[state_idx] = conv_kernel_size
            # The shape is always static, so we init as such
            self.conv_states[state_idx] = torch.zeros(
                (*conv_states.shape[:-1], conv_kernel_size),
                dtype=conv_states.dtype,
                device=conv_states.device,
            )
            # Mark as static address to be able to use cudagraphs
            if not is_torchdynamo_compiling() and not self.record_past:
                torch._dynamo.mark_static_address(self.conv_states[state_idx])
            self.is_conv_states_initialized[state_idx] = True

        if recurrent_states is not None:
            # The shape is always static, so we init as such
            self.recurrent_states[state_idx] = torch.zeros_like(recurrent_states)
            # Mark as static address to be able to use cudagraphs
            if not is_torchdynamo_compiling():
                torch._dynamo.mark_static_address(self.recurrent_states[state_idx])
            self.is_recurrent_states_initialized[state_idx] = True

    def update_conv_state(
        self, conv_states: torch.Tensor, state_idx: int = 0, conv_kernel_size: int | None = None, **kwargs
    ) -> torch.Tensor:
        """
        Update the linear attention cache in-place, and return the necessary conv states.

        Args:
            conv_states (`torch.Tensor`): The new conv states to cache.

        Returns:
            `torch.Tensor`: The updated conv states.
        """
        # Lazy initialization
        if not self.is_conv_states_initialized[state_idx]:
            self.lazy_initialization(conv_states=conv_states, state_idx=state_idx, conv_kernel_size=conv_kernel_size)

        # This is prefill, simply pad the conv_states if necessary
        if not self.has_previous_state[state_idx]:
            full_conv_states = conv_states
            self.has_previous_state[state_idx] = True
            # In this case, need to pad it to fit the conv_kernel_size
            if not self.record_past and full_conv_states.shape[-1] < self.conv_kernel_size[state_idx]:
                padding_length = self.conv_kernel_size[state_idx] - full_conv_states.shape[-1]
                full_conv_states = torch.nn.functional.pad(full_conv_states, (padding_length, 0), value=0)
        # We need to return the concatenation of the current state and the full new one so that the causal conv can see the
        # correct left context - however we usually cache only the last part
        else:
            full_conv_states = torch.cat([self.conv_states[state_idx], conv_states], dim=-1)

        # Usually, keep only the last `conv_kernel_size` tokens
        if not self.record_past:
            # Copy instead of assigning to keep the static address
            self.conv_states[state_idx].copy_(full_conv_states[..., -self.conv_kernel_size[state_idx] :])
        # If we need to record the past, keep the full states for now to be able to rollback later
        else:
            self.conv_states[state_idx] = full_conv_states

        # Return full states no matter what
        return full_conv_states

    def update_recurrent_state(self, recurrent_states: torch.Tensor, state_idx: int = 0, **kwargs) -> torch.Tensor:
        """
        Update the linear attention cache in-place, and return the necessary ssm states.

        Args:
            smm_states (`torch.Tensor`): The new ssm states to cache.

        Returns:
            `torch.Tensor`: The updated ssm states.
        """
        if not self.is_recurrent_states_initialized[state_idx]:
            self.lazy_initialization(recurrent_states=recurrent_states, state_idx=state_idx)
        # Note that we copy instead of assigning, to preserve the static address for cudagraphs
        self.recurrent_states[state_idx].copy_(recurrent_states)
        return self.recurrent_states[state_idx]

A full_attention layer’s cache is a DynamicLayer, which grows with every position; a linear_attention layer’s is a LinearAttentionLayer.

cache_utils.py 1265–1273 ↗ · huggingface/transformers @ 18329f106538

Excerpt
    "full_attention": DynamicLayer,
    # From a cache point of view, sliding and chunked are the same in how they should behave, only the mask differs
    "sliding_attention": DynamicSlidingWindowLayer,
    "chunked_attention": DynamicSlidingWindowLayer,
    "indexed_attention": DynamicIndexedLayer,
    # Linear-attention-shaped placeholders (no per-token KV; recurrent state only).
    # "conv" reuses the same cache shape as linear attention but stores a conv state buffer rather than recurrent SSM state
    "conv": LinearAttentionLayer,
    "linear_attention": LinearAttentionLayer,

The query projection is read per head and split in two halves, queries and gate; queries and keys are RMS-normalised per head and rotated; keys and values go to the cache; after attention the heads are flattened, multiplied by the sigmoid of the gate and projected.

modeling_qwen3_5_moe.py 766–811 ↗ · huggingface/transformers @ 18329f106538

Excerpt
    def forward(
        self,
        hidden_states: torch.Tensor,
        position_embeddings: tuple[torch.Tensor, torch.Tensor],
        attention_mask: torch.Tensor | None,
        past_key_values: Cache | None = None,
        **kwargs: Unpack[FlashAttentionKwargs],
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        input_shape = hidden_states.shape[:-1]
        hidden_shape = (*input_shape, -1, self.head_dim)

        query_states, gate = torch.chunk(
            self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
        )
        gate = gate.reshape(*input_shape, -1)

        query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
        key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)

        cos, sin = position_embeddings
        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)

        if past_key_values is not None:
            key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)

        attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
            self.config._attn_implementation, eager_attention_forward
        )

        attn_output, attn_weights = attention_interface(
            self,
            query_states,
            key_states,
            value_states,
            attention_mask,
            dropout=0.0 if not self.training else self.attention_dropout,
            scaling=self.scaling,
            **kwargs,
        )

        attn_output = attn_output.reshape(*input_shape, -1).contiguous()
        attn_output = attn_output * torch.sigmoid(gate)

        attn_output = self.o_proj(attn_output)
        return attn_output, attn_weights

The released configuration: 92 layers of width 8,192 whose layer_types are three linear_attention layers then one full_attention layer, 23 times; Gated DeltaNet with 16 key heads and 128 value heads of 128 and a convolution kernel of 4; 64 query and 4 key–value heads of 256 with an output gate and RoPE on a quarter of each head (θ 10,000,000); 512 experts of 2,048 of which 10 are used, and a shared expert of 2,048; SiLU; RMSNorm ε 10⁻⁶; vocabulary 248,320; untied output head.

config.json 1–142 ↗ · Qwen/Qwen3.8-2.4T-A95B @ 207bd685a7e3

Excerpt
{
    "architectures": [
        "Qwen3_5MoeForCausalLM"
    ],
    "attention_bias": false,
    "attention_dropout": 0.0,
    "attn_output_gate": true,
    "bos_token_id": 248044,
    "dtype": "bfloat16",
    "eos_token_id": 248044,
    "full_attention_interval": 4,
    "head_dim": 256,
    "hidden_act": "silu",
    "hidden_size": 8192,
    "initializer_range": 0.02,
    "layer_types": [
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention",
        "linear_attention",
        "linear_attention",
        "linear_attention",
        "full_attention"
    ],
    "linear_conv_kernel_dim": 4,
    "linear_key_head_dim": 128,
    "linear_num_key_heads": 16,
    "linear_num_value_heads": 128,
    "linear_value_head_dim": 128,
    "mamba_ssm_dtype": "float32",
    "max_position_embeddings": 262144,
    "model_type": "qwen3_5_moe_text",
    "moe_intermediate_size": 2048,
    "mtp_num_hidden_layers": 1,
    "mtp_use_dedicated_embeddings": false,
    "num_attention_heads": 64,
    "num_experts": 512,
    "num_experts_per_tok": 10,
    "num_hidden_layers": 92,
    "num_key_value_heads": 4,
    "output_gate_type": "swish",
    "output_router_logits": false,
    "pad_token_id": null,
    "partial_rotary_factor": 0.25,
    "rms_norm_eps": 1e-06,
    "rope_parameters": {
        "partial_rotary_factor": 0.25,
        "rope_theta": 10000000,
        "rope_type": "default"
    },
    "router_aux_loss_coef": 0.001,
    "shared_expert_intermediate_size": 2048,
    "tie_word_embeddings": false,
    "transformers_version": "4.57.3",
    "use_cache": true,
    "vocab_size": 248320
}