Repository navigation
Left-padded training: pad queries attend only themselves - #18272
Merged
Merged
Conversation
The 4D SDPA mask unmasks fully masked rows to every key, so with left padding the last pad query, which predicts the first real token under DataCollatorForSeq2Seq, saw later tokens. In training without a KV cache, pad queries now attend only their own key.
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. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
danielhanchen
added a commit
to NilayYadav/unsloth
that referenced
this pull request
Nov 19, 2026
… sliding and global paths (unslothai#18437) ## Summary Gemma2 left-padded training still let the last pad query attend to every key, including the first real token it predicts. unslothai#18272 fixed this for the shared mask branch of `LlamaModel_fast_forward`, but Gemma2 builds its alternating sliding and global masks in its own branch, and that branch never applied the repair. ## Root cause unslothai#18272 (97b6074) added `_pad_queries_attend_self` and calls it only on the mask built by `_prepare_4d_causal_attention_mask_for_sdpa` in the shared branch. With `IS_GEMMA2`, that branch is skipped. The training masks come from `Gemma2AttentionMaskConverter(...).to_4d` and `AttentionMaskConverter(...).to_4d` instead. For a left-padded row, every pad query row in both masks is fully masked with the finite dtype minimum. `slow_attention_softcapping` adds the mask to the scores and runs softmax, so a fully masked row gets uniform weights over all keys (`[0.25, 0.25, 0.25, 0.25]` for `attention_mask = [0, 0, 1, 1]`). With `DataCollatorForSeq2Seq` left padding, the first real label is kept and, after the causal shift, it is predicted from the last pad query, which can see that token. This path runs for any Gemma2 model trained through `FastLanguageModel` with left padding. A padded 2D mask keeps `attention_mask` non-None, so the slow softcapping kernel is used even when flash-attn softcapping is installed. ## Fix - Apply `_pad_queries_attend_self` to both dynamic Gemma2 masks, under the same guard as the shared branch (`self.training` and no KV cache). Eval and generation masks are unchanged. - `_pad_queries_attend_self` now returns one `torch.where` result instead of two full-size `masked_fill` copies plus two batch-sized boolean masks. The output is bitwise identical to the old version, and the input mask is never written. ## Tests New `tests/test_gemma2_left_padding_training_mask.py` (CPU). It runs the real `LlamaModel_fast_forward` on a tiny random Gemma2 with capture layers and checks: - each pad query row allows only itself, in both the sliding and global masks (fp32 and bf16); - real-token rows match the converter masks bit for bit; - with the softcapping attention math, the pad query output does not change when later values change, and real-token outputs are bitwise identical; - eval masks are untouched; - the new helper equals the old two-`masked_fill` form bit for bit (bool, fp32, bf16). Command (per worktree): `python -m pytest -o addopts= -m "not server and not native_mxc" -p no:cacheprovider -q tests/test_gemma2_left_padding_training_mask.py tests/test_llama_left_padding_training_mask.py tests/test_gemma2_attention_masks.py tests/test_gemma2_softcap_int32_split.py` - Base (main 8ef13a7 plus the new test only): `2 failed, 20 passed, 10 skipped`. Both failures are `test_left_pad_queries_attend_only_themselves`, where the pad row allows no key at all (`[False, False, False, False, False]`). - This branch: `22 passed, 10 skipped`. - transformers 5.22.1 / torch 2.14.1 CPU, new test plus the unslothai#18272 test file: `12 passed, 6 skipped`. ## Not proven here - No GPU run. The CUDA-only Gemma2 tests in the touched files were skipped, as was an end-to-end `FastLanguageModel` Gemma2 training step with left padding. - The compiled softcapping kernel was not run. The test uses its eager math. - No other model family has its own training mask branch in `LlamaModel_fast_forward`. Cohere, Granite, Qwen2 and Mistral go through the shared branch that unslothai#18272 fixed, and Gemma3 does not use this forward. The per-model `_prepare_4d` calls in gemma, gemma2, cohere, granite and falcon_h1 are decode-only inference paths.
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Nov 24, 2026
…key (unslothai#18950) ## Summary `fix_transformers_fully_masked_rows` (unslothai#9848, for the NaN in unslothai#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` (unslothai#18272, unslothai#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, unslothai#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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Left-padded training: pad queries attend only themselves
Follow-up to #18202. Left-padded training batches now keep their padding mask, which fixed real tokens attending pads. It also exposed one leak.
_prepare_4d_causal_attention_mask_for_sdpaunmasks every fully masked row on CUDA (_unmask_unattended), and the SDPA dispatch does the same for boolean masks (no_allowed). With left padding the last pad query is fully masked, so it attends every key, including later tokens.DataCollatorForSeq2Seqwithpadding_side = "left"keeps the first real label, and the causal shift scores that label from the last pad position. So one supervised prediction per left-padded row could see the token it predicts and every token after it.Before #18202 the mask was dropped for labelled batches, so that position was causal (it attended only pads). With #18202 it was unmasked to the whole row.
Fix
unsloth/models/llama.py: in training, with no KV cache, after the 4D mask is built, every pad query attends only to its own key (_pad_queries_attend_self). The row is causal and never fully masked, so there are no NaN rows. Real-token rows are unchanged. Inference and cached decoding are unchanged. Pad positions only feed pad keys, which real queries never attend, so real-token outputs and losses do not change.Tests
tests/test_llama_left_padding_training_mask.py:test_pad_queries_attend_only_themselves(CPU): boolean and additive masks, left and interior padding. Pad rows keep only the diagonal; real rows are unchanged; nothing above the diagonal is allowed.test_left_padded_pad_query_prediction_does_not_see_later_tokens(GPU): a left-padded row with tokens after position 6 changed. The logits up to position 5, including the last pad position that predicts the first real token, must not change. This fails on main and passes here.The rest of the left-padding and masked SDPA alignment tests pass on torch 2.14.1 and 2.12.1.