Skip to content

Fix fp16 LoRA training with plain transformers.Trainer (fused CE gradients underflowed) - #13152

Merged
danielhanchen merged 3 commits into
mainfrom
fix-fp16-trainer-scaler
Oct 11, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fix-fp16-trainer-scaler

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 is d(loss * scale) / d(hidden). Only the generated TRL / RL trainer wrappers in unsloth/models/rl.py set that attribute.

A plain transformers.Trainer never sets it. That is the trainer the TTS notebooks use (Orpheus, Llasa, Spark, Oute). In fp16 (T4, V100, any fp16=True run) 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_loss already wraps Trainer.compute_loss for every trainer. It now attaches trainer.accelerator.scaler to the model chain (through peft and module / _orig_mod wrappers), the same way rl.py does 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 (plain Trainer, r=64, lr 2e-4, bs 1 x ga 4), 40 steps:

Run loss step 1 step 20 step 40 mean of last 10 steps grad norm steps 1-3
plain HF + PEFT, fp16 5.5727 4.9357 4.8527 4.782 0.2631, 0.2889, 0.2704
plain HF + PEFT, bf16 5.5735 4.9412 4.8589 4.789
Unsloth main, bf16 5.5737 4.9415 4.8587 4.789
Unsloth main, fp16 (B200) 5.5728 5.6272 5.3562 5.273 nan, 0.3539, 0.3266
Unsloth main, fp16 (Colab T4) 5.5717 5.6280 5.3555 5.271
this PR, fp16 (B200) 5.5728 4.9356 4.8527 4.782 0.2631, 0.2889, 0.2705

One-batch LoRA gradient check against a plain HF fp32 reference (same LoRA weights in every arm), cosine similarity per LoRA parameter:

Arm mean worst
plain HF fp16 0.9999 0.997
Unsloth main bf16 0.9997 0.998
Unsloth main fp16 0.954 -0.268 (layer 27 k_proj)

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.py checks 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.

@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-11T03:39:44.469775Z aa27bb1 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
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 24c82c385d

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

@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: 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".

Comment thread unsloth/models/_utils.py
Comment on lines +4865 to +4866
scaler = getattr(getattr(trainer, "accelerator", None), "scaler", None)
if scaler is None or getattr(model, "accelerator_scaler", None) is scaler:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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

Comment thread unsloth/models/_utils.py
Comment on lines +4865 to +4866
scaler = getattr(getattr(trainer, "accelerator", None), "scaler", None)
if scaler is None or getattr(model, "accelerator_scaler", None) is scaler:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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.

@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. More of your lovely PRs please.

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

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] Orpheus_tts espanish finetune ,cannot generate valid voice

1 participant