Skip to content

studio: give minimax-h3 the sd.cpp graph-cut flags so it renders on a smaller card - #8644

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-h3-graph-cut
Aug 14, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-h3-graph-cut

Conversation

@mahiatlinux

Copy link
Copy Markdown
Contributor

Part of #8636 (issue 2). unsloth/MiniMax-H3-GGUF cannot render on a card smaller than its checkpoint, and fails in a way that reads as the model never loading.

The problem

offload_flags() produces --offload-to-cpu, which parks parameters in RAM, but each module is still allocated whole on the device when its graph runs. H3's pruned denoiser is 20.5 GB and its Qwen3-VL encoder 17 GB, so on a 12 GB card the allocation fails outright:

ggml_backend_cuda_buffer_type_alloc_buffer: allocating 17723.41 MiB on device 0: cudaMalloc failed: out of memory
alloc_tensor_range: failed to allocate CUDA0 buffer of size 18584340480
ggml_extend.hpp:1948 - qwen3vl prepare graph weights failed
conditioner.hpp:2058: GGML_ASSERT(!hidden_states.empty()) failed

The abort lands in the conditioner before any tensor is resident, so VRAM never rises and the UI shows a bare "generation failed". That looks like a model that never loaded rather than an out-of-memory error, which is what makes it hard to diagnose.

The change

sd.cpp already ships the graph-cut executor that splits a module into segments that fit; Studio never asked for it. The H3 native path now appends --max-vram -1 --stream-layers.

A negative --max-vram auto-detects free VRAM per device sparing that many GiB, rather than pinning a fixed ceiling, so it adapts to whichever card the graph lands on. A module that already fits merges back into a single segment, so a setup with room pays nothing:

minimax_h3 graph cut max_vram=2508.00 MB merged 51 segments -> 11 segments
generate_video completed in 23.77s

Deliberately not gated on the memory mode. auto and fast are what users reach first and are exactly the modes that fail; low_vram is not where this belongs.

sd_cpp_supports_graph_cut() reads both options out of --help and fails closed — the opposite default to sd_cpp_supports_minimax_h3() next to it. That gate refuses a build, so "cannot tell" has to keep it; this one adds flags, and sd-cli exits non-zero on an option it does not know, so an unreadable probe must emit nothing rather than break a build that renders today. Both markers are required, since --stream-layers is documented as a no-op without --max-vram. The probe runs under the same _tree_reader claim as every other one on this path, and the CPU runtime never asks, since it allocates from system RAM.

Testing

Focused tests for the probe (both flags required, fails closed on an unreadable or non-zero --help) and for the load path (flags emitted on an accelerator, absent on an older build, absent on CPU).

Verified against fake sd-cli executables through the real subprocess probe path: a build advertising both flags gates open, one without them gates shut, and a binary exiting non-zero yields no flags. The auto-mode argv comes out --offload-to-cpu --diffusion-fa --max-vram -1 --stream-layers.

Flag semantics confirmed against examples/common/common.cpp in leejet/stable-diffusion.cpp.

No H3 render was run here — the 23.8s figure and the log above are the reporter's, measured on a 12 GB RTX 4070 Ti at 320x192, 22 frames, 2 steps.

Issue 3 in that report (--split-mode layer always short by ~157 MB) is upstream C++ and untouched here.

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

mahiatlinux and others added 2 commits August 13, 2026 16:23
… smaller card

H3 allocates each module whole on the device when its graph runs, so --offload-to-cpu is
not enough on its own: the 20.5 GB pruned denoiser and the 17 GB Qwen3-VL encoder ask for
the full module at once and cudaMalloc fails on a 12 GB card. The abort lands in the
conditioner before any tensor is resident, so VRAM never rises and it presents as a model
that never loaded rather than an out-of-memory error.

sd.cpp's graph-cut executor is what splits a module into segments that fit, and Studio
never asked for it. The H3 native path now adds --max-vram -1 --stream-layers. A negative
budget auto-detects free VRAM per device, sparing that many GiB, and a module that already
fits merges back into a single segment, so a setup with room pays nothing for this. It is
deliberately not gated on the memory mode: auto and fast are what users reach first and are
exactly the modes that fail.

sd_cpp_supports_graph_cut reads both options out of --help and fails closed, the opposite
default to the H3 gate next to it. sd-cli exits non-zero on an option it does not know, so
an unreadable probe has to emit nothing rather than break a build that renders today. The
CPU runtime never asks, since it allocates from system RAM.

Part of unslothai#8636.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4ef33533a9

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

The identity gate added in unslothai#8560 reads --help for a stable-diffusion.cpp banner before the
H3 capability marker, so these fixtures need one to reach the load path they exercise.
@mahiatlinux
mahiatlinux force-pushed the fix/studio-h3-graph-cut branch from 4ef3353 to 0d263aa Compare August 13, 2026 04:29
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 0d263aa28f

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

Went through this one carefully, including the thing that looked like a blocking bug and is not.

The supports_graph_cut scope question: not a bug

supports_graph_cut is assigned inside the with block at line 1638 and read at line 1729, which reads like a conditional assignment. It is not: an AST dump of _run_load_h3_native lists that With as a bare top-level statement of the function, a sibling of the others, not nested in any if. binary_identity sits in the same block and is read at 1738 by pre-existing code. Every path that reaches 1729 has executed 1698; the only alternative is an exception out of the with, which never reaches the read. No NameError.

The flags are right, and I checked them against upstream rather than the description

leejet/stable-diffusion.cpp examples/common/common.cpp puts --max-vram in string_options (takes a value) with the help text "0 disables graph splitting; a negative value auto-detects free VRAM, sparing the specified value", and --stream-layers in bool_options (no argument). docs/performance.md documents --offload-to-cpu --max-vram -1 --stream-layers as the recommended shape. The argv this builds is well formed.

Appended exactly once: native_offload is built at 1725, += runs once at 1730, and the tuple is stored on the immutable runtime dataclass and only read per generation, so it cannot accumulate. native_device != "cpu" is evaluated after the CPU fallback at 1544, so the Linux-CPU-prebuilt path is correctly excluded, and there is test coverage for all three cases.

Fail-closed confirmed: _sd_cpp_probe_output returns None on exec failure, on a 20 s timeout, and on a non-zero exit, which is exactly how an older sd-cli rejects an unknown flag, and sd_cpp_supports_graph_cut maps None to False. Requiring both markers makes a prose false positive implausible.

No duplicate --max-vram anywhere: a repo-wide grep finds only the new constant, its one use, and the help marker. offload_flags never emits it and de-duplicates its own output.

One real finding: --stream-layers is inert under memory_mode = "fast"

Upstream docs/performance.md: "This flag only takes effect when the diffusion params backend is CPU, so it must be combined with --offload-to-cpu ... a warning is logged and the flag is ignored otherwise."

But line 1702 maps "fast" to policy "none", and offload_flags emits --offload-to-cpu only for group / model / sequential. So on a GPU with memory_mode = "fast" the flags go out as --max-vram -1 --stream-layers with no --offload-to-cpu, and upstream logs a warning and ignores the second one. --max-vram -1 still segments, so it degrades rather than breaks, but the comment on line 1728 says "not gated on memory mode because auto and fast are what OOM" and on fast half of the fix is doing nothing. Either gate --stream-layers on "--offload-to-cpu" in native_offload, or say so in the comment. No test covers memory_mode = "fast".

Minor

This adds a third --help spawn per load, after sd_cpp_binary_vets_for_h3, each with a 20 s timeout. The file already has the reuse pattern for exactly this (help_text_supports_minimax_h3 takes help text in hand) and lines 1625 to 1630 comment on doing the re-vet under one reader claim. Correct as written, just an avoidable subprocess.

Scope note, not a regression from this PR: the sd-server image path never gets graph-cut flags, so a large image model still OOMs. sd_cpp_supports_graph_cut is generic enough to reuse there.

Tests

Head, on this box:

studio/backend $ python -m pytest tests/test_sd_cpp_backend.py tests/test_video_backend.py -q
1 failed, 316 passed in 19.27s

The single failure is test_a_quantized_reference_load_resolves_the_reference_denoiser, and it is pre-existing, not yours: it fails identically on this PR's merge base 22cb12ec6 and passes on current main, so it is a diffusers-revision gate that main has since moved past. A rebase clears it.

The first run of that suite had 78 failures, all from av and sqlite_vec missing in my environment rather than anything in the code. Numbers above are after installing both.

What I could not verify

No real sd-cli build with the graph-cut executor was run here, so the flags are validated against upstream source and docs only, not against a live render. Nothing was checked on MPS, which also gets the flags now, and I did not confirm sd.cpp's per-device VRAM auto-detect does anything sane on Metal. A real H3 render on a 12 GB card in auto, fast and low-memory modes, with peak VRAM recorded, is the evidence this change deserves before it lands.

danielhanchen pushed a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026
@danielhanchen
danielhanchen force-pushed the fix/studio-h3-graph-cut branch from c09bed3 to 7819bde Compare August 13, 2026 13:36
@danielhanchen

Copy link
Copy Markdown
Member

Took this over and pushed a commit that gates --stream-layers on --offload-to-cpu.

Before and after

Before: MiniMax-H3 allocates each module whole on the device (20.5 GB DiT, 17 GB encoder), so --offload-to-cpu alone still cudaMallocs and a 12 GB card OOMs.

After: when the binary advertises the graph-cut executor, the load also passes --max-vram -1, and --stream-layers when the parameters are actually on the CPU.

Real issue. The only thing wrong with the original patch was that half of it was inert in one memory mode.

Why I changed it

Upstream leejet/stable-diffusion.cpp, docs/performance.md:

--stream-layers ... only takes effect when the diffusion params backend is CPU, so it must be combined with --offload-to-cpu ... a warning is logged and the flag is ignored otherwise.

and separately, for the other flag:

--max-vram <GiB> sets a VRAM budget the graph-cut segmenter respects. Negative values auto-detect free VRAM and spare the given amount.

memory_mode = "fast" maps to policy "none", and offload_flags emits --offload-to-cpu only for group / model / sequential. So on a GPU with fast, the original patch sent --max-vram -1 --stream-layers with no --offload-to-cpu, and upstream warned and ignored the second one. The comment said "not gated on memory mode because auto and fast are what OOM", which is exactly the mode where half the fix did nothing.

The constant is now split, so --max-vram still stands alone (it segments independently, and the same doc says the flags stack) while --stream-layers only rides along with an offload policy. GRAPH_CUT_AUTO_FLAGS is kept as an alias of both.

Does it break anything

The important direction is old sd-cli builds, because sd-cli exits non-zero on an unknown option, which would kill every render rather than degrade. That is still fail-closed: _sd_cpp_probe_output returns None on exec failure, on a 20 s timeout and on a non-zero exit, and sd_cpp_supports_graph_cut maps None to False, and it requires both markers in --help.

I ran the whole platform and accelerator product through the real load with a stubbed sd-cli, since the flags depend only on what --help advertises, which device the load committed to, and the memory mode:

  row                              max-vram  stream  offload   verdict
  Linux + NVIDIA, auto             True      True    True      ok
  Linux + NVIDIA, fast             True      False   False     ok
  Linux + NVIDIA, balanced         True      True    True      ok
  Linux + NVIDIA, low_vram         True      True    True      ok
  Windows + NVIDIA, auto           True      True    True      ok
  Windows + NVIDIA, fast           True      False   False     ok
  WSL2 + NVIDIA, auto              True      True    True      ok
  Linux + AMD (ROCm), auto         True      True    True      ok
  Linux + AMD (ROCm), fast         True      False   False     ok
  macOS + Apple silicon, auto      True      True    True      ok
  macOS + Apple silicon, fast      True      False   False     ok
  CPU only prebuilt, auto          False     False   False     ok
  CPU only prebuilt, fast          False     False   False     ok
  older sd-cli, GPU, auto          False     False   True      ok
  older sd-cli, GPU, fast          False     False   False     ok
  older sd-cli, CPU only           False     False   False     ok
  half-featured build, GPU         False     False   True      ok
  empty --help, GPU                n/a       n/a     n/a       ok (load refused)

0 failing rows

Two rules enforced there: no graph-cut flag ever reaches a build whose --help does not advertise both, and --stream-layers never goes out without --offload-to-cpu. The half-featured row (a build advertising --stream-layers but not --max-vram) gets neither, which is the right answer since the flag is a no-op without the budget. The empty-help row is refused earlier by the pre-existing H3 vetting gate with a clear message, before graph cut is ever consulted.

The CPU rows matter too: native_device != "cpu" is evaluated after the CPU fallback, so the Linux host with only the CPU prebuilt is correctly excluded, and nothing changes for it.

The thing that looked like a blocking bug and is not

supports_graph_cut is assigned inside the with at line 1638 and read at 1729, which reads like a conditional assignment. An AST dump of _run_load_h3_native lists that With as a bare top-level statement of the function, a sibling of the others, not nested in any if. binary_identity sits in the same block and is read by pre-existing code. Every path reaching the read has executed the assignment; the only alternative is an exception out of the with, which never reaches it. No NameError.

Tests

studio/backend $ python -m pytest tests/test_sd_cpp_backend.py tests/test_video_backend.py -q
1 failed, 317 passed in 19.05s

The one failure is test_a_quantized_reference_load_resolves_the_reference_denoiser, and it is not from this PR: it fails identically on the merge base 22cb12ec6 and passes on current main, so it is a diffusers-revision gate that main has moved past. A rebase clears it.

New test test_h3_native_drops_stream_layers_without_cpu_offload covers the fast case; the existing accelerator test is the both-flags case and now asserts --offload-to-cpu explicitly.

Still not verified, and worth doing before merge

No real sd-cli with the graph-cut executor was executed here, so the flags are validated against upstream source and docs only. The evidence this change actually deserves is a real H3 render on a 12 GB class card in auto, fast and low_vram, with peak VRAM recorded, against a run with graph cut disabled. Nothing was checked on MPS either, which also receives the flags now, and I did not confirm sd.cpp's per-device VRAM auto-detect behaves sanely on Metal.

Minor, non-blocking: this adds a third --help spawn per load, each with a 20 s timeout, and the file already has the reuse pattern for exactly that.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7819bde072

ℹ️ 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 753ed31 into unslothai:main Aug 14, 2026
7 of 50 checks passed
@mahiatlinux
mahiatlinux deleted the fix/studio-h3-graph-cut branch September 25, 2026 05:33
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.

2 participants