Prepare Q, K, V

Query and gate projection

×

Map the input to 64 heads of 256 query and 256 gate features.

[ q  g ]=xattnWQ[\,{\htmlClass{vl-stream-q}{q}}\;{\htmlData{light=gate-split}{g}}\,]={\htmlData{light=x}{x_{\mathrm{attn}}}}W_{{\htmlClass{vl-stream-q}{Q}}}
in
xattnx_{\mathrm{attn}} [B batch, 1 position, 8192 d]
out
[ q  g ][\,q\;g\,] [B batch, 1 position, 32768 heads × (query + gate)]
Parameters268,435,456 × 23 layers

268,435,456 parameters per instance.

ComponentCalculationParameters
Weight matrix8,192 × 32,768268,435,456

This projection has no bias parameter.

The reference module holds the weight output by input, [out, in].

One in each of the 23 attention layers, each with its own weights.

Sources

In codeself.q_proj(hidden_states) · 778

Open pinned code ↗

Direct evidence

Gated attention owns a query projection twice as wide as the query heads (queries and gate), key and value projections to the key–value heads, an output projection, and RMSNorms over each query and key head; scaling is head_dim^−0.5.

modeling_qwen3_5_moe.py 737–764 ↗ · huggingface/transformers @ 18329f106538

Excerpt
class Qwen3_5MoeAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""

    def __init__(self, config: Qwen3_5MoeConfig, layer_idx: int):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
        self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
        self.scaling = self.head_dim**-0.5
        self.attention_dropout = config.attention_dropout
        self.is_causal = True
        self.q_proj = nn.Linear(
            config.hidden_size, config.num_attention_heads * self.head_dim * 2, bias=config.attention_bias
        )
        self.k_proj = nn.Linear(
            config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
        )
        self.v_proj = nn.Linear(
            config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
        )
        self.o_proj = nn.Linear(
            config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
        )
        self.q_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)  # unlike olmo, only on the head dim!
        self.k_norm = Qwen3_5MoeRMSNorm(
            self.head_dim, eps=config.rms_norm_eps
        )  # thus post q_norm does not need reshape

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