Prepare Q, K, V

Kept inputs

×

state · kept between calls

The last 4 inputs of the short convolution, kept between forward calls.

shape
mm m [B batch, 20480 channels, 4 kept inputs]

Prefill keeps the last 4 of the prompt’s inputs for the next call, then runs the convolution over the prompt (modeling_qwen3_5_moe.py 573–588; cache_utils.py 1080–1118). 81,920 values, whatever the length of the sequence.

Sources

In codecache_params.layers[self.layer_idx].conv_states[0] · 563, 574–576

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]

The input is masked for padding, projected to the mixed queries, keys and values, to z, b and a; the mixed channels are convolved (with the kept inputs when decoding) and split into queries, keys and values, read as heads; β = sigmoid(b), g = −exp(A_log) · softplus(a + dt_bias) in float32; queries and keys are repeated to the value heads; the kernel runs recurrently for one new position with a cache and chunked otherwise, with the L2 normalisation of queries and keys inside it; the recurrent state is kept.

modeling_qwen3_5_moe.py 538–642 ↗ · huggingface/transformers @ 18329f106538

Excerpt
    def forward(
        self,
        hidden_states: torch.Tensor,
        cache_params: Cache | None = None,
        attention_mask: torch.Tensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ):
        hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)

        # Set up dimensions for reshapes later
        batch_size, seq_len, _ = hidden_states.shape
        use_precomputed_states = cache_params is not None and cache_params.has_previous_state(
            self.layer_idx, state_idx=0
        )

        mixed_qkv = self.in_proj_qkv(hidden_states)
        mixed_qkv = mixed_qkv.transpose(1, 2)

        z = self.in_proj_z(hidden_states)
        z = z.reshape(batch_size, seq_len, -1, self.head_v_dim)

        b = self.in_proj_b(hidden_states)
        a = self.in_proj_a(hidden_states)

        if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past:
            conv_state = cache_params.layers[self.layer_idx].conv_states[0]
            # Single-token cached decode: the fused per-step kernel updates the conv state in-place.
            mixed_qkv = causal_conv1d_update(
                mixed_qkv,
                conv_state,
                self.conv1d.weight.squeeze(1),
                self.conv1d.bias,
                self.activation,
            )
        else:
            if cache_params is not None:
                mixed_qkv = cache_params.update_conv_state(
                    mixed_qkv, self.layer_idx, conv_kernel_size=self.conv_kernel_size
                )

            mixed_qkv = causal_conv1d_fn(
                mixed_qkv,
                self.conv1d.weight.squeeze(1),
                self.conv1d.bias,
                activation=self.activation,
                **kwargs,
            )

            # Drop the additional previous states
            if cache_params is not None:
                mixed_qkv = mixed_qkv[:, :, -seq_len:]

        mixed_qkv = mixed_qkv.transpose(1, 2)
        query, key, value = torch.split(
            mixed_qkv,
            [
                self.key_dim,
                self.key_dim,
                self.value_dim,
            ],
            dim=-1,
        )

        query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
        key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
        value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)

        beta = b.sigmoid()
        # If the model is loaded in fp16, without the .float() here, A might be -inf
        g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
        if self.num_v_heads // self.num_k_heads > 1:
            query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
            key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)

        recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None
        if use_precomputed_states and seq_len == 1:
            core_attn_out, last_recurrent_state = torch_recurrent_gated_delta_rule(
                query,
                key,
                value,
                g=g,
                beta=beta,
                initial_state=recurrent_state,
                output_final_state=cache_params is not None,
                use_qk_l2norm_in_kernel=True,
                cu_seqlens=kwargs.pop("cu_seq_lens_q", None),
                **kwargs,
            )
        else:
            core_attn_out, last_recurrent_state = torch_chunk_gated_delta_rule(
                query,
                key,
                value,
                g=g,
                beta=beta,
                initial_state=recurrent_state,
                output_final_state=cache_params is not None,
                use_qk_l2norm_in_kernel=True,
                cu_seqlens=kwargs.pop("cu_seq_lens_q", None),
                **kwargs,
            )

        # Update cache
        if cache_params is not None:
            cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)

The causal convolution: over a whole sequence a depthwise conv1d padded by kernel − 1 on the left and cut to the sequence; for one new position with a cache, the kept inputs move up by one, the new input goes last, and the convolution is taken over them; SiLU after either.

modeling_qwen3_5_moe.py 238–277 ↗ · huggingface/transformers @ 18329f106538

Excerpt
def causal_conv1d_update(
    hidden_states: torch.Tensor,
    conv_state: torch.Tensor,
    weight: nn.Parameter,
    bias: nn.Parameter | None = None,
    activation: str | None = None,
):
    _, hidden_size, seq_len = hidden_states.shape
    state_len = conv_state.shape[-1]

    hidden_states_new = torch.cat([conv_state, hidden_states], dim=-1).to(weight.dtype)
    conv_state.copy_(hidden_states_new[:, :, -state_len:])
    out = F.conv1d(hidden_states_new, weight.unsqueeze(1), bias, padding=0, groups=hidden_size)
    out = out[:, :, -seq_len:]
    if activation is not None:
        out = ACT2FN[activation](out)
    return out.to(hidden_states.dtype)


@use_kernel_func_from_hub_with_fallback("causal_conv1d_fn", "causal_conv1d")
def causal_conv1d_fn(
    hidden_states: torch.Tensor,
    weight: nn.Parameter,
    bias: nn.Parameter | None = None,
    activation: str | None = None,
    **kwargs,
):
    _, hidden_size, seq_len = hidden_states.shape
    padding = weight.shape[-1] - 1

    out = F.conv1d(
        hidden_states.to(weight.dtype),
        weight=weight.unsqueeze(1),
        bias=bias,
        padding=padding,
        groups=hidden_size,
    )[:, :, :seq_len]
    if activation is not None:
        out = ACT2FN[activation](out)
    return out.to(hidden_states.dtype)