Fix non-causal MLA attention under the default sdpa (and flash_attention_2) mode
Fixes #15 (the same report on GitHub: inclusionAI/Ling#27).
What's wrong
The MLA attention layers (BailingMoeV3MultiLatentAttention, which the MTP layer uses too) always calleager_attention_forward, whatever attn_implementation is. That function only adds the mask it is
handed:
- Under
sdpa, the default, the model's mask helper returnsNonefor unpadded input without a cache, and
leaves causality to the kernel'sis_causalflag. So these layers attend to future tokens in any unpadded
forward over a full sequence: prefill, teacher-forced training, scoring. (With padding, or after a cache, the
helper builds a 4D mask and the layers are masked correctly.) - Under
flash_attention_2, the model passesNonewhen nothing is padded, so every multi-token forward
attends to future tokens; with padding it passes a 2D mask, which this function slices as if it were 4D,
raising anIndexError.
Decode steps themselves (one query) are unaffected, but the prompt's prefill is not, so generations differ
from eager's too. As diagnosed by @bighead-liat in #15.
The fix
eager_attention_forward applies a 4D mask exactly as before. When it gets no 4D mask, it builds the causal
mask itself for a causal module with more than one query (offset by the cached keys, so a chunked prefill
after a cache is masked correctly too under flash_attention_2) and applies a 2D padding mask if one is
given, so padded flash_attention_2 inputs work instead of failing. One-token decode without a mask is
unchanged. This is the second option proposed in #15, building the mask inside the eager path: every
attention mode then computes exactly what eager computes. One function, +12 / −1.
How it was checked
- Real weights: Ling-3.0-tiny at 9a98e35 in BF16 with transformers 4.57.6, on four prompts (a fact, a
word problem, code, a translation). Every position's next-token logits and a 32-token greedy continuation
were compared withattn_implementation="eager", which gets a full 4D causal mask:- before,
sdpa: top-1 agreement with eager 0.61–0.80 per prompt, max |logit diff| 4.1–16.7, greedy text
equal on 1 of 4 prompts; - with this change,
sdpa: logits equal to eager (max |diff| 0.000), top-1 agreement 1.00, greedy text
equal on 4 of 4.
- before,
- The function on synthetic tensors (CPU), against PyTorch's
scaled_dot_product_attention:- prefill without a mask equals causal attention (max |diff| 3e-7; before, 2.5);
- one-token decode is bit-identical to before;
- a chunked prefill after cached keys matches the offset causal mask;
- the 4D-mask path is bit-identical to before;
- a 2D left-padding mask gives causal plus padding masking;
- a non-causal module stays unmasked.
- The real-weight comparison covers
sdpa, the default.flash_attention_2was checked only on the function
with synthetic tensors (the no-mask and 2D-padding cases above), not on the model.
Check it yourself
No weights needed. This runs the function from the file against PyTorch's causal attention:
import ast, torch
src = open("modeling_bailing_moe_v3.py").read() # main, or this PR
fn = next(n for n in ast.parse(src).body if getattr(n, "name", "") == "eager_attention_forward")
ns = {"torch": torch, "nn": torch.nn, "repeat_kv2": lambda x, n: x}
exec("from __future__ import annotations\n" + ast.get_source_segment(src, fn), ns)
attn = torch.nn.Module(); attn.is_causal, attn.num_key_value_groups = True, 1 # as in the MLA layers
q, k, v = (torch.randn(1, 2, 6, 8) for _ in range(3))
out, _ = ns["eager_attention_forward"](attn, q, k, v, None, scaling=8**-0.5) # sdpa mode, no padding: no mask
ref = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True).transpose(1, 2)
print((out - ref).abs().max().item()) # main: ~1 to 3 (attends to future tokens); this PR: ~1e-7
The same modeling file is used by the other Ling-3.0-tiny repos (base, FP8, INT4) and by several
Ling-3.0-flash variants, so this change fixes them too once they carry the updated copy; Ling-3.0-flash has its own copy of
the file, and the same change is proposed there in https://huggingface.co/inclusionAI/Ling-3.0-flash/discussions/20.