Skip to content

Studio diffusion: record each card's CUDA graphs on its own capture stream, so compiled renders on a second GPU are correct - #14915

Merged
danielhanchen merged 2 commits into
mainfrom
studio-cuda-graph-capture-stream-per-card
Oct 23, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-cuda-graph-capture-stream-per-card

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Compiled renders are wrong on the second GPU after any model has rendered on the first GPU in the same Studio process. The first render on the second card is close to correct. Every render after it returns noise that has little to do with the prompt or the seed. For example: load a model on GPU 0, then load one on GPU 1 (picked in the UI). The same thing happens with a CFG-parallel or layer-split load whose primary lands on GPU 1. Nothing is logged and nothing recompiles.

The cause is torch.cuda.graph. Without stream=, it records on a single process-wide default_capture_stream, and that stream is created on whichever card captured first. Entering it makes that card current. So a later capture for a model on cuda:1 ran capture_begin on a cuda:0 stream, while the forward's kernels went to cuda:1's own stream and ran uncaptured. The graph recorded none of the forward. From then on every replay only copied the inputs and returned the static outputs of the step that ran during the recording.

The render thread is pinned to the right card. Before the capture: current_device=1. Inside capture_begin, without this change: current_device=0 stream_device=cuda:0. With this change: current_device=1 stream_device=cuda:1.

Change

  • diffusion_cuda_graph._capture_stream(card) keeps one capture stream per card. It reuses torch's own default stream for the card that stream was made on, so the first card records on exactly the same stream as before. Pool blocks are reused only from the stream that recorded them, which is why it is one stream per card rather than a new one per capture.
  • The first capture passes stream=_capture_stream(card) to torch.cuda.graph, where card is the card the step's inputs are on. Re-captures (_graph_without_flush) use the same stream.

Evidence

Unit tests

  • test_a_step_graph_on_the_second_card_records_its_forward (two real cards, tests/test_diffusion_multigpu_cuda.py): captures a step graph on cuda:0, then one on cuda:1, and replays each with new inputs. Fails on base (the cuda:1 replays differ from eager). Passes on head.
  • test_each_card_records_on_its_own_capture_stream (stub torch): each card gets its own capture stream, and a card that captures twice reuses its stream.
  • Base here is current main (b9bb997). Run against it with the new tests copied in, the two-card test fails (the cuda:1 replays return the recording's output, and torch warns "The CUDA Graph is empty"). The stub test errors on base because _capture_stream does not exist there.
  • One card, test_diffusion_cuda_graph.py, test_diffusion_offload_cuda_graph.py, test_diffusion_offload_step_graphs.py, test_diffusion_failed_capture_pool.py, test_diffusion_block_graph.py: 252 passed on main, 253 passed on head (the new stub test). No failures on either side.
  • Two cards, test_diffusion_multigpu_cuda.py, test_diffusion_multigpu.py, test_diffusion_layer_split.py, test_diffusion_layer_split_cuda.py and test_diffusion_cfg_parallel_tier.py: 190 passed, 1 skipped on main, 191 passed, 1 skipped on head (the new two-card test). The skip is the same FLUX.3 test on both sides (this diffusers has no FLUX.3).

Studio end to end
Tiny FLUX.2 Klein (real config, random weights) on two B200s, base = current main, through DiffusionBackend.begin_load + generate, speed default (compile + CUDA graphs). Arms in one process:

  • one card on cuda:0
  • one card on cuda:1, run twice
  • eager on cuda:0

Each arm renders 6 times: first prompt, same prompt, a 108-word prompt, a new seed, CFG toggled, and back. Image PSNR is against the cuda:0 compiled arm.

render base: cuda:1 vs cuda:0 head: cuda:1 vs cuda:0
first prompt 31.3 dB bit-identical
same prompt again 31.3 dB bit-identical
108-word prompt 14.8 dB bit-identical
new seed 14.9 dB bit-identical
CFG toggled 14.8 dB bit-identical
back 15.0 dB bit-identical

Other checks:

  • The cuda:1 arm against its own repeat is bit-identical on both base and head, so base is deterministic and wrong, not noisy.
  • On the earlier base effa4c3: with UNSLOTH_DIFFUSION_CUDA_GRAPHS=0, cuda:1 matches cuda:0 bit for bit, which isolates the bug to the graph capture, and a model that is the first to capture in its process is unaffected on any card.
  • Compiled vs eager on cuda:0 is 45.7 dB on both base and head; this change does not touch it.
  • Graph breaks, recompiles and captures per render are the same on base and head: 0 / 0 / 1 on the first render, then 0 / 0 / 0 on every later render of every arm. The second render does not re-capture.

Real weights (run on the earlier base effa4c3, before this branch moved onto current main; not re-run on current main): unsloth/FLUX.2-klein-base-4B, int8, both cards capped at 8 GiB so Studio streams the denoiser, 1024x1024, 4 steps. One card on cuda:0, then one card on cuda:1, in the same process.

render base: cuda:1 vs cuda:0 head: cuda:1 vs cuda:0
first prompt 18.5 dB (a blurred blob where the subject should be) bit-identical
same prompt again 17.8 dB bit-identical
108-word prompt, new seed, CFG toggled, back bit-identical bit-identical

Under streaming, the first wrong graph is re-recorded on the second render through the re-capture path, which already picked the card's own stream. That is why only the first two renders are wrong on base there.

Not covered

  • ROCm. HIP graphs go through the same torch.cuda.graph default-stream code, so this change applies there too, but no multi-GPU AMD host was available.
  • Real weights were checked only for FLUX.2 Klein Base under streaming. The fix is in the shared capture path, the same for every family.

Two real consumer cards (Kaggle 2x T4, torch 2.13)

Compiled tiny FLUX.2 Klein rendered on cuda:1 after a render on cuda:0, two cuda:1 loads, 6 renders each:

main b9bb997a this PR
CUDA graph on cuda:1 capture fails with cudaErrorStreamCaptureInvalidated in both loads, the load falls back to eager recorded in both loads
Follow-up render time 0.040 to 0.073 s 0.027 s
Recompiles / graph breaks / re-captures on follow-ups n/a (eager) 0 / 0 / 0
Images vs cuda:0 58.8 dB 59 dB

On T4 the defect shows up as a silent loss of CUDA graphs on the second card rather than wrong images. The same card in two separate processes already differs at about 59 dB on T4, so bit-identity cannot be shown there.

torch.cuda.graph without stream= records on one process-wide stream created
on the first card that captured. After a model had captured on cuda:0, a
model loaded on cuda:1 (a second GPU picked in the UI, or a CFG-parallel
primary there) entered that cuda:0 stream, so capture_begin ran on cuda:0
while the forward's kernels ran uncaptured on cuda:1. The graph recorded
none of them and every replay returned the recorded step's output: renders
after the first were wrong on that card. Each card now records on its own
stream, keeping torch's default stream for the card it was made on.
@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@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-23T05:17:43.488016Z eabd769 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. 🎉

Reviewed commit: eabd7699a2

ℹ️ 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 abe4383 into main Oct 23, 2026
@danielhanchen
danielhanchen deleted the studio-cuda-graph-capture-stream-per-card branch October 23, 2026 12:26
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Oct 23, 2026
…reads' syncs out of a recording (unslothai#14964)

## Problem

Studio records its whole-step diffusion CUDA graphs with
`torch.cuda.graph(...)` in its default `capture_error_mode="global"`
(and `_graph_without_flush` passes `"global"` explicitly). The PyTorch
docs for `torch.cuda.graph` / `CUDAGraph.capture_begin` say: "During
cuda graph capture, some actions, such as cudaMalloc, may be unsafe.
"global" will error on actions in other threads, "thread_local" will
only error for actions in the current thread". In global mode, a
"potentially unsafe" call from any other thread during the recording
invalidates the capture, and the call itself raises `operation not
permitted when stream is capturing` on that other thread.

Studio runs CUDA work on several threads at once: the image and video
backends each have their own render thread and their own
`_generate_lock`, and the two can render side by side once both are
loaded under `fit` / `always`. There are also the video background
pinner, the stream encode worker, bg compile, the download-plan settle
and the unload paths. The existing gates (`hold_off_capture`,
`outside_capture` / `held_work`, and unslothai#14777's retired-pool wait) only
cover the progress poller, preview, ring drop and CFG replica work.
Everything else is ungated. Two captures also never excluded each other,
so the second capture's entry `torch.cuda.synchronize()` (and
`torch.cuda.graph.__enter__`'s own sync) landed inside the first
capture's recording.

What each call does when another thread makes it while a capture is
recording on the same card (torch 2.14.1+cu130, B200, one fresh process
per cell):

| call on the other thread | global | thread_local |
|---|---|---|
| kernel launch on a warm thread, non_blocking H2D, fresh cudaMalloc,
`mem_get_info`, new stream | ok | ok |
| first cuBLAS matmul in a thread | invalidated (`cublasCreate` fails) |
ok |
| first cuDNN conv in a thread | invalidated | ok |
| `.item()` / `.cpu()`, default or side stream | invalidated | ok |
| `event.query()`, `event.synchronize()`, `stream.synchronize()` |
invalidated | ok |
| `pin_memory()` | invalidated | ok |
| `empty_cache()` with free cached blocks | invalidated | ok |
| `torch.cuda.synchronize()` | invalidated | invalidated |

On main these races are real. The new tests fail there, and one of them
fails because of the cross-thread call itself:
- If another thread runs a VAE-decode style tail (cuBLAS, cuDNN, a host
read, an event query, a pinned buffer) during a recording, it raises
`CUDNN_STATUS_INTERNAL_ERROR_DEVICE_ALLOCATION_FAILED`.
- If two threads capture at once, the second wrapper is poisoned:
`operation not permitted when stream is capturing ... cuCtxSynchronize`.
The load then runs eager.

## Fix

- **Thread-local capture mode.** Whole-step captures now record in
`capture_error_mode="thread_local"` (`CAPTURE_MODE`). This covers both
`torch.cuda.graph` (`_graph_with_flush`) and the no-flush re-record.
Per-block graphs already record this way, and so do torch.compile's own
CUDA graphs (`torch/_inductor/cudagraph_trees.py`). The mode changes
only which calls CUDA checks; it does not change what gets recorded.
  - Other threads' kernels never reach the private capture stream.
  - The capturing thread is still checked exactly as before.
- The one cross-thread call that still breaks a recording, the
device-wide synchronize, still errors loudly. It never corrupts
silently.
- **Captures exclude each other.** `_capturing()` waits for any other
thread's recording to end before it raises the depth. The wait is
bounded by `RETIRED_FLUSH_WAIT_S`, after which it raises
`CaptureRefused` and that step runs eager. A thread's own nested
captures still nest.
- **Studio's device syncs take the shared side.**
`synchronize_outside_capture(device)` replaces the bare
`torch.cuda.synchronize` at Studio's in-process sync sites. It waits for
another thread's recording to end and is counted as a hold while it
runs, so no capture enters during it. This is one process-wide
reader/writer gate: captures exclusive, syncs shared.
- Sites converted: capture entry, settled memory snapshot
(download-plan, loads), offload restore / return, ring drop and abandon,
bg compile, CFG batch timing, VMM arena unmap, measured peaks, the int8
/ nvfp4 / convrot / moss / attention device probes, and
`clear_gpu_cache` (unload beside the other backend).
- A capture's own pre-record sync refuses rather than breaking the other
recording.
- Under `hold_off_capture`, or inside the thread's own recording, it
syncs directly, so it never re-takes the non-reentrant lock.
- **Cost.** Uncontended, the shared side is one lock section before the
sync and one after. Per-thread gate state moved to class defaults on a
`threading.local` subclass, so hot-path reads take no missing-attribute
path. CUDA graphs stay on by default, nothing new syncs, and the graphs
are unchanged.

## Tests

- **New: `tests/test_diffusion_capture_serialises.py`.**
- Three CUDA races that fail on main and pass here: the decode tail
during a recording, two threads capturing at once (both keep their graph
and replay on the next call with no second capture), and a Studio device
sync during a recording (it waits it out).
- CPU tests of the gate: a capture waits for another thread's recording;
nested captures do not wait on themselves; a capture held out too long
is refused; the sync waits and is counted; a sync under
`hold_off_capture` or inside the thread's own recording runs straight
away; a capture's own sync refuses while a plain sync still runs.
- **Existing stub update.** The `torch.cuda.graph` stub in
`tests/test_diffusion_cuda_graph.py` now accepts `capture_error_mode`.
- **Main vs branch, 30 test files, failing test IDs compared**
(`temp/venv_core`, torch 2.14.1, one B200). Files run:
`test_diffusion_offload_cuda_graph.py`,
`test_diffusion_offload_step_graphs.py`,
`test_diffusion_block_graph.py`, `test_diffusion_cuda_graph.py`,
`test_diffusion_failed_capture_pool.py`, the multigpu files
(`test_diffusion_multigpu*.py`, `test_video_multigpu_wiring.py`,
`test_diffusion_cfg_parallel_tier.py`), `test_video_backend.py`, and the
test files of every module whose sync was converted.
  - Only on main: the 13 new tests fail.
  - Only on the branch: nothing.
  - Red on both sides, pre-existing:
    - `test_diffusion_multigpu.py`: 5 tests that need a second card.
    - `test_diffusion_memory.py`: 8 pinned / top-level onload tests.
-
`test_diffusion_int8_gemm.py::test_no_compiled_variant_spills_to_local_memory`.
    - `test_polled_probe_costs.py`: 3 CPU-percent / process-tree tests.
-
`test_system_poll_no_cuda_context.py::test_the_probe_would_catch_a_regression`:
an nvidia-smi subprocess timeout on a loaded host.
- **Paired step benchmark.** A compiled 12-block DiT-like module
(d=1024, fp16, batch 4x1024 tokens) under `GraphedForward`, one device
sync per step, with global + bare sync and thread_local + gate
interleaved in one process.
- Both arms record once on the first render and replay for every later
render, so the second render does not re-capture.
- No dynamo recompiles in the timed renders, and outputs are
bit-identical.
- Median s/step: 3.84 ms vs 3.75 ms. The host was saturated (load
average above 1000) and individual renders ranged from 1.4 ms to 11 ms,
so this is noise, not a speedup.
- The gate's own CPU cost on that host: about 1.7 us per sync call,
against 0.04 us for a bare call with `synchronize` stubbed.

## Two T4s

Kaggle 2x Tesla T4, torch 2.11.0+cu128, head `6b458f30b`,
`tests/test_diffusion_capture_serialises.py` +
`tests/test_diffusion_multigpu_cuda.py`, run 3 times in one kernel:

| arm | run 1 | run 2 | run 3 |
|---|---|---|---|
| head `6b458f30b` | 19 passed | 19 passed | 19 passed |
| base `4b9c85f98` (new tests overlaid) | 8 passed, 11 failed, 7 errors
| | |

The first T4 pass on `6dc4fd37f` failed
`test_a_recording_survives_another_threads_decode_tail` with `Offset
increment outside graph capture encountered unexpectedly`. Cause: up to
torch 2.11, `CUDAGraph::capture_begin` calls `capture_prologue()` on the
device's default generator, which sets a `capturing_` flag on the
generator state shared by every thread. A draw from that generator on a
thread whose stream is not capturing then fails
`TORCH_CHECK(!capturing_, ...)` in `CUDAGeneratorState::increase`
(`aten/src/ATen/cuda/CUDAGeneratorImpl.cpp`, same code from 2.6 through
2.11). The error comes from the other thread, before any offset or
kernel change, so the recording is kept and the generator keeps working
once the capture ends. torch 2.12 keys the capture RNG state by capture
id (pytorch/pytorch#176752), so a draw on a non-capturing thread there
is just a normal eager draw. Explicit `torch.Generator(device=...)`
objects that are not registered with the graph are not affected on any
version.

Studio's render noise already comes from explicit generators. The NVFP4
/ MXFP8 load probes (`diffusion_nvfp4_dispatch`, `diffusion_nvfp4_ops`,
`diffusion_comfy_block`) drew from the default generator, so on torch
2.11 or older they could fail if they ran while another thread was
recording, and the NVFP4 verify caches that failure for the process.
They now seed from an explicit generator. In the tests, the other-thread
decode now draws the way a render does, and a new test checks how a
default-generator draw behaves on each torch version.

Local B200: torch 2.11.0+cu128 3/3 and torch 2.12.1+cu130 3/3 (12
passed, 7 skipped each; the two-card tests need a second card).

## Interaction with per-card capture streams

Main (with unslothai#14915, per-card capture streams) is merged in at
`f906e1e98`. The recorder call is now `recorder(graph, pool = pool,
stream = _capture_stream(card))`, so every capture records in
thread_local mode on its card's own capture stream. On the merge,
`test_diffusion_capture_serialises.py`, `test_diffusion_cuda_graph.py`
and `test_diffusion_multigpu_cuda.py` give 127 passed, 8 skipped on one
B200 (torch 2.12.1; the skips need two cards), and 135 passed, 0 skipped
on two B200s (torch 2.14.1).

The gate is process-wide, so captures on different cards record one at a
time. That is safe in either capture mode.

Measured on two B200s (thread A records on card 0 while thread B,
already warm, works on card 1):

| what thread B does on card 1 | global | thread_local |
|---|---|---|
| `torch.cuda.synchronize(1)` | ok | ok |
| first cuBLAS in a thread, `.item()` | breaks card 0 | ok |
| `empty_cache()` (every card) | breaks card 0 | ok |
| `torch.cuda.synchronize(0)` | breaks card 0 | breaks card 0 |
| a full `torch.cuda.graph` capture on card 1 | breaks card 0 | both
graphs valid |

So under thread_local, captures on different cards could record
concurrently. Under global they cannot. Letting captures on different
cards record at the same time (a per-device depth, shared pool ids
checked per card) is left to a follow-up. Recordings are short, so
serialising them costs little.

## Not covered

- **Third-party device syncs on other threads still break a recording in
any mode.** Examples: Triton / Inductor autotune `do_bench` inside the
bg compile thread's compiled forwards, and syncs inside diffusers or
accelerate code. Only Studio's own sync sites are gated.
- **`_RegisteredHostBuffer.__del__`** still calls
`torch.cuda.synchronize` directly. A finalizer can run on a thread that
already holds the capture lock, so it must not take the gate.
- **Cross-card behaviour rests on one probe run with toy kernels**, not
on a real two-card render.
- **s/step was measured on a shared, heavily loaded host.** No exclusive
card was available, so this PR makes no throughput claim beyond the
gate's per-call cost.
- **The merge `f906e1e98` has not run on torch 2.11.** The Kaggle T4x2
numbers above are from `6b458f30b`, before the merge, and Kaggle had no
free T4x2 slot for a rerun. On two B200s with torch 2.14.1 the merge
passes all three files with every two-card test running (135 passed, 0
skipped).
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