Skip to content

Restore process-global torch.compile config on torch 2.12 so gradient checkpointing backward honors it - #7019

Merged
danielhanchen merged 5 commits into
mainfrom
fix/torch212-dynamo-config-thread-visibility
Jul 9, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix/torch212-dynamo-config-thread-visibility

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

On torch 2.12, gpt-oss fine-tuning with gradient checkpointing (both GRPO and SFT) crashes at the first training step's backward:

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

Root cause

torch 2.12 changed torch/utils/_config_module.py to store config user overrides in per-thread ContextVars (its docstring now reads "User overrides are thread-local"); torch 2.11 and earlier stored them process-globally. Unsloth raises the dynamo recompile limit on the main thread (config.recompile_limit = 1024 in unsloth_zoo/patching_utils.py, and 256 in the gpt-oss patches). The autograd engine runs backward() on its own worker threads, and Unsloth's gradient checkpointing recomputes the @torch.compile(fullgraph=True) gpt-oss kernels there.

On torch 2.12 those worker threads never see the main-thread override, so they read the built-in default recompile_limit = 8. The compile cache is shared per code object and already holds more than 8 entries (accumulated legitimately under the visible 1024 limit on the main thread), so the first guard miss inside backward hits the limit, and because the kernel is fullgraph=True torch raises the hard FailOnRecompileLimitHit instead of falling back to eager.

Minimal reproduction of the thread split:

import threading, torch
torch._dynamo.config.recompile_limit = 1024
seen = {}
threading.Thread(target=lambda: seen.setdefault("v", torch._dynamo.config.recompile_limit)).start()
# torch 2.11: worker thread reads 1024   torch 2.12: worker thread reads 8

This explains why setting the limit higher (early or late, up to 1000000) never changed the reported "8" (all set on the main thread), why torch._dynamo.reset() did not help (the recompiles are real, not stale), and why torch 2.11 runs the same job fine.

Fix

fix_dynamo_config_thread_visibility() in import_fixes.py mirrors direct torch._dynamo.config / torch._inductor.config assignments into the config entry's process-global default, restoring the torch 2.11 cross-thread semantics. The scoped config.patch(...) API writes ContextVars directly (not through __setattr__), so its intended context-local behavior, including dynamo's own per-context recompile override, is left untouched.

It is gated to torch 2.12 and up with a structural check that user_override is actually a ContextVar, so it is an exact no-op on torch 2.11 and on any torch without this internal layout. It is idempotent and runs from _gpu_init.py before the compile patches raise the limits.

Results (gpt-oss-20b, bnb-4bit, compiled)

before after
GRPO train FailOnRecompileLimitHit at step 0 runs
SFT train FailOnRecompileLimitHit at step 0 runs
SFT steady-state step (crashed) 2.15 s

The fix is also a speedup rather than a cost. The same thread split silently forced non-fullgraph backward frames into eager (RUN_ONLY) fallback on the worker threads, so restoring the visible limit keeps them compiled: SFT steady-state is 2.15 s/step here, matching torch 2.11 (2.29 s/step), versus 3.41 s/step when the crash was only worked around with a cache reset.

Compatibility

Pure Python, touches only torch.utils._config_module semantics: no CUDA/HIP/XPU/MPS paths, no transformers / TRL / vllm imports, so it is independent of their versions (transformers 4.57.x through 5.x, TRL 0.22.x through 1.x, vllm 0.11.2 and up). No-op on torch 2.11 and earlier. Linux, Mac, Windows, WSL.

Supersedes #7004: that PR added a compile-cache reset to avoid this crash on the SFT path only, but the reset does not help GRPO (the rollout recompiles inside the loop). This fixes the shared root cause for both, so #7004 can be closed.

… threads honor them

torch 2.12 stores config user overrides in ContextVars, so direct
assignments like torch._dynamo.config.recompile_limit = 1024 no longer
reach the autograd engine worker threads. Gradient checkpointing
recomputes fullgraph-compiled gpt-oss kernels inside backward on those
threads, which then read the default recompile limit of 8 and raise
FailOnRecompileLimitHit at step 0 of GRPO/SFT. Mirror direct config
assignments into the process-global entry defaults on torch >= 2.12,
restoring the torch <= 2.11 cross-thread semantics while leaving the
context-scoped config.patch API untouched.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@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: 987bc1f42c

ℹ️ 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/import_fixes.py
Comment on lines +1109 to +1110
if entry is not None and entry.alias is None:
entry.default = value

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 torch config patch thread-local semantics

On torch versions with the ContextVar-backed config layout this patch intercepts every ConfigModule.__setattr__, but torch._dynamo.config.patch(...) / torch._inductor.config.patch(...) also enter and exit by calling __setattr__. As a result, any temporary config patch in one thread now writes its temporary value into entry.default, making it visible to other threads for the duration of the context and turning the restore path into another global default write. That contradicts the intended scoped behavior and can change unrelated compilations whenever code uses torch's config patch context managers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, fixed in 0790b44. config.patch does assign through setattr, so a per-thread depth counter now marks patch enter/exit and the mirror skips those writes, keeping config.patch context-local while direct assignments still restore the cross-thread default.

config.patch(...) also assigns through ConfigModule.__setattr__, so the
default-mirror was leaking its scoped, thread-local writes into the
process-global entry default. Track patch enter/exit with a per-thread
depth counter (wrapping ConfigModule.patch) and skip mirroring while
inside a patch, so only genuine direct assignments restore the torch
2.11 cross-thread semantics and config.patch stays context-local.
@danielhanchen
danielhanchen force-pushed the fix/torch212-dynamo-config-thread-visibility branch from 20eb26f to 0790b44 Compare July 9, 2026 07:06
@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: 0790b441c9

ℹ️ 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/import_fixes.py
try:
entry = self.__dict__["_config"].get(name, None)
if entry is not None and entry.alias is None:
entry.default = value

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 Avoid leaking load_config replays into defaults

PyTorch's ConfigModule.load_config() restores saved Dynamo/Inductor configs by calling setattr for each key, so after this wrapper is installed any torch._dynamo.config.load_config(...) or torch._inductor.config.load_config(...) will hit this line and rewrite entry.default process-wide. In processes that load a per-run/minifier/compile config after importing Unsloth, those values can leak to other threads and subsequent compiles as stale defaults, instead of remaining in the current ContextVar context. Please exempt load_config the same way config.patch is exempted, or mirror only true top-level assignments.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d5bf421. load_config restores via setattr per key, so it now runs under the same per-thread depth counter as config.patch (renamed _scoped_depth) and the mirror skips it; only true top-level assignments restore the cross-thread default. Verified on torch 2.12.1: after load_config({recompile_limit: 7}) a worker thread still reads the mirrored default 1024 while the calling thread reads 7.

load_config restores a saved dynamo/inductor config by calling setattr
per key, which the default-mirror would otherwise leak process-wide just
like config.patch did. Wrap load_config with the same per-thread depth
counter (renamed to _scoped_depth) so both scoped writers skip the mirror
and stay context-local, while genuine direct assignments still restore the
torch 2.11 cross-thread default.
@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: d5bf421aba

ℹ️ 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/import_fixes.py Outdated
if Version(torch.__version__) < Version("2.12.0"):
return
import torch._dynamo.config as _dynamo_config
import torch._inductor.config as _inductor_config

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 Avoid importing Inductor config before compile env is set

In the normal import path this runs from _gpu_init.py before unsloth/models/_utils.py calls patch_torch_compile(), but importing torch._inductor.config here installs Inductor's config module and evaluates its environment-derived defaults immediately. patch_torch_compile() later only sets env vars such as TORCHINDUCTOR_AUTOTUNE_REMOTE_CACHE, so when this eager import has already happened those settings are ignored and Unsloth silently loses the compile/autotune cache behavior it previously enabled; avoid importing _inductor.config until after those env vars are set, or mirror the intended values directly into the config.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Checked end-to-end and this is not introduced by this change. On base main without this PR, torch._inductor.config.autotune_remote_cache is already None after import unsloth even with TORCHINDUCTOR_AUTOTUNE_REMOTE_CACHE=1, because unsloth's existing import chain loads the dynamo/inductor config modules before patch_torch_compile runs; with this PR the value is identical (None). The probe here only needs torch._dynamo.config, and importing torch._dynamo.config itself transitively imports torch._inductor.config, so the import timing is the same with or without this line. fx_graph_cache, the local cache that matters, uses env_name_force and is read lazily, so it stays True regardless of import order.

Comment thread unsloth/import_fixes.py
Comment on lines +1180 to +1181
if entry is not None and entry.alias is None:
entry.default = value

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 Invalidate config caches across contexts

When a config value is mirrored by mutating entry.default, only the thread/context that ran original_setattr() has its torch config hash and _get_dict caches marked dirty; other worker threads that already read the config can keep their ContextVar-backed cached dict/hash even though their fallback default has changed. On torch versions with the ContextVar config layout this can make later Dynamo/Inductor config changes from the main thread appear in plain attribute reads but still use stale compile cache keys or serialized config in autograd worker threads, so the cross-thread override is incomplete unless those per-context caches are invalidated or the override is represented in a way ConfigModule itself dirties for every context.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

_is_dirty and _hash_digest are bypass keys (ConfigModule._bypass_keys), so they are plain process-global attributes, not ContextVars; get_hash recomputes whenever the global _is_dirty is True. The mirror calls original_setattr first, which sets _is_dirty = True globally, and _get_dict is rebuilt fresh on each call (no per-context cache), reading entry.default when a thread has no user_override. Verified on torch 2.12.1: after a worker computes get_hash (clearing the global dirty flag), a main-thread mirror flips _is_dirty back to True and a subsequent worker-thread get_hash reflects the new value, so there is no per-context hash or dict cache left stale for the mirrored default.

@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: d5bf421aba

ℹ️ 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/import_fixes.py Outdated
Comment on lines +1195 to +1197
current = entry.user_override.get()
if current is not _UNSET_SENTINEL:
entry.default = current

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 Avoid replaying scoped overrides as global defaults

When Unsloth is imported while a torch._dynamo.config.patch(...) or _inductor.config.patch(...) context is already active, this replay treats the patch's thread-local override as a prior direct assignment and writes it into entry.default. After the with block exits, the main thread restores the old value but autograd/compiler worker threads still see the temporary patched value as the new global default, so a scoped import-time override can leak into later training. The new wrappers only suppress patch writes created after this function runs; they do not protect already-active patch contexts.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in db9f78e by removing the replay. It was redundant: this installs from _gpu_init before unsloth sets any dynamo/inductor config, so the setattr wrapper mirrors every later assignment (patch_torch_compile's recompile_limit included), and dropping it removes the transient bake you flagged plus the now-unused _inductor.config import. Verified on torch 2.12.1: cross-thread recompile_limit visibility still holds via the wrapper, an active config.patch during import no longer changes the default even transiently, and the gpt-oss GRPO smoke still runs (RAN_OK, dynamo_reset_count=0).

The replay was redundant: this runs from _gpu_init before unsloth sets any
dynamo/inductor config, so the __setattr__ wrapper already mirrors every
later assignment (recompile_limit included). It could also read a value
that belonged to a config.patch context still active at import time and
write that thread-local override into the global default. Removing it keeps
the cross-thread fix and drops the now-unused _inductor.config import.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: db9f78efa7

ℹ️ 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 0d4bd50 into main Jul 9, 2026
52 checks passed
@danielhanchen
danielhanchen deleted the fix/torch212-dynamo-config-thread-visibility branch July 9, 2026 09:26
cmxela added a commit to thinkube/thinkube-notebooks-examples that referenced this pull request Aug 27, 2026
…tion note

Unsloth compiles the model's hot paths with torch.compile, and this notebook
was switching that off and carrying a monkey-patch to survive the consequences.
Both were working around an Unsloth older than the PyTorch it ran against:
under torch 2.12 the dynamo config became thread-local, so the recompile limit
raised on the main thread never reached the autograd backward threads, which
hard-failed at step 0. Fixed upstream in unslothai/unsloth#7019.

- Drop UNSLOTH_COMPILE_DISABLE, so compilation runs.
- Delete the log-softmax shim in section 9; the path it patched works.
- Section 1 now explains that flags are read at import time, and that changing
  one also requires deleting unsloth_compiled_cache/ or it silently does
  nothing.
- Section 9 explains how to read a step-0 FailOnRecompileLimitHit that ignores
  recompile_limit: it means Unsloth is older than its PyTorch.

Section 3 claimed FlashAttention-2's wheel was broken on aarch64. It is not:
the kernel returns correct results on this GPU when called directly. FA2 fails
only in combination with compilation, and the note now says exactly that,
including what the observation does not establish and which combinations
remain unmeasured.

Also: warmup_ratio is deprecated in TRL v5.2, so use warmup_steps; and the
puzzle generator reprinted its progress line on every failed attempt at a
multiple of 200.

Verified by running the real training path end to end - mirrored model load,
2000-puzzle dataset, solver-graded reward, compilation on, no workarounds -
for two GRPO steps: rewards 0.1681 then 0.3122, gradients flowing.

Outputs cleared; they belong to that two-step run, not to a full one.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant