Mix and project
×Mix each head’s values by its weights, join the 64 heads and project back to 7,168 features.
All 3 steps
- in
- [B batch, 64 heads, T queries, T keys] [B batch, 64 heads, T positions, 128 value]
- out
- [B batch, T positions, 7168 d]
Parameters58,720,256
58,720,256 parameters per instance, across its learned components
| Component | Calculation | Parameters |
|---|---|---|
| Output projection | 8,192 × 7,168 | 58,720,256 |
Explanation
The output projection is the only step that mixes heads.
Sources
In codeattn_output · 836–848
Direct evidence
The rotary parts are rotated; each head’s query and key join their non-rotated and rotated parts, the key’s rotated part being the shared rotary key; scores are scaled, masked by the causal mask, normalized and used to mix values.
modeling_deepseek.py 794–836 ↗ · moonshotai/Kimi-K2.6 @ 7eb5002f6aad
Excerpt
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
query_states = k_pe.new_empty(bsz, self.num_heads, q_len,
self.q_head_dim)
query_states[:, :, :, :self.qk_nope_head_dim] = q_nope
query_states[:, :, :, self.qk_nope_head_dim:] = q_pe
key_states = k_pe.new_empty(bsz, self.num_heads, q_len,
self.q_head_dim)
key_states[:, :, :, :self.qk_nope_head_dim] = k_nope
key_states[:, :, :, self.qk_nope_head_dim:] = k_pe
if past_key_value is not None:
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
key_states, value_states = past_key_value.update(
key_states, value_states, self.layer_idx, cache_kwargs)
attn_weights = (
torch.matmul(query_states, key_states.transpose(2, 3)) *
self.softmax_scale)
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
raise ValueError(
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
f" {attn_weights.size()}")
assert attention_mask is not None
if attention_mask is not None:
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights + attention_mask
# upcast attention to fp32
attn_weights = nn.functional.softmax(attn_weights,
dim=-1,
dtype=torch.float32).to(
query_states.dtype)
attn_weights = nn.functional.dropout(attn_weights,
p=self.attention_dropout,
training=self.training)
attn_output = torch.matmul(attn_weights, value_states)Head outputs are flattened and projected back to the model width.
modeling_deepseek.py 843–848 ↗ · moonshotai/Kimi-K2.6 @ 7eb5002f6aad
Excerpt
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(bsz, q_len,
self.num_heads * self.v_head_dim)
attn_output = self.o_proj(attn_output)