Prepare Q, K, V

Take the gate

×

Each head’s last 256 features are its gate; the heads are joined again into 16,384 features.

gh=[ q  g ]h, 257:512{\htmlData{light=gate gate-split}{g_h}}=[\,{\htmlClass{vl-stream-q}{q}}\;{\htmlData{light=gate gate-split}{g}}\,]_{h,\,257:512}
in
[ q  g ][\,q\;g\,] [B batch, 1 position, 32768 heads × (query + gate)]
out
gg [B batch, 1 position, 16384 heads × d_h]
Sources

In codegate.reshape(*input_shape, -1) · 777–780

Open pinned code ↗

Direct evidence

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