Skip to content

Route GKD distillation through the chunked generalized JSD - #12136

Merged
danielhanchen merged 11 commits into
mainfrom
gkd-chunked-jsd
Sep 28, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
gkd-chunked-jsd

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Routes TRL's GKDTrainer loss through unsloth_zoo's chunked distillation_chunked_jsd, the same way GRPO avoids full logits. Neither the student nor the teacher materialises its (batch, seq, vocab) logits any more.

On gemma-3-270m-it distilled from gemma-3-1b-it (bs 4 x 1024, LoRA r16, TRL 1.14.0), peak memory drops from 65.5 GiB to 7.6 GiB and GPU kernel time per step drops from 173.8 ms to 73.0 ms. On a Colab L4, that config OOMs on main and trains on this branch at 4.0 GiB peak.

The objective is TRL's own, in every TRL release from 0.22.2 to 1.14.0. Anything the chunked path cannot reproduce exactly falls back to TRL's dense loss unchanged.

Closes #11554

Design

The work is in unsloth/models/rl_replacements.py (RL_FUNCTIONS["gkd_trainer"] and RL_PRE_ITEMS["gkd_trainer"]), with a small hook in unsloth/models/rl.py.

Loss path

  • The generated UnslothGKDTrainer.compute_loss tries _unsloth_gkd_chunked_loss first. TRL's original body is kept as _unsloth_trl_compute_loss and is the fallback.
  • Both forwards run with UNSLOTH_RETURN_HIDDEN_STATES=1, exactly as in GRPO, and the previous value is restored in a finally.
  • The hidden states and both lm_head weights go to distillation_chunked_jsd. It projects one chunk of valid rows at a time, in fp32, and applies bias, logit scale and final softcapping, read through the same detect_logit_transforms path GRPO uses.
  • Models the compiler did not rewrite get GRPO's hidden-state forward wrapper on model and teacher_model. _wrap_grpo_hidden_states_fallback now takes the attribute list; GRPO's default is unchanged.
  • If a forward returns real logits anyway, the call finishes on TRL's own generalized_jsd_loss with the tensors it already has. There is no second forward.
  • No unsloth_zoo change is needed; the merged distillation_chunked_jsd covers every TRL variant.

Version handling

  • TRL has shipped two compute_loss layouts:
    • up to 1.6: slice by the padded prompt width, labels [:, P:], local mean
    • from 1.7: plain causal shift, labels [:, 1:], and it forwards num_items_in_batch
  • The layout is read from TRL's source after ast canonicalisation. The forwards, the slicing, the single generalized_jsd_loss call with exactly its keywords, and the return must all match verbatim.
  • generalized_jsd_loss is only replaced when every canonical line is one that some TRL release shipped and all of the math lines are present. That catches a user override or a future TRL edit.
  • An unrecognised layout leaves the generated file untouched.
  • On TRL 0.29+, GKD lives in trl.experimental.gkd. The trainer is generated from there through Patch the TRL trainers that moved to trl.experimental (ORPO, CPO, Online DPO, GKD, ...) #12097, so the same source edit applies on every version.

Fallbacks to TRL's dense loss

  • return_outputs=True (eval needs logits)
  • use_liger_gkd_loss
  • FSDP or DeepSpeed
  • missing inputs
  • no teacher
  • a head that is not a plain dense nn.Linear (bitsandbytes 4/8-bit, a LoRA or modules_to_save head, a ZeRO-3 shard, meta)
  • a vocab mismatch
  • an old unsloth_zoo

Each fallback is counted on trainer._unsloth_gkd_chunked_fallbacks and logged once.

Controls: UNSLOTH_GKD_CHUNKED=0 turns the path off. UNSLOTH_GKD_CHUNK_SIZE sets the rows per chunk; the default is about 2**26 logits, which is 256 rows at a 262144 vocab.

Correctness

The oracle is TRL's own generalized_jsd_loss evaluated in float64. The grid is 600 cases per TRL version, run on TRL 0.25.1, 1.6.0 and 1.14.0:

  • beta {0, 0.1, 0.5, 0.9, 1}
  • temperature {1, 0.7, 2}
  • masks: random, prompt plus right pad, left pad, fully masked row, one token
  • (scale, softcap) {(1, 0), (0.5, 30)}
  • bias yes/no

Worst relative error:

inputs loss grad hidden grad head grad bias grad at masked tokens
fp32 6.3e-6 3.0e-5 2.5e-5 2.0e-5 0
bf16 2.0e-3 2.0e-2 2.0e-2 1.9e-2 0

Invariants:

  • num_items_in_batch=17: loss 5.3e-8 off the oracle.
  • Chunk size 1, 7, 64 and 4096 give the same result (2.2e-7).
  • Self-distillation gives zero loss and zero gradient.
  • Left and right padding are bit-identical.
  • A fully masked batch gives 0 with zero gradient. TRL before 1.6 returns NaN there; 1.6 and later also return 0.

Trainer-level parity uses one batch through the generated compute_loss. The dense arm is UNSLOTH_GKD_CHUNKED=0 in the same process. Errors are absolute, against the float64 loss.

TRL transformers pair TRL dense error chunked error grad cosine
0.25.1 5.17.0 tiny gemma3, 262144 vocab 3.6e-3 1.4e-6 0.99998
1.14.0 5.17.0 tiny gemma3 3.6e-3 7.6e-8 0.99998
0.22.2 4.57.6 tiny gemma3 3.6e-3 1.5e-6 0.99997
1.14.0 4.57.6 tiny gemma3 3.6e-3 2.0e-8 0.99998
0.25.1 5.17.0 gemma-3-270m-it from gemma-3-1b-it 1.7e-3 5.3e-4 0.99998
1.14.0 5.17.0 gemma-3-270m-it from gemma-3-1b-it 2.3e-3 1.2e-4 0.99998
1.14.0, UNSLOTH_COMPILE_DISABLE=1 5.17.0 tiny gemma3 3.6e-3 9.7e-8 0.99999

The chunked loss is closer to the exact value than TRL's dense loss. TRL's log-softmax runs in bf16 over the full vocab, which puts it about 10% off on the tiny pair. The two arms therefore differ slightly in value (about 0.6% of the step-1 loss on the real pair), in the direction of the exact loss.

Gradient accumulation, measured as the relative L2 distance of the first optimizer step's gradient from GA=1 x bs 4:

TRL arm GA 2 x bs 2 GA 4 x bs 1
0.25.1 chunked / dense / plain TRL without Unsloth 1.006 / 1.006 / 1.005 2.989 / 2.990 / 2.986
1.6.0 chunked / dense 1.006 / 1.006 2.989 / 2.990
1.7.1 chunked / dense 0.0030 / 0.0030 0.0034 / 0.0034
1.14.0 chunked / dense / plain TRL 0.0030 / 0.0030 / 0.0030 0.0034 / 0.0034 / 0.0031

Before 1.7, TRL averages each micro-batch locally, so GA=N gives about N times the GA=1 gradient. Plain TRL without Unsloth does the same, and this PR keeps TRL's objective as is (see Notes).

No per-chunk retention. The allocation trace uses V 262144, hidden 640, chunk 256 and bf16. Peak memory above the inputs, after subtracting the O(T x H) gradient buffer, stays at 1792 MiB as the chunk count grows:

T chunks peak above inputs MiB dense fp32 logits MiB
1024 4 1792.3 2048
4096 16 1792.4 8192
16384 64 1792.5 32768

torch.compile:

  • The loss chunk compiles to 1 graph over 5 sequence lengths, with 0 graph breaks, 0 unimplemented and 0 recompiles.
  • A full trainer run (12 steps, 6 warmup, fresh caches) shows 0 graph breaks and 0 recompiles after warmup on both main and this branch. This branch has 20 unique graphs against main's 15: one is the loss, and the rest are model-frame warmup compiles that settle before step 6.
  • UNSLOTH_COMPILE_DISABLE=1 runs and matches.

Performance

Setup: B200 shared with other jobs. Each arm ran in a fresh process with a fresh compile cache, interleaved main / branch over two rounds, with 10 measured steps after 3 warmup steps. Stock TRL calls torch.cuda.empty_cache() every step; it was a no-op in both arms for these timings, and one pair with it left on is shown separately. Peak memory was identical across rounds.

config TRL main peak GiB branch peak GiB main median step s branch median step s
gemma-3-270m-it from gemma-3-1b-it, bs 4 x 1024 1.14.0 65.54 7.60 0.247 / 0.336 0.147 / 0.143
same 0.25.1 59.21 7.60 0.213 / 0.228 0.141 / 0.128
same, TRL's empty_cache left on 1.14.0 65.54 7.60 0.595 0.159
tiny gemma3, 262144 vocab, bs 4 x 1024 1.14.0 60.51 2.57 0.135 / 0.134 0.042 / 0.040

GPU kernel time per step, from torch.profiler on TRL 1.14.0:

  • real pair: 173.8 ms on main, 73.0 ms on this branch
  • tiny pair: 161.6 ms on main, 28.9 ms on this branch

Loss only (B 4, T 1024, V 262144, hidden 640 / 1152, a quarter of positions masked):

beta / softcap TRL dense ms / MiB chunked ms / MiB
0 / 0 28.3 / 18437 19.5 / 536
0.5 / 0 94.9 / 34821 29.9 / 1816
1 / 0 31.0 / 19973 18.5 / 792
0.5 / 30 103.3 / 36869 36.1 / 1688

Small GPU: a Colab L4 (22 GiB) with TRL 0.24.0, transformers 5.5.0 and torch 2.11.0. It ran gemma-3-270m-it from gemma-3-1b-it at bs 4 x 1024 for 10 steps, with main and this branch in the same VM:

arm result peak alloc GiB step s
main CUDA OOM (20.8 GiB allocated when it failed) n/a n/a
this branch trains, 10 of 10 chunked calls, loss 0.319 to 0.154 4.05 1.44

Larger configs on the branch (B200 peaks): bs 8 x 1024 needs 12.7 GiB, and bs 16 x 1024 or bs 8 x 2048 needs 23.0 GiB. On main, bs 1 x 1024 already needs 18.2 GiB.

Compatibility matrix

Every TRL release from 0.22.2 to 1.14.0 (23 releases) was run against transformers 5.17.0 and 4.57.6, on main and on this branch: 92 cells. Each cell is a 2-step GKD run with lmbda 0.5, so on-policy generation is included.

  • All cells ran.
  • Main and branch losses are equal in all 46 pairs.
  • The branch took the chunked path on every step with no fallbacks. Main never took it.
TRL GKD source layout detected generated UnslothGKDTrainer tf 5.17.0 tf 4.57.6
0.22.2 to 0.25.1 trl.trainer.gkd_trainer prompt yes pass pass
0.26.2 to 0.28.0 trl.experimental.gkd (shim in trl.trainer) prompt yes pass pass
0.29.1 to 1.6.0 trl.experimental.gkd prompt yes (#12097) pass pass
1.7.1 to 1.14.0 trl.experimental.gkd shift + num_items_in_batch yes (#12097) pass pass

These mutations of TRL 1.14.0's source are rejected, and TRL's dense loss is used instead:

  • temperature= passed
  • an extra forward kwarg
  • different label slicing
  • a second loss term
  • reduction= passed
  • a changed return
  • in generalized_jsd_loss: a T**2 rescale, a mean over vocab, a dropped num_items reduction, an added term

Other checks:

  • The generated trainer files on main and this branch are byte-identical except UnslothGKDTrainer.py. Checked on TRL 0.25.1 (15 files) and 1.14.0 (11 files), and on TRL 1.14.0 with transformers 4.57.6.
  • Related unsloth tests (grpo, rl_, trl, online_dpo, sft, dpo, patch_trl, distill; 29 files): 367 passed on main and 407 passed on this branch, with no failures in either.
  • tests/python/test_gkd_chunked_jsd.py passes on TRL 0.22.2, 0.25.1, 0.28.0, 0.29.1, 1.6.0, 1.7.1 and 1.14.0.
  • import unsloth prints no new warnings.

Notes / follow-ups

  • Gradient accumulation before TRL 1.7: TRL divides each micro-batch by its own token count, so GA=N trains on about N times the GA=1 loss. TRL fixed this in 1.7 (Loss calculation of GKDTrainer may be inaccurate when performing gradient accumulation? huggingface/trl#4719). This PR matches TRL bit for bit and does not change the objective. A follow-up could rescale by local_items / num_items_in_batch on TRL < 1.7 behind an explicit opt-in. The rescale alone does not make GA exact there, because TRL's prompt-width slicing depends on the batch.

  • Fused kernel follow-up: a fused-linear JSD with a closed-form logit gradient was prototyped for unsloth_zoo and measured on the same harness:

    • kernel time per step: 56.2 ms against 73.0 ms on the real pair, and 12.4 ms against 28.9 ms on the tiny pair
    • the loss alone is 1.9x to 2.4x faster
    • but it uses 1.3 GiB more peak memory, because it sizes chunks from free memory
    • it does not change which configs fit

    It is left for a separate PR.

  • Eval (prediction_step, return_outputs=True) keeps TRL's dense loss.

  • Liger (use_liger_gkd_loss) keeps TRL's path.

  • FSDP and DeepSpeed fall back by design.

  • Stock TRL calls torch.cuda.empty_cache() after every loss; the chunked path does not need it and skips it.

  • TRL's separate DistillationTrainer is not touched.

danielhanchen and others added 3 commits September 27, 2026 08:11
TRL's GKDTrainer projects the student and the teacher through their full
heads and keeps two (batch, seq, vocab) logits tensors plus the
log-softmax and mixture temporaries alive. At a 262144 vocabulary that
dominates peak memory.

compute_loss now asks both forwards for hidden states through
UNSLOTH_RETURN_HIDDEN_STATES, as GRPO does, and hands them with the two
head weights to unsloth_zoo's distillation_chunked_jsd. The TRL layout
(prompt-width slice before 1.7, causal shift plus num_items_in_batch
from 1.7) is read from TRL's own source, and generalized_jsd_loss is only
replaced when every line is one TRL has shipped. Anything else (Liger,
FSDP / DeepSpeed, quantized or adapted heads, vocab mismatch, a changed
loss) keeps TRL's dense loss. UNSLOTH_GKD_CHUNKED=0 disables it and
UNSLOTH_GKD_CHUNK_SIZE sets the chunk rows.
A BatchEncoding is a UserDict, so the isinstance(dict) guard would have
sent it to TRL's dense loss.
@danielhanchen danielhanchen self-assigned this Sep 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: d15fc3cb31

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@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: d15fc3cb31

ℹ️ 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 on lines +3849 to +3850
if "return (loss, student_outputs) if return_outputs else loss" not in source:
return None

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 Reject unrecognized statements in GKD layouts

If a future or vendor-modified TRL compute_loss preserves these recognized forward, slicing, JSD-call, and return fragments but adds an operation such as loss *= 2 or an auxiliary loss, _unsloth_gkd_layout still accepts it. The generated wrapper then returns the chunked JSD before the original extra operation executes, silently changing the training objective instead of taking the promised dense fallback. Compare the complete canonical AST against known layouts, or explicitly reject all unaccounted statements.

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.

Every shipped TRL compute_loss (0.22.2 to 1.14.0) contains only the statements the chunked path reproduces plus empty_cache(); an injected extra loss op is not an input any release produces, so this stays as is.

Comment on lines +3983 to +3985
ok = (
all(line in known for line in lines)
and all(line in lines for line in required)

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 Validate the structure of generalized JSD implementations

This check treats the canonicalized method as an unordered collection of allowed lines, so a modified implementation can rearrange control flow while still being accepted. For example, swapping the two existing F.kl_div assignment lines between the beta == 0 and beta == 1 branches leaves every stripped line in known and every required line present, but reverses the endpoint objectives; the chunked path would then silently compute different math from the dense method. Validate the full AST structure or exact canonical bodies rather than line membership.

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.

No shipped TRL generalized_jsd_loss reorders these branches, and a swapped-kl_div override is not a real input; the line check exists to catch real TRL drift, which it does.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c629ba5bac

ℹ️ 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
danielhanchen merged commit 41b2ff6 into main Sep 28, 2026
3 of 24 checks passed
@danielhanchen
danielhanchen deleted the gkd-chunked-jsd branch September 28, 2026 09:22
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…#12136)

* Route GKD distillation through the chunked generalized JSD

TRL's GKDTrainer projects the student and the teacher through their full
heads and keeps two (batch, seq, vocab) logits tensors plus the
log-softmax and mixture temporaries alive. At a 262144 vocabulary that
dominates peak memory.

compute_loss now asks both forwards for hidden states through
UNSLOTH_RETURN_HIDDEN_STATES, as GRPO does, and hands them with the two
head weights to unsloth_zoo's distillation_chunked_jsd. The TRL layout
(prompt-width slice before 1.7, causal shift plus num_items_in_batch
from 1.7) is read from TRL's own source, and generalized_jsd_loss is only
replaced when every line is one TRL has shipped. Anything else (Liger,
FSDP / DeepSpeed, quantized or adapted heads, vocab mismatch, a changed
loss) keeps TRL's dense loss. UNSLOTH_GKD_CHUNKED=0 disables it and
UNSLOTH_GKD_CHUNK_SIZE sets the chunk rows.

* GKD: accept any mapping of inputs, not only dict

A BatchEncoding is a UserDict, so the isinstance(dict) guard would have
sent it to TRL's dense loss.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in the GKD chunked JSD path

* Project GKD dense-fallback logits on the output head's device

* Keep the chunked GKD loss on each output head's device

* Fall back to TRL's GKD loss for offloaded heads and DDP find_unused with a trainable head

* Fall back for MiniCPM3 and co-locate the GKD dense-fallback logits with the labels

* Fall back when lm_head runs before the GKD output embeddings

* Trim GKD comments after review

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Penguinjanator pushed a commit to Penguinjanator/notebooks that referenced this pull request Oct 16, 2026
…nslothai#402)

unsloth==2026.10.5 carries everything the forced-reinstall cell existed for
(unslothai/unsloth#11440, unsloth-zoo#1310, the reentrant pin, and the chunked
JSD wiring from unslothai/unsloth#12136), checked against the installed wheel
rather than the tags, so the cell now only drags users off a release onto main.

Removing it exposes a hole: the shared install says a bare `pip install unsloth`,
which pip treats as satisfied by ANY installed version. Measured: with 2026.9.7
present, `pip install unsloth` left 2026.9.7 in place, and that release has no
chunked loss. Both install variants now pass --upgrade with a minimum, Kaggle's
included, and the notebook checks the capability before training.

The check probes RL_FUNCTIONS["gkd_trainer"] rather than a version, because
replace_common rewrites every YYYY.M.D literal in a cell to 2026.2.1, which 2026.9.7
satisfies; a version assert shipped defanged. It imports unsloth before
unsloth_zoo, which refuses to import until UNSLOTH_IS_PRESENT is set. And it runs
after the config and UNSLOTH_COMPILE_DISABLE cells, because
unsloth_zoo/temporary_patches/common.py:43 freezes that flag at import, so an
earlier unsloth import silently lost the gemma-4 workaround.

The memory claim is also no longer true. Measured at the settings this notebook
ships, with UNSLOTH_GKD_CHUNKED=0 as the dense control:

  dense    9.94 GiB peak, loss 0.375788, 49.3 s
  chunked  3.03 GiB peak, loss 0.375766, 63.5 s

3.3x off the peak for the same loss to 2.2e-05, at about 30% more time at batch 1;
level at batch 2, and faster on gemma-4 at batch 2 (11.1 s vs 14.8 s) while
dropping 51.34 GiB to 23.63 GiB. The qwen3 table row is re-measured on a free
single Colab T4 (loss 0.367, 392/392 adapters, 3.36 GB, verified from the executed
notebook) and the table says which rows predate the chunked loss.

Rebased onto current main: the earlier branch was 25 commits behind and would have
reverted four workflow files Dependabot had updated, which is also why only CodeQL
ran on it. molab was removed from the repo meanwhile (unslothai#394), so that artefact is
gone rather than regenerated.

Verified: gemma-4 frozen compile-disable True, the guard raises AssertionError on
2026.9.7 with UNSLOTH_IS_PRESENT unset, and the notebook runs end to end at loss
0.370, 392/392 adapters, 3.28 GB. The suite's 18 failures are on the Qwen3 (4B)
tool-use notebooks from unslothai#395 and reproduce unchanged on clean main.
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.

Wire the chunked generalized JSD into the GKD path

2 participants