Sliding-window attention
×Each query reads the last 128 positions, its own included, in 128 query heads sharing 8 key–value heads; a learned sink per head can take part of the weight.
Why
128 positions. In the authors’ ablation on a 32B dense model, a window of 128 and one of 512 score alike on general benchmarks; after long-context extension the window of 128 surpasses the all-global baseline, while the window of 512 degrades significantly on most of the long-context benchmarks. MiMo-V2-Flash report §2.2.1
The authors hypothesize that a tight window acts as an inductive bias toward local context and leaves long-range dependencies to the global layers, a clearer division of labour; a wider window blurs it. MiMo-V2-Flash report §2.2.2
All 17 steps
- in
- [B batch, 1 position, 6144 d] [B batch, 1 position, 64 rotary features]
- out
- [B batch, 1 position, 6144 d]
Parameters267,387,008 × 60 layers
267,387,008 parameters per instance, across its learned components
| Component | Parameters |
|---|---|
| Prepare Q, K, V | 166,723,584 |
| Attention sink | 128 |
| Merge and project | 100,663,296 |
| Per-instance total | 267,387,008 |
One in each of the 60 window layers, each with its own weights.
Explanation
The cache keeps the keys and values of the last 127 positions only (cache_utils.py 212–214): with the new position they make the 128 a query reads.
Which attention function runs is a setting of the transformers library (modeling_mimo_v2.py 323–330); the cards quote the eager reference, eager_attention_forward (71–102), which states the arithmetic step by step. Other functions take the sink as s_aux and the window as sliding_window (340–345); with the sink, SDPA falls back to the eager reference (326–330).
Sources
In codeself.self_attn · MiMoV2Attention(config, is_swa=True)
Direct evidence
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)
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 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
The sliding-window overlay keeps a key whose index is greater than the query’s minus the window, and the sliding-window causal mask is that overlay and the causal mask together.
masking_utils.py 90–118 ↗ · huggingface/transformers @ aad13b87ed59
Excerpt
def sliding_window_overlay(sliding_window: int) -> Callable:
"""
This is an overlay depicting a sliding window pattern. Add it on top of a causal mask for a proper sliding
window mask.
"""
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
return kv_idx > q_idx - sliding_window
return inner_mask
def chunked_overlay(chunk_size: int, left_padding: torch.Tensor) -> Callable:
"""
This is an overlay depicting a chunked attention pattern. Add it on top of a causal mask for a proper chunked
attention mask.
"""
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
return (kv_idx - left_padding[batch_idx]) // chunk_size == (q_idx - left_padding[batch_idx]) // chunk_size
return inner_mask
def sliding_window_causal_mask_function(sliding_window: int) -> Callable:
"""
This return the mask_function function to create a sliding window mask.
"""
return and_masks(sliding_window_overlay(sliding_window), causal_mask_function)