Skip to content

Sync before re-reading a buffer stored in an Inductor reduction loop (torch < 2.14) - #15000

Merged
danielhanchen merged 11 commits into
mainfrom
fix-inductor-readback-barrier
Oct 24, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
fix-inductor-readback-barrier

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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:

Qwen3.5-0.8B LoRA SFT, bf16, L4, torch 2.11 grad norm, batches 1 to 5
block compile off (reference) 0.81, 0.91, 0.88, 0.90, 0.79
main, reduction autotuned to R0_BLOCK 128 0.81, 0.91, 0.87, 0.90, 0.79
main, reduction autotuned to R0_BLOCK 256 (4 of 6 processes) 27618, 28110, 36716, 26878, 54194

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-back warpsPerCTA = [2, 1].

The fix

fix_inductor_reduction_readback_race in unsloth/import_fixes.py backports pytorch/pytorch#190519:

  • wraps TritonKernel.load / TritonKernel.get_load_buffer so a load of a buffer whose store left the CSE cache (cse.invalidated_stores) is preceded by tl.debug_barrier(), written into the same buffer the load goes to (loop body, or hoisted body);
  • skips itself when TritonKernel.load already reads invalidated_stores (torch 2.14+), so it never doubles the barrier, and is idempotent;
  • sets a no-op post_grad_custom_post_pass whose uuid() 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.py right after fix_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 real TritonKernel on both.
  • The upstream test function from #190519 (two-pass layer norm): no barrier on main, barrier with this change, both match eager.
  • Qwen3.5-0.8B SFT with the reduction forced to the racy R0_BLOCK 256: main corrupted on all 5 batches (a per-call probe recomputing the kernel output in torch from pre-launch inputs: 29 of 30 calls wrong), this change clean in 3 of 3 processes (0 of 30 calls wrong, max relative error 0.0033 = bf16 rounding, barrier present in the kernel); with free autotuning 2 of 2 clean.

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:

model main medians (s) this change medians (s) ratio main spread kernels with a barrier (main / this change) peak memory
Qwen3.5-0.8B 0.3178, 0.3190, 0.3113 0.3205, 0.3258, 0.3206 1.009 2.4% 7 / 8 of 96 2.853 GB both
Qwen3-0.6B 0.2316, 0.2248, 0.2253 0.2276, 0.2283, 0.2246 1.011 3.0% 5 / 5 of 41 2.326 GB both

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.

@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@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 commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T23:54:19.621536Z — Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

Comment thread unsloth/import_fixes.py Outdated
Comment on lines +7319 to +7320
if getattr(inductor_config, "post_grad_custom_post_pass", None) is None:
inductor_config.post_grad_custom_post_pass = ReadbackBarrierCacheKey()

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

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.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Comment thread unsloth/import_fixes.py Outdated
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

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

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.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Two of the Repo tests reds here come from this PR's new tests/test_inductor_readback_barrier.py. Both are absent on main:

  • tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe flags test_inductor_readback_barrier.py:215: torch.cuda.is_available(). The CPU CI spoof makes that probe return True, so the GPU case un-skips on CPU runners. Gating on has_real_cuda() (from real_accelerator import has_real_cuda), as the other GPU tests do, clears it.
  • test_torch_without_custom_graph_pass_skips_the_fx_graph_cache asserts torch._inductor.config.fx_graph_cache is False, but it is True on the runner's torch 2.10.0+cpu. Either the patch did not engage on that path, or the assertion expects a torch where it applies.

llama.cpp build + smoke failed on an Ubuntu mirror 404 for libcurl4-openssl-dev (transient), so I re-ran it. gate is the Kaggle T4 quota gate, which is exhausted until 2026-10-24 00:00 UTC; it can be ignored.

danielhanchen added a commit that referenced this pull request Oct 23, 2026
`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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 4b7d3767fa

ℹ️ 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 Oct 23, 2026
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.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: ffee4ce667

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

ℹ️ 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 Oct 24, 2026
…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.
@danielhanchen
danielhanchen merged commit 082c52a into main Oct 24, 2026
39 of 40 checks passed
@danielhanchen
danielhanchen deleted the fix-inductor-readback-barrier branch October 24, 2026 14:13
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant