Repository navigation
Settle deferred compile-mode switches between training steps - #7955
Conversation
torchao is an optional dependency that unsloth never pins tightly, so the
version a notebook resolves is whatever the index serves that day. Several
recent torchao releases broke `import unsloth` outright, each in a different
place. This collects the fixes.
1. An old torchao aborts LoRA creation that never uses it.
`peft.import_utils.is_torchao_available` returns False when torchao is
absent, but raises when it is installed and older than peft's minimum:
ImportError: Found an incompatible version of torchao. Found version
0.10.0, but only versions above 0.16.0 are supported
peft calls it from `dispatch_torchao` for every LoRA layer, so one stale
optional dependency ends `get_peft_model` for a model that has nothing to
do with torchao. Kaggle ships torchao 0.10.0 preinstalled, so the
difference between pass and fail was one `pip install` line in a notebook.
`fix_peft_stale_torchao_import_error` answers False and warns once, naming
the upgrade. Only the version complaint is caught; any other ImportError
still propagates. Both binding sites are patched, since
`from peft.import_utils import is_torchao_available` copies the original
into peft.tuners.lora.torchao, the actual caller.
2. torchao 0.18 imports torch symbols that torch below 2.10 does not have.
0.17 guarded the import behind `torch_version_at_least("2.10.0")`; 0.18.0
left it at module level:
ImportError: cannot import name 'ScalingType' from 'torch.nn.functional'
It surfaces while importing transformers, so it reaches the user as a bare
Exception naming neither torchao nor torch, and kills `import unsloth`.
`fix_torchao_torch_symbol_skew` supplies placeholders that import cleanly
and refuse to be used: 0.17 simply left these names undefined on old torch,
so anything wanting them already raised, and a stub impersonating a real
enum could hand a float8 path a meaningless value. The symbol list comes
from the whole installed package, not one file:
grep -rh "from torch.nn.functional import" torchao/
which is how scaled_grouped_mm got in. Reading only mx_formats/mx_tensor.py
gives ScalingType and SwizzleType and misses the one on the path of a plain
`import torchao`. scaled_dot_product_attention exists on every supported
torch, and the loop skips anything torch already provides.
3. torchao 0.18 also wants an aten op that torch below 2.8 does not have.
It registers a float8 handler at module scope with
`@implements([aten._grouped_mm.default])`, and the attribute lookup raises
before the decorator is applied. Sibling of the symbol skew but a different
lookup: that one goes through torch.nn.functional, this one through
torch.ops, so supplying the functional names does nothing for it. The
schema is registered and nothing else, as a FRAGMENT into aten, and calling
it raises: torchao only wants somewhere to hang a handler this torch will
never dispatch to, and a plausible-looking grouped matmul would be worse
than the crash it replaces.
4. The in-process fix does not reach vLLM. vLLM inspects model architectures
in a separate process which imports torchao itself, so with
fast_inference = True the run still died, and the user saw only
"Model architectures ['...'] failed to be inspected".
`propagate_torchao_fix_to_subprocesses` stages a sitecustomize on
PYTHONPATH, which children inherit. It chains to any other sitecustomize on
sys.path rather than shadowing it, guarded so a broken one elsewhere cannot
become a startup crash for every subprocess. The logic is inlined rather
than importing unsloth, which would pay the full import cost at the start of
every subprocess on the machine and could recurse. Writes via os.replace so
a concurrent run cannot expose a truncated file, and uses os.pathsep for
Windows.
5. torchao 0.18.0 moved torchao/dtypes/nf4tensor.py to
torchao/quantization/quantize_/workflows/nf4/nf4_tensor.py. torchtune still
imports the old path and xcodec2 imports torchtune, so TTS work died with
ModuleNotFoundError one cell after a green install. `fix_torchao_nf4tensor_move`
appends a meta path finder after the real finders, so an older torchao that
still ships the module always wins, and the loader returns the relocated
module itself rather than a hand-copied stub, so it cannot rot as symbols
are added. Resolution is lazy, so `import unsloth` does not pay for a
torchao import nobody asked for.
Every fix is gated on torchao being installed, the version actually having the
bug, and the torch symbol genuinely being absent. On a healthy pair none of
them do anything, so nothing is masked. The symbol fix is also called from the
MLX branch of __init__.py, which never reaches _gpu_init.
Tests: 84 across five files. They build real package trees and import them in
subprocesses rather than stubbing sys.modules, since appended-versus-inserted
finders and PYTHONPATH inheritance only mean anything to the real import
machinery. 82 pass here; 2 skip because this machine has torchao installed and
a torch that already provides the symbols.
_gpu_init.py calls fix_torchao_torch_symbol_skew() immediately before
propagate_torchao_fix_to_subprocesses(). The first adds a placeholder to
torch.nn.functional for every symbol torch is missing and registers the
aten::_grouped_mm schema; the second then asked hasattr(F, n) and
_torch_op_is_missing("aten", "_grouped_mm") and read both as healthy. So it
returned before staging anything, in exactly the environments it exists for.
Measured on torch 2.9.1: the fix places all three symbols, propagate returns
None, nothing is written and PYTHONPATH is untouched. vLLM's architecture
inspector child therefore still died with the original ImportError, which is
the whole reason for that half of the change.
The gate now asks whether TORCH provides the symbol rather than whether one is
merely present, using the __unsloth_placeholder__ marker the placeholder
already carries, and treats a registered _aten_grouped_mm_library as proof the
op was missing. Reordering the two calls in _gpu_init.py would also work today
but leaves the same landmine for the next reorder.
The decisive symbol test never ran. Its skip predicate was any(hasattr(F, n)
for n in _TORCHAO_TORCH_SYMBOLS), and that tuple contains
scaled_dot_product_attention, which the test above it asserts exists on every
supported torch, so it was unconditionally true. It skipped on every machine,
including this one, which is genuinely missing ScalingType and SwizzleType. Now
gated on the two symbols the reproduced import line actually names, and it
passes.
The nf4 alias is installed on the MLX path too. _gpu_init.py was its only
caller and the _IS_MLX branch never reaches it, so an Apple Silicon user whose
audio work reaches xcodec2 and torchtune still hit the ModuleNotFoundError this
fix exists for. It sits next to the symbol fix already called there.
The alias loader no longer corrupts the relocated module's specification.
create_module returns the real module, and module_from_spec then overwrites its
__spec__ with the old-name one, because importlib/_bootstrap.py assigns
__spec__ unconditionally while guarding every other attribute. find_spec for
the new name reported the old one, and reload ran the alias loader's no-op
exec_module instead of the file. exec_module now restores it.
Tests: 90 pass, 1 skip, over the five torchao files. 4 new, each failing
without its fix.
unsloth is Apache-2.0 (LICENSE, and pyproject license = "Apache-2.0"), and 303 of its 314 test files carry no header at all while 10 carry the Apache one. The new files here went in with an AGPL-3.0 notice attributed to Unsloth Zoo, which is the wrong licence, the wrong project and against the convention here.
CI now installs torchao 0.18.0, which broke two premises. test_the_real_environment_is_left_alone decided "this machine has the old layout" from find_spec, but by then the session had imported unsloth and the alias answers that query, so a new-layout runner looked like an old-layout one and the assert fired. Ask the filesystem instead, in a child, like every other case in that file. test_it_does_nothing_when_torchao_is_absent shadowed torch on PYTHONPATH but could not un-install torchao, and importlib.metadata is what the hook reads, so the runner's real torchao made "absent" false. Run that child in a venv without system packages.
…wn placeholders
The rebuild dropped empty components. An empty component is an import
location, not padding: it is what PYTHONPATH="$PYTHONPATH:/opt/lib" leaves
behind when PYTHONPATH was unset, and CPython reads it as the cwd (3.11+
absolutises every component in Modules/getpath.py and abspath("") is the cwd;
3.10 puts the literal "" on sys.path and site.removeduppaths() absolutises
it). Dropping them took an import location away from every descendant. The
opposite case still has to be handled: a set-but-empty PYTHONPATH is ignored
by CPython, so splitting it would ADD the cwd. Hence the 'if current' guard
rather than dropping the filter outright.
Two test probes had the mirror-image bug. conftest.py imports unsloth, so on
the environment these fixes exist for the placeholders are already on
torch.nn.functional before any test runs, and a plain hasattr reads that as a
healthy torch. Use _torch_really_has, and drop the placeholders first in the
two tests that need to observe the 'before' state.
pre-commit.ci's ruff-format-with-kwargs hook reported "files were modified by
this hook" and could not push the result back, so the check stayed red.
Applied locally instead.
Three source-asserting tests had to be made robust rather than re-pinned,
since the reformatting is legitimate and will happen again:
- test_the_flag_is_recorded_beside_the_dtype counted the literal
"self._autocast_enabled = (", which the formatter collapsed onto one line.
Now pairs each _autocast_dtype initialiser with a nearby flag assignment by
position, so it still catches a genuinely missing one.
- test_the_original_error_is_still_reported anchored on a whole f-string
literal, which the formatter merged with the hint that follows it. Anchors
on the message text alone now; either shape satisfies the intent.
- test_the_source_beats_the_version_fallback exposed a real fragility rather
than a test problem: the detector matched the literal "kw_only=True", so any
whitespace in transformers' own source would have read an install that needs
nothing as one that needs patching. Made whitespace-tolerant.
The generated hook probed each sys.path entry for a sitecustomize.py file, so an existing sitecustomize installed as a package or shipped as a bare .pyc was skipped in every child process. Use PathFinder.find_spec instead, which is what CPython itself would have done.
…r/torchao-import-survival
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ff5ea7fb18
ℹ️ 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".
| # Only the version complaint. A torchao that fails to import for | ||
| # any other reason is a real problem and must still surface. | ||
| message = str(exc) | ||
| if "torchao" not in message.lower(): |
There was a problem hiding this comment.
Narrow stale torchao suppression to version errors
This check suppresses every ImportError whose text mentions torchao, although the comment says only the stale-version complaint should be swallowed. In an environment where torchao is installed but broken for another reason, such as No module named 'torchao.quantization' or a missing libtorchao...so, is_torchao_available() now returns False and PEFT continues without surfacing the broken optional dependency. Please match the incompatible-version/min-version message before converting the error to False.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 53917f1. "torchao" not in message also swallowed No module named 'torchao.quantization' and libtorchao_ops_cuda.so: cannot open shared object file, both of which say torchao and neither of which is a version complaint. Pre-fix probe: stale version -> False (ok), broken submodule -> False (should raise), broken .so -> False (should raise). Now matched with _TORCHAO_STALE_VERSION_ERROR, which covers peft's "incompatible version of torchao" plus two rewordings so an upstream edit does not silently turn suppression back into a raise. tests/test_peft_stale_torchao.py gains 4 broken-install cases (fail pre-fix, pass post-fix) and 3 version-complaint spellings.
| info = os.lstat(directory) | ||
| if stat.S_ISLNK(info.st_mode) or info.st_uid != os.getuid(): |
There was a problem hiding this comment.
Validate existing subprocess fix directory permissions
When this directory already exists on POSIX, os.makedirs(..., exist_ok=True) does not tighten its permissions, and the validation only rejects symlinks or wrong owners. If /tmp/unsloth_subprocess_import_fix-$UID was left group/world-writable, another local user can replace the sitecustomize.py that gets prepended to PYTHONPATH, so every Python subprocess after import unsloth executes their code. Please also reject or chmod directories with group/other write bits before staging the hook.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 53917f1. Probe against pre-fix source, pre-creating the directory at each mode: 0777 -> returned, final mode 0777; 0770 -> 0770; 0707 -> 0707. exist_ok = True never re-applies mode, and the owner check passes because the directory is ours, so a loose one stays writable while holding the sitecustomize on PYTHONPATH. Now chmod back to 0700, re-lstat, and raise if the write bits do not come off (some network and FUSE mounts accept chmod and change nothing). propagate_... already wraps this in try/except, so a refusal degrades to no subprocess fix. Two new tests in tests/test_torchao_subprocess_fix.py fail pre-fix (assert not (511 & 18)) and pass post-fix.
| all(_torch_really_has(F, n) for n in _TORCHAO_TORCH_SYMBOLS) | ||
| and _aten_grouped_mm_library is None | ||
| and not _torch_op_is_missing("aten", "_grouped_mm") | ||
| ): | ||
| return None # this torch is new enough; nothing to do |
There was a problem hiding this comment.
Propagate the NF4 alias to child interpreters
When torchao 0.18 is paired with a torch that already satisfies these symbol checks, this returns without staging any sitecustomize, but fix_torchao_nf4tensor_move() only appends a sys.meta_path alias in the parent process. Any child interpreter that imports torchtune/xcodec2 still starts with a fresh import system and raises ModuleNotFoundError for torchao.dtypes.nf4tensor; even when the symbol-skew hook is staged, the generated hook does not include the NF4 alias. Please stage the NF4 alias independently of this symbol-skew gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining the ask. The premise is right (the alias is parent-only and is not in the generated hook) but staging it independently of the symbol-skew gate is wrong. That gate is what keeps this narrow: it writes nothing and leaves PYTHONPATH alone on a healthy pair. Staging on torchao >= 0.18 alone would put a directory whose sitecustomize.py runs in every subprocess on the machine into environments where nothing is broken, to fix an import that nothing there performs. The alias exists for torchtune, and xcodec2 via torchtune; both are imported in this process, and the vLLM model-architecture inspector this hook was built for imports neither. If a child that does import torchtune ever turns up, the alias should be inlined into the hook then, alongside the symbol fix.
You did catch a stale claim in propagate_torchao_fix_to_subprocesses: it said fix_peft_stale_torchao_import_error is "the only other torchao one", which stopped being true the moment fix_torchao_nf4tensor_move landed in the same commit. Corrected in 53917f1 to name both and to record why neither needs a child.
|
Live result from a Kaggle T4: this pair does not fix The fix installed and ran. The deferral message is in the artifact: So the budget bump worked, the call finished compiled, and the eager switch was deferred exactly as designed. The notebook still died in the same place: Most likely gap: bumping A mid-step compile-mode flip is still a real hazard and this change may well be worth having on its own terms, but it should not be described as fixing that notebook. Keeping the row as a regression until the remaining window is closed. |
…ode for PR unslothai#7955 Match peft's stale-version complaint instead of the word "torchao", so a half-installed torchao ("No module named 'torchao.quantization'") or an unloadable extension still surfaces rather than being reported as absent. Tighten an already-existing subprocess fix directory: os.makedirs(exist_ok) leaves a group- or world-writable directory alone, and that directory holds the sitecustomize on PYTHONPATH. chmod it back to 0700, re-read, and refuse it if the bits do not come off.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 53917f1fda
ℹ️ 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".
| import torch | ||
| import torch.nn.functional as F |
There was a problem hiding this comment.
Avoid importing torch in every Python child
When torchao >= 0.18 is paired with a torch missing these symbols, this directory is prepended to the process-wide PYTHONPATH, so this sitecustomize runs for every subsequently launched Python descendant. _apply() then imports torch during interpreter startup even when that child never uses torch or torchao, adding torch's substantial startup and memory cost to unrelated Python utilities and worker processes. Please defer this work until a child actually imports torchao, for example with an import hook, rather than eagerly importing torch from sitecustomize.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and measured. With the generated sitecustomize and torchao 0.18 metadata on PYTHONPATH, python3 -c 'import sys; print("torch" in sys.modules)' printed True and took 1.284s wall (8.1s CPU) against 0.011s without it, in a child that never touches torchao. Fixed in fa67e9c: sitecustomize now installs a small meta_path finder that fires on the torchao import and applies the fix there, which is still before torchao's module body, so the propagation still works. Same child is now 0.017s with torch unimported. tests/test_torchao_subprocess_fix.py::test_it_does_not_import_torch_until_torchao_is asserts both halves and fails pre-fix.
… PR unslothai#7955 The generated sitecustomize goes on PYTHONPATH, so it runs in every Python descendant, and it called _apply() eagerly: with torchao 0.18 installed that imported torch during interpreter startup even in children that never touch torchao (0.011s to 1.284s for python -c pass here). Defer it behind a meta_path finder that fires on the torchao import, which is still before torchao's module body.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fa67e9cb79
ℹ️ 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".
| existing = open(target, "r", encoding = "utf-8").read() | ||
| except Exception: | ||
| existing = None | ||
| if existing != source: |
There was a problem hiding this comment.
Replace untrusted pre-existing hook files
When this directory was previously group/world-writable, another user could have planted sitecustomize.py as an attacker-owned file or symlink whose initial contents exactly match source. Tightening the directory permissions does not revoke write access to that file or its symlink target, and this equality check then skips os.replace, allowing the attacker to change the hook after it has been added to PYTHONPATH and execute code in later Python subprocesses. Reject non-regular or foreign-owned targets, or atomically replace the target regardless of matching contents after securing a previously existing directory.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 1315dc4. Repro: directory left 0777 with a sitecustomize.py symlink to a file outside it whose contents match ours. After propagate_torchao_fix_to_subprocesses() the directory was tightened to 0700 but target is symlink: True, so rewriting the link target ran ATTACKER CODE RAN IN THIS CHILD in a child started with that PYTHONPATH. New _existing_hook_is_trustworthy() only lets the contents-match fast path apply to a regular file owned by us with no group/world write bit; anything else is replaced atomically, and the file we write is chmod 0600. Post-fix the same repro reports target is symlink: False and empty child stdout. Tests: test_a_planted_hook_is_not_trusted[symlink|group_writable], test_a_foreign_owned_hook_is_not_trusted, test_our_own_hook_file_is_trusted, test_a_planted_hook_is_replaced_even_when_it_matches[symlink|group_writable] - all fail on the parent commit, pass now (43 passed in test_torchao_subprocess_fix.py).
| if previous is None: | ||
| sys.modules.pop("sitecustomize", None) | ||
| else: | ||
| sys.modules["sitecustomize"] = previous |
There was a problem hiding this comment.
Leave the chained sitecustomize package importable
When the existing customization is a sitecustomize package, restoring the Unsloth module under this name after executing the package means later import sitecustomize returns the generated hook rather than the installed package. This also breaks callbacks in that package which perform delayed relative imports, because their sitecustomize parent in sys.modules is now a non-package without the original __path__. Preserve the chained module under its canonical name after initialization rather than restoring the shadowing hook.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 1315dc4. Repro with a package-form chained sitecustomize that registers an atexit callback doing from . import extra: pre-fix the child printed IMPORT sitecustomize -> <<our hook, no NAME>>, HAS __path__ -> False and then ImportError: cannot import name 'extra' from 'sitecustomize' at exit. The chained module is now left in sys.modules under its own name on success (which is also what import sitecustomize returns when we are not installed); the previous entry is restored only if exec_module raised, so a half-initialised one is not left behind. Our own module object is held in _SELF since the meta_path finder outlives that name. Post-fix: NAME the_real_package, PACKAGE True, LATER OK submodule. Tests: test_a_chained_package_stays_importable (fails pre-fix) and test_a_broken_chained_module_does_not_keep_our_name.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
…ed sitecustomize for PR unslothai#7955
|
@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". |
Same intent, fewer lines: collapse the multi-paragraph explanations in import_fixes.py and the new tests to their load-bearing sentences, and drop the restatements of what the code beside them already says. No code changes.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: de2eb47c1c
ℹ️ 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 not entry or os.path.normcase(os.path.abspath(entry)) == here: | ||
| continue |
There was a problem hiding this comment.
Resolve symlinks before chaining sitecustomize
When PYTHONPATH already contains a symlink alias of the generated hook directory, this abspath comparison treats the alias as a different location and PathFinder loads this same generated sitecustomize as the hook to chain. The two path spellings then recursively execute one another until RecursionError is swallowed, leaving hundreds of _TorchaoImportHook instances in sys.meta_path; a later import torchao runs the fix through every instance. Compare canonical paths (for example with realpath/samefile) or reject a discovered spec whose origin resolves to this hook.
Useful? React with 👍 / 👎.
| tmp = target + ".%d.tmp" % os.getpid() | ||
| with open(tmp, "w", encoding = "utf-8") as handle: | ||
| handle.write(source) |
There was a problem hiding this comment.
Create the temporary hook without following symlinks
When upgrading from a run that left this directory group/world-writable, another local user can pre-create the predictable sitecustomize.py.<pid>.tmp path as a symlink to a file they own and make writable. This open follows that symlink; the subsequent chmod failure is swallowed, and os.replace installs the symlink itself as sitecustomize.py, allowing the attacker to rewrite its target after the directory has been secured and execute code in later Python children. Create a randomized temporary file with exclusive/no-follow semantics inside the secured directory before replacing the target.
Useful? React with 👍 / 👎.
…te temp file Two symlink holes in the generated sitecustomize for PR unslothai#7955. A symlink alias of the hook directory also on PYTHONPATH compared unequal to the string spelling the hook was loaded from, so PathFinder handed back this same file as the sitecustomize to chain to. The two spellings executed one another until the stack ran out, and every unwound level installed another import hook: 246 of them in sys.meta_path here, each one running the fix on a later import torchao, and the real sitecustomize elsewhere on the path never ran at all. Compare canonical paths, and refuse a spec whose origin resolves to this hook. The staging file used a predictable name (sitecustomize.py.<pid>.tmp). In the upgrade case the directory tightener exists for, a directory left group- or world-writable by an older run still holds whatever was planted in it, so that name can already be a symlink to a file another user owns. The write followed it, the chmod failed silently, and os.replace installed the link itself as sitecustomize.py, leaving it theirs to rewrite after the directory was secured. Create the file with a random name under O_CREAT|O_EXCL|O_NOFOLLOW instead, and remove it if anything fails.
|
Main moved that assertion to |
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
Pairs with unslothai/unsloth-zoo#1001, and is the half that actually closes the window. Merge that one first; without it this is a no-op, guarded by a try/except import.
The failure
Gemma4_(E2B)-Vision.ipynbdies intrainer.train()on a T4:right after
torch.compile ran out of recompilation cache for Gemma4RMSNorm.forward; running it eagerly from here.Non-reentrant checkpointing packs the forward and recomputes it during the backward, then checks the two agree. A region packed compiled and recomputed eagerly does not agree, so the eager fallback turns a speed problem into a dead training step.
The change
The zoo side now keeps the call compiled and marks the patched function for a switch instead of flipping mid-call. Something has to settle that debt at a point where no checkpoint region is half-packed, and the natural one is the start of a training step.
patch_gradient_accumulation_fixwrapsTrainer.training_stepto callapply_pending_eager_fallbacks()first.The zoo has documented this contract for a while:
_fall_back_to_eager_on_recompile_limitsays the latch "leaves one mixed step ... Seeforce_eager_fallbackbelow, which unsloth uses to close it."grep -rn force_eager_fallbackover this repo returned nothing, so the consumer it describes had never been written.Guarded three ways: an install-once flag so repeated patching does not stack wrappers, a try/except around the import so an older unsloth_zoo is simply a no-op, and a try/except around the call so settling can never fail a step.
Tests
tests/test_settle_eager_fallbacks_between_steps.py, 3 tests. They skip against an unsloth_zoo without the deferred switch, and against one with it the key test fails before this change and passes after.