Skip to content

Left padded training: fully masked pad queries attend only their own key - #18950

Merged
danielhanchen merged 4 commits into
mainfrom
fix/left-pad-query-rows-attend-self
Nov 24, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fix/left-pad-query-rows-attend-self

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

fix_transformers_fully_masked_rows (#9848, for the NaN in #9708) opens a query row that attends to nothing to every key. In a left padded training row the last pad query's logits predict the first real token, so that position reads the token it is trained to predict and every later token. The loss and the LoRA gradients of a left padded batch then depend on future tokens. The patch also replaced the module global sdpa_mask that eager_mask builds from, so eager attention lost upstream's all-min rows too. With attention sinks (gpt-oss, Inkling) an all-min row puts all of its weight on the sink and outputs 0, which is what plain transformers and flex give.

This PR changes two things:

  1. A fully masked query row now attends to its own key only. That is the rule the fast path already uses in _pad_queries_attend_self (Left-padded training: pad queries attend only themselves #18272, Gemma2 training masks: left pad queries attend only themselves on the sliding and global paths #18437). It is causal and never empty, so the NaN fix still holds. Queries are taken as the last q_len keys, so prefill on top of a cache picks the query's own position.
  2. Only the "sdpa" entry of ALL_MASK_ATTENTION_FUNCTIONS is replaced, so eager_mask builds from upstream's sdpa_mask again. The two Unsloth encoder registrations that read the module global (_decision_fast.py, _sentence_transformer_unpadding.py) now read the registry entry, so they keep the NaN fix.

Rows that already attend to something are unchanged. Right padded and unpadded batches give identical masks, so their results are bitwise identical.

Who is affected

Every model that builds its training mask through transformers' masking_utils (create_causal_mask, create_sliding_window_causal_mask, chunked masks) with sdpa or eager. In practice that means FastModel and FastVisionModel models and any model on transformers' own forward. Examples are Gemma 3 / 3n / 4, gpt-oss when run with eager, Qwen3.5 / Qwen3-Next, Llama 4, Mistral 3 / Ministral, Olmo 2, Inkling, and the VLMs. The fix applies on every transformers build whose sdpa_mask leaves such rows fully masked, which the probe confirmed on 4.57.6, 5.22.1 and 5.24.0 with torch 2.14. The Llama-family and Gemma 2 fast paths were already correct. Flex attention and flash attention varlen were not affected.

Only one label per left padded row is affected: the first real token, predicted from the last pad position. It reaches the loss when that label is kept:

collator, left padded tokenizer label at the first real token affected
DataCollatorForSeq2Seq, labels = input_ids kept yes
DataCollatorForLanguageModeling(mlm=False) kept yes
DataCollatorForSeq2Seq, prompt labels -100 (train_on_responses_only) -100 no
TRL SFT collator (always pads right) n/a no
GRPO / DPO (prompt left padded, loss on completions only) not in the loss no

Numbers

CPU, fp32, LoRA r 4, transformers 5.24.0, torch 2.14.1. The batch has row 0 left padded by 6 and row 1 right padded by 5, out of 24 tokens. "Future probe" is the change in the last pad position's logits when the token 3 positions after the first real token is changed (0 = causal).

model, attention arm last pad term future probe LoRA grad rel vs plain transformers + PEFT
Olmo2 tiny, sdpa transformers + PEFT 36.583 0 0
Unsloth main 26.492 4.06 0.70
this PR 17.872 0 0.59 (0 without that one label)
gpt-oss tiny, eager (sinks), transformers + this mask fix only main's fix 12.199 0.039 0.27
this PR 12.181 0 0 (bitwise)
Olmo2 tiny, eager Unsloth main 26.492 4.06 0.42
this PR 22.434 7.55 (upstream's own uniform row) 0 (bitwise)

The loss over all other labels matches plain transformers and the same row run unpadded in every arm. On sdpa the term at the last pad position differs from plain transformers in value only. transformers leaves the row fully masked, and torch then returns 0 for it on CPU. That 0 is the row this patch exists to avoid (NaN on some GPU backends, #9708). Here the row attends to its own pad key instead, which carries no information from real tokens.

Inkling 2 (tiny fake, Unsloth FastModel, left padded row): eager vs flex worst LoRA grad rel goes from 0.120 (dloss 7.4e-4) to 4.0e-6 (dloss 0). Right padded (4.4e-6) and unpadded (4.2e-6) results are unchanged.

Tests

tests/test_sdpa_fully_masked_rows.py now checks:

  • pad queries attend only to their own key
  • the own key sits on the last q_len keys when there is a cache
  • eager keeps upstream's all-min rows, and only the registry entry is patched
  • end to end on a random tiny Llama with sdpa, the last pad position's logits do not move when a later token changes, and real rows are bitwise unchanged

On main the new checks fail (5 of them) on transformers 4.57.6, 5.22.1 and 5.24.0. With this PR all 17 pass on all three. Failing test IDs in the neighbouring suites (test_decision_model, sentence transformer unpadding, Llama left padding mask, flex decode, async GRPO tree) are the same on main and on this PR.

Update

A second commit fixes what review found in the first one, plus two neighbouring spots that use the same rule.

  1. The own key is the query's absolute position, not one of the last q_len keys. With a preallocated cache (StaticCache, a static sliding window layer, Unsloth's growable KV cache) the mask has more key columns than filled slots, so "the last q_len keys" picked unfilled slots or other positions. The wrapper now reads the query coordinates sdpa_mask itself builds the mask from (cache_position on 4.57.6, q_offset and kv_offset on 5.x, also a tensor q_offset from static caches) and opens column position - kv_offset. It is one scatter, so the correction allocates one mask-sized tensor instead of two, and the registered path has no shape branch (one graph under dynamic=True).

    left padded prefill, tiny Llama sdpa first commit now
    StaticCache(max_cache_len=16), 4 pads, own key of pad queries 0..3 6, 7, 8, 9 0, 1, 2, 3
    Unsloth growable cache (256 slots), 60 pads, own key of query 59 115 59
    Mistral sliding static, 3 pads, own key of pad queries 0..2 2, 3, 4 0, 1, 2
    StaticCache last pad logits change when a later token changes 0.0128 0
  2. Both bindings are patched again, the "sdpa" registry entry and the module global sdpa_mask. The first commit left the global alone so eager kept upstream's rows. That broke two things. A custom mask registered as AttentionMaskInterface.register("name", sdpa_mask) lost the NaN fix (2 fully masked rows again). And for eager models without attention sinks, upstream's all-min row is uniform attention over every key, which is the same future token leak, and in fp16 score + finfo(fp16).min overflows to -inf once every score in that row is below about -16, so the row turns NaN and spreads to the real rows. A tiny fp16 Llama on eager built to hit that gives non-finite logits at 6 of 6 positions on the first commit (and on plain transformers), and 0 of 6 now and on main.

    Sink-free eager rows now get the same own key as sdpa. Models with attention sinks (gpt-oss, Inkling, DeepSeek V4, MiMo V2 Flash, HunYuan V4, and the others in _ATTENTION_SINK_MODEL_TYPES) keep upstream's all-min row, because there the sink takes all of the weight and the pad query outputs 0, the same as flex. None of those models support sdpa, so their sdpa mask is only ever built for eager. A sink model missing from that list would get one own key: causal and finite, only not bitwise upstream on pad rows.

  3. Unsloth's own SDPA dispatch (utils/attention_dispatch.py) had the old rule as well: a causal row that attends to nothing was opened to every key. It now gets its own key only. Non-causal rows still open every key.

Rows that already attend to something are unchanged everywhere, so right padded and unpadded batches are bitwise identical to main in every arm below. With sliding window or chunked masks a trailing right pad query can be fully masked; it now gets its own key instead of every key. That changes only that pad row, and real rows, the loss and the LoRA grads stayed bitwise identical in the right padded runs.

Same harness as above (CPU, fp32, LoRA r 4, transformers 5.24.0, row 0 left padded by 6, row 1 right padded by 5). "Future probe" is the change in the last pad position's logits when a later token changes.

model, attention, arm future probe: main / first commit / now LoRA grad rel vs plain transformers, without the first real label right padded and unpadded vs main
Olmo2 tiny, sdpa, Unsloth 4.06 / 0 / 0 0 bitwise
Olmo2 tiny, eager, Unsloth 4.06 / 7.55 / 0 0 bitwise
Gemma3 tiny, eager, Unsloth 0.052 / 0.053 / 0 3.4e-7 (Unsloth vs plain transformers noise, same on unpadded) bitwise
gpt-oss tiny, eager (sinks), transformers + this fix 0.039 / 0 / 0 0 (bitwise plain transformers, all labels too) bitwise

On sink-free eager the one term at the last pad position now differs from plain transformers in value, as on sdpa, because plain transformers reads later tokens there. Every other label matches.

Tests

tests/test_sdpa_fully_masked_rows.py adds:

  • a live StaticCache and DynamicCache, with and without a cached prefix, through create_causal_mask: pad queries attend their own slot
  • the coordinates read from both signatures (positional and keyword, int and tensor offsets)
  • a register("name", sdpa_mask) alias keeps the fix
  • fp16 sink-free eager: the softmax of a pad row with very negative scores is one-hot on the own key (NaN before)
  • gpt-oss eager rows stay upstream's
  • one graph and no breaks under torch.compile(dynamic=True, fullgraph=True)
  • the native SDPA dispatch opens only the own key for a causal pad row
  • the Decision encoder registers the repaired builder

On the first commit 7 of these fail on 4.57.6 and 6 on 5.22.1 and 5.24.0. On main 13 fail on 4.57.6 and 12 on 5.x. All pass now (27 on 4.57.6; on the 5.x CPU environments two tests skip because unsloth.utils needs vLLM there). The neighbouring mask and attention suites (attention dispatch, flex mask, Gemma 2 and Llama left padding, Mistral sliding window, masked SDPA alignment, flex decode routing, padding free, online DPO left padding, sentence transformers) have the same failing test IDs before and after on all three transformers versions.

Not covered here: no GPU run, so the CUDA SDPA backends and the original fp16 NaN on B200 are not re-measured, and gpt-oss inside FastModel and Inkling were not rerun with this commit.

…key in the masking_utils path

The sdpa_mask fix for NaN on left padded rows opened a query row that attends to
nothing to every key. In a left padded training row the last pad query's logits
predict the first real token, so that position read the token it is trained on
and later ones, and the loss and LoRA gradients of a left padded batch depended
on future tokens. The fix also replaced the module global sdpa_mask that
eager_mask builds from, so eager lost upstream's all-min rows (0 output with
attention sinks, as flex gives).

Now such a row attends to its own key only (the rule the fast path already uses
in _pad_queries_attend_self), and only the sdpa registry entry is replaced, so
eager_mask is upstream's again. Rows that attend to something, right padded and
unpadded batches are unchanged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T03:47:21.067731Z a948eb0 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

…both bindings, sink-free eager and native SDPA dispatch too

The own key is column cache_position / q_offset minus kv_offset, read from the
builder's signature (4.57.6 cache_position, 5.x q_offset/kv_offset, tensor
q_length), not the last q_len keys, which are unfilled slots in a StaticCache,
a sliding static layer or the growable cache. One scatter, no shape branch on
the registered path.

Both the registry entry and the module global sdpa_mask are patched again, so
register(name, sdpa_mask) aliases keep the NaN fix and sink-free eager rows get
the own key: an all-min eager row was uniform over every key, and in fp16 it
overflows to -inf and NaN. Attention sink families keep upstream's all-min row.

The native SDPA dispatch opens only the own key for causal fully masked rows.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 896321d460

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

… tail

The causal fully masked row fix in run_attention took the own key as K's last
q_len columns, the tail rule the masking_utils path no longer uses. When K has
more columns than filled slots (a preallocated cache), that column is an
unfilled slot, and the 2D padding mask branch built its causal mask from the
same tail offset, so a real query could also see later filled positions.

Both now take the query offset from the context's kv_seq_len (the filled keys)
when it lies between q_len and K's length, and fall back to the tail otherwise.
Every in-tree caller concatenates the cache, so kv_seq_len equals K's length
there and nothing changes for them.
…a softmax logit

The sink exception kept upstream's all-min pad rows for every family with
attention sinks. That is safe only where eager appends the sink as an extra
softmax column (gpt-oss, flint, hy_v4, deepseek_v4, inkling2): the row's weight
goes to the finite sink and the output is 0 in every dtype.

Granite SWA and GraniteMoE SWA run a plain softmax and then scale by
sigmoid(lse - sink), and MiMo V2 Flash has sinks only in its sliding layers.
In fp16 an all-min row overflows to -inf once its scores are below about -16,
so those pad rows came out NaN and so did the q / k / v gradients, even with
the pad outputs left out of the loss. Those three families now get the own
key like sink-free models: causal, finite, no later token read.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: a948eb0301

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit e8b9205 into main Nov 24, 2026
@danielhanchen
danielhanchen deleted the fix/left-pad-query-rows-attend-self branch November 24, 2026 02:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant