Skip to content

Reset torch.compile cache poisoned by a stray forward before trainer.train() - #6511

Merged
danielhanchen merged 10 commits into
mainfrom
fix/stray-forward-poisons-compiled-training
Jun 22, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
fix/stray-forward-poisons-compiled-training

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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.

Symptom

Loss stays flat and grad_norm is NaN/Inf from 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 with grad_norm NaN from step 1, with both use_gradient_checkpointing="unsloth" and =True.

Root cause

The stray training-mode pass is the first one in the process, so torch.compile / torch._dynamo compiles 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. When trainer.train() reuses that cached compiled graph the gradients come out NaN/Inf.

Evidence that pins it to the compile cache (single B200, transformers 4.57.6, TRL 0.25.1, torch 2.9.1):

run result
no probe (clean) learns, loss 4.29 -> 0.0002
probe + backward (current behaviour) dead, loss frozen ~4.25, grad_norm NaN
probe under UNSLOTH_COMPILE_DISABLE=1 learns
probe + torch._dynamo.reset() before train learns (4.29 -> 0.0002), identical to clean
probe + buffer reset / zero_grad / empty_cache / for_training (no dynamo reset) still NaN

So a single torch._dynamo.reset() before training fully cures it; resetting tensors, grads, or the gradient-checkpointing buffers does not.

Fix

  • get_peft_model attaches a one-shot forward pre-hook that records whether a forward ran before train() (model agnostic, works for "unsloth" and True gradient checkpointing).
  • prepare_for_training_mode checks it at the start of train(). If a pre-train forward was seen and torch.compile is enabled, it calls torch._dynamo.reset() (plus a pristine gradient-checkpoint reset and zero_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 + fix reproduces the clean curve exactly and that a clean run with the fix installed is unchanged and emits no warning.

Compatibility

  • transformers 4.57.x and 5.x, TRL 0.22.x through 1.x: the change lives in prepare_for_training_mode and get_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.
  • Skips entirely under UNSLOTH_COMPILE_DISABLE=1, where the bug cannot occur.

…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.

@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 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.

Comment thread unsloth/models/_utils.py Outdated
Comment on lines +205 to +213
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

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.

high

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.

Suggested change
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

Comment thread unsloth/models/rl.py Outdated
Comment on lines +405 to +433
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

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.

high

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 = None

@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: 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".

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/_utils.py Outdated
return model

def _mark(_module, _inp):
marker["seen"] = True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@danielhanchen

Copy link
Copy Markdown
Member Author

Addressed the review feedback in a follow-up commit:

  • The detector now only records a grad-enabled forward, so a no-grad sanity probe (with torch.no_grad(): model(...)) no longer triggers a dynamo reset, recompile or warning on an otherwise clean run.
  • The reset walks the model wrapper chain (PeftModel / DDP / base model) so a probe that ran on a different wrapper than self.model is still detected, and every detector hook in the chain is torn down.
  • Re-installing the detector is idempotent and only re-registers when a prior hook was already removed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/rl.py Outdated
Comment on lines +420 to +422
_nxt = getattr(_curr, "model", None)
if _nxt is None:
_nxt = getattr(_curr, "base_model", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up commit: the marker chain walk now also follows DDP/FSDP .module (in addition to .model and .base_model), so a pre-train probe that fired on the model below a DDP wrapper is still detected and its hook torn down.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/_utils.py Outdated
return model
marker = getattr(model, "_unsloth_pretrain_marker", None)
if isinstance(marker, dict):
marker["seen"] = False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/rl.py Outdated
Comment on lines +450 to +454
for _m in markers:
hook = _m.pop("hook", None)
if hook is not None:
try: hook.remove()
except Exception: pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/rl.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/rl.py
Comment on lines +453 to +455
# Drop any torch.compile graph cache poisoned by a stray pre-train forward.
try:
_unsloth_reset_stray_compile_cache(self)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment thread unsloth/models/llama.py
Comment on lines +3374 to +3376
# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

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 get_peft_model, but the reset only ran inside RL trainers via prepare_for_training_mode. I wrapped SFTTrainer.train in _patch_sft_trainer_auto_packing to call _unsloth_reset_stray_compile_cache(self) before the original train. That helper both drops the poisoned Dynamo cache and tears down every one-shot detector hook in the wrapper chain, so the SFT path no longer leaves the cache poisoned or a per-step hook installed. For UnslothSFTTrainer (compiled cache), its own later self.train = MethodType(prepare_for_training_mode(...), self) cleanly supersedes the instance wrapper, so there is no double reset.

P2 (PEFT pass-through early return). Added _unsloth_install_pretrain_detector(model) just before the Already have LoRA adapters! We shall skip this step. early return, so externally loaded / pre-wrapped PEFT models also arm the detector and an RL trainer can consume the marker. The helper is idempotent, so the existing end-of-function install is unaffected.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/_utils.py
Comment on lines +205 to +209
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread unsloth/models/llama.py
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

Both addressed in 202d731.

Preserve a seen pre-train forward when reinstalling (_utils.py). Correct - the idempotent re-install cleared marker['seen'] before the live-hook early return, so a re-entrant get_peft_model/patch_peft_model after a grad-enabled probe wiped the recorded poisoning while the hook stayed live, and train() then skipped the reset. Moved the seen = False so it only runs when registering a fresh hook (no live hook, or after teardown). A live hook now keeps whatever it recorded; _unsloth_reset_stray_compile_cache still resets seen when it consumes and tears it down.

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 transformers.Trainer flow (patched via _fast_inner_training_loop) left the cache poisoned and the hook installed. I inject _unsloth_reset_stray_compile_cache(self) as the first body statement of the generated _fast_inner_training_loop (anchored on self.accelerator.free_memory()), so it runs before the first training-step forward. It is idempotent with the TRL-wrapper reset (the wrapper clears the markers first; the loop's call then finds nothing), and degrades to a harmless no-op if upstream ever drops that anchor line. Verified the transformed loop still parses.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/trainer.py Outdated
# (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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Sharp catch, and correct - this made the previous two commits no-ops on the non-generated paths. _unsloth_reset_stray_compile_cache (and prepare_for_training_mode) only existed inside the RLTrainer_replacement template string, so from unsloth.models.rl import _unsloth_reset_stray_compile_cache raised ImportError, which both the SFT new_init wrapper and the injected _fast_inner_training_loop swallowed. Confirmed via AST: neither is a module-level symbol in rl.py.

Fixed in bc134a7 by relocating the canonical implementation to unsloth.models._utils (right next to _unsloth_install_pretrain_detector, exported in __all__). The RL trainer template now does from unsloth.models._utils import _unsloth_reset_stray_compile_cache (with a no-op fallback so a generated module can never NameError), and both trainer.py and the llama.py loop import it from _utils as well. So all three entry points - generated RL/SFT trainers, the plain SFT auto-packing path, and bare transformers.Trainer - now run the same reset and tear down the detector hook. _utils only does lazy imports inside the function, so no new import cycle.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: de6c777442

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

@danielhanchen
danielhanchen merged commit 9dbd40e into main Jun 22, 2026
42 of 50 checks passed
@danielhanchen
danielhanchen deleted the fix/stray-forward-poisons-compiled-training branch June 22, 2026 12:39
@danielhanchen

Copy link
Copy Markdown
Member Author

Addressed both findings from the latest review.

P2 (_utils.py, preserve seen on reinstall): _unsloth_install_pretrain_detector no longer clears marker["seen"] before the live-hook early return. A re-entrant get_peft_model/patch_peft_model after a grad-enabled probe now keeps the recorded poisoning; seen is only reset when registering a fresh hook or after teardown.

P2 (llama.py, plain Trainer path): the reset is now injected at the start of the generated _fast_inner_training_loop (anchored on self.accelerator.free_memory()), so a bare transformers.Trainer.train() also drops a poisoned compile cache and tears down the detector hook. It is idempotent with the TRL SFT/RL wrapper reset.

Root cause behind the second finding: _unsloth_reset_stray_compile_cache only existed inside the RLTrainer_replacement template string, so from unsloth.models.rl import _unsloth_reset_stray_compile_cache raised ImportError and every non-RL consumer silently no-op'd. The canonical implementation now lives in unsloth.models._utils (next to the detector, exported in __all__); the RL template imports it with a no-op fallback, and trainer.py / llama.py import it from _utils too.

Added tests/test_pretrain_compile_reset.py (GPU-free, runs under tests/conftest.py): the seen-evidence guard on reinstall, grad-vs-no-grad marking, the reset's warn/clear/teardown and wrapper-chain walk, and module-level importability.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9dbd40e5b3

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

danielhanchen added a commit that referenced this pull request Jun 22, 2026
* 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>
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.

2 participants