Skip to content

Keep the padding mask for left-padded label-less training forwards - #13154

Merged
danielhanchen merged 7 commits into
mainfrom
fix-left-padding-label-less-mask
Oct 11, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix-left-padding-label-less-mask

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Fixes #3705

Problem

LlamaModel_fast_forward drops the 2D attention mask in training mode because it assumes right padding (causal attention never reaches trailing pads). When the forward has no labels it also zeroes the pad embeddings (the DPO block). A left-padded, label-less batch therefore has every real token attending to zeroed pad positions, and the gradients go NaN.

That is exactly the ms-swift generative reranker flow from the issue: ms-swift pads reranker batches on the left by default (--padding_side left, "only support --padding_side left" in its listwise example at the version the reporter used), pops the per-sequence labels before calling the model, and reads the last token's yes/no logits. Plain transformers + PEFT keeps the mask and trains fine.

Fix

Keep the mask in training when the forward has no labels and some row starts with a pad (left padding). Everything else is unchanged:

  • Right padded or unpadded batches still drop the mask and take the fast path.
  • Labelled forwards (SFT) never run the new check, so they gain no device sync.
  • GRPO and Online DPO already right-align rows (left_pack_padding) and DPO flushes left, so their masks never trigger it. PPO keeps its existing opt-in flag.

Cost

The check is a host sync, so it runs only for label-less training forwards (_has_no_labels short-circuits it for SFT) and reads only the first mask column. B200, exclusive GPU, per call:

Mask full-row scan first column (this PR) bare torch.cuda.synchronize()
8 x 512 45.1 us 22.4 us 5.1 us
8 x 4096 55.3 us 23.5 us 5.4 us
64 x 2048 59.2 us 24.7 us 5.4 us

Behind queued GPU work all three read ~360 us, which is the queued work finishing, not added GPU time.

End to end, DPO on unsloth/Qwen3-0.6B (every forward label-less and right padded, so the check runs and the mask is still dropped), 40 steps, 8 runs ABBA on one exclusive B200, fresh process and compile cache each: median step time base 276 ms (runs 210 to 326 ms), head 236 ms (223 to 316 ms), difference 95% CI [-90, +61] ms, a tie inside the host noise. Losses are bit-identical across all 8 runs.

Results

Qwen3-Reranker, LoRA r=64 alpha=128, bf16, use_gradient_checkpointing="unsloth", GA 16, lr 2e-4, 8 sequences per group (1 positive + 7 negatives from mteb/scidocs-reranking), ms-swift's listwise generative reranker loss and RerankerTrainer.compute_loss reproduced verbatim, B200.

Model Arm grad_norm per step
Qwen3-Reranker-0.6B main, left padding nan on all 20 steps
Qwen3-Reranker-0.6B this PR, left padding 235.0, 313.2, 212.8, ... all finite
Qwen3-Reranker-0.6B transformers + PEFT, left padding 15.2, 19.5, 13.5, ... all finite
Qwen3-Reranker-0.6B main vs this PR, right padding identical losses and grad norms on all 20 steps
Qwen3-Reranker-8B main, left padding nan on all 5 steps
Qwen3-Reranker-8B this PR, left padding 59.8, 42.5, 59.3, 25.3, 18.3
Qwen3-Reranker-8B transformers + PEFT, left padding 3.76, 2.59, 3.69, 1.56, 0.99

The constant ~16x between the Unsloth and transformers columns is gradient accumulation, not this bug: the batch counter returns num_items_in_batch = None for per-sequence labels, and ms-swift's compute_loss only divides by GA when it is not None. With max_grad_norm=1.0 and AdamW the updates match; the per-step loss ratio is 14x to 18x across the run.

Tiny Qwen3, bf16, training mode: the left-padded row's logits vs the same row alone differ by up to 5.5e-2 on main (logits are ~4e-2) and 3.7e-4 with this PR.

Tests

  • tests/test_llama_left_padding_training_mask.py: the mask predicate over long, int, bool and float masks, plus a GPU test that the left-padded label-less training forward matches the unpadded row and gives finite LoRA gradients. The GPU test fails on main (Greatest absolute difference: 0.0549 (up to 0.005 allowed)) and passes here.
  • tests/test_ppo_trainer_patches.py: the source check for the training-mode mask branch now matches the new condition.

Unsloth's training forward drops the attention mask because it assumes
right padding. Label-less forwards (custom losses such as ms-swift's
generative rerankers, which left-pad and read the last token) also zero
the pad embeddings, so every real token attended to them and gradients
went NaN on the first step. Keep the mask for those batches only; right
padded and labelled forwards take the same path as before.

Fixes #3705
@danielhanchen danielhanchen self-assigned this Oct 9, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T04:18:58.511924Z 78cfb5c 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48c669d334

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

Comment thread unsloth/models/llama.py Outdated
Comment on lines +993 to +994
mask = attention_mask.bool()
return bool((mask[:, 1:] & ~mask[:, :-1]).any())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid a data-dependent Python branch in compiled forwards

When a label-less training forward is run under torch.compile(..., fullgraph=True) or CUDA graph capture, converting the device result of .any() to a Python bool requires a data-dependent scalar read: Dynamo cannot retain this in a full graph, and CUDA capture cannot perform the host synchronization. This path runs for every non-None mask, including all-ones and right-padded masks, so compiled custom-loss and reranker training can now fail before attention; guard tracing/capture and conservatively retain the mask there, or otherwise avoid the Python scalar conversion.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a regression: torch.compile(model, fullgraph=True) on this training forward already fails on main with the same Unsupported error (tiny Qwen3, LoRA, label-less, measured on both trees), and the default torch.compile (fullgraph=False) runs on both with finite logits. The fast forward is not CUDA graph captured in training.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 9f92a672c6

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

A left-padded row always starts with a pad, so one column answers the
question with a single small kernel instead of a full-mask scan; the
host sync stays, but only on label-less training forwards.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: bc93b24863

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

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 5caf67f8e4

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

torch.cuda.is_available() is patched to True by the CUDA spoof the
version_compat suites install, so the GPU test un-skipped on CPU-only
runners sharing their pytest session.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 78cfb5cb10

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Gradient explosion (NaN) when training Qwen 3 Reranker with Unsloth backend on A100

1 participant