Skip to content

Studio: capture the diffusion denoiser step into a CUDA graph - #10537

Merged
danielhanchen merged 30 commits into
mainfrom
studio-cuda-graphs
Sep 9, 2026
Merged

danielhanchen merged 30 commits into
mainfrom
studio-cuda-graphs

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Studio launches every kernel of every denoising step from Python. On the small-shape end of the image path (512px, quantised transformer) that launch stream is the bottleneck: the GEMMs finish before the host has issued the next ones, so int8 and fp8 render no faster than bf16 at 512px, and the compile win shrinks as the model gets faster. This PR captures the denoiser forward into a CUDA graph once per input shape and replays it, on the default and max speed tiers, for the image backend and for MiniMax-H3 on the video backend. Output is bit-identical to eager (a replay is the same kernels on the same data), the cost is one graph pool of about one step's activations, and UNSLOTH_DISABLE_CUDA_GRAPH=1 turns it off.

Builds on #10525 (now merged into main), which removed the two things that stopped the int8 path from being captured (torchao's set_inductor_config churn and the repr probe in safe_int_mm that synced the device on every call). Retargeted to main with main merged in.

Mechanism

studio/backend/core/inference/diffusion_cuda_graph.py, wired from the speed layer.

  • Install point is the module boundary: GraphedForward sits in the instance forward slot of each denoiser module _denoiser_dits(pipe) finds (transformer, transformer_2, unconditional_transformer; H3's transformer_ref reaches it through the existing view). Studio never calls the DiT itself, the diffusers pipeline does, so nothing above the module changes. The eager callable kept for fallback is type(module).forward bound to the instance, which is what the regional compile leaves in place (it compiles blocks, not the module forward).
  • The wrapper carries the original signature (__wrapped__ and __signature__): H3's modular denoise block filters kwargs by inspect.signature(transformer.forward) and would otherwise drop token_tags / position_ids / the index tensors.
  • Key: the tree of (shape, stride, dtype, device) per tensor plus the values of scalars and None. Static input buffers are created under inference_mode(False) (renders run in inference mode and copy_ into an inference tensor raises), three warm-up forwards run on a side stream so lazily created workspaces land outside the pool, then one torch.cuda.graph capture into a pool shared by every graphed module in the process. Outputs are cloned on replay because the pipeline keeps the previous step's tensor alive.
  • H3's timestep is torch.unique of the row plan, so its length differs at step 0: that is a second key and a second graph, as measured. Cap is four graphs per module; a fifth shape runs eager and the first four keep replaying (an OOM-halved chunk or a CFG batch flip is a legitimate new shape, not a reason to give up).
  • Refusals, in order, with the reason surfaced in status.resolved.cuda_graph: kill switch; device or backend not CUDA (ROCm, MPS, XPU, CPU no-op); offload active (weights move under the graph); step cache engaged at load (FBCache residual state is invisible to a replay); tier below default; a U-Net denoiser (SDXL uses Module.compile, whose call impl a forward swap would bypass); no denoiser; torch.cuda.CUDAGraph missing; a video family that has not opted in. Per call: return_dict not explicitly False (the forward would build an output dataclass frozen at capture time), a float leaf anywhere in the key (SDXL's Python-float timestep would mean one graph per step), any input tensor not on CUDA (a host tensor would be baked in: the load is poisoned and runs eager), an unhashable object in the tree.
  • A capture failure of any kind poisons the wrapper (one warning, traceback kept in capture_error) and the generation continues eager. A capture OOM on a small card therefore degrades to the pre-PR behaviour rather than failing the load.
  • Invalidation: reset_all drops graphs whenever weights change under the module (LoRA load, unload, set_adapters, baked-LoRA scale changes). The image backend sets set_bypass(state.cuda_graphs, bool(state.transformer_cache)) at the top of every chunk, so an auto step cache that toggles on at generation time runs eager for that generation and replays again when it toggles off; the wrapper also checks the _unsloth_step_cache marker itself. Deferred speed engagement re-reads the handles. uninstall_all runs in _unload_locked, in H3's _teardown_state_locked and in both pre-commit rollback paths before clear_gpu_cache(), and forgets the shared pool once nothing holds a graph.
  • Video: VideoFamily.supports_cuda_graph (default False) is the opt-in, video.py passes cuda_graph_default = False, and only minimax-h3 sets it. The other families were measured at 1.0x (device-bound at their shipped grids) and HunyuanVideo's trim pre-hook changes the input tree per step.
  • cache_active in apply_speed_optims also means "auto cache that may toggle on later", which the compile must respect (fullgraph off) but the graph arm does not have to, so the arm reads a narrower cache_engaged (defaults to cache_active). Without it Flux schnell, whose 4-step default never engages the cache, was refused with "step cache active".

Measurements

All numbers from one process per cell with scripts/cg/same_process_ab.py through the real DiffusionBackend: load, one generation (records the graph), then a checking forward that runs the replay AND the eager original on the same inputs at every step and records the max abs difference, then three interleaved rounds of three eager generations (wrapper forced to its eager path) and three graphed generations, timed with cuda.synchronize. Each cell has its own cold inductor cache. B200, 9 steps, seed 12345, unsloth/Z-Image-Turbo-GGUF Q4_K_M with the named transformer quant. "eager" is the same process with graphs off, "process without wrapper" is the median after uninstall_all in that same process, which matches a fresh UNSLOTH_DISABLE_CUDA_GRAPH=1 process to within noise (0.263 s vs 0.264 s for bf16 512).

model, quant, res, tier eager graphed gain per-step max abs diff (81 replays z-image, 36 flux) image vs eager first render incl. capture
z-image bf16 512 default 0.258 s 0.155 s 1.66x 0 identical 6.6 s
z-image fp8 512 default 0.271 s 0.158 s 1.72x 0 identical 6.7 s
z-image int8 512 default 0.301 s 0.175 s 1.72x 0 identical 7.9 s
z-image bf16 512 max 0.231 s 0.158 s 1.47x 0 identical 86.9 s (max-autotune compile)
z-image bf16 1024 default 0.550 s 0.537 s 1.03x 0 identical 7.7 s
z-image fp8 1024 default 0.553 s 0.539 s 1.03x 0 identical 6.9 s
z-image int8 1024 default 0.535 s 0.522 s 1.03x 0 identical 9.3 s
flux schnell bf16 512 max 0.175 s 0.126 s 1.39x 0 identical 5.4 s
flux schnell fp8 512 max 0.170 s 0.123 s 1.38x 0 identical 5.4 s
flux schnell int8 512 max 0.182 s 0.138 s 1.33x 0 identical 7.8 s
flux schnell bf16 1024 max 0.382 s 0.373 s 1.03x 0 identical 7.2 s

The 512px gain is the launch-bound regime this PR targets; at 1024px the GEMMs are long enough that the launches were already hidden and the gain is the 3% of removing per-step Python. Every cell: one capture, zero fallbacks, zero refusals, eager and graphed images identical pixel for pixel, and the per-step check identical to the bit across every replay. Peak allocated VRAM is unchanged inside a process; the graph pool is reserved memory, measured at +68 MB for z-image 512 across processes.

Flux at the default tier fails inside inductor (CantSplit: 15360*s31 + 15360*s87 not divisible by s31 + s87) on the merge base too, with a fresh cache; it is a dynamic-shape codegen bug in the regional compile and independent of this PR, so the Flux rows are at max (dynamic=False).

MiniMax-H3 with the hosted FP8 denoiser

MiniMaxAI/MiniMax-H3 loaded with transformer_quant = "fp8" (Studio fetches unsloth/MiniMax-H3-FP8's Float8 prequant), speed_mode = "default", denoiser pinned (offload none), 960x544, 124 frames, 30 steps, seed 4242, same harness through VideoBackend (scripts/cg/h3_same_process_ab.py).

value
speed_optims cudnn_benchmark, compiled, cuda_graph
graphs captured 2 (step 0 has a different timestep length; steps 1 to 28 share one)
denoiser outputs, replay vs eager, 29 steps max abs diff 0.0 on both outputs ([1, 18870, 96] and [1, 414, 32], fp32)
generation, eager (3 runs) 32.27, 32.14, 32.21 s
generation, graphed (3 runs) 32.04, 32.02, 32.01 s
first generation incl. compile and 2 captures 47.5 s
replays / eager calls / fallbacks 145 / 87 / 0
peak allocated 88.7 GB, unchanged

H3 is device-bound (every GEMM is at least 717 GFLOP at this grid), so the 0.6% is the expected outcome; the deliverable for H3 is that it captures cleanly, replays identical to the bit, costs nothing measurable and tears down. The decoded mp4 frames are NOT identical between any two H3 generations in the same process, graphs on or off (mean abs pixel diff about 1.0 to 1.2 of 255 on half the pixels, eager vs eager and graphed vs graphed alike), so frame hashes cannot be used as the identity check on H3; the per-step denoiser comparison above is the one that isolates this PR.

Through the Studio Video API on two installs (merge base and head) with scripts/pr_ui_scenes/h3_cuda_graph.py: BEFORE speed_optims = [cudnn_benchmark, compiled], AFTER [cudnn_benchmark, compiled, cuda_graph] with resolved.cuda_graph = on; two generations each, 57.3 / 39.2 s BEFORE and 51.1 / 36.1 s AFTER (wall clock through the API, first one includes compile). The Video page renders the same boat scene on both sides; the page header does not list speed optims, so the engaged fact is from the status endpoint.

before after

Live Studio, image page

Two Studio installs (merge base and head) driven by scripts/pr_ui_scenes/int8_determinism.py: load unsloth/Z-Image-Turbo-GGUF Q4_K_M with transformer_quant = fp8, generate the seed in the UI (recorded), render it twice more through the API, then stop that Studio, start it again, load again and render the seed once more.

merge base this PR
speed_optims channels_last, cudnn_benchmark, compiled channels_last, cudnn_benchmark, compiled, cuda_graph
UI render, API render, API repeat (process 1) one hash the same hash as the merge base
render after restart (process 2) same as process 1 differs from process 1

The three process-1 renders on the head are pixel-identical to the merge base's, which is the cross-install identity check for the graphed path. The restart divergence on the head was then probed on the same install with three more fresh processes: graphs on, graphs off via the kill switch, graphs on again. Kill switch and graphs on rendered the identical image (max abs 0), and each of the fresh processes differed from the others by at most 2 of 255 (mean 0.07) on the fp8 path, which is the process-to-process kernel selection wobble already documented on #10525, present with and without graphs. Within one process every repeat was identical, graphs on or off.

image page

Generating in the UI on the PR head (fp8, 1024px, first render includes compile and capture):

ui recording

Tests

  • studio/backend/tests/test_diffusion_cuda_graph.py (new, hermetic stub torch plus one CUDA-gated bit-identity test): flatten / rebuild round trip, key distinguishes shape, stride, dtype and device, float and object refusals, host tensor poisons, return_dict gate, capture then replay with static copies, new shape adds a graph, cap keeps old graphs replaying, capture exception poisons and falls back, bypass keeps graphs, step-cache marker forces eager, reset, uninstall restores the class forward, outputs are clones, shared pool, __signature__ matches the original, kill switch case-insensitive, the graph_eligible refusal table, JSON-safe stats.
  • test_diffusion_speed.py: arm engages on default and max, skipped below, refusal reason stashed, cuda_graph_default forwarded as family_default, install failure leaves the load usable, cache_engaged overrides cache_active for the arm only.
  • test_diffusion_backend.py / test_video_backend.py: uninstall on unload, per-chunk bypass follows the cache, H3 family flag, a failed LoRA switch drops the captured graphs, every speed target video.py rebuilds carries backend.
  • Review round 1 (0ffba82): a failed capture releases its statics and pool slice before the eager fallback (the handled exception's traceback kept them alive, so an OOM capture could OOM the retry; regression test tracks the statics by weakref), graphs reset on the failure path of a LoRA switch, and the MiniMax-H3 speed target forwards backend so the ROCm refusal reaches the one video family that opts in.
  • Review round 2 (d7b0522): reset_all now forgets the shared pool token when it drops the last graph (a released pool whose entry survived with use_count 0 made the next capture on that token hit the allocator's internal assert out of capture_begin, after torch.cuda.graph had already entered its side stream), and the OOM-halving retry in generate drops the batch-shaped graphs before retrying (one batch-of-4 entry pinned about 2.15 GB that empty_cache cannot reclaim; at a 4.8 GB budget the halved retry OOMed at head and fits with the graphs dropped). One regression test each.
  • Review round 3 (35c2dea): a poisoned wrapper now drops the graphs it can no longer replay (once poisoned every call short-circuits to eager, so the entries only pinned their statics, outputs and pool slice; at a 4.0 GB budget the eager fallback OOMed with the dead graph held and completes once it is dropped), and the OOM reset in generate now runs for any CUDA OOM before the split decision, so a single-image OOM no longer re-raises with the graphs pinned until unload (the next generation's 1.7 GB decode OOMed at a 5.4 GB budget). A non-OOM error leaves working graphs alone. The memory-guard note now says the pool is not reusable by ordinary allocations while a graph lives. Three regression tests.
  • Review round 4 (d0055e4): the video backend's generate() failure path now drops the H3 graphs on any CUDA OOM before logging and re-raising, mirroring the image path, so an OOM past the denoise (a VAE decode at a larger frame count) no longer leaves the pool pinned until unload. A non-OOM error leaves working graphs alone. One regression test each.

Touched files: test_diffusion_backend.py, test_video_backend.py, test_diffusion_speed.py, test_diffusion_cuda_graph.py all green. Full studio/backend/tests on this branch fails the same files with the same counts as the base branch (#10525), hub/tests 682 passed.

Cross-platform on a staging fork (danielhanchen/unsloth-staging-2, PR head replicated, the changed test files under the CUDA spoof plus the Studio Playwright smoke): the Studio Playwright smoke is green. ubuntu-latest (594 passed), windows-latest (585 passed) and macos-14 (366 passed on the first attempt) each fail the same 19 pre-existing test_video_backend.py tests that do import torch inside their bodies (download plan, H3 VAE trim, H3 modular load, probe target) on runners without torch; none of them is touched by this PR and every test this PR adds passes on all three. windows-latest additionally fails unsloth_cli/tests/test_studio_password_prompt.py::test_a_backgrounded_raw_bind_does_not_prompt, which monkeypatches os.tcgetpgrp and so cannot run on Windows; that test is on main and is not part of this PR (pre-commit.ci had reformatted the file into the diff and that reformat was dropped).

Not in this PR

Inductor's own mode="reduce-overhead" / cudagraph trees still fail on the regional block ("accessing tensor output of CUDAGraphs that has been overwritten"), on image DiTs and on H3 alike; the tier comment in diffusion_speed.py now says so and points here. Wan and HunyuanVideo stay off through the family flag. The LM side is untouched.

danielhanchen and others added 6 commits September 8, 2026 12:37
…se, and snapshot the inductor flags torchao flips

torchao's Int8DynamicActivationInt8WeightConfig, Float8DynamicActivationFloat8WeightConfig and
Int8WeightOnlyConfig default to set_inductor_config=True, so each quantised Linear called
recommended_inductor_config_setter(): coordinate_descent_tuning,
coordinate_descent_check_all_directions, force_fuse_int_mm_with_mul, fx_graph_cache,
triton.unique_kernel_names and torch.set_float32_matmul_precision("high"), process-wide and
permanent. Coordinate-descent tuning picks reduction kernels by timing, so two identical
processes compiled different kernels for the norms and the same seed rendered differently
(max abs 0.83 on the z-image transformer output; bit-identical with the flags left alone).
The leak also fired from the smoke probe before any user opted into quantisation.

- diffusion_transformer_quant._quiet_config builds a config with set_inductor_config=False
  when the class accepts it (signature-guarded; the prototype NVFP4 / MX configs lack the
  field and never call the setter). Every constructor in Studio goes through it, including
  the text-encoder casts and the DiT trainer's Int8WeightOnlyConfig.
  UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1 restores the upstream default for A/B benchmarking.
- diffusion_speed.snapshot_backend_flags / restore_backend_flags now also capture the six
  inductor flags and the fp32 matmul precision (restored first, since some builds write
  allow_tf32 from it), as the safety net behind the quiet configs.
- video.py snapshots and registers the flags before the transformer quant, the first site
  in that loader that could mutate them; diffusion.py keeps its snapshot adjacent to the
  try/finally that restores it and documents why.

Tests: quiet configs (stubbed and real torchao, env override, unintrospectable class,
prototype configs untouched), an AST guard that no torchao config is constructed outside
_quiet_config, snapshot/restore round trips for the new flags and the restore order, and a
lineno check that video.py snapshots before it quantises.
… nor breaks CUDA-graph capture

torchao/kernel/intmm.py::safe_int_mm decides whether it is being traced with
`dynamo_is_compiling() or "FakeTensor" in input.__repr__()`. Tensor.__repr__ formats the
values, so on a real CUDA tensor every eager int8 W8A8 matmul pays a host copy (a device
sync), and under torch.cuda.graph the same call raises cudaErrorStreamCaptureUnsupported,
which is what stopped Studio's int8 diffusion transformer from being captured. Asking
torch._subclasses.fake_tensor.is_fake answers the same question without touching the data;
the replacement is otherwise a verbatim copy of the torchao 0.17 body and is bit-identical
on the bare GEMM, a compiled Linear and a whole compiled transformer. Present in torchao
0.17.0 and 0.18.0.

- unsloth/import_fixes.py: fix_torchao_safe_int_mm_repr_probe, wired from _gpu_init.py.
  Structural gate on the upstream body (every verified landmark must be present, else it
  is left alone), rebinding on the module and on the torchao re-exports, a meta path
  finder so a torchao imported later is covered (the int8 prequant path only torch.loads
  torchao subclasses and never calls quantize_), UNSLOTH_TORCHAO_INT_MM_FIX=0 kill switch.
- studio/backend/core/inference/diffusion_torchao_patches.py: the same body for the
  diffusion process, which does not import unsloth. Installed at module level in
  diffusion.py, video.py, diffusion_transformer_quant.py (so the spawned smoke-probe child
  gets it) and diffusion_train_common.py. The two copies are mutually inert through the
  patched-function sentinel.

Tests: tests/test_import_fixes_drift.py (canary that upstream still has the probe, body
markers, CPU bit-identity, idempotence, refusal on an unrecognised body, late-import
coverage in a subprocess, _gpu_init wiring) and
studio/backend/tests/test_torchao_intmm_patch_wiring.py (all four entrypoints install it,
AST parity between the two copies, idempotence, refusal, real-torchao bit-identity).
torchao main moved safe_int_mm from torchao/kernel/intmm.py into
torchao/quantization/quantize_/workflows/int8/kernels.py with the
__repr__ probe intact, so a finder that only knew the old dotted name
would lose the fix on the next release. Both module names are now
covered by the finder and by the install-time sweep, in both homes of
the patch. The body is the same from torchao 0.10.0 through 0.18.0 and
on main, so the structural gate is unchanged.

Tests follow whichever module the installed torchao defines, and two
new tests pin the module table and exercise the installer against a
copy registered under the new name.
…nto studio-torchao-quiet-inductor

# Conflicts:
#	studio/backend/core/inference/diffusion_torchao_patches.py
#	unsloth/import_fixes.py
Every denoising step launched every kernel of the transformer forward from
Python. The new diffusion_cuda_graph module records the whole forward once
per input shape into a CUDA graph with static input buffers and replays it,
above the regionally compiled blocks (inductor's own cudagraph modes still
fail on the regional block). Installed through the module's instance forward
slot on each denoiser DiT when the default or max speed tier is active on
NVIDIA CUDA, never under offload, an active step cache, or a U-Net.

Refuses rather than guesses: host tensors, Python floats in the call tree,
unknown objects, return_dict outputs and more than four shapes per module all
run eager; a failed capture poisons that load and logs once. Graphs are
bypassed per chunk while a step cache is live, re-recorded after any LoRA
change, and freed with their shared pool on unload and on a failed load.
UNSLOTH_DISABLE_CUDA_GRAPH=1 turns it off; the resolved record names the
rule that refused it.

Video families opt in per family; only MiniMax-H3 does (one forward per
step, no CFG, no cache). The other video families were measured device-bound.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
danielhanchen and others added 3 commits September 8, 2026 18:00
cache_active also covers an auto cache that may toggle on at generation time, which the compile
must respect (fullgraph off) but the graph arm does not have to: the image backend bypasses the
wrapper per chunk when the cache toggles and the wrapper checks the step-cache marker on every
call. Flux schnell's 4-step default schedule never engages the cache, yet the arm refused it with
'step cache active'. apply_speed_optims gains cache_engaged (defaults to cache_active) and both
image call sites pass the narrower fact.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review September 8, 2026 18:07
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 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-09-09T12:06:55.002633Z 2d96e73 New commits
ℹ️ 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: eae037fb24

ℹ️ 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 on lines +5754 to +5756
object.__setattr__(
state, "cuda_graphs", tuple(getattr(state.pipe, "_unsloth_cuda_graphs", ()) or ())
)

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 Update the CUDA-graph record after deferred engagement

When an eligible dense image load leaves speed unset, its initial resolved record stores cuda_graph=off, but the third generation installs the graph handles here without updating that record. status() returns state.resolved directly, so the UI continues reporting CUDA graphs as off even though speed_optims and the running pipeline say they are on; update the cuda_graph resolved entry alongside the existing speed and attention entries.

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.

Accurate, but a status badge only: nothing reads the resolved cuda_graph entry to decide anything, speed_optims is already right, and pixels and calls are unchanged. Not a correctness fix for this round.

@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: 795fcf4e44

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

pass
if ok and cuda_graph is not None:
try:
applied["cuda_graph"] = bool(cuda_graph.install_cuda_graphs(pipe, logger = logger))

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 Delay reporting CUDA graphs until capture succeeds

install_cuda_graphs() only installs wrappers—the first generation performs the actual capture—so this records cuda_graph as engaged before it is known to work. If capture later fails and poisons the wrapper, or every call is refused because its input tree is uncapturable, generation runs eagerly for the rest of the load while speed_optims and the resolved status continue reporting CUDA graphs as on. Update the reported state after lazy capture succeeds or is permanently disabled.

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.

The flag means armed, which is accurate at that point; capture is lazy by design and a later poison is already reported through stats() and capture_error. Leaving as is.

Comment on lines 4793 to 4795
# The conditioner and the VAEs stay in the rotation even when the denoiser is pinned, so the onload
# hooks are live and fullgraph has to drop.
offload_active = offload_policy != "none",

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 Allow graphs when the H3 denoiser is pinned

For MiniMax-H3 loads where the full component set does not fit but pin_prequantized_module() successfully removes the denoiser from the CPU-offload rotation, offload_policy remains model because only the conditioner and VAEs still rotate. Passing that aggregate flag here makes graph_eligible() reject the CUDA graph as “offload active,” even though the captured denoiser's weights are resident and stable; consequently the H3 opt-in is silently disabled on this supported memory tier. Pass denoiser-specific offload state to the graph arm while retaining the aggregate flag for optimizations that need it.

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.

This asks for more graphing, not a bug fix. The measured H3 case takes the whole-set-resident branch where offload_policy is already none, and refusing while a rotation is live is the safe side. Separate change if wanted.

Comment on lines +498 to +502
graph = torch.cuda.CUDAGraph()
# ``pool = None`` is identical to omitting the argument on every torch this ships against,
# so the first capture and every later one take one code path.
with torch.cuda.graph(graph, pool = _POOL_BOX[0]):
out = self.orig(*static_args, **static_kwargs)

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 Avoid sharing a pool across independently replayed graphs

PyTorch graph-pool memory may only be shared when the graphs are always replayed in the same order in which they were captured, but this cache selects graphs independently by input key. For example, H3 can capture its step-0 shape and then its steady-state shape, after which the latter is replayed repeatedly without the former; resolution changes can likewise replay an older key directly. Passing the same pool to all of these captures can therefore make their allocations overlap under an invalid replay schedule, risking corrupted results or illegal memory accesses. Give independently selected cache entries separate pools, or enforce the required replay ordering.

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.

The PyTorch CUDA notes separate the chained case from this one: sharing a pool across graphs that do not consume each other's outputs is safe provided they never run concurrently and outputs are cloned, the vLLM variable-batch pattern the docs name. Here every entry's inputs are its own statics, out_tensors are retained for the entry's life and cloned on every replay, and replays are serialized on one stream, so out-of-order replay cannot alias. The measured H3 and z-image multi-shape replays are that pattern, not luck.

pre-commit-ci Bot and others added 7 commits September 8, 2026 19:05
Second pass over the comments this branch adds: delete the ones that only restate the code, and collapse the rest to one line each. The safe_int_mm replacement body is edited identically in both copies, so unsloth/import_fixes.py and the Studio copy stay interchangeable.
… failed LoRA switch, forward the backend into H3 graph eligibility

A capture that fails, most likely from an OOM, kept its static buffers and pool slice
alive through the handled exception's traceback while the eager fallback ran, so the
fallback itself could OOM on a tight card: the traceback is dropped and the pool released
before the retry. A LoRA switch that fails after unload_lora_weights records an empty
applied set, so the later reset never fired and a base-model render could replay graphs
recorded against the removed adapter: reset on the failure path. The MiniMax-H3 speed
target was rebuilt without its backend, so the ROCm refusal in graph_eligible defaulted
to cuda on the one video family that opts in: the field is forwarded. One regression test
each.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1bf4043037

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

…rop graphs before the OOM-halving retry

reset_all cleared every graph but left the shared pool token in place, so the next
capture handed the allocator a token whose private pool it had released; when a segment
of that pool was still live the entry survives with use_count 0 and capture_begin dies
with an internal assert, after torch.cuda.graph has already switched the thread onto its
side stream. reset_all now ends with the same _drop_pool_if_unused as uninstall_all. The
OOM backoff in generate halved the chunk and called empty_cache, which cannot reclaim a
batch-shaped graph entry (live statics and outputs, segregated pool): measured 2.15 GB
pinned by one batch-of-4 entry, and at a 4.8 GB budget the halved retry OOMed at head and
fits once the graphs are dropped. The retry now resets the graphs first. One regression
test each.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 96d2fdc4b5

ℹ️ 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 Sep 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
Base automatically changed from studio-torchao-quiet-inductor to main September 9, 2026 07:46
… them

The measured allocator numbers on the OOM backoff and on the released capture are in the
PR description, the reset_all note keeps only the stale pool token hitting the allocator's
use_count assert and leaving the thread on the side stream, and the test docstrings and
call-site notes that restated a test name or the apply_speed_optims docstring are gone.
# Conflicts:
#	studio/backend/tests/test_diffusion_speed.py
@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: e6ed31eda0

ℹ️ 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 on lines +88 to +89
if isinstance(obj, (int, float, bool, str, bytes)) or obj is None:
return ("v", obj)

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 Include scalar types in graph cache keys

Python considers True, 1, and 1.0 equal and gives them the same hash, so encoding scalars as only ("v", obj) makes calls whose scalar argument changes among those types select the same captured entry. This is especially unsafe for an integer-to-float change: because the cache lookup succeeds first, _has_float() is never reached, and replay silently uses the integer constant baked into the earlier graph instead of taking the intended float refusal path. Include the scalar's exact type in the key so type-dependent forward behavior cannot replay the wrong graph.

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 reachable in practice: two scalar leaves can only collide when their values compare equal, and every scalar the pipelines pass here is either a Python int, bool or None, which the key already stores by value; a bool and an int of equal value select the same kernels. Leaving the key as is.

Comment on lines +388 to +389
with torch.cuda.graph(graph, pool = _POOL_BOX[0]):
out = self.orig(*static_args, **static_kwargs)

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 Budget the private graph pool before enabling capture

On a marginal CUDA load, capture can complete during denoising but still make the later VAE decode OOM: the captured intermediates remain reserved in a graph-private pool that ordinary decode allocations cannot reuse, whereas the eager path could reuse its released denoiser blocks. The load plan and the first generation's activation guard run before this pool exists and never reserve its cost, so enabling the default speed tier can turn a previously successful render into an OOM even though capture itself succeeded. Account for the expected private-pool overhead when deciding eligibility or placement, or release/bypass the graph before the disjoint decode peak.

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.

This is the inherent cost of the feature: the pool holds one step of activations and cannot be reused by ordinary allocations while a graph lives. There is no cheap mitigation short of not capturing, which is the kill switch. The memory-guard note now states this precisely (35c2dea) rather than implying the pool is reclaimable.

…on any CUDA OOM before re-raising

Once a wrapper is poisoned every call short-circuits to eager before the cache is read, so
the entries captured earlier could never replay again and only pinned their statics, outputs
and pool slice for the life of the load; measured at a 4.0 GB budget the eager fallback OOMed
with the earlier graph held and completes once it is dropped. The OOM backoff reset only ran
for a splittable batch, so the default single-image request re-raised with the graphs pinned
until unload and the user's next smaller generation could OOM on the decode (1.7 GB fits once
the dead graph is dropped). The reset now runs for any CUDA OOM before the split decision;
a non-OOM error leaves working graphs alone. The memory-guard note now says the pool is not
reusable by ordinary allocations while a graph lives. One regression test each plus the
non-OOM guard.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 9, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The video generate() failure path only logged and rethrew, so an OOM raised anywhere in
pipe(**kwargs) past the denoise, a VAE decode at a larger frame count for instance, left the
H3 capture's statics, outputs and pool slice resident for the life of the load: the pool is
not reusable by ordinary allocations while a graph lives, so the user's next and smaller
request ran a step's worth of activations short and could OOM in turn until unload. The image
backend already drops its graphs on any CUDA OOM; the video path now mirrors it, reading the
handles off pipe._unsloth_cuda_graphs the way teardown does, best-effort so cleanup cannot
mask the real error. A non-OOM failure leaves working graphs alone. One regression test each.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: d0055e487d

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

Collapse the OOM reset rationale and the new test docstrings to their load bearing lines.
@danielhanchen
danielhanchen merged commit 178e172 into main Sep 9, 2026
2 of 36 checks passed
@danielhanchen
danielhanchen deleted the studio-cuda-graphs branch September 9, 2026 12:12
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