ModernBERT: local-attention window is computed from sequence index, not `position_ids`, so non-monotonic positions get a silently different window
System Info
transformers5.17.0,torch2.14.0+cpu, Python 3.13.1, Windows 11 (CPU)- Same behaviour on Kaggle 2×T4:
torch2.10.0+cu128,transformers5.17.0, Python 3.12
Who can help?
@vasqu @ArthurZucker
Reproduction
ModernBERT's local layers restrict attention to a window, and its rotary embeddings use position_ids. The window, however, is built from sequence index, so it silently diverges from the positions the model sees whenever position_ids aren't arange(seq_len). One setting where that happens: several segments that share a prefix and all restart at the same position (parallel context windows / shared-prefix packing), which is how you'd ask K independent questions about one document in a single pass.
Where it happens (v5.17.0):
- With a 2D mask or no mask,
ModernBertModel.forwardbuilds the sliding mask withcreate_bidirectional_sliding_window_mask(modeling_modernbert.py#L453-L462), whose overlay isabs(q_idx - kv_idx) <= sliding_window(masking_utils.py#L142-L150): sequence index. The rotary embeddings useposition_ids(modeling_modernbert.py#L464-L466). - (Already noted by a maintainer in #38040, repeated here because it interacts with point 1.) A custom 4D mask is returned as-is (masking_utils.py#L811-L813) and is used for both layer types, so under
sdpa/eagerthe local layers get no window at all:sdpa_attention_forwarddoesn't use thesliding_windowkwarg that the attention module passes. - Only a per-layer-type dict (
{"full_attention": ..., "sliding_attention": ...}, accepted at L453) gives the caller control of the window.
No warning is raised in cases 1 or 2. Point 1 is the new part: even with the dict route from #38040, the natural way to build the sliding entry (the stock helper plus an and_mask_function, as in the repro) keeps the window on sequence index.
Minimal repro: tiny random ModernBertConfig, no downloads, CPU, a few seconds. It packs a 40-token prefix plus two 10-token blocks that both restart at position 40, isolates the blocks with an and_mask_function, and compares each block's hidden states with the same block encoded alone after the prefix (where index == position):
import torch
from transformers import ModernBertConfig, ModernBertModel
from transformers.masking_utils import and_masks, create_bidirectional_mask, create_bidirectional_sliding_window_mask
for attn in ("sdpa", "eager"):
torch.manual_seed(0)
cfg = ModernBertConfig(vocab_size=97, hidden_size=64, intermediate_size=96, num_hidden_layers=6,
num_attention_heads=4, local_attention=16, global_attn_every_n_layers=3,
max_position_embeddings=512, pad_token_id=0, bos_token_id=1, eos_token_id=2,
cls_token_id=1, sep_token_id=2, attn_implementation=attn)
model = ModernBertModel(cfg).eval()
w = model.config.sliding_window # 8
# A 40-token shared prefix, then two 10-token blocks that both restart at position 40.
S, Q = 40, 10
g = torch.Generator().manual_seed(1)
prefix, q1, q2 = (torch.randint(4, 97, (n,), generator=g) for n in (S, Q, Q))
ids = torch.cat([prefix, q1, q2])[None]
pos = torch.cat([torch.arange(S), torch.arange(S, S + Q), torch.arange(S, S + Q)])[None]
seg = torch.tensor([0] * S + [1] * Q + [2] * Q)
def block(b, h, q, kv): # the prefix sees itself; each block sees the prefix and itself
return (seg[kv] == 0) | (seg[kv] == seg[q])
def window_on_positions(b, h, q, kv):
return (pos[0, q] - pos[0, kv]).abs() <= w
kw = dict(config=model.config, inputs_embeds=model.embeddings(input_ids=ids),
attention_mask=torch.ones_like(ids), and_mask_function=block)
stock = {"full_attention": create_bidirectional_mask(**kw),
"sliding_attention": create_bidirectional_sliding_window_mask(**kw)}
fixed = {"full_attention": stock["full_attention"],
"sliding_attention": create_bidirectional_mask(**{**kw, "and_mask_function": and_masks(block, window_on_positions)})}
with torch.no_grad():
# Reference: each block encoded alone after the prefix (positions 0..S+Q-1, so index == position).
alone = [model(input_ids=torch.cat([prefix, q])[None]).last_hidden_state[0, S:] for q in (q1, q2)]
def err(mask):
h = model(input_ids=ids, attention_mask=mask, position_ids=pos).last_hidden_state[0]
return [(h[S + k * Q:S + (k + 1) * Q] - alone[k]).abs().max().item() for k in (0, 1)]
print(f"[{attn}] max |packed - alone| for block 1, block 2")
print(" stock sliding mask (window on sequence index):", ["%.1e" % e for e in err(stock)])
print(" single 4D mask (used as-is by every layer) :", ["%.1e" % e for e in err(stock["full_attention"])])
print(" sliding mask built from position_ids :", ["%.1e" % e for e in err(fixed)])Output:
[sdpa] max |packed - alone| for block 1, block 2
stock sliding mask (window on sequence index): ['1.0e-05', '8.3e-03']
single 4D mask (used as-is by every layer) : ['8.5e-03', '8.4e-03']
sliding mask built from position_ids : ['1.0e-05', '1.2e-05']
[eager] max |packed - alone| for block 1, block 2
stock sliding mask (window on sequence index): ['1.0e-05', '8.3e-03']
single 4D mask (used as-is by every layer) : ['8.5e-03', '8.4e-03']
sliding mask built from position_ids : ['1.0e-05', '1.2e-05']Block 1 sits right after the prefix, so index and position distances agree and it matches. Block 2 is 10 tokens further by index than by position, so its local layers see a different slice of the prefix. With a 4D mask neither block gets a window.
On real checkpoints this changes predictions, not just hidden states. With Ettin-68m (512-token prefix, 20 blocks) and a randomly initialised MLP scorer on each option marker, the index-based window changed 8 of 20 argmax answers on CPU (7 of 64 on a T4), while building the window from positions matched the one-block-at-a-time answers on all of them (details: https://github.com/johnmofficial16-prog/ikken/blob/main/experiments/01-read-once-prototype/RESULTS.md).
Expected behavior
Is this intended? If the window is meant to follow token positions (as RoPE does), two options:
- When
position_idsare passed, build the sliding overlay from them, e.g.abs(position_ids[b, q_idx] - position_ids[b, kv_idx]) <= sliding_window, for the mask-based backends (sdpa,eager,flex_attention).create_bidirectional_sliding_window_maskhas noposition_idsargument today;create_causal_maskalready takes one (forfind_packed_sequence_indices), so there is a precedent for passing it through. FlashAttention applieswindow_sizeby index inside the kernel, so it would keep today's behaviour (or warn whenposition_idsaren't monotonic). - Or keep the current behaviour and document it: the local window is on sequence index; a 4D
attention_maskis used as-is by every layer (no window); pass a per-layer-type dict to control the window. A one-time warning when non-arangeposition_idsare combined with a non-dict mask would also catch it.
Happy to open a PR for either.
Source: huggingface/transformers