Queries
×128 heads of 192 query features, the first 64 rotated by position.
- shape
- [B batch, 128 heads, 1 position, 192 d_h]
Sources
Contextual evidence from Prepare Q, K, V
The fused projection is split into queries, keys and values, read as 128 query heads of 192, 8 key heads of 192 and 8 value heads of 128.
modeling_mimo_v2.py 358–391 ↗ · XiaomiMiMo/MiMo-V2.6-Pro-RL @ b61f21852680
Excerpt
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
if self.projection_layout == "fused_qkv":
qkv_states = self.qkv_proj(hidden_states)
query_states, key_states, value_states = qkv_states.split([self.q_size, self.k_size, self.v_size], dim=-1)
else:
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(*input_shape, self.num_attention_heads, self.head_dim).transpose(1, 2)
key_states = key_states.view(*input_shape, self.num_key_value_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(*input_shape, self.num_key_value_heads, self.v_head_dim).transpose(1, 2)
return self._forward_attention(
query_states,
key_states,
value_states,
input_shape,
position_embeddings,
attention_mask,
past_key_values=past_key_values,
cache_position=cache_position,
position_ids=position_ids,
)
Values are multiplied by the value scale; the first rope_dim features of each query and key head are rotated and the rest concatenated after them; keys and values go to the cache; the eager path receives the sink bias, other attention functions the sink as s_aux and the window; the heads are joined and projected.
modeling_mimo_v2.py 290–356 ↗ · XiaomiMiMo/MiMo-V2.6-Pro-RL @ b61f21852680
Excerpt
def _forward_attention(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
input_shape: torch.Size,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
) -> tuple[torch.Tensor, torch.Tensor]:
if self.v_scale is not None:
value_states = value_states * self.v_scale
cos, sin = position_embeddings
query_rope, query_nope = query_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
key_rope, key_nope = key_states.split([self.rope_dim, self.head_dim - self.rope_dim], dim=-1)
query_rope, key_rope = apply_rotary_pos_emb(query_rope, key_rope, cos, sin)
query_states = torch.cat([query_rope, query_nope], dim=-1)
key_states = torch.cat([key_rope, key_nope], dim=-1)
if past_key_values is not None:
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
attn_implementation = self.config._attn_implementation
if attn_implementation is not None and attn_implementation.startswith("paged|"):
raise ValueError(
"MiMoV2 remote code does not support paged attention cache. "
"Please use eager, sdpa, flex_attention, or flash_attention_2."
)
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
attn_implementation, eager_attention_forward
)
if self.attention_sink_bias is not None and attn_implementation == "sdpa":
logger.warning_once(
"MiMoV2 attention sink bias is not supported by SDPA; falling back to eager attention for correctness."
)
attention_interface = eager_attention_forward
attention_kwargs = {
"dropout": 0.0 if not self.training else self.attention_dropout,
"scaling": self.scaling,
"position_ids": position_ids,
"is_causal": self.is_causal,
}
if attention_interface is eager_attention_forward:
attention_kwargs["sinks"] = self.attention_sink_bias
else:
if self.attention_sink_bias is not None:
attention_kwargs["s_aux"] = self.attention_sink_bias
if self.sliding_window is not None:
attention_kwargs["sliding_window"] = self.sliding_window
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
**attention_kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
The attention of a window layer takes the swa_* heads, widths and window, of a global layer the main ones; the rotary dimension is int(head_dim · partial_rotary_factor); scaling is head_dim^−0.5; the value scale is attention_value_scale; a sink bias of one value per query head exists where the configuration adds it; Pro stores one fused query–key–value projection, and the output projection maps heads × v_head_dim back to the width.
modeling_mimo_v2.py 220–288 ↗ · XiaomiMiMo/MiMo-V2.6-Pro-RL @ b61f21852680
Excerpt
class MiMoV2Attention(nn.Module):
"""MiMoV2 attention.
`projection_layout` only controls how checkpoint weights are named and
stored: Flash uses separate q/k/v projections, while Pro uses fused qkv.
The attention computation after projection is shared.
"""
def __init__(self, config, is_swa: bool, layer_idx: int, projection_layout: str = "split"):
super().__init__()
if projection_layout not in {"split", "fused_qkv"}:
raise ValueError(f"Unsupported MiMoV2 attention projection layout: {projection_layout}")
self.config = config
self.layer_idx = layer_idx
self.is_swa = is_swa
self.is_causal = True
self.projection_layout = projection_layout
default_head_dim = config.hidden_size // config.num_attention_heads
default_v_head_dim = getattr(config, "v_head_dim", default_head_dim)
if is_swa:
self.head_dim = getattr(config, "swa_head_dim", getattr(config, "head_dim", default_head_dim))
self.v_head_dim = getattr(config, "swa_v_head_dim", default_v_head_dim)
self.num_attention_heads = getattr(config, "swa_num_attention_heads", config.num_attention_heads)
self.num_key_value_heads = getattr(config, "swa_num_key_value_heads", config.num_key_value_heads)
else:
self.head_dim = getattr(config, "head_dim", default_head_dim)
self.v_head_dim = getattr(config, "v_head_dim", self.head_dim)
self.num_attention_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.rope_dim = int(self.head_dim * getattr(config, "partial_rotary_factor", 1.0))
if self.rope_dim % 2 != 0:
raise ValueError(
f"MiMoV2 rotary dimension must be even, got {self.rope_dim} from "
f"head_dim={self.head_dim} and partial_rotary_factor={getattr(config, 'partial_rotary_factor', 1.0)}"
)
self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
self.attention_dropout = getattr(config, "attention_dropout", 0.0)
self.scaling = self.head_dim**-0.5
self.sliding_window = getattr(config, "sliding_window", None) if is_swa else None
self.q_size = self.num_attention_heads * self.head_dim
self.k_size = self.num_key_value_heads * self.head_dim
self.v_size = self.num_key_value_heads * self.v_head_dim
self.o_hidden_size = self.num_attention_heads * self.v_head_dim
self.v_scale = getattr(config, "attention_value_scale", None)
self.attention_sink_bias = (
nn.Parameter(torch.empty(self.num_attention_heads), requires_grad=False)
if (
(getattr(config, "add_full_attention_sink_bias", False) and not is_swa)
or (getattr(config, "add_swa_attention_sink_bias", False) and is_swa)
)
else None
)
attention_bias = getattr(config, "attention_bias", False)
if self.projection_layout == "fused_qkv":
self.qkv_proj = nn.Linear(
config.hidden_size,
self.q_size + self.k_size + self.v_size,
bias=attention_bias,
)
else:
self.q_proj = nn.Linear(config.hidden_size, self.q_size, bias=attention_bias)
self.k_proj = nn.Linear(config.hidden_size, self.k_size, bias=attention_bias)
self.v_proj = nn.Linear(config.hidden_size, self.v_size, bias=attention_bias)
self.o_proj = nn.Linear(self.o_hidden_size, config.hidden_size, bias=False)
Contextual evidence from Query–key products
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
Contextual evidence from Key cache
A DynamicSlidingWindowLayer returns the kept keys and values with this call’s, then keeps only the last sliding_window − 1 positions.
cache_utils.py 168–217 ↗ · huggingface/transformers @ aad13b87ed59
Excerpt
class DynamicSlidingWindowLayer(DynamicLayer):
"""
A cache layer that grows dynamically as more tokens are generated, up until the sliding window size.
It stores the key and value states as tensors of shape `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`.
"""
is_sliding = True
def __init__(self, sliding_window: int):
super().__init__()
self.sliding_window = sliding_window
self.cumulative_length = 0
self._sliding_window_tensor = torch.tensor(self.sliding_window, dtype=torch.long)
def lazy_initialization(self, key_states: torch.Tensor, value_states: torch.Tensor) -> None:
super().lazy_initialization(key_states, value_states)
self._sliding_window_tensor = self._sliding_window_tensor.to(self.device)
def update(
self,
key_states: torch.Tensor,
value_states: torch.Tensor,
cache_kwargs: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Update the key and value caches in-place, and return the necessary keys and value states.
Args:
key_states (`torch.Tensor`): The new key states to cache.
value_states (`torch.Tensor`): The new value states to cache.
cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
Returns:
tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
"""
# Lazy initialization
if not self.is_initialized:
self.lazy_initialization(key_states, value_states)
self.cumulative_length += key_states.shape[-2]
# Compute the full states
full_key_states = torch.cat([self.keys, key_states], dim=-2)
full_value_states = torch.cat([self.values, value_states], dim=-2)
# Only cache the last `self.sliding_window - 1` tokens (or all of them if lower than that)
self.keys = full_key_states[:, :, -self.sliding_window + 1 :, :]
self.values = full_value_states[:, :, -self.sliding_window + 1 :, :]
# Return the full states
return full_key_states, full_value_statesDynamicCache built from a configuration gives a sliding_attention layer a DynamicSlidingWindowLayer of the configuration’s window and any other layer a DynamicLayer.
cache_utils.py 950–980 ↗ · huggingface/transformers @ aad13b87ed59
Excerpt
self,
ddp_cache_data: Iterable[tuple[torch.Tensor | None, ...]] | None = None,
config: PreTrainedConfig | None = None,
offloading: bool = False,
offload_only_non_sliding: bool = False,
):
layers = []
# If a config is passed, use it to infer the layer types and initialize accordingly
if config is not None:
decoder_config = config.get_text_config(decoder=True)
sliding_window = getattr(decoder_config, "sliding_window", None) or getattr(
decoder_config, "attention_chunk_size", None
)
layer_types = getattr(decoder_config, "layer_types", None)
if layer_types is None:
layer_types = [
"sliding_attention" if sliding_window is not None else "full_attention"
for _ in range(decoder_config.num_hidden_layers)
]
# Some models have shared layers thus no cache is needed for them (e.g. Gemma3n)
if hasattr(decoder_config, "num_kv_shared_layers"):
layer_types = layer_types[: -decoder_config.num_kv_shared_layers]
for layer_type in layer_types:
# From a cache point of view, both sliding and chunked are the same in how they should behave and how many
# states they should return - only the mask changes to make them different at the end!
if layer_type in ("sliding_attention", "chunked_attention"):
layers.append(DynamicSlidingWindowLayer(sliding_window=sliding_window))
else:
layers.append(DynamicLayer())
Contextual evidence from Rotate by position
RoPE turns a query and a key by rotating halves: x·cos + rotate_half(x)·sin.
modeling_mimo_v2.py 47–60 ↗ · XiaomiMiMo/MiMo-V2.6-Pro-RL @ b61f21852680
Excerpt
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies rotary position embedding to query and key tensors."""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed