Repository navigation
Stop a left-padded row that attends to nothing returning NaN (#9708) - #9848
Conversation
transformers' sdpa_mask returns a boolean mask with no correction for query
rows that attend to no key at all, and the parameter that used to make that
correction is now documented "Deprecated and has no effect. Will be removed in
version 5.18.0.". 4.57.6 still carried it, guarded on
`not _is_torch_greater_or_equal_than_2_5`: upstream retired it believing torch
2.5 had made it unnecessary.
It has not. Measured on a B200, torch 2.13.0+cu130, transformers 5.15.1,
unquantized fp16 google/gemma-4-E2B-it, with no unsloth in the process: a single
forward pass returns NaN logits on exactly the rows that received a left pad
token and finite logits on every row that did not, 16 rows of 16 across batch
sizes 2, 4 and 8, and under generate those rows decode to the empty string.
A fully masked row makes SDPA produce NaN and the NaN then spreads along the row
through 0 * NaN where the next layer mixes values.
Restoring the correction, on the same machine and the same unsloth-free
reproduction:
gemma-4 fp16 before 16 NaN rows, batches 2/4/8 all disagree
after 0 NaN rows, batches 2/4/8 all AGREE exactly
gemma-4 bf16 before no NaNs but 2/4/8 disagree
after 2/4/8 all agree
Qwen3.5-2B unchanged, as expected: it diverges with equal-length prompts
and no padding at all, which is a different mechanism
Probe-gated on behaviour rather than a version, because the parameter was live
in 4.x and the retirement landed mid-5.x. The correction is self-neutralising -
mask | ~mask.any(-1) contributes nothing once a row attends to something - so if
a future transformers restores its own guard this becomes a no-op rather than
permanent damage. Both bindings are moved: the module global that eager_mask
resolves at call time, and the interface entry that captured the original.
12 tests, 8 mutations caught, including a negative control that fails if the
upstream defect disappears so the fix cannot outlive its bug unnoticed.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b0b36310ae
ℹ️ 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".
| """ | ||
| if mask is None or mask.is_floating_point(): | ||
| return mask | ||
| return mask | ~mask.any(dim = -1, keepdim = True) |
There was a problem hiding this comment.
Skip the quadratic rewrite when no row is fully masked
When SDPA materializes a mask for an unaffected input, such as a right-padded batch or a compile/static-cache path, this expression still scans the entire 4D mask and allocates another full-size mask even though every row already attends to a key. For long sequences that adds an unconditional O(batch × query × key) operation and temporarily doubles mask storage, potentially causing a material performance regression or OOM for users who never use left padding; gate the correction using the 2D padding information or otherwise avoid producing a replacement mask when there are no empty rows.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The measurement first: the ~mask.any(dim = -1, keepdim = True) term is (batch, 1, q, 1), not full size, so the only full-size allocation is the result of the |, and it replaces a tensor that is freed as the expression returns. That is one extra mask alive for the duration of one elementwise op, on a path only reached when transformers already materialised a mask -- sdpa_mask returns None via _ignore_causal_mask_sdpa when there is no padding, and the wrapper returns None unchanged.
The suggested gate is what I cannot do. The 2D padding information is not in scope inside the wrapper, which sees only the 4D result, and any gate derived from the result itself (if empty.any(): ...) is a data-dependent branch on tensor contents: that forces a device sync and graph-breaks every compiled forward that materialises a mask. Trading a certain regression in the compiled path for a speculative one is the wrong direction.
In-place would remove the second allocation, and upstream's own retired guard did exactly that (causal_mask |= torch.all(~causal_mask, dim=-1, keepdim=True)), but it did so on a tensor it had just built and therefore owned. A wrapper cannot assume ownership across every transformers this has to support: a version returning a broadcast or expanded view would raise "more than one element of the written-to tensor refers to a single memory location" instead, which is a hard crash where today there is bounded transient memory.
| and a `dtype == torch.bool` check then answers "not affected" for a reason | ||
| that has nothing to do with the bug. | ||
| """ | ||
| return torch.tensor([[False, True], [True, True]], dtype = torch.bool) |
There was a problem hiding this comment.
Create probe tensors on an explicit supported device
If torch.set_default_device("meta") or a meta device context is active before import unsloth, this probe mask is created on meta while newer sdpa_mask implementations default their index tensors to CPU. The resulting exception is interpreted as “not affected,” so the patch is silently skipped for the rest of the process; on implementations that return a meta mask, the later bool(...) conversion can instead abort the import. Construct both the probe mask and cache_position explicitly on CPU and pass a matching device argument when supported.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5b2f660. Correct, and the second half was the worse of the two: the read-back of the probe result sat outside the try, so a mask whose truth value cannot be taken propagated out of import unsloth rather than answering "not affected". Both probe tensors are now built with an explicit device = "cpu", a device kwarg is passed when the signature has one, and the read is inside the guard. New test drives it under torch.set_default_device("meta") and fails if either half is reverted.
| if getattr(masking_utils, _SDPA_MASK_PATCH_FLAG, False): | ||
| return |
There was a problem hiding this comment.
Verify the installed wrapper before trusting the patch flag
If transformers.masking_utils is reloaded after this function runs, Python re-executes the module in the existing namespace, so the Unsloth flag remains True while sdpa_mask and its registry entry are reset to the upstream implementations. A subsequent call probes the defect successfully but returns here without restoring the wrapper, leaving left-padded inference vulnerable again; the guard should verify that the current function and registry are actually patched rather than relying on the persistent module flag alone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5b2f660. The guard was asking the wrong object. importlib.reload re-executes the module body in the existing namespace, so sdpa_mask and the registry entry revert to upstream while an attribute we set on the module survives, and the guard then refuses to re-patch a build that is vulnerable again. The mark now travels on the wrapper and _sdpa_mask_is_patched asks both live bindings, so a reloaded or half-installed state is patched rather than skipped. Two tests, one reconstructing exactly what a reload leaves behind.
The probe built its mask on the ambient default device, so a
torch.set_default_device("meta") around the import put it on meta, where
sdpa_mask builds its own index tensors on CPU. The read-back of the result also
sat outside the try, so a mask whose truth value cannot be taken propagated out
of import unsloth instead of answering the question. Pin both probe tensors to
CPU and move the read inside the guard.
The idempotence guard read a flag on the module. importlib.reload re-executes a
module body in the existing namespace, so sdpa_mask and the registry entry
revert to upstream while the flag survives, and the guard then refuses to
re-patch a build that is vulnerable again. Mark the wrapper itself and ask both
live bindings, so a reloaded or half-installed state is patched rather than
skipped.
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
…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.
Fixes #9708 for the gemma-4 half, inside unsloth. No upstream change required.
What is wrong
transformers.masking_utils.sdpa_maskbuilds a boolean mask and returns it with no correction for query rows that attend to no key at all. The parameter that used to make that correction is now:In 4.57.6 the same function still carried it, guarded on
not _is_torch_greater_or_equal_than_2_5, with a docstring saying it exists "in order to avoidnanpropagation (this does not change the final result)". Upstream retired it believing torch 2.5 had made it unnecessary.It has not. A left-pad query row is causally restricted to keys the padding mask then removes, so the row is entirely masked, SDPA returns NaN for it, and the NaN spreads along the row through
0 * NaNwhere the next layer mixes values.Measured
NVIDIA B200 (sm_100), torch 2.13.0+cu130, transformers 5.15.1, unquantized fp16
google/gemma-4-E2B-it, no unsloth in the process: a single forward pass — nogenerate, no cache — returns NaN logits on exactly the rows that received a left pad token and finite logits on every row that did not. 16 rows of 16 across batch 2/4/8. Undergeneratethose rows decode to the empty string. bitsandbytes is not involved; the unquantized arm is identical row for row. Three repeats per batch size are byte-identical.Same machine, same reproduction, with this patch:
[0,1,2,3,4,5,6][]Qwen3.5-2B is deliberately not claimed: it diverges with equal-length prompts and no padding at all (batch 2 disagrees, 4 and 8 agree, stably over three repeats), which is a linear-attention/gated-delta model and a different mechanism. It stays open.
The change
One probe and one wrapper in
unsloth/import_fixes.py, in the shape that file already uses for third-party patches (_transformers_needs_bare_annotation_fix/fix_transformers5_bare_annotation_configs), called from_gpu_init.pyatimport unsloth.eager_maskresolves at call time, and theALL_MASK_ATTENTION_FUNCTIONSentry that captured the original when the class body ran. Confirmed by search:sdpa_maskis defined once in transformers and no other module references it.mask | ~mask.any(-1)contributes nothing once a row attends to something, so if a future transformers restores its own guard this becomes a no-op rather than permanent damage.finfo(dtype).minand survives softmax's max-subtraction as uniform attention already.__wrapped__, every failure swallowed intologger.infoso a patch that cannot apply never breaks an import.Compatibility
Verified on transformers 4.57.6 (torch 2.9.1) and 5.15.1 (torch 2.13.0): probe True on both, patch removes the empty row on both, idempotent on both, registry rebound on both. 4.57.6 is affected too — its guard only fires for torch < 2.5.
No device, dtype or platform branch; no vLLM path touched, so
fast_inference = TrueGRPO is unaffected. The wrapper is ordinary tensor algebra thattorch.compiletraces, and it sits below unsloth_zoo'screate_causal_maskwrapper, so the two compose in either order.Tests
12 tests in
tests/test_sdpa_fully_masked_rows.py, all driving the real functions rather than a hand-written dict, 8 of 8 mutations caught (no-op correction, correction widened to every row, float masks no longer excluded, registry not rebound, idempotence flag dropped, probe not unwrapping, probe mask dtype, gate removed).The first test is a negative control: it fails if the upstream defect disappears, and says to re-measure rather than delete the fix. A correction nobody can justify is how a workaround outlives its bug.
tests/root-level suite: 5417 passed. The two failures on it (test_source_read_encoding,test_studio_root_resilience) reproduce on an unmodified checkout and are not from this change.GPU-level regression coverage for batched generation against a
*ForConditionalGenerationmodel lands with the Kaggle Default leg in #9700 — that leg is what found this.