Repository navigation
Reset torch.compile cache after a pre-train generate, not just a grad probe - #7004
danielhanchen wants to merge 2 commits into
Conversation
… 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.
There was a problem hiding this comment.
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.
| _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 |
There was a problem hiding this comment.
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.
| _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 |
|
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. |
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. Amodel.generate()before training slips through two ways:generate()), andno_grad, which the detector deliberately ignores.But a no-grad generate still specializes the
fullgraph=TrueMoE 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, whichfullgraph=Trueturns into a hard error instead of an eager fallback:This reproduces on the gpt-oss (20B) fine-tuning notebook, whose pre-train inference cell generates before
trainer.train().Fix
for_inferencerecords 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_cachenow resets the compiled-graph cache when either a grad probe (seen) or a pre-train generation (generation) precededtrain(). The reset path (dynamo reset, gradient-checkpointing buffer reset,zero_grad) is unchanged.Because the reset only runs once at
train()entry (viaprepare_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:Same codebase and expert config across the neutralized and active rows, so the generation-aware reset is the sole variable.