Skip to content

Stop SFTTrainer downcasting configs that subclass SFTConfig - #11440

Merged
danielhanchen merged 5 commits into
mainfrom
fix-sft-config-subclass-downcast
Sep 21, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix-sft-config-subclass-downcast

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The problem

GKDTrainer under Unsloth fails at construction with

ValueError: The specified `eos_token` ('<EOS_TOKEN>') is not found in the vocabulary
of the given `processing_class` (Qwen2Tokenizer).

which is #1941. That error is the visible half. The silent half is worse, and is the reason this is worth fixing carefully: every GKD-only config field is dropped on the way in.

Unsloth: `temperature` is not a valid SFTConfig argument for the installed TRL and will be IGNORED.
Unsloth: `lmbda` is not a valid SFTConfig argument for the installed TRL and will be IGNORED.
Unsloth: `beta` is not a valid SFTConfig argument for the installed TRL and will be IGNORED.
Unsloth: `max_new_tokens` is not a valid SFTConfig argument ...
Unsloth: `teacher_model_name_or_path` is not a valid SFTConfig argument ...
Unsloth: `teacher_model_init_kwargs` is not a valid SFTConfig argument ...
Unsloth: `disable_dropout` is not a valid SFTConfig argument ...
Unsloth: `seq_kd` is not a valid SFTConfig argument ...

Without the eos_token crash to stop it, a run like that looks perfectly healthy while training against a different objective than the one that was asked for.

Root cause

The trainer compiler is not at fault. It discovers gkd_trainer, generates a correct UnslothGKDTrainer.py, and rebinds trl.GKDTrainer to it. The damage happens afterwards.

Replacing trl.trainer.sft_trainer.SFTConfig leaves two live classes of that name:

trl.SFTConfig            id=1027885296   (ours, renamed for pickle identity)
GKDConfig.__mro__[2]     id=1028136560   (pristine, what GKDConfig derives from)
same object?             False

SFTTrainer.__init__ guards with

elif isinstance(args, TrainingArguments) and not isinstance(args, SFTConfig):
    dict_args = args.to_dict()
    ...
    args = SFTConfig(**dict_args)

Measured against our class, that predicate is true for a GKDConfig, so the config is rebuilt as a plain SFT one and everything the subclass added is gone. Observed chain:

UnslothGKDTrainer.py:1434   __init__  -> super().__init__(
UnslothGKDTrainer.py:915    __init__  -> super().__init__(
sft_trainer.py:602          __init__  -> args = SFTConfig(**dict_args)
UnslothSFTTrainer.py:819    __init__  -> _unsloth_filter_config_init_kwargs(SFTConfig, ...)

This is not specific to GKD. It hits any TRL trainer whose config subclasses SFTConfig.

The fix

The guard exists to convert a plain TrainingArguments. A subclass of SFTConfig already is an SFT config, so widen the isinstance test to accept the pristine class, while calling the name still builds ours. This is the same shape as the existing _pin_pristine_sft_loss_type, which handles the other half of the pristine-class problem, and it lives in the same if trainer_file == "sft_trainer": hook.

It is a no-op when nothing was replaced, idempotent across repeated patch_trl_rl_trainers() passes, and keeps the module and qualname of the class it stands in for so pickling and reprs are unchanged.

Verification

Qwen3-0.6B distilled from Qwen3-1.7B, LoRA r=8, trl 0.25.1, transformers 5.17.0, torch 2.13.0+cu130, B200.

before after
construction ValueError on eos_token OK
type(trainer.args) downcast to SFTConfig GKDConfig
lmbda / beta / temperature all IGNORED 0.25 / 0.75 / 0.9
training never started 3 steps, loss 0.2289
adapter tensors changed n/a 112 / 112
peak VRAM n/a 3.49 GB

No SFT regression. The same SFT run with and without this change gives a bit-identical loss of 2.6346049308776855, and a bare TrainingArguments is still converted exactly as before.

Suites run on this branch:

  • tests/security 725 passed, 7 skipped
  • tests/test_rl_config_compat.py plus the new file, 37 passed
  • scripts/enforce_kwargs_spacing.py reports no changes for the edited lines

Tests added

tests/test_sft_config_subclass_downcast.py, 9 cases. It lifts the helpers out of rl.py with ast the same way tests/_rl_source.py does, so it stays CPU-only and needs neither torch nor trl. Covered: the downcast is reproduced without the fix, widening stops it and the subclass keeps its fields, a plain TrainingArguments is still converted, instances of both classes match, calling the name still builds the generated config, idempotence, the no-op path, module and qualname preservation, and issubclass widening.

Fixes #1941

Replacing trl.trainer.sft_trainer.SFTConfig leaves two live classes of that
name: ours, and the pristine one every SFTConfig subclass in TRL still derives
from. SFTTrainer.__init__ guards with

    isinstance(args, TrainingArguments) and not isinstance(args, SFTConfig)

and rebuilds args = SFTConfig(**args.to_dict()) when it fires. Measured against
our class that test is true for a GKDConfig, so the config is rebuilt as a plain
SFT one and every field the subclass added is dropped: lmbda, beta, temperature,
max_new_tokens, teacher_model_name_or_path, teacher_model_init_kwargs,
disable_dropout and seq_kd, each with only an "is not a valid SFTConfig
argument" line. The rebuilt config also carries the mirrored eos_token
placeholder, which then raises

    ValueError: The specified eos_token ('<EOS_TOKEN>') is not found in the
    vocabulary of the given processing_class (Qwen2Tokenizer)

which is the crash reported in #1941. The silent half is the worse one: without
that error a run looks fine while training against a different objective than
the one asked for.

The guard exists to convert a plain TrainingArguments, and a subclass of
SFTConfig already is an SFT config, so widen the isinstance test to accept the
pristine class while calling the name still builds ours. Same shape as the
existing _pin_pristine_sft_loss_type, which handles the other half of the
pristine-class problem.

Verified on Qwen3-0.6B distilled from Qwen3-1.7B with LoRA, trl 0.25.1,
transformers 5.17.0, torch 2.13.0. Before: construction raises. After:
trainer.args stays a GKDConfig, lmbda/beta/temperature arrive as 0.25/0.75/0.9,
three steps run and all 112 adapter tensors change.

Plain SFT is unaffected: same run with and without this change gives a
bit-identical loss of 2.6346049308776855, and a bare TrainingArguments is still
converted as before.

Fixes #1941
@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-21T12:39:17.215637Z 3ec3bc8 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: e1c7f8dcf6

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

pre-commit-ci Bot and others added 2 commits September 21, 2026 10:32
Simulating the branch turned up two things the first pass missed, both from
installing the shim only at the guard's own module.

torch.save(trainer.args, ...) is how Trainer._save writes training_args.bin,
and pickle stores a class as __module__ plus __qualname__ and refuses unless
the object living there IS the class. The shim advertised the displaced class's
home while the displaced class still sat there, so an instance built by calling
trl.trainer.sft_trainer.SFTConfig raised PicklingError. That is the exact
failure _patch_config_pickle_identity already exists to prevent, so take the
same route: move every binding of the displaced class onto the shim and route
anything still holding the displaced class through _register_config_pickle_fallback.
No flow under unsloth was observed to construct such an instance, since the
generated trainer converts args before the pristine __init__ sees them, so this
was latent rather than user visible, but it costs nothing to close.

Leaving the top level name behind also made trl.SFTConfig and
trl.trainer.sft_trainer.SFTConfig different objects, so the two spellings gave
different isinstance answers for the same config. Both now resolve to the shim.

Three tests, each failing on the previous commit and passing here. Enumerating
the widened predicate over every TrainingArguments subclass reachable from trl,
transformers, peft and accelerate gives 21 cells, 20 identical, 1 moving, and
the one that moves is GKDConfig. The widened check costs 89 ns against 27 ns at
its single call site in SFTTrainer.__init__, and the binding sweep is 10.6 ms
once at import against a 12 s import.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 21, 2026
Running both repositories' suites base against head caught the previous commit
doing more than it needed to. Rebinding every module attribute that held the
generated config moved trl.SFTConfig and trl.trainer.sft_config.SFTConfig onto
the shim, and other patching passes rely on those staying the generated class:
tests/python/test_rl_config_pickling.py asserts the class's own base carries no
patched marker, and the pristine-class walk in tests/version_compat/ walks back
with "_unsloth_patched_rl_config" in cls.__dict__. Base failed 1 test in that
selection, the previous commit failed 2 and then 2 again, and head now fails the
same 1, which is pre-existing and fails identically on the merge base.

The pickle hazard needed none of that. Pickle resolves a class through its own
__module__ and __qualname__, so pointing the shim at the module it is actually
installed at, trl.trainer.sft_trainer, makes it resolvable there while the
generated class keeps trl.trainer.sft_config to itself. Both pickle, and every
binding other than the guard's own resolves exactly as it did before this branch.

The shim also carries the patched-config marker in its own __dict__ now, so a
walk back to TRL's pristine class steps over it instead of stopping on it and
reading back Unsloth's field set.

trl.SFTConfig therefore still answers isinstance the way it does on main. That
is stated rather than fixed: it is not a regression, the guard TRL actually runs
reads the sft_trainer binding, and making the two spellings agree costs more
than the inconsistency does.

13 tests, all passing; the three added here fail on the commit before this one
or on af1ba00 as appropriate. GKD end to end is unchanged at loss
0.22892586886882782, 112/112 adapters, 3.49 GB, and saves a checkpoint.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3ec3bc83b3

ℹ️ 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-only. Six multi-line blocks collapsed to one line each, keeping the fact
in every case and dropping the restatement: 66 comment lines down to 34 on this
file, 29.1 percent to 17.1 percent, and 9.3 to 8.4 overall. AST verified as
comments and docstrings only; 13 tests still pass.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 21, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 21, 2026
@danielhanchen
danielhanchen merged commit d48ab69 into main Sep 21, 2026
26 of 28 checks passed
@danielhanchen
danielhanchen deleted the fix-sft-config-subclass-downcast branch September 21, 2026 13:48
pull Bot pushed a commit to earyantLe/unslothai_notebooks that referenced this pull request Sep 22, 2026
* Add a knowledge distillation notebook

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.

* Document which configs are blocked and why

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.

* Use an install block that can load every config, and record T4 results

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.

* Pin trl 0.25.1 and let Unsloth choose the precision

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.

* Hand back the allocator reserve before loading the teacher

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.

* Give the planner explicit budgets for the teacher

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.

* Note the sequence length floor GKD imposes

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.

* Say what each config actually does on two T4s

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.

* Filter rows whose prompt leaves no room for a completion

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.

* Guard the prompt filter against single-turn rows

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.

* Filter on total length, not prompt length

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.

* gemma-4 trains on two T4s

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.

* Disable torch.compile for Muse Glimmer as well

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.

* Record the Muse Glimmer result: correct, but not on two T4s

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.

* Narrow the compile workaround to gemma-4, and say what it is really for

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.

* Restyle the distillation notebook to match the rest of the repo

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.

* Make the self-distillation teacher actually be the frozen base

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.

* Add the missing molab generation for the distillation notebook

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.

* Regenerate the molab conversion with the pinned marimo and ruff

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.

* Add the molab badge row for the distillation notebook

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.

* Fix a Python 3.11 syntax error, check token ids not vocabulary width

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.

* Initialise teacher_processor, pin TRL 0.25.1 everywhere, label the molab 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.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…i#11440)

Patching rebinds trl.trainer.sft_trainer.SFTConfig to the generated config,
which leaves two live classes of that name: ours, and the pristine one every
SFTConfig subclass in TRL still derives from. SFTTrainer.__init__ guards with
isinstance(args, TrainingArguments) and not isinstance(args, SFTConfig) and
rebuilds args = SFTConfig(**args.to_dict()) when it fires. Against our class that
test is true for a GKDConfig, so the config was rebuilt as a plain SFT one and
every field the subclass added was dropped: lmbda, beta, temperature,
max_new_tokens, teacher_model_name_or_path, teacher_model_init_kwargs,
disable_dropout and seq_kd each vanished behind a single warning line, and the
rebuilt config carried the mirrored eos_token placeholder, which then raised
'The specified eos_token (<EOS_TOKEN>) is not found in the vocabulary'. The
silent half was worse than the crash. Fixes unslothai#1941.

The guard exists to convert a plain TrainingArguments, and a subclass of
SFTConfig already is an SFT config, so widen the test to accept the pristine
class while calling the name still builds ours. Only the module holding TRL's
guard is rebound: moving trl.SFTConfig and the class's home module as well was
tried and is worse, because other patching passes rely on the generated class
being what trl.SFTConfig resolves to. The shim answers to the module it is
installed at, so it and the generated class each remain the object living at
their own __module__ plus __qualname__ and both still pickle, which keeps
torch.save(trainer.args, ...) working from Trainer._save. It also carries the
patched-config marker in its own __dict__, so a walk back to TRL's pristine
class steps over it rather than stopping on it.

Enumerated over every TrainingArguments subclass reachable from trl,
transformers, peft and accelerate: 21 cells, 20 identical, 1 moves, 0
violations, and the one that moves is GKDConfig. The widened check costs 89 ns
against 27 ns at its single call site in SFTTrainer.__init__, once per trainer
construction and never per token.

Verified end to end on TRL 0.22.2, 0.24.0, 0.25.1 and 1.13.0, on PEFT 0.18.0,
0.19.0 and 0.20.0, with the compiled cache wiped and regenerated, and under
UNSLOTH_COMPILE_DISABLE=1. GKD trains with lmbda/beta/temperature intact and
saves a checkpoint; plain SFT is unchanged. Full suite: 40 failures at head
against 41 on the merge base, no new ones. 13 CPU-only tests.
Penguinjanator pushed a commit to Penguinjanator/notebooks that referenced this pull request Oct 16, 2026
…nslothai#402)

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

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

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

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

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

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

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

Verified: gemma-4 frozen compile-disable True, the guard raises AssertionError on
2026.9.7 with UNSLOTH_IS_PRESENT unset, and the notebook runs end to end at loss
0.370, 392/392 adapters, 3.28 GB. The suite's 18 failures are on the Qwen3 (4B)
tool-use notebooks from unslothai#395 and reproduce unchanged on clean main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

trying to run GKD with unsloth

1 participant