Gated DeltaNet layer

Gated DeltaNet

×

Each of 128 heads keeps a 128 × 128 memory that every position decays, updates by the delta rule and reads with its query.

Why

Gated delta. Linear attention keeps a memory of fixed size, and two mechanisms have been used to manage it: a gate, which can erase the memory quickly, and the delta rule, which changes one key’s entry precisely. The authors of Gated DeltaNet find them complementary and combine them in one rule. Gated Delta Networks §1

Decay alone forgets every association at the same rate; the delta rule alone replaces one pair at a time and cannot clear outdated content quickly, for instance when the context switches. Gated Delta Networks §1

Δattn=oWO\Delta_{\mathrm{attn}}=oW_{O}
All 22 steps
Prepare Q, K, V:\text{Prepare {\htmlClass{vl-stream-q}{Q}}, {\htmlClass{vl-stream-k}{K}}, {\htmlClass{vl-stream-v}{V}}:}
m=xattnWQKVm=x_{\mathrm{attn}}W_{QKV}
ct=SiLU⁡ ⁣(∑j=03wj⊙mt−j)c_t=\operatorname{SiLU}\!\Big(\sum_{j=0}^{3}w_j\odot m_{t-j}\Big)
qh=c1:2048{\htmlClass{vl-stream-q}{q^{\mathrm h}}}=c_{1:2048}
kh=c2049:4096{\htmlClass{vl-stream-k}{k^{\mathrm h}}}=c_{2049:4096}
V=c4097:20480{\htmlClass{vl-stream-v}{V}}=c_{4097:20480}
qr[h]=qh[⌊h/8⌋]{\htmlClass{vl-stream-q}{q^{\mathrm r}}}[h]={\htmlClass{vl-stream-q}{q^{\mathrm h}}}\big[\lfloor h/8\rfloor\big]
kr[h]=kh[⌊h/8⌋]{\htmlClass{vl-stream-k}{k^{\mathrm r}}}[h]={\htmlClass{vl-stream-k}{k^{\mathrm h}}}\big[\lfloor h/8\rfloor\big]
q^=qr/∥qr∥22+10−6\hat {\htmlClass{vl-stream-q}{q}}={\htmlClass{vl-stream-q}{q^{\mathrm r}}}/\sqrt{\lVert {\htmlClass{vl-stream-q}{q^{\mathrm r}}}\rVert_2^2+10^{-6}}
k^=kr/∥kr∥22+10−6\hat {\htmlClass{vl-stream-k}{k}}={\htmlClass{vl-stream-k}{k^{\mathrm r}}}/\sqrt{\lVert {\htmlClass{vl-stream-k}{k^{\mathrm r}}}\rVert_2^2+10^{-6}}
Decay gate:\text{Decay gate:}
a=xattnWaa=x_{\mathrm{attn}}W_{a}
α=exp⁡ ⁣(−eAsoftplus⁡(a+bΔ))\alpha=\exp\!\big(-e^{A}\operatorname{softplus}(a+b_{\Delta})\big)
Write gate:\text{Write gate:}
b=xattnWbb=x_{\mathrm{attn}}W_{b}
β=σ(b)\beta=\sigma(b)
S←α SS\leftarrow\alpha\,S
S←S+β k^ (v−S⊤k^)⊤S\leftarrow S+\beta\,\hat {\htmlClass{vl-stream-k}{k}}\,({\htmlClass{vl-stream-v}{v}}-S^{\top}\hat {\htmlClass{vl-stream-k}{k}})^{\top}
o~=S⊤q^/128\tilde o=S^{\top}\hat {\htmlClass{vl-stream-q}{q}}/\sqrt{128}
z=xattnWzz=x_{\mathrm{attn}}W_{z}
Gate, merge and project:\text{Gate, merge and project:}
og=RMSNorm⁡(o~)⊙SiLU⁡(z)o^{g}=\operatorname{RMSNorm}(\tilde o)\odot\operatorname{SiLU}(z)
Δattn=oWO\Delta_{\mathrm{attn}}=oW_{O}
in
xattnx_{\mathrm{attn}} [B batch, 1 position, 8192 d]
out
Δattn\Delta_{\mathrm{attn}} [B batch, 1 position, 8192 d]
Parameters438,387,072 × 69 layers

438,387,072 parameters per instance, across its learned components

ComponentCalculationParameters
Prepare Q, K, V167,854,080
Decay gate1,048,832
Write gate1,048,576
Output gate projection8,192 × 16,384134,217,728
Gate, merge and project134,217,856
Per-instance total438,387,072

One in each of the 69 GDN layers, each with its own weights.

Explanation

Prefill, and a first call with nothing kept, run the rule in its chunked form; a decoding step from the kept memory runs its recurrent form, one position (modeling_qwen3_5_moe.py 612–638).

Sources

In codeself.linear_attn · Qwen3_5MoeGatedDeltaNet

Open pinned code ↗

Direct evidence

Gated DeltaNet owns one projection to queries, keys and values (2 × 16 × 128 + 128 × 128 = 20,480 channels), one depthwise causal convolution over them without bias, a projection to the output gate z as wide as the values, one projection each to the write strength b and the decay a, one per value head, a per-head A_log and dt_bias, a gated RMSNorm over each value head and an output projection.

modeling_qwen3_5_moe.py 492–535 ↗ · huggingface/transformers @ 18329f106538

Excerpt
class Qwen3_5MoeGatedDeltaNet(nn.Module):
    def __init__(self, config: Qwen3_5MoeConfig, layer_idx: int):
        super().__init__()
        self.hidden_size = config.hidden_size
        self.num_v_heads = config.linear_num_value_heads
        self.num_k_heads = config.linear_num_key_heads
        self.head_k_dim = config.linear_key_head_dim
        self.head_v_dim = config.linear_value_head_dim
        self.key_dim = self.head_k_dim * self.num_k_heads
        self.value_dim = self.head_v_dim * self.num_v_heads

        self.conv_kernel_size = config.linear_conv_kernel_dim
        self.layer_idx = layer_idx
        self.activation = config.hidden_act
        self.layer_norm_epsilon = config.rms_norm_eps

        # QKV
        self.conv_dim = self.key_dim * 2 + self.value_dim
        self.conv1d = nn.Conv1d(
            in_channels=self.conv_dim,
            out_channels=self.conv_dim,
            bias=False,
            kernel_size=self.conv_kernel_size,
            groups=self.conv_dim,
            padding=self.conv_kernel_size - 1,
        )

        # time step projection (discretization)
        # instantiate once and copy inv_dt in init_weights of PretrainedModel
        self.dt_bias = nn.Parameter(torch.ones(self.num_v_heads))

        # Lower bound kept away from 0 so log(A) never becomes -inf
        A = torch.empty(self.num_v_heads).uniform_(0.01, 16)
        self.A_log = nn.Parameter(torch.log(A))

        self.norm = Qwen3_5MoeRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
        self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)

        self.layer_type = config.layer_types[layer_idx]

        self.in_proj_qkv = nn.Linear(self.hidden_size, self.key_dim * 2 + self.value_dim, bias=False)
        self.in_proj_z = nn.Linear(self.hidden_size, self.value_dim, bias=False)
        self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
        self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)

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 kernel’s output passes the gated RMSNorm, gated by z, head by head, is flattened and projected to the model width.

modeling_qwen3_5_moe.py 644–651 ↗ · huggingface/transformers @ 18329f106538

Excerpt
        # reshape input data into 2D tensor
        core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
        z = z.reshape(-1, self.head_v_dim)
        core_attn_out = self.norm(core_attn_out, z)
        core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)

        output = self.out_proj(core_attn_out)
        return output

The gated delta rule per head, one position at a time: queries and keys optionally L2-normalised, queries divided by √d_k; the state is multiplied by exp(g), the write is β times the key times the difference between the value and what the state returns for the key, and the output reads the updated state with the query; in float32.

modeling_qwen3_5_moe.py 426–485 ↗ · huggingface/transformers @ 18329f106538

Excerpt
def torch_recurrent_gated_delta_rule(
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    g: torch.Tensor,
    beta: torch.Tensor,
    initial_state: torch.Tensor | None = None,
    output_final_state: bool = False,
    use_qk_l2norm_in_kernel: bool = False,
    **kwargs,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Computes linear attention using the gated delta rule, by iterating over each token in the sequence dimension.
    Same args and return value as torch_chunk_gated_delta_rule, except for `chunk_size` because the sequence dim is not
    chunked."""
    initial_dtype = query.dtype
    batch_size, sequence_length, _, k_head_dim = key.shape
    num_v_heads, v_head_dim = value.shape[-2:]
    decay = g  # rename for clarity: argument name must stay "g" to match flash_linear_attention's API

    # Make sure all tensors are fp32 and reshape them to [batch_size, num_*_heads, seqlen, ...]
    query, key, value, beta, decay = [
        x.transpose(1, 2).to(torch.float32, memory_format=torch.contiguous_format)
        for x in (query, key, value, beta, decay)
    ]
    # If enabled, normalize query and key vectors (done once in fp32 for better accuracy)
    if use_qk_l2norm_in_kernel:
        query = l2norm(query, dim=-1, eps=1e-6)
        key = l2norm(key, dim=-1, eps=1e-6)

    # And always normalize queries by the head dimension
    query = query / (query.shape[-1] ** 0.5)

    # Create the storage for the last recurrent state, which will be updated in place. If a previous state is provided,
    # it is the starting point, otherwise start with a zeroed buffer.
    if initial_state is None:
        recurrent_state_shape = (batch_size, num_v_heads, k_head_dim, v_head_dim)
        last_recurrent_state = torch.zeros(recurrent_state_shape, dtype=value.dtype, device=value.device)
    else:
        last_recurrent_state = initial_state.to(value)
    core_attn_out = torch.zeros_like(value)

    # Loop over each token and update the recurrent state
    for i in range(sequence_length):
        q_t, k_t, v_t = query[:, :, i], key[:, :, i], value[:, :, i]
        # Decay the recurrent state
        decay_t = decay[:, :, i].exp()[..., None, None]
        last_recurrent_state = last_recurrent_state * decay_t
        # Update the recurrent state with the current token
        beta_t = beta[:, :, i].unsqueeze(-1)
        kv_mem = (last_recurrent_state * k_t.unsqueeze(-1)).sum(dim=-2)
        delta = (v_t - kv_mem) * beta_t
        last_recurrent_state = last_recurrent_state + k_t.unsqueeze(-1) * delta.unsqueeze(-2)
        # And use it to compute the attention output for the current token
        core_attn_out[:, :, i] = (last_recurrent_state * q_t.unsqueeze(-1)).sum(dim=-2)

    # Discard the final state if not requested
    last_recurrent_state = None if not output_final_state else last_recurrent_state
    # Convert back to the original shape [batch_size, sequence_length, num_v_heads, v_head_dim] and dtype
    core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
    return core_attn_out, last_recurrent_state