Query–key products
×Score every key for every query within each head.
- in
- [B batch, 128 heads, 1 position, 192 d_h] [B batch, 128 heads, 128 read positions, 192 d_h]
- out
- [B batch, 128 heads, 1 query, 128 keys]
Sources
In codetorch.matmul(query, key_states.transpose(2, 3)) · 84
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