Skip to content

Reset torch.compile cache after a pre-train generate, not just a grad probe - #7004

Closed
danielhanchen wants to merge 2 commits into
mainfrom
fix/gptoss-generate-poisons-compiled-training
Closed

danielhanchen wants to merge 2 commits into
mainfrom
fix/gptoss-generate-poisons-compiled-training

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Follow-up to #6511. That PR resets the torch.compile graph cache poisoned by a stray forward/backward before trainer.train(), but its detector only catches a grad-enabled manual forward. A model.generate() before training slips through two ways:

  • generation drives the inner model, so the forward pre-hook the detector installs on the wrapper never fires (confirmed: the hook records zero calls across a full generate()), and
  • generation runs under no_grad, which the detector deliberately ignores.

But a no-grad generate still specializes the fullgraph=True MoE kernels (e.g. gpt-oss RMSNorm / SwiGLU). When training's gradient-checkpointing backward recompute reuses that context, Dynamo needs to recompile and hits the recompile limit, which fullgraph=True turns into a hard error instead of an eager fallback:

torch._dynamo.exc.FailOnRecompileLimitHit: Hard failure due to fullgraph=True

This reproduces on the gpt-oss (20B) fine-tuning notebook, whose pre-train inference cell generates before trainer.train().

Fix

  • for_inference records the generation on the existing pre-train marker via a new module-level helper _unsloth_flag_pretrain_generation (walks the wrapper chain, no-op if no detector was installed).
  • _unsloth_reset_stray_compile_cache now resets the compiled-graph cache when either a grad probe (seen) or a pre-train generation (generation) preceded train(). The reset path (dynamo reset, gradient-checkpointing buffer reset, zero_grad) is unchanged.
  • The existing grad-probe warning is preserved. A pre-train generate is a normal pattern, so its reset is silent.

Because the reset only runs once at train() entry (via prepare_for_training_mode, the SFT auto-packing wrapper, or the plain-Trainer loop), GRPO and other in-loop generation are unaffected.

Validation

gpt-oss-20b (auto-routed unsloth/gpt-oss-20b-unsloth-bnb-4bit), LoRA SFT, generate-before-train, 20 steps:

Run Result
main (base, with #6511) FailOnRecompileLimitHit
this branch, fix neutralized (helper monkeypatched to no-op) FailOnRecompileLimitHit
this branch, fix active trains cleanly, loss 2.13 to 1.40, coherent post-train output

Same codebase and expert config across the neutralized and active rows, so the generation-aware reset is the sole variable.

… probe

PR #6511 drops the torch.compile graph cache that a stray forward/backward before
trainer.train() poisons, but its forward-hook detector only fires for a grad-enabled
manual forward. A model.generate() before training slips through: generation drives
the inner model (so the wrapped-forward hook never fires) and runs under no_grad
(which the detector ignores), yet it still specializes the fullgraph MoE kernels
(e.g. gpt-oss). The training recompile then hard-fails with FailOnRecompileLimitHit
under fullgraph=True.

for_inference now flags the generation on the pre-train marker via a new
_unsloth_flag_pretrain_generation helper, and _unsloth_reset_stray_compile_cache
resets the cache when either a grad probe or a generation preceded train(). The
grad-probe warning is unchanged; a pre-train generate is a normal pattern, so its
reset is silent.

Verified on gpt-oss-20b (bnb-4bit) LoRA SFT: generate-then-train hard-fails on main
and with the fix neutralized, and trains cleanly (loss 2.13 to 1.40) with the fix
active.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner July 9, 2026 01:57

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a mechanism to flag when a compiled generation runs before training via _unsloth_flag_pretrain_generation, allowing the torch.compile cache to be cleared to prevent training recompile failures. This flag is integrated into the inference setup for both LLaMA and Vision models. The feedback suggests simplifying the wrapper-walking logic in the new function by reusing the existing _iter_wrapped_models helper to reduce code duplication.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread unsloth/models/_utils.py
Comment on lines +329 to +342
_curr = model
_visited = set()
while _curr is not None and id(_curr) not in _visited:
_visited.add(id(_curr))
_m = getattr(_curr, "_unsloth_pretrain_marker", None)
if isinstance(_m, dict):
_m["generation"] = True
# Follow the wrapper chain: Unsloth/HF (.model), PEFT (.base_model), DDP/FSDP (.module).
_nxt = getattr(_curr, "model", None)
if _nxt is None:
_nxt = getattr(_curr, "base_model", None)
if _nxt is None:
_nxt = getattr(_curr, "module", None)
_curr = _nxt

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The wrapper-walking logic can be simplified by reusing the existing _iter_wrapped_models helper function defined at line 168 of this file. This reduces code duplication and improves maintainability.

Suggested change
_curr = model
_visited = set()
while _curr is not None and id(_curr) not in _visited:
_visited.add(id(_curr))
_m = getattr(_curr, "_unsloth_pretrain_marker", None)
if isinstance(_m, dict):
_m["generation"] = True
# Follow the wrapper chain: Unsloth/HF (.model), PEFT (.base_model), DDP/FSDP (.module).
_nxt = getattr(_curr, "model", None)
if _nxt is None:
_nxt = getattr(_curr, "base_model", None)
if _nxt is None:
_nxt = getattr(_curr, "module", None)
_curr = _nxt
for module in _iter_wrapped_models(model):
_m = getattr(module, "_unsloth_pretrain_marker", None)
if isinstance(_m, dict):
_m["generation"] = True

@danielhanchen

Copy link
Copy Markdown
Member Author

Closing in favor of #7019, which fixes the shared root cause.

This PR reset the torch.compile cache to avoid the crash on the SFT path, but the reset does not help GRPO, where the rollout recompiles inside the training loop after the reset. #7019 traces the crash to torch 2.12 storing dynamo config overrides in thread-local ContextVars, so the recompile limit Unsloth sets on the main thread is invisible to the autograd backward worker threads that run gradient checkpointing recompute. Restoring process-global config semantics fixes both SFT and GRPO at the root, and is faster.

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