Repeat key heads
×Copy each of the 8 key heads to the 16 query heads of its group.
- in
- [B batch, 8 kv heads, 1001 cached positions, 192 d_h]
- out
- [B batch, 128 heads, 1001 cached positions, 192 d_h]
Heads are counted from zero: query heads 16h to 16h + 15 read key and value head h (modeling_mimo_v2.py 63–68). The repeat follows the cache, so the cache holds 8 heads.
Sources
In coderepeat_kv(key, module.num_key_value_groups) · 82
Direct evidence
The eager attention: keys and values repeated to the query heads, scores scaled, the mask added; with sinks, each head’s sink bias is appended to every row of scores as one more column; the row’s maximum is subtracted, the softmax taken in float32, the sink’s column dropped, and the values mixed by the weights.
modeling_mimo_v2.py 71–102 ↗ · XiaomiMiMo/MiMo-V2.6-Pro-RL @ b61f21852680
Excerpt
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
sinks: Optional[torch.Tensor] = None,
**kwargs,
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
if sinks is not None:
sinks = module.attention_sink_bias.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
attn_weights = torch.cat([attn_weights, sinks], dim=-1)
attn_weights = attn_weights - attn_weights.max(dim=-1, keepdim=True).values
probs = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
if sinks is not None:
probs = probs[..., :-1]
attn_weights = nn.functional.dropout(probs, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
repeat_kv copies each key–value head to the query heads of its group.
modeling_mimo_v2.py 63–68 ↗ · XiaomiMiMo/MiMo-V2.6-Pro-RL @ b61f21852680
Excerpt
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)