Gated attention

Repeat key heads

×

Copy each of the 4 key heads to the 16 query heads of its group.

KG[h]=K[⌊h/16⌋]{\htmlData{light=keys-grouped k-repeat}{{\htmlClass{vl-stream-k}{K_{\mathrm G}}}}}[h]={\htmlData{light=keys}{{\htmlClass{vl-stream-k}{K}}}}\big[\lfloor h/16\rfloor\big]
in
KK [B batch, 4 heads, T positions, 256 d_h]
out
KGK_{\mathrm G} [B batch, 64 heads, T positions, 256 d_h]

Heads are counted from zero: query heads 16h to 16h + 15 read key and value head h (modeling_qwen3_5_moe.py 700–709). The repeat follows the cache, so the cache holds 4 heads.

Sources

In coderepeat_kv(key, module.num_key_value_groups) · 722

Open pinned code ↗

Direct evidence

The eager attention: keys and values repeated from the key–value heads to the query heads, scores scaled, the mask added when given, softmax in float32, values mixed by the weights.

modeling_qwen3_5_moe.py 700–734 ↗ · huggingface/transformers @ 18329f106538

Excerpt
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
    """
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    """
    batch, num_key_value_heads, slen, head_dim = hidden_states.shape
    if n_rep == 1:
        return hidden_states
    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)


def eager_attention_forward(
    module: nn.Module,
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    attention_mask: torch.Tensor | None,
    scaling: float,
    dropout: float = 0.0,
    **kwargs: Unpack[TransformersKwargs],
):
    key_states = repeat_kv(key, module.num_key_value_groups)
    value_states = repeat_kv(value, module.num_key_value_groups)

    attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
    if attention_mask is not None:
        attn_weights = attn_weights + attention_mask

    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
    attn_output = torch.matmul(attn_weights, value_states)
    attn_output = attn_output.transpose(1, 2).contiguous()

    return attn_output, attn_weights