Repository navigation
Training forward: keep the padding mask for left and interior padded batches - #18202
Merged
Merged
Conversation
…l token LlamaModel_fast_forward dropped the attention mask in training mode unless the batch was label-less and left padded. With labels present (every SFT step), a left-padded or interior-padded batch therefore ran plain causal attention and real tokens attended to the pad tokens before them. LoRA gradients differed from the same rows run unpadded by 100% to 180% on tiny Qwen3 and Llama, and the Trainer with DataCollatorForSeq2Seq and padding_side="left" produced a grad norm 10% to 33% off the right-padded run of the same rows. Drop the mask only when every pad comes after the last real token (right padding or no padding), with or without labels. The check is one elementwise pass over the 2D mask and one host sync per forward; right-padded and unpadded batches keep the fast causal path.
Keeping the padding mask in training sends left- and interior-padded batches
through masked SDPA inside the per-block compiled region. On torch 2.11, 2.12
and 2.13, Inductor stores the head-expanded attention bias of the
memory-efficient backward densely, so any sequence length that is not a
multiple of 8 faults ("attn_bias is not correctly aligned" or a misaligned
address). torch 2.14.0 and later, and eager SDPA, are not affected.
On those versions only, and only for a traced masked training call, pad Q, K,
V and the mask by 2 to 9 rows to the next multiple of 8 (padded keys masked,
padded query rows sliced off). This is exact, adds no graph breaks, and a pad
that is never 0 or 1 avoids a dynamo specialisation and its recompile.
Unmasked (right-padded or unpadded) calls are untouched.
Member
Author
|
@codex review |
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: Didn't find any major issues. Keep them coming! 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". |
[skip ci]
danielhanchen
added a commit
that referenced
this pull request
Nov 17, 2026
…8224) ## Gate the masked SDPA compiled backward test on a real CUDA device `tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe` fails on `main` since #18202: ``` these skip guards read a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide ... test_masked_sdpa_alignment.py:94: torch.cuda.is_available() ``` ### Cause #18202 added `test_compiled_masked_training_sdpa_backward_at_unaligned_lengths`, a CUDA-only test, behind `@pytest.mark.skipif(not torch.cuda.is_available(), ...)`. `tests/_zoo_aggressive_cuda_spoof.py` patches that probe to `True` process-wide. As a result, the test un-skips on a CPU-only runner whenever it shares a pytest session with `tests/version_compat` or `tests/vllm_compat`. The lint exists to catch exactly that. ### Fix The guard now uses `has_real_cuda()` from `tests/_shared/real_accelerator.py`, the same helper the other CUDA-only tests use (e.g. #18204). The test body is unchanged, so on a real GPU it runs exactly as before. ### Verification - `tests/python/test_accelerator_skip_guards.py`: fails on `main` on this line, passes with this change. - `tests/test_masked_sdpa_alignment.py`: passes on CPU, and the CUDA-only cases still skip.
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Nov 18, 2026
…8272) ## Left-padded training: pad queries attend only themselves Follow-up to unslothai#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_sdpa` unmasks 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. `DataCollatorForSeq2Seq` with `padding_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 unslothai#18202 the mask was dropped for labelled batches, so that position was causal (it attended only pads). With unslothai#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.
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.
Problem
LlamaModel_fast_forwarddrops the attention mask in training mode and runs plain causal attention. That is exact only when every pad comes after the last real token (right padding or no padding). The only exception kept the mask for label-less, left-padded batches, so any labelled step (every SFT step) on a left-padded or interior-padded batch let real tokens attend to the pad tokens before them. Interior padding was also missed in the label-less case, because the old check only read column 0.Unsloth's own tokenizer pads on the right during training, so this is reached by collators that pad on the left, for example
DataCollatorForSeq2Seqwithtokenizer.padding_side = "left", or a user who setspadding_side = "left".Fix
unsloth/models/llama.py: drop the mask in training only when no pad precedes a real token, with or without labels:Right-padded and unpadded batches keep the fast causal path. The check is one elementwise pass over the 2D mask and one host sync per forward (the label-less path already paid one sync for its column-0 check).
unsloth/utils/attention_dispatch.py: keeping the mask sends left- and interior-padded batches through masked SDPA inside the per-block compiled region. On torch 2.11, 2.12 and 2.13, Inductor stores the head-expanded attention bias of the memory-efficient backward densely, so any sequence length that is not a multiple of 8 faults withattn_bias is not correctly alignedor a misaligned address. This already happened on main for label-less left-padded batches. On those torch versions only, and only for a traced masked training call, Q, K, V and the mask are padded by 2 to 9 rows to the next multiple of 8 (padded keys masked, padded query rows sliced off). The padded call is exact. A pad of 2 to 9, never 0 or 1, avoids a dynamo specialisation and the recompile it would cause. Eager calls, unmasked calls and torch 2.14 and later are untouched.Evidence
Gradients against the same rows run unpadded
Tiny Qwen3 (
trl-internal-testing/tiny-Qwen3ForCausalLM) and tiny Llama (hf-internal-testing/tiny-random-LlamaForCausalLM), LoRA r=8 on all projections with nonzero LoRA B, float32, torch 2.12.1. The table shows the worst relative LoRA gradient error over rows.Through
transformers.TrainerwithDataCollatorForSeq2Seq, one step at lr 0, padding the same rows left and then right: the grad norms differed by 10.4% (Qwen3) and 33.5% (Llama) on main, and by under 1e-7 with this PR.Torch matrix for the compiled masked SDPA backward
Tiny Qwen3, LoRA, bf16,
use_gradient_checkpointing = "unsloth", per-block compile on, transformers 4.57.6, sequence lengths 9 to 17. Each cell shows how many of the 9 lengths ran without a fault, for left-padded, interior-padded and label-less left-padded batches. Each padded row is checked against the same row run unpadded.Tests
tests/test_llama_left_padding_training_mask.py:tests/test_masked_sdpa_alignment.py(new):tests/test_ppo_trainer_patches.py: the source pin follows the new condition.Related padding, packing, padding-free, block compile, SDPA bucketing, PPO, distillation and Online DPO suites, one process per file:
Every difference is a test going from fail to pass. Every test that fails with this PR fails on main too:
test_block_does_not_recompile_per_length_mod_8[torch_guard], the two cuDNN bucket length tests,test_qwen3_5_gdn_block_has_no_break, onetest_hf_packed_attentioncase and thetest_lora_initcuSolver cases.