Skip to content

Decode graphs: release() and invalidate() re-arm a model that a capture failure disabled - #15217

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
lonexreb:fix/decode-graphs-rearm-after-release
Nov 14, 2026
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
lonexreb:fix/decode-graphs-rearm-after-release

Conversation

@lonexreb

Copy link
Copy Markdown
Contributor

What

unsloth/models/_decode_graphs.py keeps a per-model state.disabled reason once graph decode gives up (a capture that raised, a None fingerprint from parameters on another device / a non-LoRA adapter, or an eligibility reason). Nothing ever cleared it: release(), release_for_training() and invalidate() drop the graphs, statics, pool and buffers, but leave disabled set, so the model runs the eager decode step for the rest of its life. stats(model)["disabled"] is the only place it shows.

Why it matters

#15188 calls release_for_training(model) on every RL step. The memory-tight case that produces a capture OOM mid-GRPO is exactly the case where the next step, after that release, would capture fine; instead the whole run silently loses graph decode after one bad step. The same holds for invalidate(), whose docstring promises "they re-capture on the next decode".

How

Clear state.disabled where the graphs and buffers it was decided against are dropped: in release() (and so release_for_training()) and in invalidate(). The next decode re-runs _eligible / _fingerprint; a structural reason (model type, block swap, non-LoRA adapter, multi-device) is two attribute reads and disables again on that step. A capture that fails persistently retries once per release, which is once per RL step; UNSLOTH_DECODE_CUDA_GRAPHS_STRICT=1 still raises on the first failure for diagnosis.

Deliberately not done: a retry budget or a per-reason split. Both add state for a case (persistent capture failure) that the strict flag already surfaces.

Verification

CPU, tests/test_decode_cuda_graphs_default.py::test_release_rearms_a_disabled_model (new): sets disabled on a model's state and asserts release() and invalidate() each clear it.

release() invalidate()
main (ceedcaf26b) reason kept reason kept
this branch None None

ruff check, enforce_kwargs_spacing.py and the ruff-format-with-kwargs hook pass; both files parse under Python 3.9. I have no CUDA box, so the GPU tests in this file ran only in CI.

🤖 Generated with Claude Code

danielhanchen added a commit that referenced this pull request Oct 25, 2026
…5239)

## Summary

`Source lint` is red on main, and so on every PR (for example #15212 and
#15217). The step that fails is `Duplicate definitions (whole tree)`:

```
tests/test_fp8_torchao_import_route.py:13: has_real_cuda is imported twice from the same module (first at line 11)
```

#15211 and c993bf3 (skip the QAT MX and FP8 block GEMM GPU cases on the
recorded real CUDA) landed the same `from real_accelerator import
has_real_cuda` fix 18 minutes apart. Their import lines sit at different
spots, so git merged both without a conflict and left the name bound
twice. `scripts/lint_duplicate_definitions.py` exists to catch exactly
this merge damage.

## Change

- Drop the second import. Nothing else in the file changes.

## Verification

- `python scripts/lint_duplicate_definitions.py
tests/test_fp8_torchao_import_route.py`: on main `duplicate definitions
(1)` with exit 1. With this change: `clean: 1 file(s) checked` and exit
0.
- `tests/test_fp8_torchao_import_route.py` and
`tests/python/test_accelerator_skip_guards.py`: `52 passed, 1 skipped`.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…ranks (#15250)

## Summary


`tests/test_float8_training_fsdp2_gloo.py::test_float8_linear_trains_under_native_fsdp2`
fails in the `Repo tests (CPU, rest)` shard on unrelated PRs (#15212,
#15217, #15218) and passes when run on its own:

```
Mismatched elements: 1 / 4:  Max relative difference: 6.84e-05
Index | Obtained          | Expected
3     | 5.603824138641357 | 5.603440761566162 ± 5.6e-05
```

The sharded run is the correct one. Training the same unsharded fp8
model in a clean process gives `5.603824139` at step 4, and the result
is identical with 1, 2, 4 and 8 threads. The value that moved is the
reference. The test trained it inside the pytest worker, so it inherited
whatever earlier tests in the shard had left in that process, while the
two gloo ranks start fresh under `spawn`. The tolerance is fine. The two
sides were simply not run under the same conditions.

## Change

- The unsharded reference trains in its own spawned process
(`_reference_worker`, `nprocs = 1`), so both sides of the comparison
start from a clean interpreter. The tolerance is unchanged (`rel = 1e-5,
abs = 1e-6`).
- The JSON reads and both writes name `encoding = "utf-8"`.

## Verification

- `tests/test_float8_training_fsdp2_gloo.py`: passes, and the clean
reference matches the sharded losses exactly.
- Sabotage 1 (the CI failure): a pytest plugin that changes only the
parent process (scales `F.cross_entropy` by `1 + 1e-4`, which `spawn`
children do not inherit). The old test fails with `Max relative
difference: 2.0e-04`. The new test passes.
- Sabotage 2 (the guard still bites): scaling the sharded ranks' losses
by `1 + 1e-4` makes the new test fail.

I did not pin down which earlier test leaves the state behind. With this
change, the comparison no longer depends on it.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…d copy (#15264)

`tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process[llama-True-lora_kwargs4]`
fails now and then in `Repo tests (CPU, rest)` on unrelated PRs (#15159,
#15174, #15217, #15218, #15222, #15225) with only `AssertionError:
base_model.model.lm_head.weight`. Gradients, losses and norms all match
in those runs. Only the saved `lm_head` copy differs.

## Cause

The test, not the product. That case trains a full `lm_head` copy
(`modules_to_save`, 512000 entries) with AdamW at lr 1e-2 and the
default eps of 1e-8. At g = 0, Adam's `g / (sqrt(v) + eps)` has slope lr
/ eps = 1e6. Measured on main on this host:

| | value |
| --- | --- |
| median step-0 lm_head grad | 5.7e-6 |
| entries with step-0 grad below 1e-8 | 313 |
| step-0 grad of the 10 worst saved-weight entries | 4e-11 to 7e-9 |
| worst saved-weight diff / tolerance | 0.46 |

So reduction-order noise of about 1e-12 on a near-zero gradient becomes
about 5e-6 of weight. That is already half the `atol = 1e-5` here. A
runner whose CPU kernels sum in a different order goes over it.

## Fix

- Both arms use `AdamW(eps = 1e-6)`. The optimizer is still identical on
both sides, and 1e-6 is small next to the typical gradient, so the head
still trains. The worst entry drops to 0.0075 of the tolerance (60x
headroom).
- The saved-weight assert now keeps `assert_close`'s mismatch detail. It
used to print only the key, which is why the CI logs never showed how
far off the weight was.

## Verification

- `tests/test_tp_native_gloo.py`: 38 passed.
- Sabotage on the last step, after the norms are taken, so only the
saved weight can catch it:
- TP arm skips the lm_head update: fails, 511627 / 512000 mismatched,
max abs diff 1.0e-2.
- Each dp half's lm_head gradient scaled by +/-15% (a stand-in for a
missing dp reduction): fails, 493693 / 512000 mismatched, max abs diff
8.1e-4.
  - No sabotage: passes.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…15270)

`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
fails on main since #15237. It shows on the studio shard of every newer
PR, for example #15217:

```
test_decode_graphs_kv_growth_device.py:127: torch.cuda.is_available()
test_decode_graphs_kv_growth_device.py:127: torch.cuda.device_count()
```

## Cause

The guard is right. `tests/_zoo_aggressive_cuda_spoof.py` patches
`torch.cuda.is_available()` and `device_count()` process-wide, so these
skips would un-skip on a CPU-only runner whenever they share a session
with the spoofing suites. The two-GPU test would then call
`torch.cuda.set_device(0)` there.

## Fix

- `test_decode_graphs_kv_growth_device.py` now gates on
`has_real_cuda()` from `tests/_shared/real_accelerator.py`, the answer
recorded before any spoof:
  - the two-GPU skip short-circuits on it before `device_count()`;
  - the module-level `cuda` marker gates on it too.
- The guard only scans decorator `skipif` calls, so it does not see that
marker. It is the same spoofable read, so it is changed here as well.

## Verification

- `test_accelerator_skip_guards.py`: 1 failed on main; 24 passed here.
- On CPU, the file's three CUDA tests skip with the same reasons as
before.
- On a real GPU host, `has_real_cuda()` returns True, so the CUDA tests
still run there.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…ard (#15291)

`Repo tests (CPU, rest)` has been running out of time. Its pytest step
is capped at `timeout --signal=INT --kill-after=60 2100`.

- On most runs today pytest received SIGINT before finishing. Every run
I checked had a `KeyboardInterrupt` banner and a reported time of 2090
to 2097 s, stopping between 74% and 98% of the shard.
- The tail of the shard therefore never ran, and nothing said so. Those
runs were also red for other reasons, which hid it.
- Now that those reds are fixed on main, the shard fails on the timeout
alone (`Process completed with exit code 124`, at 75%), for example on
#15217, #15218 and #15226.
- The one complete run I found took 1920 s, already close to the cap.

## Cause

The shard is the catch-all. It has picked up the multi-rank gloo suites
added recently: tensor parallel, pipeline parallel, context parallel,
float8 and fp8 under FSDP2. Each spawns 2 to 4 ranks per test. This is
the same thing that happened with the FSDP2 gloo files, which is why
they already have their own `fsdp2` shard.

Measured locally at this job's shape (`-n 4 --dist loadgroup`, pinned to
4 cores, one selection per core set):

| selection | wall |
| --- | --- |
| the 7 non-FSDP2 gloo files | 578 s |
| the catch-all without them | 680 s |
| the existing `fsdp2` shard | 648 s |

So the gloo files are about 46% of the catch-all. Folding them into
`fsdp2` would push that shard to the cap instead; its jobs already run
17.5 to 29 minutes on CI.

## Fix

A `gloo` shard takes every `*gloo*` file except `test_fs*`, which are
`fsdp2`'s. It is written as two globs, `tests/test_[!f]*gloo*.py` and
`tests/test_f[!s]*gloo*.py`, because an explicit file root cannot be
filtered with `--ignore`, as the matrix notes already say. `rest`
ignores the same two globs. A new multi-rank gloo file lands in the new
shard without a workflow edit.

This adds a check, `Repo tests (CPU, gloo)`. No existing check name
changes.

## Verification

- `tests/studio/test_backend_ci_parallel_isolation.py` pins the number
of parallel pytest runs; it now expects eight, five of them
repo-cpu-tests shards (it failed at seven before that update). It and
`tests/test_ci_repo_cpu_shards.py` together: 54 passed.
- `tests/test_ci_repo_cpu_shards.py` on its own: 13 passed. It fails
both ways if the split is broken: drop the new shard and its files are
reported as dropped; drop the `rest` ignores and they are reported as
run twice.
- Collected ids at main (`--collect-only` with the same shell glob
expansion): the old `rest` has 17751. The new `rest` (17666) plus `gloo`
(85) is identical, with nothing in both and nothing shared with `fsdp2`.
- `test_gloo_spawn_cpu_guard.py` matches neither glob and stays in
`rest`. It is a guard, not a multi-rank suite.

## Not proven here

Runner timing is estimated by scaling: the catch-all is about 1258 s
locally against roughly 2800 s projected on CI. That puts the new `rest`
near 1500 s and `gloo` near 1270 s, both under 2100 s. This PR's own run
will show the real numbers.
…re failure disabled

A capture that raises (a CUDA OOM mid-GRPO, a parameter that was on another device for that step) sets state.disabled, and nothing cleared it: release_for_training() runs on every RL step and drops the buffers and pool the decision was made against, but the model stayed on the eager decode step for its life, visible only through stats(). Clear the reason where the graphs and buffers are dropped, so the next decode re-checks eligibility and captures again; a structural reason (model type, block swap, non-LoRA adapter) is cheap to re-derive and disables again on the next step.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@lonexreb
lonexreb force-pushed the fix/decode-graphs-rearm-after-release branch from bd6ada5 to 16c38e5 Compare October 31, 2026 23:30
…rm-after-release

# Conflicts:
#	tests/test_decode_cuda_graphs_default.py
#	unsloth/models/_decode_graphs.py
@danielhanchen danielhanchen self-assigned this Nov 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T08:40:13.370746Z aaa9a82 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

Copy link
Copy Markdown

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

Reviewed commit: aaa9a8283e

ℹ️ 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 17cab85 into unslothai:main Nov 14, 2026
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.

2 participants