Skip to content

Pass GradScaler to GKD chunked JSD with an older-Zoo fallback - #13190

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
taking-lying-flat:fix/gkd-fp16-grad-scaling
Oct 11, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
taking-lying-flat:fix/gkd-fp16-grad-scaling

Conversation

@taking-lying-flat

Copy link
Copy Markdown
Contributor

Pass the trainer's active GradScaler to GKD's chunked generalized JSD so FP16 gradients are scaled before the loss precomputes them in its forward pass. Without this, a finite loss can accompany zero LoRA gradients and no adapter update; the later outer scaler.scale(loss).backward() cannot recover gradients that have already underflowed.

Companion loss implementation: unslothai/unsloth-zoo#1659. Merge and release that Zoo change first, then merge this caller update.

When scaling is enabled but the installed Zoo has no scaler parameter, return through the existing TRL loss fallback before running either model forward. That preserves correct scaling with older Zoo, at the cost of its ordinary full-logits memory use. With an absent or disabled scaler, the existing chunked call remains compatible with old Zoo. No dependency version bump is required for compatibility.

Validation

Rebased onto 4527f330.

  • A local source-isolated harness executes the generated compute_loss, this production helper, and the installed TRL loss/fallback. All six combinations of old/current Zoo and enabled/disabled/absent scaler pass loss and gradient parity. It also verifies that the old-Zoo fallback takes only one student forward and restores the hidden-state environment flag. These local tests are outside this production-only diff.
  • Combined Zoo and caller validation: 101 passed, 3 skipped. The three skipped cases need two CUDA devices. This includes 79 existing Zoo JSD tests, FP16 autocast/gradient accumulation, upstream loss weighting, and trainable/frozen head and bias combinations.
  • Native small Llama + PEFT on CPU: fixed/reference gradients and optimizer updates match exactly for 64, 512, and 1024 valid tokens.
  • Native CUDA on an RTX A1000 Laptop GPU, both eager and compiled JSD: the original path has all-zero LoRA gradients at 512/1024 tokens; the fixed paths update adapters and stay below 0.18% gradient relative L2 error against ordinary externally scaled JSD. Configuration and measured results are in the companion Zoo PR.
  • uvx --from ruff==0.15.12 ruff check unsloth/models/rl_replacements.py and git diff HEAD^ HEAD --check: passed.

CPU validation commands (the last two files are local-only checks):

UNSLOTH_COMPILE_DISABLE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 \
  .venv/bin/python -m pytest \
  tests/test_distillation_chunked_jsd.py \
  tests/test_gkd_gradscale_local.py \
  tests/test_gkd_trainer_scale_local.py -q -p no:cacheprovider

The command runs from the Zoo checkout with both source repositories on PYTHONPATH. Full GKDTrainer training and distributed training have not been validated; the local complete trainer-suite import was blocked by environment/package setup, so the caller checks execute the generated production source directly. The CUDA checks are model forward/backward/optimizer comparisons, not a convergence claim.

Open-PR searches for GKD, JSD, and GradScaler found no overlapping JSD repair. #13152 fixes scaler attachment for fused cross entropy under plain transformers.Trainer; it does not pass a scaler to GKD's chunked JSD.

Only production code is included. AI assistance was used to prepare the change and run the local validation.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 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:40:35.231799Z c344f04 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.

@Etherll

Etherll commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

Under FP16, GKD's chunked JSD now receives the trainer's GradScaler, so gradients computed during the forward pass are scaled before they can underflow. This needs unslothai/unsloth-zoo#1659. With an Unsloth Zoo that has no scaler argument, FP16 GKD falls back to TRL's dense loss. bf16 and fp32 take the same path as before.

What changed

  • Under FP16, the chunked JSD computed gradients before GradScaler scaling, so small per-token gradients underflowed and LoRA updates came out too small. The active scaler is now passed in and applied first.
  • With a Zoo that can't take the scaler, FP16 GKD switches to TRL's dense loss before any forward pass, instead of training on underflowed gradients.

Tested on 29f98d9 with a real Unsloth GKD FP16 run on one GPU (Qwen2.5-0.5B-Instruct, LoRA, ~900-token completions, teacher close to the student). On main, the LoRA gradient norm was 20% (step 1) and 31% (step 2) below TRL's dense loss. This PR with unslothai/unsloth-zoo#1659 matched it within 0.005%. Main with only the Zoo change stayed 20% low, so both halves are needed. Gradients did not go fully to zero in this setup. The current Zoo release falls back and matches the dense loss. bf16 matches main, and the existing GKD tests pass. Multi-GPU FP16 was not run.

Until unslothai/unsloth-zoo#1659 ships and the unsloth_zoo>=2026.10.3 floor is raised, FP16 GKD (T4/Colab) uses the dense loss and its higher memory, so merge order matters.

Fork CI: Etherll#225 (running).

@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c344f04879

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

3 participants