Repository navigation
Add a knowledge distillation notebook - #374
Conversation
Distillation trains a small student against a larger teacher's output distribution rather than one-hot labels, and it is the most requested thing in unslothai/unsloth#3008 that Unsloth had no runnable example for. The notebook drives TRL's GKDTrainer, which Unsloth patches like any other TRL trainer, and ships a CONFIGS dict so the same cells cover a small proven pair, a Gemma-4 student/teacher pair, and self-distillation for the 27B and 30B models where only one copy of the weights fits. Three things the notebook has to get right, each of which was a real failure before it was handled: - A *ForConditionalGeneration checkpoint hands back a multimodal processor, not a tokenizer. Passing it to a text-only trainer makes it resolve the rendered chat prompt as an image source and raise. The notebook unwraps to the inner tokenizer. - FineTome ships ShareGPT from/value, while the chat template wants role/content, so the dataset is standardized before use. - Gemma-4 "E" checkpoints are elastic, so under torch.compile the gradient-checkpoint recompute can select a different compiled graph than the forward and training dies with a CheckpointError. That family alone sets UNSLOTH_COMPILE_DISABLE=1. Measured peaks at these settings, since GKD holds full (batch, seq, vocab) logits for both models and the vocabulary drives cost more than the weights do: Qwen3 0.6B <- 1.7B is 10.9 GB, Gemma-4 E2B <- E4B is 35.4 GB. The install cell pins unsloth and unsloth-zoo to main because GKD needs unslothai/unsloth#11440 and unslothai/unsloth-zoo#1310, which are merged but not yet released. Without them the generated trainer downcasts GKDConfig back to SFTConfig and silently drops lmbda, beta and temperature. Generated files come from update_all_notebooks.py, which also gains "Knowledge Distillation" as a known notebook type so the README table has a populated Type column.
|
You have reached your Codex usage limits for security reviews. Please try again later. |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9f17bd206c
ℹ️ 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 teacher_name is None:\n", | ||
| " # Self-distillation. Under LoRA the frozen base IS the teacher, so this costs\n", | ||
| " # no extra weights: the adapters are disabled for the teacher forward pass.\n", | ||
| " teacher = student\n", |
There was a problem hiding this comment.
Leave the self-distillation teacher unset
When CONFIG is qwen3.8 or muse-glimmer, this aliases the teacher to the PEFT student but never disables its adapters. GKDTrainer receives the alias as a normal non-null teacher, so both forwards use the same active adapters and produce identical distributions, yielding zero useful distillation gradient (and eventually failing the changed > 0 assertion). Pass None to select the trainer's adapter-disabled reference path, or explicitly disable adapters during the teacher forward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in afbc5e3. I measured it rather than taking it on the read: with the student passed straight through, the max teacher-student logit gap on Muse Glimmer was exactly 0.000e+00 and the first loss was 2.8e-04, which looks like a converged run rather than a broken one. After wrapping the teacher so the adapters are disabled for its forward, the gap is 7.875 and the loss 1.35e-01.
One correction to the suggested fix: passing None does not work here. GKDTrainer has no adapter-disabled reference path, unlike DPOTrainer. It calls self.teacher_model(...) directly, so the teacher has to be an object that disables the adapters itself. The wrapper also keeps the student out of its submodules on purpose, since the trainer calls teacher.eval() on every step and that would otherwise take the student out of training mode too.
Chasing this turned up something larger that the wrapper alone does not fix. lora_B is zero-initialised, so a freshly adapted student is its own base, and GKD's loss is a divergence and nothing else, meaning it starts at its global minimum with zero gradient. Self-distillation from a fresh adapter cannot learn anything regardless of how the teacher is wired. So qwen3.8 and muse-glimmer are now documented as exercising the memory path on a large model rather than demonstrating distillation, the two configs that do demonstrate it are named, and there is a logit-gap check that reports the gap and warns when it is zero.
Kaggle 2x T4 runs of the gemma-4, qwen3.8 and muse-glimmer configs all fail in the load cell within about three minutes, with one shared cause: those architectures need transformers 5.15.x, and every TRL that ships alongside it has moved GKD out of the top level. Verified against the wheels: GKDTrainer resolves from trl 0.22.2 through 0.28 and on nothing after, TRL 1.9.2 exposes neither GKD nor Distillation at the top level, and TRL 1.10+ exposes DistillationTrainer instead. So GKD and those three models cannot be in one environment today. Say that in the config cell rather than leaving entries that look runnable.
Kaggle 2x T4 resultsRan all four configs on Kaggle 2x T4. One passes, three fail for a single shared reason.
All three failures are the same version hole, not three separate problems, and none of them is a defect in these cells: every one dies in the model-load cell before a trainer is constructed. The version holeThose three architectures need
So The path for them is but it does not yet complete a step, failing with a device-side assert at What changed hereThe config cell now states this plainly instead of listing entries that look runnable. |
The notebook was picking up the canonical transformers==4.56.2 because update_all_notebooks.py selects an install block by filename, and this one is named for its default student. That pin loads none of gemma-4, Qwen3.8 or Muse Glimmer, which is why all three died in the load cell. Register a knowledge_distillation install block instead, pairing transformers==5.15.1 with trl==0.22.2 installed --no-deps. 5.15.1 is the floor that covers every architecture here; the --no-deps keeps the old trl, which is the last line that still exposes GKDTrainer at the top level, from dragging transformers back below it. The Qwen3.8 conversational Kaggle notebook already ships exactly this pairing. With that fixed all three reach real work and then run out of memory on two T4s, so record the measured outcome per config rather than implying they are untested. Qwen3.8 and Muse Glimmer both die building the trainer, where the kbit prep upcasts the dense lm_head to float32: 4.74 and 5.01 GiB for a single tensor, which no batch size reaches. gemma-4 dies earlier loading its separate teacher.
Correction, and the real Kaggle 2x T4 resultsMy earlier comment on this PR was wrong and I have removed the claim from the notebook. It said GKD and these three models could not be in the same environment, because The The actual bug was that Results with the install fixed
All three now get well past the load cell that was failing before, so the install fix is doing its job. What stops them is memory on a 14.56 GiB card, which is a real result rather than a configuration mistake. The two self-distillation configs are worth understanding before anyone reaches for a smaller batch. The config table in the notebook now records each of these outcomes instead of implying the entries are untested. |
Two separate things stopped the large configs on Kaggle 2x T4, both in this notebook rather than in Unsloth. First, the trl pin. TRL's prepare_peft_model runs peft's prepare_model_for_kbit_training, which freezes every parameter and then upcasts each non-Params4bit one to float32. The one that matters is the lm_head, which Unsloth keeps dense so a distillation loss can project through it. On trl 0.22.2 that call is guarded only by 'if is_qlora and not is_sharded_qlora'; from 0.24.0 it also requires 'not isinstance(model, PeftModel)', which is our case, since Unsloth has applied LoRA before the trainer is built. Without the clause the upcast costs 4.74 GiB on Qwen3.8 and 5.01 GiB on Muse Glimmer and both OOM with the weights already loaded across both cards. 0.24.0 through 0.26.2 all have the clause and still expose GKDTrainer at the top level. Second, the precision. GKDConfig was setting fp16 from is_bf16_supported(), which is True on a T4, overriding Unsloth's own decision. Unsloth rules float16 out for qwen3_5 and switches to float32, so forcing fp16 left the dense lm_head at float16 while activations arrived as bfloat16, and training died in a plain nn.Linear with 'expected mat1 and mat2 to have the same dtype'. The Qwen3.8 conversational notebook already documents this: do not set fp16 or bf16, Unsloth picks the precision for the architecture.
Kaggle 2x T4, after the install and pin fixesBoth large configs now get much further, and both still fail. Reporting the current state rather than waiting for a clean run.
Each round the failure has moved later, which is the useful signal:
Muse Glimmer's remaining failure is honest arithmetic rather than a defect: it asks for 216 MiB with 14.34 of 14.56 GiB in use. The large redundant allocation is gone and what is left is a 30B model with a large vocabulary being genuinely tight at sequence length 512 on a T4. Qwen3.8 is different and looks like an Unsloth-side inconsistency worth raising separately. At load: Unsloth rules float16 out for this architecture and switches to float32, but the dense I first read this as the notebook overriding Unsloth's choice, since So the notebook is not the blocker for Qwen3.8 any more. |
gemma-4 is the only config with a genuinely separate teacher, and it was running out of memory placing it, which looked like the pair simply not fitting two T4s. It is not: both cards are in use and the weights fit. The student lands 4.445 GiB on cuda:0 and 3.092 GiB on cuda:1, the teacher wants 5.253 GiB and 4.866 GiB, so about 17.6 GiB of weights against roughly 29 GiB of capacity. Unsloth's planner budgeted 8.94 GiB on cuda:0 for the teacher, but at that moment the card had 4.70 GiB free with 9.86 GiB in use, against only 4.445 GiB of student weights. The difference is PyTorch's caching allocator still holding reserve from the student's load and LoRA setup. So collect and empty_cache before the second model is placed, and print what is actually free so the next person does not have to infer it from an OOM message.
Emptying the cache was treating a symptom. The planner sizes a load with
free, _total = torch.cuda.mem_get_info(d)
raw_budgets[d] = int(free)
so it claims every byte that looks free and keeps nothing back for the
transient buffers the load itself needs. That is fine for the only model
in the process and wrong for the second one: on gemma-4 E2B <- E4B it
budgeted 8.94 GiB on cuda:0 while 9.93 GiB was free, and by the time the
weights were being placed the card had 4.70 GiB left.
Both cards were in use and the weights fit, roughly 17.6 GiB across
about 29 GiB, so this was never the pair being too large for two T4s.
max_memory reaches the planner through planner_kwargs_with_max_memory,
so pass it and hold 2 GiB back per card, and print free and budget per
device so the next person reads the numbers instead of inferring them
from an OOM message.
GKD scores the completion, so if the prompt fills the whole budget there
are no completion tokens left and the loss indexes a zero-length axis:
IndexError: The shape of the mask [1, 384] at index 1 does not match
the shape of the indexed tensor [1, 0, 262144] at index 1
Seen at 256 on Muse Glimmer and at 384 on gemma-4 with FineTome, both
while shortening the sequence to fit two T4s. Worth saying next to the
setting, because the obvious response to running out of memory is to cut
the sequence, and that walks straight into this.
gemma-4 on 2x T4: where the window actually isWith unslothai/unsloth-zoo#1328 installed the teacher loads, so the config is no longer blocked on placement. It is now bounded from both sides by sequence length, which is worth recording because the two limits push in opposite directions.
Below the floor there is nothing for GKD to score, because the prompt consumes the whole budget. Above the ceiling the loss itself does not fit: at 768 with a 262144 vocabulary one The 768 run reached further than any previous attempt: Trying 512 next. If the window turns out to be too narrow to be comfortable, the honest answer for this config on two T4s is a smaller teacher or a bigger card, and the config table will say so rather than shipping a setting that only just fits. |
gemma-4 now loads on two T4s with unslothai/unsloth-zoo#1328 in: both models go resident, the teacher is frozen and the trainer builds. What has no answer is sequence length. 256, 384 and 512 all leave GKD nothing to score because the prompt fills the budget; 768 runs out of memory in the loss by 336 MiB, since a full (batch, seq, 262144) float32 logit tensor is 805 MB and GKD holds several. Something between 512 and 768 might pass on FineTome and fail on a longer dataset, so the table says this config wants a bigger card rather than naming a lucky number. qwen3.8 is blocked on a dtype mismatch in the gated delta net rather than on memory, and it does not reproduce on a card with bfloat16, so the note says that instead of guessing at a cause.
gemma-4 on 2x T4: no usable sequence length512 also fails, and it fails at the floor rather than the ceiling, which closes the question.
So the floor is above 512 and the ceiling is below 768. Whatever passes lives in a window narrower than 256 tokens, and its position depends on how long the prompts happen to be, so it would pass on FineTome and fail on someone else's data. I am not shipping a number like that as a default. Worth separating clearly, because the loading problem really is solved. With unslothai/unsloth-zoo#1328 the 768 run got: Both models resident, teacher frozen, config intact, trainer built. What runs out is the loss, not placement: GKD materialises a full That is exactly what unslothai/unsloth-zoo#1310's chunked loss removes, and it is not reachable from GKD until the trainer wiring lands. Until then this config wants a card bigger than a T4, and the config table now says so. The |
GKD scores the completion, so a row whose prompt already fills
max_length truncates the completion to nothing and the loss indexes a
zero-length axis:
IndexError: The shape of the mask [1, 512] at index 1 does not match
the shape of the indexed tensor [1, 0, 262144] at index 1
I read that as the sequence budget being too small and spent several
runs bisecting it, which was wrong. Measured against FineTome with the
gemma-4 tokenizer, the median prompt is 54 tokens and the budget is
ample; the problem is the tail. The 99th percentile is 2287 tokens and
the longest is 2767, so at 512 about one row in ten has no room at all,
and with batch size 1 a single such row ends the run. Raising the budget
does not fix it either: 23 of 500 rows still overflow at 1024.
So filter on prompt length instead, keeping at least 64 tokens for a
completion, and print how many rows survive. That makes the shorter
sequence lengths usable, which matters because gemma-4 on two T4s also
has a ceiling: at 768 the full-logit GKD loss runs out by 336 MiB.
FineTome always has at least two turns, so this changes nothing for the notebook as shipped, but the config cell invites swapping the dataset and a single-turn row would ask the chat template to render an empty prompt.
My previous filter measured the wrong thing. GKD's collator returns a
prompts tensor alongside input_ids and the loss slices with it:
prompt_lengths = inputs["prompts"].shape[1]
shifted_student_logits = logits[:, prompt_lengths - 1 : -1, :]
When a row is longer than max_length the collator truncates it and the
prompt is what goes, so prompts comes back with width 0 and the slice
becomes logits[:, -1:-1, :], empty, while the labels stay full width.
Instrumenting compute_loss shows it directly: healthy rows arrive as
prompts (1, 30) with input_ids (1, 385), and the row that fails arrives
as prompts (1, 0) with input_ids (1, 512), truncated to exactly the
budget.
So the quantity that matters is the whole conversation, not the prompt.
Filtering on prompt length let a 30 token prompt with a 2000 token
answer through, and that row still lost its prompt and still broke the
run. On FineTome the median prompt is 54 tokens while total lengths run
to 3818, which is why the earlier filter kept 434 of 500 rows and
changed nothing.
Verified locally on gemma-4 E2B <- E4B at max_seq_length 512: keeps
288/500 rows, train loss 0.07044039443135261, 410/410 adapters moved,
peak 25.76 GB.
Confirmed on Kaggle 2x T4 with unslothai/unsloth-zoo#1328 installed and the total-length row filter in place: teacher loaded, 0 trainable parameters vocabularies match: 262144 train loss : 0.07908515930175782 adapters changed: 410/410 peak memory : 14.32 GB DISTILLATION VERDICT: PASS The table said this config needed a bigger card. That was my conclusion from bisecting max_seq_length, and it was wrong: the failures at 256, 384 and 512 were the collator dropping the prompt on over-long rows, not the budget being too small, and the one at 768 was the only real memory limit.
gemma-4 trains on two T4sConfirmed on Kaggle 2x T4, with the install verified from the executed notebook before reading the result: Two of the configs in this notebook now train on two T4s: The root cause, which was not what I first reportedI had this wrong twice, so it is worth stating plainly. The GKD's collator returns a prompt_lengths = inputs["prompts"].shape[1]
shifted_student_logits = student_outputs.logits[:, prompt_lengths - 1 : -1, :]
shifted_labels = inputs["labels"][:, prompt_lengths:]When a row is longer than My first filter measured prompt length, which is the wrong quantity: a 30 token prompt with a 2000 token answer passes it, still overflows, still loses its prompt. That is why it kept 434 of 500 rows and changed nothing. The filter now drops rows whose whole conversation does not fit, which keeps 288 of 500 at 512 on FineTome. Shortening the sequence made this worse rather than better, because more rows overflow, which is exactly backwards from how it looked while bisecting. Config tableCorrected in 9a7c921. It previously said gemma-4 needed a bigger card, which was my conclusion from that bisection and is wrong: it trains at 14.32 GiB peak, well inside a single card's 14.56. Still open
|
Muse Glimmer routes tokens to a subset of experts, so like gemma-4's elastic checkpoints it runs a data-dependent graph. Under torch.compile the gradient checkpoint recompute takes a different path than the forward pass did and training dies inside torch.utils.checkpoint with a saved-tensor count mismatch (81 vs 79 on a Kaggle 2x T4 at sequence length 384). Disabling compile for those two families costs the others nothing. Also drop the stale note about a sequence length floor. That floor was the collator symptom, not a real constraint, and the total-length row filter removed it.
With compile disabled and the total-length row filter on, Muse Glimmer self-distillation reaches the training step at sequence length 384 and then runs out of memory 208 MiB short of the 14.56 GiB card, down from 326 MiB short at 512. The gap closes slowly because the 22.2 GiB of 4-bit weights, not the logits, dominate what is left, so the table now says to use a card with more memory per device rather than to shorten the sequence further.
|
Muse Glimmer is now resolved as far as a 2x T4 can take it, which completes the sweep of all four configurations. It failed twice more after the collator fix, and each failure was a different problem:
The second one is the same class of failure gemma-4 had. Muse Glimmer routes tokens to a subset of experts, so its graph is data dependent, and under torch.compile the gradient checkpoint recompute can take a different path than the forward pass did. gemma-4 already had With compile disabled it got past the checkpoint error and ran out of memory again, 208 MiB short of the 14.56 GiB card, down from 326 MiB at 512. I stopped there rather than bisecting further. The gap closes slowly because the 22.2 GiB of 4-bit weights, not the logits, dominate what is left, so shortening the sequence spends accuracy to buy very little. The table now says to use a card with more memory per device. Current state of the four configurations on a Kaggle 2x T4:
gemma-4 needed three independent fixes to get there: a dedicated install block pairing The filter is the interesting one and it is worth stating the root cause plainly, because it looked like a bug in the loss. GKD's collator truncates any row longer than So the fix is to drop rows that do not fit as a whole, not rows whose prompt is long. I had filtered on prompt length first, which kept 434 of 500 rows and changed nothing, and I should have treated that as a refutation rather than a near miss. Filtering on total conversation length keeps 288 of 500 at 512 and fixes it. Two things that follow from this and are worth noting for anyone hitting the same wall. Shortening |
Muse Glimmer's CheckpointError was a configuration bug, not a property of the architecture. GKDConfig inherits gradient_checkpointing=True from SFTConfig, so transformers put every layer on the non-reentrant checkpoint path, which is the only one that compares what the forward and the recompute saved. With unslothai/unsloth#11519 pinning use_reentrant back to True, all 103 checkpointed layers report reentrant and it trains with torch.compile on. Only memory stops it now. gemma-4 is a separate and still open problem. With that same fix installed and all 52 layers confirmed reentrant, it still fails, and the recompute disagrees about tensor rank rather than count: [1, 474, 512] saved against [1, 474, 1, 512] recomputed. So compile stays off for gemma-4 alone. Also corrects the note that called Muse Glimmer a mixture of experts. It is dense, with alternating sliding and full attention.
|
Correcting two things I said earlier in this thread, and reporting what the root cause actually turned out to be. What I got wrongMuse Glimmer is not a mixture of experts. Its config has no expert fields at all. It is dense, with alternating sliding and full attention layers, a vision tower, and final logit softcapping. I had explained its Disabling torch.compile was a workaround for a configuration bug, not a property of those architectures. I described it as the fix. It was hiding the problem. The actual cause
That silently overrides the Unsloth already guards this and the comment in The fix pins the value instead of removing it, for every TRL version: unslothai/unsloth#11519. Controlled arm on a Kaggle 2x T4, same notebook, torch.compile left enabled in both:
Where each configuration stands now
One thing still opengemma-4 is a genuinely separate problem and I am not claiming it is solved. With unslothai/unsloth#11519 installed and all 52 of its layers confirmed on Two tensors, adjacent positions, one extra axis of size 1. That is a real shape divergence between two executions of the same region, not a configuration default, so compile stays off for gemma-4 only until it is tracked down. Muse Glimmer no longer needs it. A separate bug came out of the same investigation and is filed on its own evidence rather than this one: unslothai/unsloth-zoo#1333. The generated model flips dynamo's compiler stance to |
It was an outlier against the other 116 Kaggle notebooks: 21 cells where the median is 41, a 111-line code cell where the median longest is 33, and 42 percent of code lines were comments against a median of 8. The explanation was living in code comments and a few very large cells. Moved it into markdown and split the cells, which is how every other notebook here reads: short code cell, short markdown cell in front of it. The config table, the collator truncation writeup, the device-map budgeting rationale and the version-pin note are now prose rather than comment blocks. Now 37 cells, 15 code and 22 markdown, 189 code lines, 2 percent comments, longest code cell 26 lines. No behaviour change. Verified every fix is still present (the total-length row filter, the gemma-4 compile disable, the teacher memory budget, the pinned install), that every code cell parses, and by running it: loss 0.398, 392/392 adapters changed, 8.14 GB peak.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 765f39eac6
ℹ️ 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".
| { | ||
| "cells": [ |
There was a problem hiding this comment.
Generate or exclude the new Molab notebook
Adding this template makes scripts/molab_manifest.py automatically register molab/Qwen3_(0.6B)-Knowledge_Distillation.py as an active output, but the commit includes neither that generated file nor an explicit skip entry. Consequently, tests/test_molab_generation_parity.py::test_committed_molab_file_exists fails with GENERATION MISSING; generate and commit the Molab file or explicitly exclude the notebook with a documented reason.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and it failed exactly as described. Fixed in 4578a7d and corrected in 85af491: the first generation used marimo 0.24.2 with no ruff, which failed generation parity because marimo stamps its version into __generated_with and the ruff format pass never ran. Regenerated under the pinned marimo==0.23.8 and ruff==0.15.16. The full parity suite passes, 568 tests, which also confirms no other notebook drifted.
| " \"muse-glimmer\": dict(\n", | ||
| " student = \"unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit\",\n", | ||
| " teacher = None,\n", | ||
| " ),\n", | ||
| "}\n", |
There was a problem hiding this comment.
Restore the advertised large-teacher configuration
The preceding documentation says the 26B Gemma teacher is listed for A100-class hardware, and the proposed feature describes a gemma-4-big-teacher option, but this dictionary ends without such an entry. An A100 user selecting that advertised configuration gets a KeyError before model loading; add the E4B/26B pair to CONFIGS or remove the claim that it is selectable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fair, the text was inconsistent with the code. Rather than add the config I reworded it in 8789f52, because there is no prebuilt 4-bit for unsloth/gemma-4-26B-A4B-it and at 51.6 GB it cannot run on the hardware this notebook targets, so shipping it as a selectable option would just fail for most people who picked it. It now says it is deliberately not offered and what you need to add it yourself.
GKDTrainer calls self.teacher_model(...) and nothing else, so handing it the PEFT student ran both forwards through the same active adapters. Measured on Muse Glimmer the teacher-student logit gap was exactly 0.000 and the loss sat at 2.8e-04, which reads as a converged run rather than a broken one. Wrap the student instead and disable its adapters for the teacher forward. The wrapper deliberately keeps the student out of its submodules, because the trainer calls teacher.eval() every step and that would otherwise drop the student out of training mode. Same measurement after the change: gap 7.875, loss 1.35e-01, student still training. That exposes a second thing worth saying plainly rather than shipping quietly. lora_B is zero-initialised, so a freshly adapted student IS its own base, and GKD's loss is a divergence and nothing else, so it starts at its global minimum with no gradient. Self-distillation from a fresh adapter cannot learn anything, whatever the wrapper does. The qwen3.8 and muse-glimmer configs are therefore documented as exercising the memory path on a big model rather than demonstrating distillation, and the two configs that do demonstrate it, qwen3 and gemma-4, are named as such. A logit-gap check now reports the gap and warns when it is zero. Verified end to end on the default qwen3 config: gap 17.375, loss 0.370, 392/392 adapters changed, 9.86 GB peak.
Correcting the self-distillation configs, and what they were actually measuringCodex caught a real bug in the self-distillation branch and chasing it invalidated part of what I reported earlier in this thread. Both are fixed in afbc5e3. The bug.
A loss of The larger thing. The wrapper does not rescue those configs. So I was wrong earlier in this thread when I said Muse Glimmer was "resolved as far as a 2x T4 can take it, which completes the sweep of all four configurations". The memory and checkpointing findings from those runs stand, and unslothai/unsloth#11519 came out of them, but they were never demonstrating distillation, so the sweep covered two real configurations and not four. The notebook now says this rather than implying otherwise: Verified end to end on the default |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: afbc5e3f02
ℹ️ 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".
| "max_seq_length = 1024\n", | ||
| "load_in_4bit = True\n", | ||
| "print(f\"student: {student_name}\")\n", | ||
| "print(f\"teacher: {teacher_name or '(self-distillation: the student\\'s own frozen base)'}\")" |
There was a problem hiding this comment.
Remove the backslash from the f-string expression
On Python 3.11 and earlier, this cell fails to compile with SyntaxError: f-string expression part cannot include a backslash, even for the default qwen3 configuration because the whole expression is parsed before evaluation. This notebook supports local environments where Unsloth's Python floor is 3.10, so precompute the fallback label or quote the f-string without an escape.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 8789f52. I checked it against a real 3.11.15 interpreter rather than ast.parse(feature_version=(3,11)), which does not emulate the pre-PEP-701 tokenizer and reports the file as fine. The real one gives SyntaxError: f-string expression part cannot include a backslash at the teacher line, so the cell was dead for any local 3.11 user even on the default config. The label is now bound before the f-string, and all three generated files parse on 3.11.
| "if teacher_name is not None:\n", | ||
| " s_vocab = student.config.get_text_config().vocab_size\n", | ||
| " t_vocab = teacher.config.get_text_config().vocab_size\n", | ||
| " assert s_vocab == t_vocab, f\"vocab mismatch: student {s_vocab} vs teacher {t_vocab}\"\n", |
There was a problem hiding this comment.
Compare tokenizer mappings instead of vocabulary sizes
When a user adds a teacher/student pair whose vocabularies have the same length but assign different token IDs, this assertion passes and GKD silently compares probabilities for unrelated tokens, producing invalid training rather than a shape error. Since teacher_processor is already available, verify the teacher and student token-to-ID mappings (including added/special tokens), not only config.vocab_size.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, fixed in 8789f52. The check now compares the ids the two tokenizers actually produce for a probe string as well as the width, with the Qwen2.5 0.5B/7B case named as the reason: both are 151936 wide and assign different ids, so the width check passes and the loss then compares probabilities for unrelated tokens. Tracking the library-level version of this guard in unslothai/unsloth#11556, since the notebook can only protect its own pairs.
The notebook static checks gate reported GENERATION MISSING: every notebook needs a committed molab/ conversion or a skip entry, and this one had neither. Generated with scripts/molab_generate.py. 89 tests matching the notebook pass, including generation parity, marimo validity and dependency parity.
The first generation used marimo 0.24.2 and no ruff at all, so the file failed generation parity: marimo stamps its version into __generated_with, and the ruff format pass that re-wraps marimo's ast-unparsed lines never ran. The workflow pins marimo==0.23.8 and ruff==0.15.16 for exactly this reason. Full parity suite now passes, 568 tests, which also confirms no other notebook drifted.
test_molab_readme_links requires every generated molab entry to have a README badge. Inserted the generator's own row rather than regenerating the whole README, which reorders unrelated rows from a model_created_at.csv refresh. Full suite passes locally: 18299 passed, 576 skipped.
Three review findings, all real. The teacher line put a backslash inside an f-string expression, which is a SyntaxError before Python 3.12 and so broke the whole cell for anyone running locally on 3.11, including on the default qwen3 config. Confirmed against a real 3.11.15 interpreter rather than ast feature_version, which does not emulate the pre-PEP-701 tokenizer. All three generated files now parse on 3.11. The vocabulary check compared widths only. Qwen2.5-0.5B and 7B are both 151936 wide but assign different ids, so a width check passes and the loss then compares probabilities for unrelated tokens. It now also compares what the two tokenizers produce for a probe string. The gemma-4 26B note said it was "listed for that case" when no such config existed. Reworded to say it is deliberately not offered and why. Verified: 18299 tests pass, and the notebook runs end to end with gap 17.375, loss 0.370, 392/392 adapters, 9.86 GB peak.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8789f52c63
ℹ️ 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".
| print( | ||
| f"teacher loaded, {sum((p.requires_grad for p in teacher.parameters()))} trainable (must be 0)" | ||
| ) | ||
| return teacher, teacher_processor |
There was a problem hiding this comment.
Initialize the processor on the self-distillation path
When the Molab user selects qwen3.8 or muse-glimmer, teacher_name is None, so this cell skips the only assignment to teacher_processor and then raises UnboundLocalError while constructing its return value. Initialize teacher_processor before the branch (or return it only from the separate-teacher path) and regenerate the Molab notebook so the advertised self-distillation configurations can proceed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and molab-specific: the ipynb is fine because the name is only read under the same guard that assigns it, but the molab conversion turns each cell into a function with an explicit return teacher, teacher_processor, so the self-distillation path raised UnboundLocalError before anything else could run. Bound to None up front in c2c6093.
| installation_knowledge_distillation_content = update_or_append_pip_install( | ||
| installation_content, | ||
| "transformers", | ||
| "!pip install transformers==5.15.1", | ||
| ) |
There was a problem hiding this comment.
Pin TRL 0.25.1 for non-Kaggle outputs too
This derivation only replaces the Transformers pin, so the generated Colab/local notebook and its Molab dependency metadata retain the global trl==0.22.2; only the Kaggle variant receives 0.25.1. For the Gemma and large self-distillation configurations, the preceding compatibility analysis explains that 0.22.2 unnecessarily upcasts the dense output head and can add several GiB before training, causing the memory-constrained runs to OOM. Apply the same TRL replacement to this installation block so every published form uses the tested version.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in c2c6093. The Colab and local outputs were keeping the global trl==0.22.2 while only the Kaggle variant got 0.25.1, so they would have run against a different TRL from the one the notebook was verified on. Both now carry the same pin, with an assert in the generator so the two cannot drift apart again.
| @@ -853,6 +855,7 @@ Run any of these on [molab](https://molab.marimo.io), Marimo's hosted GPU notebo | |||
| | **Qwen2** **(7B)** | Alpaca | [](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen2_(7B)-Alpaca.py) | | |||
| | **Qwen2 VL** **(7B)** | Vision | [](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen2_VL_(7B)-Vision.py) | | |||
| | **Qwen3.8** **(27B)** | Conversational | [](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen3.8_(27B)-Conversational.py) | | |||
| | **Qwen3** **(0.6B)** | | [](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen3_(0.6B)-Knowledge_Distillation.py) | | |||
There was a problem hiding this comment.
Populate the Molab notebook type
The new Molab catalog row leaves its Type column empty even though the Colab and Kaggle rows identify the same notebook as Knowledge Distillation. The Molab README generator maintains its own type-keyword list, so adding the keyword only to update_all_notebooks.py does not classify this row and future regeneration will preserve the blank metadata.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct about the cause, which is the part I would have missed: scripts/molab_readme.py keeps its own _KNOWN_TYPES_ORDERED mirrored from update_all_notebooks.py, and I had only added the keyword to the latter. Added to both in c2c6093, and the row now reads Knowledge Distillation.
…lab row Three more review findings, all real. The molab conversion turns each cell into a function with an explicit return, so `return teacher, teacher_processor` raised UnboundLocalError on the self-distillation path where only the separate-teacher branch had assigned it. Harmless in the ipynb, broken in molab. Bound to None up front. Only the Kaggle variant got the TRL 0.25.1 pin, so the Colab and local outputs kept the global 0.22.2 and would have run against a different TRL from the one this notebook was verified on. Both now carry the same pin, asserted in the generator. The molab README row had an empty Type column because scripts/molab_readme.py keeps its own keyword list mirrored from update_all_notebooks.py, and only the latter had been updated. Added there too. Verified: 18299 tests pass, all generated files parse on a real 3.11, and the notebook still runs end to end with gap 17.375, loss 0.370, 392/392 adapters, 9.86 GB peak.
|
@codex review |
|
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". |
Closes the "no runnable distillation example" half of unslothai/unsloth#3008.
Distillation trains a small student to match a larger teacher's output distribution rather than one-hot labels. Unsloth already patches TRL's
GKDTrainerlike any other TRL trainer, so this needs no new trainer, only a notebook that gets the setup right.What it does
original_template/Qwen3_(0.6B)-Knowledge_Distillation.ipynb, with aCONFIGSdict so the same cells cover several cases:qwen3(default)gemma-4gemma-4-big-teacherqwen3.8muse-glimmerThree things it has to get right
Each of these was an observed failure, not a precaution.
*ForConditionalGenerationcheckpoint returns a processor, not a tokenizer. Every model above is one. Handing the processor to a text-only trainer makes it try to resolve the rendered chat prompt as an image source:Incorrect image sourceon Gemma-4,Unsupported image fileon Muse Glimmer. The notebook unwraps to the inner tokenizer and prints what it unwrapped.from/value, the chat template wantsrole/content. Withoutstandardize_sharegptthe render raisesUndefinedError: 'dict object' has no attribute 'role'.CheckpointError: Recomputed values ... have different metadata. Reproduced on the real E2B <- E4B pair, and it persists withuse_gradient_checkpointing = False. Isolated on two axes: Qwen3 0.6B <- 1.7B passes with compile on, and Gemma-4 E2B <- E4B passes withUNSLOTH_COMPILE_DISABLE=1. So that family alone disables compile, which costs the other configs nothing.Measured
GKD holds full
(batch, seq, vocab)logits for both models, so peak memory is driven by the vocabulary more than by the weights.Install pin
The install cell pulls unsloth and unsloth-zoo from main. GKD needs unslothai/unsloth#11440 and unslothai/unsloth-zoo#1310, both merged but not yet in a release. Without them the generated trainer downcasts
GKDConfigback toSFTConfigand silently dropslmbda,betaandtemperature, which is unslothai/unsloth#1941. The cell says to delete itself once a release carries both, and the notebook assertstype(trainer.args).__name__ == "GKDConfig"so a stale install fails loudly instead of quietly degrading to SFT.Generated files
nb/,python_scripts/and the README rows all come fromupdate_all_notebooks.py, which gains"Knowledge Distillation"as a known notebook type so the README Type column is populated rather than blank. The unrelated regeneration drift that the script also produces (refreshed download counts inscripts/model_created_at.csv, and the README reordering that follows from it) is left out of this PR.