Skip to content

Add a knowledge distillation notebook - #374

Merged
danielhanchen merged 22 commits into
mainfrom
kd-notebook
Sep 22, 2026
Merged

danielhanchen merged 22 commits into
mainfrom
kd-notebook

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 GKDTrainer like 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 a CONFIGS dict so the same cells cover several cases:

config student teacher notes
qwen3 (default) Qwen3 0.6B Qwen3 1.7B proven pair, fits two T4s
gemma-4 gemma-4 E2B 4-bit gemma-4 E4B 4-bit real KD across sizes
gemma-4-big-teacher gemma-4 E4B gemma-4 26B A4B A100 or better
qwen3.8 Qwen3.8 27B 4-bit itself self-distillation
muse-glimmer Muse Glimmer 30B 4-bit itself self-distillation

Three things it has to get right

Each of these was an observed failure, not a precaution.

  1. A *ForConditionalGeneration checkpoint 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 source on Gemma-4, Unsupported image file on Muse Glimmer. The notebook unwraps to the inner tokenizer and prints what it unwrapped.
  2. FineTome ships ShareGPT from/value, the chat template wants role/content. Without standardize_sharegpt the render raises UndefinedError: 'dict object' has no attribute 'role'.
  3. Gemma-4 "E" checkpoints are elastic. Under torch.compile the gradient-checkpoint recompute can select a different compiled graph than the forward pass, and training dies with CheckpointError: Recomputed values ... have different metadata. Reproduced on the real E2B <- E4B pair, and it persists with use_gradient_checkpointing = False. Isolated on two axes: Qwen3 0.6B <- 1.7B passes with compile on, and Gemma-4 E2B <- E4B passes with UNSLOTH_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.

config measured peak adapters changed fits 2x T4
Qwen3 0.6B <- 1.7B 10.94 GB 392/392 yes
Gemma-4 E2B <- E4B 35.41 GB 410/410 not at seq 1024

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 GKDConfig back to SFTConfig and silently drops lmbda, beta and temperature, which is unslothai/unsloth#1941. The cell says to delete itself once a release carries both, and the notebook asserts type(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 from update_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 in scripts/model_created_at.csv, and the README reordering that follows from it) is left out of this PR.

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 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-09-22T18:33:06.451284Z c2c6093 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.

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

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

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.

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

Copy link
Copy Markdown
Member Author

Kaggle 2x T4 results

Ran all four configs on Kaggle 2x T4. One passes, three fail for a single shared reason.

config result detail
qwen3 (Qwen3 0.6B <- 1.7B) PASS loss 0.413, 392/392 adapters moved, 10.94 GB peak
gemma-4 (E2B <- E4B) FAIL, 3m07s ValueError: unsloth/gemma-4-E2B-it-unsloth-bnb-4bit is not supported yet in transformers==4.56.2
qwen3.8 (27B, self) FAIL, 3m08s ImportError: Unsloth: Your transformers version of 4.56.2 does not support Qwen3.5
muse-glimmer (30B, self) FAIL, 3m38s ValueError: unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit is not supported yet in transformers==4.56.2

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 hole

Those three architectures need transformers 5.15.x. Every TRL that ships alongside that has moved GKD out of the top level. Read off the published wheels rather than the release notes:

TRL top-level GKDTrainer top-level DistillationTrainer trl/trainer/*.py Unsloth's scan sees
0.22.2 - 0.28 yes no gkd_trainer
1.9.2 no no neither, both under trl.experimental.*
1.10.0 - 1.13.0 no yes distillation_trainer

So from trl import GKDConfig, GKDTrainer and these three models cannot currently be in the same environment: the stack that loads the models has no top-level GKD, and the stack that has GKD cannot load the models.

The path for them is DistillationTrainer on TRL 1.10+, which Unsloth's dir(trl.trainer) scan does discover. I confirmed it generates correctly on transformers 5.15.1 + TRL 1.13.0:

trainer_name   UnslothDistillationTrainer    (generated, not a silent fallback)
args_type      DistillationConfig            (not downcast)

but it does not yet complete a step, failing with a device-side assert at h_s = h_s[order] inside TRL's _chunked_divergence_loss. That is trainer-wiring work, not notebook work, and it is tracked separately against unslothai/unsloth#3008.

What changed here

The config cell now states this plainly instead of listing entries that look runnable. qwen3 stays the default because it is the one measured end to end.

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

Copy link
Copy Markdown
Member Author

Correction, and the real Kaggle 2x T4 results

My 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 GKDTrainer is only importable from the top level of trl 0.22.2 through 0.28 while the models need transformers 5.15.x. The premise was right; the conclusion was not. Kaggle-Qwen3.8_(27B)-Conversational.ipynb already ships exactly that combination:

!uv pip install -qqq transformers==5.15.1
!uv pip install -qqq --no-deps trl==0.22.2

The --no-deps is the whole trick: it pins the old trl on top of new transformers without dependency resolution pulling transformers back down. There is no version hole.

The actual bug was that update_all_notebooks.py picks an install block by filename. This notebook is named for its default student, so it matched no special rule and got the canonical transformers==4.56.2, which loads none of the three. Fixed by registering a knowledge_distillation block, dispatched after the Qwen3 rules so the filename does not decide it.

Results with the install fixed

config result where
qwen3 (0.6B <- 1.7B) PASS loss 0.413, 392/392 adapters, 10.94 GB
qwen3.8 (27B, self) OOM, 10m14s building GKDTrainer, 4.74 GiB
muse-glimmer (30B, self) OOM, 6m10s building GKDTrainer, 5.01 GiB
gemma-4 (E2B <- E4B) OOM, 4m38s loading the teacher, 5.25 GiB

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. GKDTrainer's kbit prep upcasts every parameter that is not Params4bit to float32, and the one that matters is the lm_head, which Unsloth deliberately leaves dense so the distillation projection stays valid. At these vocabularies that single tensor is 4.74 GiB for Qwen3.8 (248320 tokens) and 5.01 GiB for Muse Glimmer, on a card already holding 12 to 14 GiB of weights. No sequence length or batch size reaches it. gemma-4 fails earlier and more plainly: it is the only config with a genuinely separate teacher, so it is loading a second model.

The config table in the notebook now records each of these outcomes instead of implying the entries are untested. qwen3 stays the default because it is the one measured end to end on this tier.

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

Copy link
Copy Markdown
Member Author

Kaggle 2x T4, after the install and pin fixes

Both large configs now get much further, and both still fail. Reporting the current state rather than waiting for a clean run.

config result where
qwen3 (0.6B <- 1.7B) PASS loss 0.413, 392/392 adapters, 10.94 GB
qwen3.8 (27B, self) CELL_ERROR, 9m13s first training step, dtype mismatch
muse-glimmer (30B, self) OOM, 6m41s first training step, asking for 216 MiB
gemma-4 (E2B <- E4B) OOM, 4m38s loading the teacher, 5.25 GiB

Each round the failure has moved later, which is the useful signal:

  1. transformers==4.56.2 could not load any of the three. Fixed by giving the notebook its own install block (5.15.1).
  2. trl==0.22.2 upcast the dense lm_head to float32 while building the trainer: 4.74 GiB for Qwen3.8, 5.01 GiB for Muse Glimmer. Fixed by pinning trl 0.25.1, which carries TRL's own not isinstance(model, PeftModel) guard.
  3. Both now reach the first training step.

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: Using float16 precision for qwen3_5 won't work! Using float32.
output head Linear (248320, 5120) torch.float16
Unsloth: Switching to float32 training since model cannot work with float16

Unsloth rules float16 out for this architecture and switches to float32, but the dense lm_head is still materialised as float16. Training then dies in a plain nn.Linear:

RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != c10::Half

I first read this as the notebook overriding Unsloth's choice, since GKDConfig was setting fp16 from is_bf16_supported(), which is True on a T4. Removing that override is correct on its own terms, and the Qwen3.8 conversational notebook documents the same rule, but it did not fix this: the failure reproduces with no fp16 or bf16 in the config at all.

So the notebook is not the blocker for Qwen3.8 any more. qwen3 remains the default because it is the config measured end to end.

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

Copy link
Copy Markdown
Member Author

gemma-4 on 2x T4: where the window actually is

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

sequence outcome
256 too short: zero completion tokens, IndexError: mask [1, 256] vs tensor [1, 0, 262144]
384 too short: same IndexError
768 too long: OOM in the training step, short by 336 MiB

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 (1, 768, 262144) float32 logit tensor is 805 MB, and GKD materialises several for student, teacher and mixture.

The 768 run reached further than any previous attempt:

410 trainable tensors
teacher loaded, 0 trainable parameters
vocabularies match: 262144
args GKDConfig: lmbda=0.0 beta=0.5 temperature=1.0
Num GPUs used = 2

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

Copy link
Copy Markdown
Member Author

gemma-4 on 2x T4: no usable sequence length

512 also fails, and it fails at the floor rather than the ceiling, which closes the question.

sequence outcome
256 zero completion tokens, IndexError: mask [1, 256] vs tensor [1, 0, 262144]
384 zero completion tokens
512 zero completion tokens
768 OOM in the training step, short by 336 MiB

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:

410 trainable tensors
teacher loaded, 0 trainable parameters
vocabularies match: 262144
args GKDConfig: lmbda=0.0 beta=0.5 temperature=1.0
Num GPUs used = 2

Both models resident, teacher frozen, config intact, trainer built. What runs out is the loss, not placement: GKD materialises a full (batch, seq, vocab) tensor for student, teacher and mixture, and at a 262144 vocabulary one of those in float32 is 805 MB at sequence 768.

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 qwen3 default is unaffected and remains the config measured end to end: loss 0.413, 392/392 adapters moved, 10.94 GB peak.

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

Copy link
Copy Markdown
Member Author

gemma-4 trains on two T4s

Confirmed on Kaggle 2x T4, with the install verified from the executed notebook before reading the result:

teacher loaded, 0 trainable parameters (must be 0)
vocabularies match: 262144
train loss         : 0.07908515930175782
adapters changed   : 410/410
peak memory        : 14.32 GB
loss first -> last : 0.0773 -> 0.0990
DISTILLATION VERDICT: PASS

Two of the configs in this notebook now train on two T4s: qwen3 and gemma-4.

The root cause, which was not what I first reported

I had this wrong twice, so it is worth stating plainly. The IndexError at 256, 384 and 512 was never about the sequence budget being too small.

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 = student_outputs.logits[:, prompt_lengths - 1 : -1, :]
shifted_labels = inputs["labels"][:, prompt_lengths:]

When a row is longer than max_length the collator truncates it, and the prompt is what goes. prompts comes back with width 0, so the slice becomes logits[:, -1:-1, :], empty, while the labels stay full width. Instrumenting compute_loss shows it directly:

healthy row:  prompts (1, 30)   input_ids (1, 385)
failing row:  prompts (1, 0)    input_ids (1, 512)   <- truncated to the budget

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 table

Corrected 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 at 512 now reaches the training step with no IndexError, so the filter works there too, but runs out of memory by 326 MiB. Retrying at 384, which is only worth doing now that sequence length no longer interacts with the collator bug.

qwen3.8 is unchanged and unrelated: expected mat1 and mat2 to have the same dtype, but got: BFloat16 != Half inside the gated delta net, which does not reproduce on hardware that supports bfloat16.

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

Copy link
Copy Markdown
Member Author

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:

  1. At sequence length 512 it reached the training step with no IndexError, so the total-length row filter had done its job, and then ran out of memory 326 MiB short.
  2. At 384 it hit CheckpointError: A different number of tensors was saved during the original forward and recomputation. Number of tensors saved during forward: 81. Number of tensors saved during recomputation: 79.

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 UNSLOTH_COMPILE_DISABLE=1 for the same reason, its elastic checkpoints being data dependent in a different way, so I widened that condition to cover Muse Glimmer.

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:

config weights result
qwen3 1.2 + 3.4 GB PASS, loss 0.413, 392/392 adapters changed, 10.9 GB peak
gemma-4 8.1 + 10.9 GB PASS, loss 0.079, 410/410 adapters changed, 14.3 GB peak
muse-glimmer 22.2 GB OOM by 208 MiB at seq 384, needs a larger card
qwen3.8 22.3 GB dtype mismatch in the gated delta net, tracked separately

gemma-4 needed three independent fixes to get there: a dedicated install block pairing transformers==5.15.1 with --no-deps trl==0.25.1 (the install blocks are selected by filename, so a new notebook silently inherits the wrong one), unslothai/unsloth-zoo#1328 removing a 5.25 GiB transient while the teacher is placed, and the row filter.

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 max_length and, in doing so, drops the prompt. inputs["prompts"] then comes back with width 0, and the loss slices logits[:, prompt_lengths - 1 : -1, :], which at width 0 is logits[:, -1:-1, :], an empty tensor, while the labels stay full width. That is the IndexError. Instrumenting compute_loss showed it directly: a healthy step has prompts (1, 30) against input_ids (1, 385), the failing one has prompts (1, 0) against input_ids (1, 512).

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 max_seq_length used to make the collator problem more likely rather than less, which is why the earlier memory bisections kept producing confusing errors, and that is no longer true now that the filter is in. And the sequence length floor documented in an earlier revision of this notebook was never real; it was this symptom, and I have removed the note.

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

Copy link
Copy Markdown
Member Author

Correcting two things I said earlier in this thread, and reporting what the root cause actually turned out to be.

What I got wrong

Muse 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 CheckpointError as expert routing making the graph data dependent, and that explanation was invented rather than checked. Unsloth's own loader says so plainly in the log: No MoE expert parameters were found to be replaced for muse_glimmer (expected for non-MoE).

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

GKDConfig inherits gradient_checkpointing = True from SFTConfig. The notebook never asks for gradient checkpointing at the trainer level, but because that default is on, the transformers Trainer calls gradient_checkpointing_enable(gradient_checkpointing_kwargs = None), and transformers substitutes {"use_reentrant": False} for a None.

That silently overrides the use_gradient_checkpointing = "unsloth" the notebook did ask for, and puts every layer on the non-reentrant checkpoint path. That path is the only one that recomputes each packed forward during backward and compares what the two passes saved, so it is the only one that can raise

CheckpointError: A different number of tensors was saved during the original
forward and recomputation.
Number of tensors saved during forward: 81
Number of tensors saved during recomputation: 79.

Unsloth already guards this and the comment in rl.py names the mechanism exactly: TRL 0.27.0+ forces use_reentrant=False and Unsloth gradient checkpointing requires True. But the guard works by deleting the key and is gated on TRL 0.27.0+. On TRL 0.25.1 the key is never set, so there is nothing to delete and transformers picks False on its own. Deleting a key cannot fix a key that was never there.

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:

arm what the layers got result
before None from the config, so transformers used {'use_reentrant': False} CheckpointError on the first step, 81 against 79
after {'use_reentrant': True} on all 103 checkpointed layers no CheckpointError, runs to the memory limit

Where each configuration stands now

config weights result on a Kaggle 2x T4
qwen3 1.2 + 3.4 GB PASS, loss 0.413, 392/392 adapters changed, 10.9 GB peak
gemma-4 8.1 + 10.9 GB PASS with compile off, loss 0.079, 410/410 adapters changed, 14.3 GB peak
muse-glimmer 22.2 GB compiles and trains now, OOM by 208 MiB at seq 384, needs a larger card
qwen3.8 22.3 GB dtype mismatch in the gated delta net, still open

One thing still open

gemma-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 use_reentrant=True, and compile enabled, it still fails, but differently: the recompute disagrees about tensor rank rather than count.

saved metadata:      {'shape': torch.Size([1, 474, 512]), 'dtype': torch.float32}
recomputed metadata: {'shape': torch.Size([1, 474, 1, 512]), 'dtype': torch.float32}

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 eager_on_recompile on the second label-free forward and never restores it, and a GKD teacher forward is label-free. I checked whether that explained the CheckpointError and it does not, so the PR rests on the measured cost instead: once flipped, no further frame is compiled for the rest of training.

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

Comment on lines +1 to +2
{
"cells": [

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

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.

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.

Comment on lines +133 to +137
" \"muse-glimmer\": dict(\n",
" student = \"unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit\",\n",
" teacher = None,\n",
" ),\n",
"}\n",

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

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.

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

Copy link
Copy Markdown
Member Author

Correcting the self-distillation configs, and what they were actually measuring

Codex 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. teacher = student handed GKDTrainer the PEFT student directly. GKDTrainer calls self.teacher_model(...) and nothing else, so both forwards ran through the same active adapters. Measured on Muse Glimmer:

max teacher-student logit gap first loss
before 0.000e+00 7.4e-05
after, teacher wraps the student with adapters disabled 7.875 1.4e-01

A loss of 7e-05 reads as a converged run, which is why this survived several rounds of review including mine.

The larger thing. The wrapper does not rescue those configs. 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 however the teacher is wired. The apparent training afterwards is the optimiser amplifying numerical noise.

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. unsloth/Muse-Glimmer-30B and unsloth/Qwen3.8-27B are each published at a single size, so there is no smaller sibling to distil from either, and a second copy does not fit on two T4s.

The notebook now says this rather than implying otherwise: qwen3 and gemma-4 are named as the configurations that demonstrate distillation, qwen3.8 and muse-glimmer are documented as exercising the memory path on a large model, and a logit-gap check reports the gap and warns when it is zero.

Verified end to end on the default qwen3 config after the change: gap 17.375, loss 0.370, 392/392 adapters changed, 9.86 GB peak.

@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: 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)'}\")"

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

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.

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

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

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.

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

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

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.

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.

Comment thread update_all_notebooks.py
Comment on lines +1008 to +1012
installation_knowledge_distillation_content = update_or_append_pip_install(
installation_content,
"transformers",
"!pip install transformers==5.15.1",
)

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

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.

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.

Comment thread README.md Outdated
@@ -853,6 +855,7 @@ Run any of these on [molab](https://molab.marimo.io), Marimo's hosted GPU notebo
| **Qwen2** **(7B)** | Alpaca | [![Open in molab](https://marimo.io/molab-shield.svg)](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen2_(7B)-Alpaca.py) |
| **Qwen2 VL** **(7B)** | Vision | [![Open in molab](https://marimo.io/molab-shield.svg)](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen2_VL_(7B)-Vision.py) |
| **Qwen3.8** **(27B)** | Conversational | [![Open in molab](https://marimo.io/molab-shield.svg)](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen3.8_(27B)-Conversational.py) |
| **Qwen3** **(0.6B)** | | [![Open in molab](https://marimo.io/molab-shield.svg)](https://molab.marimo.io/github/unslothai/notebooks/blob/main/molab/Qwen3_(0.6B)-Knowledge_Distillation.py) |

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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.

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c2c6093104

ℹ️ 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 2ee3d90 into main Sep 22, 2026
9 checks passed
@danielhanchen
danielhanchen deleted the kd-notebook branch September 22, 2026 19:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant