Repository navigation
Fix fp16 LoRA training with plain transformers.Trainer (fused CE gradients underflowed) - #13152
Conversation
… gradients do not underflow
Codex Review SummaryThis 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. Bravo. 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". |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa27bb19db
ℹ️ 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".
| scaler = getattr(getattr(trainer, "accelerator", None), "scaler", None) | ||
| if scaler is None or getattr(model, "accelerator_scaler", None) is scaler: |
There was a problem hiding this comment.
Clear stale scalers when the current trainer has none
When a model previously trained with fp16 is reused by a bf16/fp32 Trainer, accelerator.scaler is None, but this return leaves the old GradScaler attached throughout the model chain. The fused CE call therefore continues saving gradients multiplied by the old scale while the new Trainer performs an unscaled backward/update, potentially producing enormous or non-finite gradients and corrupting the subsequent run. The no-scaler path should remove or neutralize any scaler previously attached by this helper rather than always being a no-op.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not a correctness issue: the fused CE backward divides the saved gradient by the same scaling it applied in the forward (scale_factor = grad_output / scaling), so a leftover GradScaler under an unscaled bf16/fp32 backward gives the same gradients. Checked on GPU with unsloth_fused_ce_loss, bf16 and fp32, 2048 tokens x 32k vocab: stale scaler (65536) vs no scaler gives identical loss and max relative gradient difference 0.0.
| scaler = getattr(getattr(trainer, "accelerator", None), "scaler", None) | ||
| if scaler is None or getattr(model, "accelerator_scaler", None) is scaler: |
There was a problem hiding this comment.
Handle DeepSpeed's loss scaler
For a plain Trainer configured with DeepSpeed fp16, Accelerate intentionally leaves accelerator.scaler as None because DeepSpeed owns loss scaling, so this helper returns without attaching any scale. The fused CE path then has the same unscaled-in-forward gradients that this change is meant to fix, causing underflow and ineffective LoRA training in a supported distributed Trainer configuration; this path needs to bridge DeepSpeed's active loss scale or decline the fused loss.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pre-existing and out of scope here: with DeepSpeed fp16 accelerate leaves accelerator.scaler as None, and the TRL trainer wrappers in rl.py assign that same None today, so SFTTrainer and friends behave identically under DeepSpeed. This PR only brings the plain Trainer to parity with the TRL path; it does not change DeepSpeed behaviour for either.
|
@codex review |
1 similar comment
|
@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". |
Fixes #3529
Problem
Unsloth's fused cross entropy computes the gradient with respect to the hidden states inside the forward pass and saves it in the model dtype. It expects the fp16 GradScaler scale through
model.accelerator_scaler, so the saved gradient isd(loss * scale) / d(hidden). Only the generated TRL / RL trainer wrappers inunsloth/models/rl.pyset that attribute.A plain
transformers.Trainernever sets it. That is the trainer the TTS notebooks use (Orpheus, Llasa, Spark, Oute). In fp16 (T4, V100, anyfp16=Truerun) the per-logit gradients are then computed unscaled. With a ~157k vocab and a few thousand tokens per sequence they sit far below the fp16 normal range and underflow before the GradScaler's factor is applied in backward. Training runs and the loss is finite, but the LoRA barely learns. bf16 has no GradScaler and is unaffected.Fix
_unsloth_pre_compute_lossalready wrapsTrainer.compute_lossfor every trainer. It now attachestrainer.accelerator.scalerto the model chain (through peft andmodule/_orig_modwrappers), the same wayrl.pydoes for TRL trainers. It is a no-op when there is no scaler (bf16 / fp32) or when the scaler is already attached, so TRL trainers are unchanged.Evidence
The reporter's own data (46 clips,
canopylabs/3b-es_it-ft-research_release), the notebook recipe (plainTrainer, r=64, lr 2e-4, bs 1 x ga 4), 40 steps:One-batch LoRA gradient check against a plain HF fp32 reference (same LoRA weights in every arm), cosine similarity per LoRA parameter:
Switching Unsloth's attention to SDPA, replacing the RoPE kernel with plain torch, and turning off gradient checkpointing each left the fp16 gradients unchanged. That points at the fused loss's saved gradient.
tests/test_trainer_fp16_scaler_attach.pychecks that the scaler reaches the CausalLM through peft and a DDP-style wrapper, that it is attached before the loss is computed, and that runs without a scaler are left alone. It fails on main and passes here.