Repository navigation
Route GKD distillation through the chunked generalized JSD - #12136
Conversation
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.
|
@codex review |
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 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".
| if "return (loss, student_outputs) if return_outputs else loss" not in source: | ||
| return None |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| ok = ( | ||
| all(line in known for line in lines) | ||
| and all(line in lines for line in required) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…ith a trainable head
|
Codex Review: Didn't find any major issues. Swish! 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". |
…#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>
…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.
Summary
Routes TRL's
GKDTrainerloss through unsloth_zoo's chunkeddistillation_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"]andRL_PRE_ITEMS["gkd_trainer"]), with a small hook inunsloth/models/rl.py.Loss path
UnslothGKDTrainer.compute_losstries_unsloth_gkd_chunked_lossfirst. TRL's original body is kept as_unsloth_trl_compute_lossand is the fallback.UNSLOTH_RETURN_HIDDEN_STATES=1, exactly as in GRPO, and the previous value is restored in afinally.lm_headweights go todistillation_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 samedetect_logit_transformspath GRPO uses.modelandteacher_model._wrap_grpo_hidden_states_fallbacknow takes the attribute list; GRPO's default is unchanged.generalized_jsd_losswith the tensors it already has. There is no second forward.distillation_chunked_jsdcovers every TRL variant.Version handling
compute_losslayouts:[:, P:], local mean[:, 1:], and it forwardsnum_items_in_batchastcanonicalisation. The forwards, the slicing, the singlegeneralized_jsd_losscall with exactly its keywords, and the return must all match verbatim.generalized_jsd_lossis 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.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_lossnn.Linear(bitsandbytes 4/8-bit, a LoRA ormodules_to_savehead, a ZeRO-3 shard, meta)Each fallback is counted on
trainer._unsloth_gkd_chunked_fallbacksand logged once.Controls:
UNSLOTH_GKD_CHUNKED=0turns the path off.UNSLOTH_GKD_CHUNK_SIZEsets 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_lossevaluated in float64. The grid is 600 cases per TRL version, run on TRL 0.25.1, 1.6.0 and 1.14.0:Worst relative error:
Invariants:
num_items_in_batch=17: loss 5.3e-8 off the oracle.Trainer-level parity uses one batch through the generated
compute_loss. The dense arm isUNSLOTH_GKD_CHUNKED=0in the same process. Errors are absolute, against the float64 loss.UNSLOTH_COMPILE_DISABLE=1The 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:
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:
torch.compile:
UNSLOTH_COMPILE_DISABLE=1runs 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.empty_cacheleft onGPU kernel time per step, from torch.profiler on TRL 1.14.0:
Loss only (B 4, T 1024, V 262144, hidden 640 / 1152, a quarter of positions masked):
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:
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.
UnslothGKDTrainertrl.trainer.gkd_trainertrl.experimental.gkd(shim intrl.trainer)trl.experimental.gkdtrl.experimental.gkdnum_items_in_batchThese mutations of TRL 1.14.0's source are rejected, and TRL's dense loss is used instead:
temperature=passedreduction=passedgeneralized_jsd_loss: aT**2rescale, a mean over vocab, a droppednum_itemsreduction, an added termOther checks:
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.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.pypasses 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 unslothprints 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
GKDTrainermay 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 bylocal_items / num_items_in_batchon 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:
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
DistillationTraineris not touched.