Repository navigation
Reset torch.compile cache poisoned by a stray forward before trainer.train() - #6511
Conversation
…train() A manual forward / forward+backward run under model.train() before trainer.train() (for example a pre-train grad-norm probe like out = model(**batch); out.loss.backward()) silently poisons training when torch.compile is enabled. The stray training-mode pass is the first one in the process, so it compiles and caches the model forward and, via AOTAutograd, its backward graph in a one-off context that does not match the real training loop. When trainer.train() reuses that cached graph the gradients come out NaN/Inf, the loss never moves, and the run looks like it trains but never learns. Observed on gpt-oss-20b (loss frozen at ~4.25, grad_norm NaN from step 1) with both use_gradient_checkpointing="unsloth" and =True. It does not reproduce when the probe runs under torch.no_grad(), nor with UNSLOTH_COMPILE_DISABLE=1, and a single torch._dynamo.reset() before training fully cures it (loss 4.29 -> 0.0002, identical to a run with no probe). Resetting the gradient-checkpointing buffers, zero_grad, empty_cache, or for_training does not help, confirming the corruption lives in the torch._dynamo / torch.compile cache. get_peft_model now attaches a one-shot forward pre-hook that records whether a forward ran before train(). prepare_for_training_mode checks it at the start of train() and, if a pre-train forward was seen and torch.compile is enabled, calls torch._dynamo.reset() (plus a pristine gradient-checkpoint reset and zero_grad) and warns once. On the normal path (no pre-train forward) it is a strict no-op: no dynamo reset, no recompilation, identical loss curve.
There was a problem hiding this comment.
Code Review
This pull request introduces a mechanism to detect manual forward or backward runs (such as pre-train probes) before trainer.train() starts, which can poison the torch.compile graph cache and lead to NaN or zero gradients. It installs a one-shot forward pre-hook on the model and resets the Dynamo cache if a pre-train forward is detected. The review feedback suggests improving the robustness of this mechanism: first, by ensuring the hook installation is fully idempotent even if the hook is missing from an existing marker; and second, by recursively traversing the model wrapper chain (such as PEFT or DDP wrappers) to ensure pre-train runs on underlying base models are correctly detected and cleaned up.
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.
| marker = getattr(model, "_unsloth_pretrain_marker", None) | ||
| if isinstance(marker, dict): | ||
| marker["seen"] = False | ||
| return model | ||
| marker = {"seen": False} | ||
| try: | ||
| model._unsloth_pretrain_marker = marker | ||
| except Exception: | ||
| return model |
There was a problem hiding this comment.
To make _unsloth_install_pretrain_detector fully idempotent and robust to hook teardown, we should check if the hook was already removed from the existing marker dictionary. If the marker exists but the hook is missing, we should re-register the hook instead of returning early.
| marker = getattr(model, "_unsloth_pretrain_marker", None) | |
| if isinstance(marker, dict): | |
| marker["seen"] = False | |
| return model | |
| marker = {"seen": False} | |
| try: | |
| model._unsloth_pretrain_marker = marker | |
| except Exception: | |
| return model | |
| marker = getattr(model, "_unsloth_pretrain_marker", None) | |
| if isinstance(marker, dict): | |
| marker["seen"] = False | |
| if "hook" in marker: | |
| return model | |
| else: | |
| marker = {"seen": False} | |
| try: | |
| model._unsloth_pretrain_marker = marker | |
| except Exception: | |
| return model |
| marker = getattr(model, "_unsloth_pretrain_marker", None) | ||
| seen = bool(marker.get("seen")) if isinstance(marker, dict) else False | ||
| if seen and os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") != "1": | ||
| try: | ||
| import torch._dynamo as _dynamo | ||
| _dynamo.reset() | ||
| except Exception: | ||
| pass | ||
| try: | ||
| reset_unsloth_gradient_checkpointing_buffers() | ||
| except Exception: | ||
| pass | ||
| try: | ||
| model.zero_grad(set_to_none = True) | ||
| except Exception: | ||
| pass | ||
| import warnings | ||
| warnings.warn( | ||
| "Unsloth: detected a manual forward/backward run before trainer.train(); " | ||
| "reset the torch.compile graph cache it poisoned so training starts clean. " | ||
| "To avoid this, run any pre-train probe under `with torch.no_grad():`." | ||
| ) | ||
| # Tear down the one-shot detector hook so it never adds per-step cost. | ||
| if isinstance(marker, dict): | ||
| hook = marker.pop("hook", None) | ||
| if hook is not None: | ||
| try: hook.remove() | ||
| except Exception: pass | ||
| marker["seen"] = False |
There was a problem hiding this comment.
If a pre-train probe is run on the base model before wrapping it with PEFT (which is a very common pattern), the base model's marker will be set to seen = True. However, _unsloth_reset_stray_compile_cache only checks the top-level self.model (the PeftModel wrapper), which has a separate marker with seen = False. This causes the poisoned cache reset to be silently skipped.
To fix this, we should recursively traverse the model wrapper chain (supporting DDP, PEFT, and other Unsloth wrappers) to detect if any underlying model has been run, and clean up the hooks across the entire chain.
seen = False
curr = model
visited = set()
while curr is not None and id(curr) not in visited:
visited.add(id(curr))
marker = getattr(curr, "_unsloth_pretrain_marker", None)
if isinstance(marker, dict) and marker.get("seen"):
seen = True
break
if hasattr(curr, "module"):
curr = curr.module
elif hasattr(curr, "base_model"):
curr = curr.base_model
elif hasattr(curr, "model") and curr.model is not curr:
curr = curr.model
else:
curr = None
if seen and os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") != "1":
try:
import torch._dynamo as _dynamo
_dynamo.reset()
except Exception:
pass
try:
reset_unsloth_gradient_checkpointing_buffers()
except Exception:
pass
try:
model.zero_grad(set_to_none = True)
except Exception:
pass
import warnings
warnings.warn(
"Unsloth: detected a manual forward/backward run before trainer.train(); "
"reset the torch.compile graph cache it poisoned so training starts clean. "
"To avoid this, run any pre-train probe under `with torch.no_grad():`."
)
curr = model
visited = set()
while curr is not None and id(curr) not in visited:
visited.add(id(curr))
marker = getattr(curr, "_unsloth_pretrain_marker", None)
if isinstance(marker, dict):
hook = marker.pop("hook", None)
if hook is not None:
try: hook.remove()
except Exception: pass
marker["seen"] = False
if hasattr(curr, "module"):
curr = curr.module
elif hasattr(curr, "base_model"):
curr = curr.base_model
elif hasattr(curr, "model") and curr.model is not curr:
curr = curr.model
else:
curr = NoneThere was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9026037298
ℹ️ 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".
| m = m.model | ||
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Reset Dynamo for non-TRL Trainer paths
When a patched Llama model is trained with the standard transformers.Trainer path, this hook is installed but the only code that consumes/removes it is the generated TRL prepare_for_training_mode wrapper in rl.py. In that supported Trainer path, a pre-train probe still leaves the poisoned Dynamo cache in place, and the new pre-hook also remains active for every training forward instead of being the claimed no-op. Please either wire the same reset into the patched HF Trainer path or avoid installing the detector where no train wrapper will handle it.
Useful? React with 👍 / 👎.
| return model | ||
|
|
||
| def _mark(_module, _inp): | ||
| marker["seen"] = True |
There was a problem hiding this comment.
Ignore no-grad pre-train probes
This marks every pre-train forward as poisoned, including the exact safe case the new warning recommends: with torch.no_grad(): model(**batch). In that common eval/sanity-check scenario there is no AOTAutograd backward graph to poison training, but trainer.train() will still reset the global Dynamo cache and emit a misleading warning, forcing unnecessary recompilation on an otherwise clean run. Please gate this marker on grad-enabled training forwards, or otherwise avoid treating no-grad/inference probes as poisoned.
Useful? React with 👍 / 👎.
| m = m.model | ||
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Install detector before early PEFT returns
Placing the detector only here means the already-adapted PEFT path returns earlier without installing _unsloth_pretrain_marker, so continuing training from an existing LoRA adapter with TRL still leaves a pre-train() probe undetected and _unsloth_reset_stray_compile_cache() becomes a no-op. Please install the marker before the compatible-adapter early return as well, or call it in that branch before returning.
Useful? React with 👍 / 👎.
…chain A no-grad forward (with torch.no_grad(): model(**batch)) builds no AOTAutograd backward graph, so it cannot poison the compiled training graph. Gate the marker on torch.is_grad_enabled() so such probes no longer trigger a needless dynamo reset, recompile and warning on an otherwise clean run. Also walk the model wrapper chain (PeftModel / DDP / base model) when resetting so a probe that ran on a different wrapper than self.model is still detected, and tear down every detector hook in the chain. Re-installing the detector is now idempotent and only re-registers when a prior hook was already removed.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Addressed the review feedback in a follow-up commit:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b77b63e498
ℹ️ 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".
| m = m.model | ||
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Add cache reset for plain HF Trainer
This detector is installed for every FastLlamaModel.get_peft_model() caller, but the only repo-wide consumer of _unsloth_reset_stray_compile_cache is the generated TRL prepare_for_training_mode wrapper; the patched plain transformers.Trainer path never invokes it. In that setup a pre-train probe still leaves the poisoned Dynamo cache in place, and the hook is never removed, so every training forward continues to execute this Python pre-hook and can interfere with torch.compile. Please also invoke the reset/removal from the HF Trainer patch, or only install this detector for trainers that wrap train().
Useful? React with 👍 / 👎.
| _nxt = getattr(_curr, "model", None) | ||
| if _nxt is None: | ||
| _nxt = getattr(_curr, "base_model", None) |
There was a problem hiding this comment.
Walk DDP wrappers when looking for the marker
When a TRL trainer is constructed with an already-wrapped model, the detector can sit on the underlying PEFT module below the wrapper, but this traversal only follows .model and .base_model. DDP-style wrappers expose the wrapped model through .module, so seen stays false and the poisoned compile cache is not reset even though the hook was installed and fired on the real model; include wrapper attributes such as .module before giving up.
Useful? React with 👍 / 👎.
| m = m.model | ||
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Install the detector before get_peft_model early returns
This hook is only attached after the non-PEFT LoRA setup finishes, so callers that hit the existing early returns in get_peft_model (for example UNSLOTH_ENABLE_FULL_FINETUNING=1, or an already-PEFT model whose config matches and is passed through) still reach the TRL train() wrapper with no _unsloth_pretrain_marker to inspect. In those supported paths, a grad-enabled pre-train probe continues to reuse the poisoned compile cache because _unsloth_reset_stray_compile_cache sees no marker; install the marker before those no-op/pass-through returns as well.
Useful? React with 👍 / 👎.
The chain walk followed only .model and .base_model, so a probe that fired on the model below a DDP/FSDP wrapper (which exposes it via .module) left the marker undetected and the poisoned compile cache un-reset. Add .module to the walk.
|
Follow-up commit: the marker chain walk now also follows DDP/FSDP |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 76d7932503
ℹ️ 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".
| m = m.model | ||
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Attach the detector before full-finetuning returns
Putting the marker install only on this PEFT return path means supported full-finetuning runs never create _unsloth_pretrain_marker: the early UNSLOTH_ENABLE_FULL_FINETUNING return above bypasses this call, and users often skip get_peft_model entirely for full finetuning, while prepare_for_training_mode relies solely on that marker before calling torch._dynamo.reset(). In those runs, a grad-enabled probe before trainer.train() can still leave the poisoned compile cache in place, so the fix does not protect full-finetuning experiments; install the detector during model load/post-patch or before the full-finetuning return as well.
Useful? React with 👍 / 👎.
get_peft_model returns early when UNSLOTH_ENABLE_FULL_FINETUNING=1, before the detector was installed, so full-finetuning runs (which still use torch.compile) did not drop a graph cache poisoned by a stray pre-train forward. Install the detector before both full-finetuning early returns (FastLlamaModel and FastBaseModel). The detector is idempotent, so this never stacks duplicate hooks when get_peft_model is also called on a LoRA model.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8596138a86
ℹ️ 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".
| return model | ||
| marker = getattr(model, "_unsloth_pretrain_marker", None) | ||
| if isinstance(marker, dict): | ||
| marker["seen"] = False |
There was a problem hiding this comment.
Preserve the recorded pre-train forward on reinstall
When the same model is passed through this installer again after a grad-enabled pre-train probe but before trainer.train(), this assignment clears marker["seen"] while the live hook is still returned unchanged. That makes the later prepare_for_training_mode reset path skip torch._dynamo.reset(), so workflows that reapply Unsloth patching/wrapping to the same PEFT model after a probe still reuse the poisoned compile cache this change is trying to avoid.
Useful? React with 👍 / 👎.
| for _m in markers: | ||
| hook = _m.pop("hook", None) | ||
| if hook is not None: | ||
| try: hook.remove() | ||
| except Exception: pass |
There was a problem hiding this comment.
Re-arm the detector for subsequent train calls
This unconditionally removes the one-shot hook at the start of the first train(), even when no stray forward was seen, and nothing in this wrapper reinstalls it after training completes. Since the same wrapper explicitly supports subsequent train() calls, a grad-enabled loss/grad-norm probe between two trainer.train() invocations will no longer be detected, so the second run can enter with the same poisoned torch.compile cache and skip the reset.
Useful? React with 👍 / 👎.
| m = m.model | ||
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Install the detector on the already-adapted path
Because this detector is only installed on the fall-through path, the already-adapted PeftModel branch above still returns early when the existing LoRA config matches, before any marker hook is attached. Loading an adapter or reusing an already-adapted model is a supported no-op path, so a grad-enabled pre-train probe in that flow will never set seen and _unsloth_reset_stray_compile_cache will skip the cache reset this change is meant to provide.
Useful? React with 👍 / 👎.
| print("Unsloth: Full finetuning is enabled, so .get_peft_model has no effect") | ||
| # Full finetuning still compiles, so a stray pre-train forward can poison the | ||
| # cache; install the detector here too (it is idempotent). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Install the full-finetune detector during load
Because the hook is only attached in this no-op get_peft_model branch, full_finetuning=True users who train the model returned from from_pretrained directly, or who run their grad-enabled probe before calling this no-op, never get a marker installed. Full finetuning still uses the compiled training path, so the cache reset should be armed during the full-finetune load/post-patch path rather than only here.
Useful? React with 👍 / 👎.
| def wrapper(self, *args, **kwargs): | ||
| # Drop any torch.compile graph cache poisoned by a stray pre-train forward. | ||
| try: | ||
| _unsloth_reset_stray_compile_cache(self) |
There was a problem hiding this comment.
Wire the reset into plain Trainer training
This reset is only called from the generated TRL prepare_for_training_mode wrapper, but FastLlamaModel.from_pretrained also supports plain transformers.Trainer by patching Trainer._inner_training_loop. In that supported path the marker set by _unsloth_install_pretrain_detector is never consumed, so a grad-enabled probe before Trainer.train() still enters training with the poisoned Dynamo cache.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d2f6eec004
ℹ️ 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".
| # Drop any torch.compile graph cache poisoned by a stray pre-train forward. | ||
| try: | ||
| _unsloth_reset_stray_compile_cache(self) |
There was a problem hiding this comment.
Wire the cache reset into non-RL training paths
This reset is only injected through prepare_for_training_mode, which is added to the generated RL trainers in unsloth/models/rl.py; the SFT/HF training path in unsloth/trainer.py only wraps SFTTrainer.__init__ and never calls this helper. Because FastLanguageModel.get_peft_model / FastBaseModel.get_peft_model now install the detector for ordinary LoRA and vision models too, a grad-enabled probe before SFTTrainer.train() still leaves the poisoned Dynamo cache in place, and the forward pre-hook also remains installed for every training forward. Please add the same reset/removal hook to the non-RL trainer entry point or avoid installing the detector on paths that never consume it.
Useful? React with 👍 / 👎.
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Install the detector on the PEFT pass-through path
Adding the detector only at the end of this method misses the supported branch above where an already-adapted PeftModelForCausalLM/PeftModelForSequenceClassification with matching LoRA settings logs “Already have LoRA adapters” and returns early. In that context, an RL trainer still has the reset wrapper, but a grad-enabled probe before trainer.train() leaves no _unsloth_pretrain_marker for it to consume, so the cache-poisoning fix is skipped for externally loaded or pre-wrapped PEFT models. Please install the marker before that early return too.
Useful? React with 👍 / 👎.
…rough The pre-train forward detector is installed for plain LoRA/vision models in get_peft_model, but only RL trainers ran the reset via prepare_for_training_mode. A grad-enabled probe before SFTTrainer.train() therefore left the poisoned Dynamo cache in place and the detector hook running on every training forward. - trainer.py: wrap SFTTrainer.train to run _unsloth_reset_stray_compile_cache, which both drops the poisoned cache and tears down the detector hook. For UnslothSFTTrainer the later prepare_for_training_mode assignment supersedes it. - llama.py: arm the detector before the 'Already have LoRA adapters' early return so pre-wrapped PEFT models keep the reset capability.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Addressed both review points in 430af17: P1 (reset not wired into non-RL training paths). The pre-train forward detector is installed for plain LoRA/vision models in P2 (PEFT pass-through early return). Added |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7a981a4708
ℹ️ 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 isinstance(marker, dict): | ||
| marker["seen"] = False | ||
| # Re-register only if the previous hook was torn down; a live hook stays (no duplicates). | ||
| if "hook" in marker: | ||
| return model |
There was a problem hiding this comment.
Preserve a seen pre-train forward when reinstalling
When the detector is installed again on a model that already has a live hook, this resets marker["seen"] before returning. In flows that re-enter get_peft_model/patch_peft_model after a grad-enabled probe on the same PEFT model, the hook has correctly recorded the poisoned compile cache, but this idempotent call clears the evidence while leaving the hook in place; trainer.train() then skips the Dynamo reset and the NaN/flat-loss failure this change is meant to fix can still occur. Only clear seen when registering a fresh hook or after teardown.
Useful? React with 👍 / 👎.
| m = m.model | ||
| # Detect a stray pre-train forward so train() can drop the torch.compile | ||
| # graph cache it would otherwise poison (see prepare_for_training_mode). | ||
| _unsloth_install_pretrain_detector(model) |
There was a problem hiding this comment.
Wire the reset into plain Trainer training
This common LoRA path installs the detector for all language models, but the commit only consumes it from TRL SFT/RL train wrappers. In a plain transformers.Trainer flow, which Unsloth still patches via Trainer._inner_training_loop, a grad-enabled probe after get_peft_model() marks the cache as poisoned, yet Trainer.train() never calls _unsloth_reset_stray_compile_cache; the same NaN/flat-loss failure remains and the hook also stays installed during training. The generic Trainer train path needs the same reset/teardown before training starts.
Useful? React with 👍 / 👎.
…er path P2 (_utils.py): _unsloth_install_pretrain_detector cleared marker['seen'] before the live-hook early return, so a re-entrant get_peft_model/patch_peft_model after a grad-enabled probe erased the recorded poisoning while leaving the hook installed, and train() then skipped the Dynamo reset. Only reset seen when (re)installing a fresh hook; keep it when a live hook is already recording. P2 (llama.py): the detector is armed for every LoRA model, but only TRL SFT/RL train wrappers consumed it. Inject _unsloth_reset_stray_compile_cache(self) at the start of the generated _fast_inner_training_loop so a bare transformers.Trainer.train() also drops a poisoned cache and tears down the hook. Idempotent with the TRL-wrapper reset.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Both addressed in 202d731. Preserve a seen pre-train forward when reinstalling (_utils.py). Correct - the idempotent re-install cleared Wire the reset into plain Trainer training (llama.py). Agreed - the detector is armed for every LoRA model but only the TRL SFT/RL wrappers consumed it, so a bare |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 202d731903
ℹ️ 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".
| # (For UnslothSFTTrainer the later prepare_for_training_mode assignment supersedes this.) | ||
| if not getattr(self, "_unsloth_train_reset_wrapped", False): | ||
| try: | ||
| from unsloth.models.rl import _unsloth_reset_stray_compile_cache |
There was a problem hiding this comment.
Export the reset helper before importing it
This import never succeeds on the plain SFT path because _unsloth_reset_stray_compile_cache is only defined inside the RLTrainer_replacement source string used to generate patched TRL trainers, not as a module-level symbol in unsloth.models.rl. Since the ImportError is swallowed here, SFT trainers keep the poisoned Dynamo cache after a grad-enabled pre-train probe and the detector hook also stays installed; the same broken import is injected into the bare Trainer loop in llama.py, so those non-generated paths do not get the reset this commit intends to add.
Useful? React with 👍 / 👎.
…lper The reset was only defined inside the RLTrainer_replacement template string, so 'from unsloth.models.rl import _unsloth_reset_stray_compile_cache' raised ImportError (swallowed) on the SFT auto-packing wrapper and the injected plain-Trainer loop - both paths kept the poisoned Dynamo cache and the dangling detector hook. Move the canonical implementation to unsloth.models._utils (next to the detector, exported in __all__). The RL trainer template now imports it (no-op fallback if the import ever fails), and trainer.py / llama.py import it from _utils too, so every training entry point actually runs the reset.
|
Sharp catch, and correct - this made the previous two commits no-ops on the non-generated paths. Fixed in bc134a7 by relocating the canonical implementation to |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@codex review |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Addressed both findings from the latest review. P2 (_utils.py, preserve seen on reinstall): P2 (llama.py, plain Trainer path): the reset is now injected at the start of the generated Root cause behind the second finding: Added @codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
* Add regression tests for the stray-forward compile-cache reset Follow-up to #6511, which fixed the bug but whose squash merge did not include the tests. These cover the two issues that fix addressed, under the GPU-free tests/conftest.py harness: - _unsloth_reset_stray_compile_cache is an exported module-level symbol in unsloth.models._utils (it previously lived only inside the RL trainer template string, so every non-RL import silently no-op'd) - _unsloth_install_pretrain_detector keeps a recorded "seen" forward on an idempotent reinstall with a live hook, and only resets it after teardown - only a grad-enabled pre-train forward marks the cache poisoned - the reset warns and clears seen when a stray forward was seen, tears the hook down even on the clean path, and walks the .model/.base_model/.module wrapper chain to reach a nested marker * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Pin UNSLOTH_COMPILE_DISABLE in the warn-path reset tests The reset only warns and resets Dynamo when UNSLOTH_COMPILE_DISABLE != "1". A GPU-free CI env that sets it to "1" would make the warn assertion in test_reset_clears_seen_and_warns_when_a_stray_forward_was_seen flaky. monkeypatch it to "0" in both warn-path tests so the warn / no-warn assertions are deterministic and test the seen flag, not the env. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
A manual forward / forward+backward run under
model.train()BEFOREtrainer.train()(for example a pre-train grad-norm probe likeout = model(**batch); out.loss.backward()) silently poisons training when torch.compile is enabled.Symptom
Loss stays flat and
grad_normisNaN/Inffrom the first step, so the model never learns even though the run completes normally.Observed on
unsloth/gpt-oss-20b-BF16: loss frozen at ~4.25 withgrad_normNaNfrom step 1, with bothuse_gradient_checkpointing="unsloth"and=True.Root cause
The stray training-mode pass is the first one in the process, so torch.compile /
torch._dynamocompiles and caches the model forward and, via AOTAutograd, its backward graph for the first time, in a one-off context that does not match the real training loop. Whentrainer.train()reuses that cached compiled graph the gradients come outNaN/Inf.Evidence that pins it to the compile cache (single B200, transformers 4.57.6, TRL 0.25.1, torch 2.9.1):
UNSLOTH_COMPILE_DISABLE=1torch._dynamo.reset()before trainSo a single
torch._dynamo.reset()before training fully cures it; resetting tensors, grads, or the gradient-checkpointing buffers does not.Fix
get_peft_modelattaches a one-shot forward pre-hook that records whether a forward ran beforetrain()(model agnostic, works for"unsloth"andTruegradient checkpointing).prepare_for_training_modechecks it at the start oftrain(). If a pre-train forward was seen and torch.compile is enabled, it callstorch._dynamo.reset()(plus a pristine gradient-checkpoint reset andzero_grad) and warns once, then removes the detection hook.On the normal path (no pre-train forward) it is a strict no-op: no dynamo reset, no recompilation, and the loss curve is byte-identical to before. Verified that
probe + fixreproduces the clean curve exactly and that a clean run with the fix installed is unchanged and emits no warning.Compatibility
prepare_for_training_modeandget_peft_model, no transformers/TRL internals touched.torch._dynamo.reset()is already used in unsloth_zoo (cross_entropy_loss.py) and is a no-op when nothing was compiled, so it is safe on eager / MLX / Mac and on NVIDIA / AMD / Intel backends.UNSLOTH_COMPILE_DISABLE=1, where the bug cannot occur.