Skip to content

Keep generated RL configs on the reentrant gradient checkpoint path - #11519

Merged
danielhanchen merged 4 commits into
mainfrom
fix-gc-use-reentrant
Sep 22, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fix-gc-use-reentrant

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

The bug

Unsloth gradient checkpointing needs the reentrant path. The non-reentrant one recomputes every packed forward during backward and compares what each pass saved, so a region packed compiled and recomputed eagerly aborts the backward:

CheckpointError: torch.utils.checkpoint: 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.

Two separate things push a generated config to non-reentrant, and only one of them was handled.

  1. TRL 0.27.0+ sets use_reentrant=False explicitly. The existing guard deleted that key, gated on trl_version >= 0.27.0.
  2. transformers substitutes {"use_reentrant": False} on its own whenever gradient_checkpointing_kwargs is None, in gradient_checkpointing_enable. An older TRL never sets the key, so there was nothing to delete and transformers picked the non-reentrant path for us.

Deleting a key cannot fix a key that was never there. The value is now pinned rather than removed, for every TRL version.

When it actually bites

Worth being precise about the blast radius, because the second path is not always reachable.

apply_unsloth_gradient_checkpointing downgrades use_gradient_checkpointing="unsloth" to plain True and unpatches smart GC below sequence length 512, since the offload is not worth it there. When smart GC IS installed, unsloth_checkpoint hard-forces use_reentrant=True and the transformers default is harmless. When it is not, stock torch runs and that default decides. Measured on a tiny model:

max_seq_length torch.utils.checkpoint.checkpoint resolves to reentrant
384 checkpoint (stock torch) decided by the transformers default, so False
1024 unsloth_checkpoint forced True, immune

So the exposure is any run where smart GC is not installed: below 512, or use_gradient_checkpointing passed as True or False, or a model that deliberately opts out.

Why distillation hit it

GKDConfig inherits gradient_checkpointing=True from SFTConfig. A knowledge distillation run therefore reaches gradient_checkpointing_enable without ever asking for gradient checkpointing, and the use_gradient_checkpointing="unsloth" the user did ask for is silently overridden.

Evidence

Kaggle 2x T4, Muse Glimmer self-distillation at sequence length 384, TRL 0.25.1, transformers 5.15.1, torch 2.10.0+cu128, torch.compile enabled in both arms.

arm checkpoint kwargs 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

The after arm reaches the same point the torch.compile-disabled workaround reached, so the compile path is no longer the blocker.

What is deliberately left alone

  • context_fn and debug. torch rejects both under use_reentrant=True and raises as soon as a checkpointed forward runs (checkpoint.py lines 499 to 502, confirmed by calling it). A config carrying either is deliberately non-reentrant and pinning it would turn a working setup into a crash. determinism_check is not in that restriction and carries over.
  • Gemma-4 E-series. _gemma4_force_nonreentrant_checkpointing in unsloth_zoo re-forces non-reentrant from inside the model's forward, on every forward, because its cross-layer KV sharing gives silently wrong gradients under the reentrant path. That runs after any gradient_checkpointing_enable, so this change cannot regress it.
  • MLX. gradient_checkpointing_kwargs is already in _MLX_COMPAT_EXTRA_ARGUMENTS, so it is tolerated and ignored there.
  • Configs with gradient_checkpointing off, since transformers never reads these kwargs then.

Tests

tests/test_gradient_checkpointing_reentrant.py drives the emitted RLConfig_post snippet directly, so it needs no GPU or checkpoint. Nine tests; the six that existed before the context_fn fix all fail on main.

  • a config that never set the kwargs gets the pin, the case transformers would otherwise fill in with False
  • an explicit False is overridden
  • unrelated checkpoint kwargs are preserved
  • a context_fn config is left alone
  • a debug=True config is left alone
  • debug=False does not block the pin, since it is the torch default
  • checkpointing off is left completely alone
  • the pin is not gated on a TRL version again
  • the snippet pins True rather than deleting the key

Scope

Generated RL configs only, and only when gradient_checkpointing is true. Behaviour on TRL 0.27.0+ is unchanged in effect: it previously ended at {} after the delete, which torch resolves to reentrant anyway, and now says so explicitly instead of relying on a default.

Unsloth gradient checkpointing needs use_reentrant=True. The non-reentrant
path recomputes every packed forward during backward and compares what each
pass saved, so a region packed compiled and recomputed eagerly aborts the
backward with

    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.

Two separate things push a config to non-reentrant, and only one of them was
handled. TRL 0.27.0+ sets use_reentrant=False explicitly, which the old guard
deleted. But transformers substitutes {"use_reentrant": False} on its own
whenever gradient_checkpointing_kwargs is None, and an older TRL never sets
the key at all, so there was nothing to delete and transformers chose the
non-reentrant path for us. Deleting a key cannot fix a key that was never
there, so the value is now pinned instead, for every TRL version.

This is not hypothetical. GKDConfig inherits gradient_checkpointing=True from
SFTConfig, so a knowledge distillation run reaches the non-reentrant path
without ever having asked for gradient checkpointing. Measured on a Kaggle
2x T4 running Muse Glimmer self-distillation under TRL 0.25.1: it fails on
the first step with the counts above, and with use_reentrant pinned to True
it trains with torch.compile still enabled, all 103 checkpointed layers
reporting {'use_reentrant': True}.

Only touched when gradient checkpointing is actually on, since transformers
does not read these kwargs otherwise.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 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-22T10:47:12.938263Z 4f6d64f 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[bot]

This comment was marked as resolved.

torch rejects both under use_reentrant=True and raises as soon as a
checkpointed forward runs:

    ValueError: Passing `context_fn` or `debug` is only supported when
    use_reentrant=False.

Verified against torch 2.10.0, checkpoint.py lines 499 to 502, and by calling
it: each raises on the backward. So a config carrying either is deliberately
non-reentrant, and pinning it would turn a working setup into a crash. Those
are now left untouched.

determinism_check is not in that restriction and still carries over.
@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. What shall we delve into next?

Reviewed commit: 4f6d64f649

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@danielhanchen
danielhanchen merged commit 9f3153c into main Sep 22, 2026
35 of 36 checks passed
@danielhanchen
danielhanchen deleted the fix-gc-use-reentrant branch September 22, 2026 11:53
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
…nslothai#11519)

* Keep generated RL configs on the reentrant checkpoint path

Unsloth gradient checkpointing needs use_reentrant=True. The non-reentrant
path recomputes every packed forward during backward and compares what each
pass saved, so a region packed compiled and recomputed eagerly aborts the
backward with

    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.

Two separate things push a config to non-reentrant, and only one of them was
handled. TRL 0.27.0+ sets use_reentrant=False explicitly, which the old guard
deleted. But transformers substitutes {"use_reentrant": False} on its own
whenever gradient_checkpointing_kwargs is None, and an older TRL never sets
the key at all, so there was nothing to delete and transformers chose the
non-reentrant path for us. Deleting a key cannot fix a key that was never
there, so the value is now pinned instead, for every TRL version.

This is not hypothetical. GKDConfig inherits gradient_checkpointing=True from
SFTConfig, so a knowledge distillation run reaches the non-reentrant path
without ever having asked for gradient checkpointing. Measured on a Kaggle
2x T4 running Muse Glimmer self-distillation under TRL 0.25.1: it fails on
the first step with the counts above, and with use_reentrant pinned to True
it trains with torch.compile still enabled, all 103 checkpointed layers
reporting {'use_reentrant': True}.

Only touched when gradient checkpointing is actually on, since transformers
does not read these kwargs otherwise.

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

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

* Leave context_fn and debug configs on the non-reentrant path

torch rejects both under use_reentrant=True and raises as soon as a
checkpointed forward runs:

    ValueError: Passing `context_fn` or `debug` is only supported when
    use_reentrant=False.

Verified against torch 2.10.0, checkpoint.py lines 499 to 502, and by calling
it: each raises on the backward. So a config carrying either is deliberately
non-reentrant, and pinning it would turn a working setup into a crash. Those
are now left untouched.

determinism_check is not in that restriction and still carries over.

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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