Merge, gate and project
×Join the 64 heads into 16,384 features, scale every feature by a sigmoid gate computed from the layer’s input, and map them back to the model width.
Why
After attention. A sigmoid gate after scaled dot-product attention, specific to each head and computed from the current token, consistently improves quality in the authors’ comparison of 30 gating variants; it also stabilizes training and tolerates larger learning rates. Gated Attention abstract, §1
Non-linear. The value and output projections of a head form one low-rank linear map; the gate puts a non-linearity between them. Gated Attention §4.1
Sparse. The gate’s scores are sparse and depend on the query, so the gate can drop context irrelevant to the current token. The authors find this removes the attention sink on the first token and reduces massive activations. Gated Attention §4.2–4.3
In Qwen3-Next the gate is kept for numerical stability: it eliminates attention sinks and massive activations, the Qwen team says. Qwen3-Next post
All 3 steps
- in
- [B batch, 64 heads, 1 position, 256 d_h] [B batch, 1 position, 16384 heads × d_h]
- out
- [B batch, 1 position, 8192 d]
Parameters134,217,728 × 23 layers
134,217,728 parameters per instance, across its learned components
| Component | Calculation | Parameters |
|---|---|---|
| Output projection | 16,384 × 8,192 | 134,217,728 |
One in each of the 23 attention layers, each with its own weights.
Explanation
The gate multiplies after the heads are joined, one gate value for each of the 16,384 features, so every head’s features are gated separately (modeling_qwen3_5_moe.py 807–808).
Sources
In codeattn_output * torch.sigmoid(gate), self.o_proj · 807–810
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_weightsGated 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