Skip to content

Training forward: keep the padding mask for left and interior padded batches - #18202

Merged
danielhanchen merged 3 commits into
mainfrom
lora-training-keeps-left-padding-mask
Nov 17, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
lora-training-keeps-left-padding-mask

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

LlamaModel_fast_forward drops 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 DataCollatorForSeq2Seq with tokenizer.padding_side = "left", or a user who sets padding_side = "left".

Fix

  1. unsloth/models/llama.py: drop the mask in training only when no pad precedes a real token, with or without labels:

    real = attention_mask != 0
    return bool((real[:, 1:] & ~real[:, :-1]).any())

    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).

  2. 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 with attn_bias is not correctly aligned or 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.

padding labels main this PR
right yes 8.3e-07 8.3e-07
left yes 1.81 (Qwen3), 1.65 (Llama) 1.4e-06, 2.7e-07
interior yes 1.25, 0.99 1.8e-06, 3.2e-07
left no 1.5e-06 1.5e-06
interior no 0.97, 0.68 1.5e-06, 5.5e-07

Through transformers.Trainer with DataCollatorForSeq2Seq, 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.

torch mask fix only this PR
2.11.0 1 / 9 (only length 16) 9 / 9
2.12.1 1 / 9 (only length 16) 9 / 9
2.13.0 1 / 9 (only length 16) 9 / 9
2.14.0 9 / 9 (left and interior run) same code path as the mask fix (gate off)
2.14.1 9 / 9 9 / 9 (no padding)
2.15.0 9 / 9 9 / 9 (no padding)
  • Faults: in float32 on 2.12.1 the mask-fix-only branch faults at every length except 12 and 16. With this PR, 0 of 9 lengths fault and the worst relative LoRA gradient error against the unpadded row is 1.9e-06 (left) and 2.7e-06 (interior).
  • bf16 errors: in bf16 the worst relative error is 0.012 to 0.071 on every torch version, which is the same spread as two unpadded rows batched together (0.003 to 0.063). On main, left padding gives 1.0 to 1.8.
  • Right-padded and unpadded batches: these still drop the mask and take the causal path. They run all 9 lengths on every version with the same numbers as before, 0 graph breaks and the same graph count.
  • Masked path: 0 graph breaks, and 4 compiled graphs over lengths 9 to 17 on every torch version, padded or not.

Tests

  • tests/test_llama_left_padding_training_mask.py:
    • The helper is checked for right, left and interior masks in four dtypes (CPU).
    • A new GPU test compares a labelled left-padded and interior-padded LoRA step with the unpadded row (loss and LoRA grads) at lengths 13 and 16.
  • tests/test_masked_sdpa_alignment.py (new):
    • The version gate.
    • The padded call matches plain SDPA on CPU in float32 (left-padded bool and additive masks, with and without GQA, lengths 5 to 17).
    • A compiled bf16 masked training call at lengths 9 to 17 runs with no fault and no graph break, and matches eager.
  • 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:

torch main (pass / fail / skip) this PR (pass / fail / skip)
2.12.1, transformers 4.57.6 613 / 38 / 33 648 / 3 / 33
2.15.0, transformers 5.23.0 613 / 55 / 16 647 / 21 / 16

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, one test_hf_packed_attention case and the test_lora_init cuSolver cases.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 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-17T19:10:56.431872Z 161d6c7 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 161d6c772d

ℹ️ 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".

[skip ci]
@danielhanchen
danielhanchen merged commit 31edb91 into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the lora-training-keeps-left-padding-mask branch November 17, 2026 19:42
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant