Query RMSNorm
×RMS-normalize each query head’s 256 features.
- in
- [B batch, 64 heads, 1 position, 256 d_h]
- out
- [B batch, 64 heads, 1 position, 256 d_h]
Zero-centred, like the model’s other RMSNorms, and computed in float32 (modeling_qwen3_5_moe.py 917–927).
Parameters256 × 23 layers
256 parameters owned by this component
| Component | Parameters |
|---|---|
| RMSNorm gain | 256 |
One in each of the 23 attention layers, each with its own weights.
One gain for each of the 256 features of a head, stored as its offset from one.
Sources
In codeself.q_norm(query_states.view(hidden_shape)) · 782
Direct evidence
The model’s RMSNorm is zero-centred: its weight is initialised to zeros and the normalised input is multiplied by (1 + weight), in float32.
modeling_qwen3_5_moe.py 912–927 ↗ · huggingface/transformers @ 18329f106538
Excerpt
@use_kernel_forward_from_hub("RMSNormZeroCentered")
class Qwen3_5MoeRMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float())
# Llama does x.to(float16) * w whilst Qwen3_5Moe is (x * w).to(float16)
# See https://github.com/huggingface/transformers/pull/29402
output = output * (1.0 + self.weight.float())
return output.type_as(x)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 reshapeThe 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