Repository navigation
Sync before re-reading a buffer stored in an Inductor reduction loop (torch < 2.14) - #15000
Conversation
|
@codex review |
1 similar comment
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b564e8e7d
ℹ️ 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 getattr(inductor_config, "post_grad_custom_post_pass", None) is None: | ||
| inductor_config.post_grad_custom_post_pass = ReadbackBarrierCacheKey() |
There was a problem hiding this comment.
Include the patch in existing custom-pass cache keys
When post_grad_custom_post_pass already contains a CustomGraphPass with a stable UUID, this branch leaves its cache key unchanged even though TritonKernel code generation has changed. An affected graph cached before upgrading Unsloth can therefore be restored without the new barrier and continue producing silently corrupted gradients. Preserve the user's pass while composing its UUID with the readback-barrier version, or disable the FX graph cache for this case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this: Unsloth must be imported before torch.compile setup, so a user pass set after the import replaces ours whatever we do here, and a user pass installed before importing Unsloth with a stable uuid and a pre-upgrade warm cache is not a setup Unsloth users run. The common path (no user pass) is keyed.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 10b5c268fd
ℹ️ 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".
| inductor_config.post_grad_custom_post_pass = ReadbackBarrierCacheKey() | ||
| except ImportError: | ||
| # torch < 2.6 keys no custom pass: skip the FX graph cache rather than reuse racy kernels. | ||
| inductor_config.fx_graph_cache = False |
There was a problem hiding this comment.
Disable the remote FX cache in the fallback
On PyTorch 2.4/2.5 when TORCHINDUCTOR_FX_GRAPH_REMOTE_CACHE=1 (or an internal default enables it), setting only fx_graph_cache = False leaves stale remote entries usable: those releases' compile_fx.py calls FxGraphCache.load when either the local or remote flag is enabled. A pre-upgrade remote entry can therefore still return a barrier-free kernel and silently corrupt results; disable fx_graph_remote_cache as well, or use force_disable_caches for this fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this: the remote FX cache is off unless TORCHINDUCTOR_FX_GRAPH_REMOTE_CACHE=1 is set and a Redis backend is configured, which is not a setup Unsloth users run, and on torch 2.4 / 2.5 only. Overriding a cache the user explicitly opted into is out of scope here.
|
Codex Review: Didn't find any major issues. Delightful! 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". |
|
Two of the
|
`studio/backend/tests/test_gguf_load_cache_reuse.py::TestLoadHubDownloadExclusion::test_load_marker_precedes_hub_guard_which_precedes_the_gpu_handoff` fails on `main`, for example in Backend CI `(Python 3.13, a-k)` on #15000 and #15001. ## Cause The test's last assertion is a literal source match: `"@_with_gguf_load_marker\n def load_model("`. #14546 added `@holds_inference` between that decorator and `def load_model`, so the string no longer appears. The load marker still wraps `LlamaCppBackend.load_model`, so the product is fine and the test was out of date. ## Fix The check now parses `llama_cpp.py`, finds `LlamaCppBackend.load_model`, and asserts that `_with_gguf_load_marker` is in its decorator list, in any position. The rest of the test, including the ordering in `routes/inference.py`, is unchanged. ## Verification - `studio/backend/tests/test_gguf_load_cache_reuse.py`: 75 passed. On `main` this test failed when run alone. - Sabotage check: removing `@_with_gguf_load_marker` from `load_model` fails the test.
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
Two tests in `studio/backend/tests/test_mlx_inference_backend.py` fail against current `unsloth_zoo` `main`, for example in the MLX CI `dispatch` job on #15000: ``` test_the_stub_answers_every_helper_zoo_imports_from_inference AssertionError: zoo imports ['fused_drafter_ops'] from mlx.inference and the stub cannot answer them test_the_stub_accepts_every_call_zoo_makes_to_an_inference_helper AttributeError: fused_drafter_ops ``` ## Cause unsloth-zoo #2031 added `from .inference import fused_drafter_ops` to `unsloth_zoo/mlx/speculative.py`. The stub module in this test answers unknown names with a neutral context manager, except for `fused_*` names. It deliberately raises `AttributeError` for those, so that a deleted fusion still reads as missing. `fused_drafter_ops` is also not a scope: it is a plain call that returns how many DFlash2 drafter modules it fused. The test is the side that needed updating. Zoo's new helper is intentional. ## Fix - New `NEUTRAL_PLAIN_HELPERS` holds `fused_drafter_ops`. Its stub returns 0, meaning nothing fused, because zoo's body needs Metal kernels. - The fixture installs it, and the call-shape test calls it as a plain function. - It is kept out of `PLAIN_HELPERS`. `test_each_plain_helper_stub_matches_zoos_body` pins each `PLAIN_HELPERS` stub to zoo's own body, and that cannot hold for this helper. An older zoo that does not import it is unaffected. ## Verification Run with zoo `main` on the path, comparing failing test IDs on base and head: - Base: the two tests above fail. - Head: both pass, and `test_each_plain_helper_stub_matches_zoos_body` still passes. - Six other tests in the file fail locally on both sides, from this host's missing `mlx_vlm`. They are green in CI.
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 ℹ️ 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". |
…m / AdamW on local shards (#15049) `Repo tests (CPU, fsdp2)` fails on `main` since #15008, for example on #14970 and #15000: ``` tests/test_fsdp2_native_optim_reentry_gloo.py::test_bnb_optimizer_cls_and_kwargs_is_refused AssertionError: (0, 'bnb.keyword', {'error': '', 'sharded': True}) ``` ## Cause #15008 made native FSDP2 keep a bitsandbytes Adam / AdamW and step each rank's local shard. `_refuse_bnb_optimizer_cls` now lets `optimizer_cls_and_kwargs = (bnb.optim.AdamW8bit, ...)` through whenever this bitsandbytes can step local shards, and refuses it otherwise (`UNSLOTH_FSDP2_BNB_LOCAL=0`). The test still expected every bitsandbytes class to be refused. The product change is intended, as the #15008 description says, so the test was out of date. ## Fix The worker now also reports `native._bnb_local_shards_available()`, and the test asserts each arm against it: - `torch.*`: accepted and sharded. - `bnb.*`: accepted and sharded when local shards are available, otherwise refused with the bitsandbytes `ValueError`. - `like.*` (`AdamW8bitLike`, a torch AdamW that only claims the bitsandbytes module): always refused, since it cannot step local shards. ## Verification The whole file gives 5 passed. Both `bnb` branches run: | `UNSLOTH_FSDP2_BNB_LOCAL` | bnb local | `bnb.*` | `like.*` | `torch.*` | |---|---|---|---|---| | 1 (default) | True | accepted, sharded | refused | accepted, sharded | | 0 | False | refused | refused | accepted, sharded | Sabotage check: making `_refuse_bnb_optimizer_cls` return early fails the test.
…already set (unslothai#15208) Follow up to unslothai#15000. ### Problem `fix_inductor_reduction_readback_race` (torch < 2.14) adds a `tl.debug_barrier()` before a reduction kernel reloads a buffer it stored in an earlier loop. So that warm FX / AOTAutograd caches do not keep serving barrier-free kernels, it sets a no-op `CustomGraphPass` whose uuid enters the cache key. That marker was only installed when `torch._inductor.config.post_grad_custom_post_pass` was `None`. If a user (or another library) had already set a `CustomGraphPass`, the key stayed that pass's uuid alone. A cache written before the fix was then still a hit, and the racy kernels came back. ### Fix `_key_inductor_caches_on_readback_barrier` now handles the existing pass: - A `CustomGraphPass` with a uuid is wrapped. The wrapper's uuid is `(barrier marker, user uuid)`, so the key changes. Calling it calls the user pass. A `CustomInferenceAwareGraphPass` is wrapped by an inference aware subclass, so `is_inference` still reaches it. - A list or tuple of passes (torch 2.13 accepts these) gets the marker pass appended. - Raw callables and passes without a uuid are left unchanged. torch already bypasses the FX cache for those. Wrapping one would make it cacheable without its identity in the key. - Re-running the fix does not wrap twice. ### Tests `tests/test_inductor_readback_barrier.py`, CPU: - `test_a_user_custom_graph_pass_keys_the_cache_on_the_barrier_too`: the wrapped uuid carries both ids, the user pass still runs, and a second run does not re-wrap. - `test_an_inference_aware_user_pass_still_gets_is_inference` - `test_a_list_of_user_passes_gets_the_marker_appended` - `test_a_raw_callable_user_pass_is_left_alone` - `test_a_warm_cache_from_before_the_fix_is_not_served_with_a_user_pass`: end to end with the Inductor CPU backend. A process without the fix warms the cache. A second process without the fix hits it, which shows the key is otherwise stable. A process with the fix misses. Results: - Before (main): 3 failed, 9 passed, 1 skipped. The warm cache test gets `fxgraph_cache_hit == 1`. - After: 12 passed, 1 skipped. The skip is the existing CUDA codegen test. ### GPU, Colab L4 Each row is a separate process. The kernel is a fused add plus layer norm reduction that reloads its stored buffer. The cache is first warmed by a process without the fix (the cache from before unslothai#15000). The rows below then run on that warm cache, each arm on its own copy of it. torch 2.13.0, user `CustomGraphPass` set before the fix: | run | barriers in the kernel | FX cache | |---|---|---| | warm, no fix | 0 | miss | | main fix on the warm cache | 0 | hit (the racy kernel is served) | | this PR on the warm cache | 1 | miss | | this PR again | 1 | hit | torch 2.13.0, no user pass (control): main and this PR both miss the warm cache and emit the barrier. torch 2.14.1 (control): the fix skips itself, and every run has the native barrier. Numerics matched eager in every run. The race itself is timing dependent, so this check covers the cache key and the kernel text, not wrong outputs. ### Not covered - A pass set after `import unsloth` replaces the marker, before and after this change.
On torch below 2.14, Inductor can generate a looped reduction that stores a buffer in one loop and reads it back in a later loop of the same kernel, with no barrier in between. Triton's coalesce pass is free to give the store and the read-back different thread layouts, so one warp reads values another warp has not written yet. The result is silently wrong gradients.
This is upstream pytorch/pytorch#198562 (Triton's view in triton-lang/triton#10924 is that the kernel author has to insert
tl.debug_barrier()). PyTorch fixed it in pytorch/pytorch#190519 (commit 62a4f51), which is in v2.14.0 and v2.14.1 but not in v2.12 or v2.13. Every torch below 2.14 that Unsloth supports generates these kernels.How it shows up in Unsloth
Block-compiled Qwen3.5 LoRA training (FastModel, which compiles each decoder layer as one region since #10744, in 2026.10.7) hits it in the full-attention q-norm + partial RoPE backward reduction (head_dim 256). When autotuning picks
R0_BLOCK = 256, the reduction loop runs once, the store of the normalized gradient and its read-back land on different warps, and about 3% of rows come out as garbage. Whether a process is hit depends only on that autotune pick, so it looks random from run to run:Forcing the config proves it is causal: R0_BLOCK 256 gave corrupted gradients in 9 of 9 processes, R0_BLOCK 128 clean in 6 of 6. The kernel run on its own with random inputs reproduces it in 4 seconds (RTX PRO 6000, torch 2.11, Triton 3.6): wrong at (XBLOCK, R0_BLOCK, num_warps) = (2, 256, 2), (4, 256, 4), (8, 256, 8), exact at R0_BLOCK 128 and 64. In the TTGIR of the failing config the loop 1 store uses
warpsPerCTA = [1, 2]and the loop 2 read-backwarpsPerCTA = [2, 1].The fix
fix_inductor_reduction_readback_raceinunsloth/import_fixes.pybackports pytorch/pytorch#190519:TritonKernel.load/TritonKernel.get_load_bufferso a load of a buffer whose store left the CSE cache (cse.invalidated_stores) is preceded bytl.debug_barrier(), written into the same buffer the load goes to (loop body, or hoisted body);TritonKernel.loadalready readsinvalidated_stores(torch 2.14+), so it never doubles the barrier, and is idempotent;post_grad_custom_post_passwhoseuuid()joins the FX graph / AOTAutograd cache key, so kernels compiled before the update are rebuilt instead of loaded from a warm cache. A user's own post-grad pass is left alone.Registered in
_gpu_init.pyright afterfix_dynamo_config_thread_visibility, so on torch 2.12+ the config value is mirrored to the autograd threads that compile the backward.Verification (Colab L4, torch 2.11, main + this change)
tests/test_inductor_readback_barrier.py: 7 passed on the L4 (6 CPU logic tests + 1 GPU codegen test). The CPU tests also pass on torch 2.6.0 and 2.13.0, and the patch applies to the realTritonKernelon both.Cost
Exclusive Colab L4, torch 2.11, LoRA SFT (batch 4, 512-token rows), fresh process and fresh Inductor / Triton caches per run, runs alternated A B B A A B, median step time over steps 11 to 30:
Qwen3-0.6B generates no kernel with this pattern, so its code is unchanged and its 1.1% is run-to-run noise; Qwen3.5's 0.9% is inside the 2.4% spread of main against itself. Losses and grad norms match between the arms.