Repository navigation
Left padded training: fully masked pad queries attend only their own key - #18950
Conversation
…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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…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]
|
@codex review |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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 globalsdpa_maskthateager_maskbuilds 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:
_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 lastq_lenkeys, so prefill on top of a cache picks the query's own position."sdpa"entry ofALL_MASK_ATTENTION_FUNCTIONSis replaced, soeager_maskbuilds from upstream'ssdpa_maskagain. 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) withsdpaoreager. 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 whosesdpa_maskleaves 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:
DataCollatorForSeq2Seq, labels = input_idsDataCollatorForLanguageModeling(mlm=False)DataCollatorForSeq2Seq, prompt labels -100 (train_on_responses_only)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).
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.pynow checks:q_lenkeys when there is a cacheOn 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.
The own key is the query's absolute position, not one of the last
q_lenkeys. 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 lastq_lenkeys" picked unfilled slots or other positions. The wrapper now reads the query coordinatessdpa_maskitself builds the mask from (cache_positionon 4.57.6,q_offsetandkv_offseton 5.x, also a tensorq_offsetfrom static caches) and opens columnposition - 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 underdynamic=True).StaticCache(max_cache_len=16), 4 pads, own key of pad queries 0..3StaticCachelast pad logits change when a later token changesBoth bindings are patched again, the
"sdpa"registry entry and the module globalsdpa_mask. The first commit left the global alone so eager kept upstream's rows. That broke two things. A custom mask registered asAttentionMaskInterface.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 fp16score + finfo(fp16).minoverflows to-infonce 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.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.
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.pyadds:StaticCacheandDynamicCache, with and without a cached prefix, throughcreate_causal_mask: pad queries attend their own slotregister("name", sdpa_mask)alias keeps the fixtorch.compile(dynamic=True, fullgraph=True)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.utilsneeds 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.