Skip to content

[Bug] Studio GPU selection never reaches image/video generation (both pin to CUDA device 0); MiniMax-H3 OOMs without graph-cut flags #8636

Closed

Description

@shadowdoggie

Note: Please do not remove the questions. Answer beside them.

  1. Did you update? pip install --upgrade unsloth unsloth_zoo — Yes, on the Studio-managed venv: unsloth 2026.8.15, unsloth_zoo 2026.8.10.
  2. Colab or Kaggle or local / cloud — Local, Unsloth Studio desktop on Windows 11 Pro (26200).
  3. Number GPUs used, use nvidia-smi — 2. CUDA0 RTX 4070 Ti 12282 MiB, CUDA1 RTX 5060 Ti 16311 MiB, driver 610.88.
  4. Which notebook? Please link! — N/A, this is Unsloth Studio's image/video generation UI, not a notebook.
  5. Which Unsloth version, TRL version, transformers version, PyTorch version? — unsloth 2026.8.15, TRL 0.23.1, transformers 5.5.0, PyTorch 2.10.0+cu130. sd.cpp prebuilt leejet/stable-diffusion.cpp master-813-bfbef5b (CUDA).
  6. Which trainer? SFTTrainer, GRPOTrainer etc — N/A, inference only (Studio image + video generation).
# Not a Python repro -- this is a Studio UI / backend wiring bug. Equivalent CLI repro
# showing that the flags Studio omits are what make the render possible:

# What Studio currently runs (fails: cudaMalloc OOM on device 0, exit 3221226505):
sd-cli --mode vid_gen \
  --diffusion-model minimax_h3_fl2va_pruned-Q8_0.gguf \
  --llm qwen3vl_32b_minimax_h3-Q4_K_M.gguf \
  --vae minimax_h3_video_vae_fp16.safetensors \
  --audio-vae minimax_h3_audio_vae_fp32.safetensors \
  --prompt "a cat walking through grass" --cfg-scale 1.0 \
  --width 320 --height 192 --fps 24 --video-frames 22 --steps 2 --rng cpu \
  --offload-to-cpu --diffusion-fa

# With the two flags Studio never emits (succeeds in 23.8s, audio included):
#   --max-vram -1 --stream-layers
# And to honour a GPU choice at all, which Studio also never emits:
#   --backend diffusion=CUDA1,te=CUDA1,vae=CUDA1

Summary

The GPU selection in Studio's settings panel is only wired into the chat/LLM runtime and training. It never reaches image generation or video generation, so both silently pin every module to CUDA ordinal 0 regardless of what the user selects. This holds for both image engines — diffusers and native sd.cpp — and for video.

Three findings, in descending severity:

  1. MiniMax-H3 cannot render at all on a card smaller than its checkpoint, because Studio never passes sd.cpp's graph-cut flags. Presents as a bare "generation failed" with no VRAM usage at any point, which reads as "the model never loaded". (Issue 2 below — this is the one I'd fix first.)
  2. GPU selection is not plumbed into image or video, so neither can use a second card. (Issue 1.)
  3. --split-mode layer in the pinned sd.cpp prebuilt is unusable, which blocks the natural multi-GPU workaround for both. (Issue 3.)

Patches for 1 and 2 are at the bottom.

On a mixed multi-GPU box this is not cosmetic: device 0 is frequently the smaller card, and for MiniMax-H3 it decides whether a render runs at all. I hit this as a hard generation failed with nothing ever appearing in VRAM.

Environment: Windows 11, Unsloth Studio desktop, unsloth 2026.8.15, sd.cpp prebuilt leejet/stable-diffusion.cpp master-813-bfbef5b (CUDA), two GPUs — CUDA0 RTX 4070 Ti (12 GB), CUDA1 RTX 5060 Ti (16 GB).


1. gpu_ids is not plumbed into image or video

Both selections toggled on in the UI, but:

  • VideoLoadRequest, POST /video/load (backend/routes/video.py) and VideoBackend.begin_load() (backend/core/inference/video.py) have no gpu_ids parameter at all.
  • POST /images/load (backend/routes/inference.py) passes 15 arguments to begin_load() and gpu_ids is not among them. backend/core/inference/diffusion.py has zero references to it.
  • Frontend-side, gpu_ids is consumed only under src/features/chat/** and src/features/model-picker/** via src/hooks/gpu-selection.ts. The image and video load calls never send it.

By contrast backend/core/inference/llama_cpp.py has ~109 references and backend/core/training/training.py uses prepare_gpu_selection() — those paths honor the setting correctly, which is what makes the UI look like it applies globally.

Consequences:

  • sd.cpp paths (GGUF image + MiniMax-H3 video): Studio never emits --backend, so sd.cpp falls back to its own default of device 0 for diffusion, te and vae.
  • diffusers path: resolve_diffusion_device_target() (backend/core/inference/diffusion_device.py:261) returns a bare device = "cuda" with no index, so torch resolves it to cuda:0.

whisper/STT (backend/core/inference/stt_sidecar.py, backend/routes/whisper.py) also has no GPU selection, though the impact there is much smaller.

Suggested fix: thread gpu_ids through the image and video request models, routes and begin_load() chains the same way the LLM path already does, then translate it to --backend diffusion=CUDA<n>,te=CUDA<n>,vae=CUDA<n> for sd.cpp and to an indexed cuda:<n> for diffusers.

As a local workaround I patched both paths to pick the largest-VRAM CUDA device automatically (parsing sd-cli --list-devices) and emit --backend for sd.cpp. Note that --clip-on-cpu / --vae-on-cpu are the deprecated spellings of te=cpu / vae=cpu, so those must win over the device pick or low_vram gets silently undone by sd.cpp's last-wins parser.


2. MiniMax-H3 OOMs on any card smaller than the checkpoint

Separate bug, same code path, and this one makes H3 unusable rather than just slow.

offload_flags() (backend/core/inference/sd_cpp_args.py:191) only ever produces --offload-to-cpu, --clip-on-cpu, --vae-on-cpu, --diffusion-fa, --vae-tiling. --offload-to-cpu parks weights in RAM but each module is still allocated whole on the device when its graph runs. With unsloth/MiniMax-H3-GGUF (minimax_h3_fl2va_pruned-Q8_0 at 20.5 GB + qwen3vl_32b_minimax_h3-Q4_K_M at 17 GB) that is an immediate cudaMalloc failure:

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
model_manager.cpp:473  - model manager alloc compute params backend buffer failed, num_tensors = 551
ggml_extend.hpp:1948 - qwen3vl prepare graph weights failed
conditioner.hpp:2058: GGML_ASSERT(!hidden_states.empty()) failed

sd-cli exits 3221226505 and the UI shows a bare "generation failed". Because the abort lands in the conditioner before any tensor is resident, VRAM usage never rises, which makes it look like the model was never loaded at all.

The pinned prebuilt already supports sd.cpp's graph-cut executor, which Studio never uses. Adding --max-vram -1 --stream-layers to the H3 native flags fixes it outright — a negative budget auto-detects free VRAM per device, and a module that already fits merges back to a single segment, so it costs fitting setups nothing:

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

Measured on the above hardware at 320x192, 22 frames, 2 steps: OOM abort → 23.8 s render with audio. An explicit --max-vram cuda0=10,cuda1=14 gave 23.3 s, so auto-detection costs nothing.

This should not be gated behind the low_vram memory mode — auto and fast are what users hit first and they are exactly the modes that OOM.


3. Related: --split-mode layer is unusable in the pinned sd.cpp build

While trying to split H3 across both GPUs (--backend "diffusion=cuda0&cuda1" --split-mode layer), the layer-split planner always requests ~157 MB more than whatever budget it is given:

--max-vram cuda0=5,cuda1=6   -> segment 25 needs 6301.3 MB on CUDA1, but only 6144.0 MB is available
--max-vram cuda0=8,cuda1=11  -> segment 46 needs 11421.2 MB on CUDA1, but only 11264.0 MB is available

6144 → 6301.3 and 11264 → 11421.2 is the same +157.2 MB constant, so no budget value ever satisfies it. Looks like fixed per-segment overhead that layer_split_partition.cpp:166 does not account for when packing. This is in leejet/stable-diffusion.cpp@bfbef5b; flagging it here since it blocks the natural multi-GPU answer to issue 1, and may be worth carrying a fix for in unslothai/stable-diffusion.cpp.


4. Minor: the prebuilt lacks the H3 fixes it warns about

The installer logs:

warning: leejet/stable-diffusion.cpp has no master-813-bfbef5b-u13b9d92; this build lacks the
MiniMax-H3 fixes, so H3 will abort on the default cfg-scale and on --vae-on-cpu, and a blanket
--type will quantize its 1-D norms into a broken render.

Studio already works around all three in video.py (forces cfg_scale = 1.0, passes vae_on_cpu = False), so this is informational — but it means every H3 user on Windows/CUDA is on the fallback build.


Repro for issue 1

  1. Two CUDA GPUs where ordinal 0 is not the largest.
  2. In Studio's GPU panel, select only the larger card (or select both).
  3. Load an image model and generate.
  4. nvidia-smi shows the allocation on ordinal 0 either way.

Both image engines are affected, so it reproduces on either kind of pick:

  • diffusers — e.g. unsloth/FLUX.2-klein-9B-GGUF. Note a GGUF filename does not imply the sd.cpp engine; this one routes to diffusers. The load line reports the bare device with no ordinal:

    diffusion.loaded: repo=unsloth/FLUX.2-klein-9B-GGUF base=black-forest-labs/FLUX.2-klein-9B
    device=cuda offload=streaming tiling=True reasons=companions exceed budget
    

    The companions exceed budget reason is itself computed from mem_get_info() on ordinal 0, so on a mixed box the offload policy is also decided against the wrong card's capacity.

  • sd.cpp — any model routed to the native engine, plus MiniMax-H3. Studio emits no --backend, so every module goes to ordinal 0.

Same for video: POST /video/load has no gpu_ids at all.


Patches

These are the changes I applied locally against the installed studio package. They are workarounds (largest-card heuristic, not the user's actual selection), but the first two are what a real fix would also have to do, and the third is a trap worth knowing about.

A. Honour a device choice in sd.cpp (image + video). sd.cpp is never told a device, so it uses ordinal 0. Emit --backend:

# backend/core/inference/sd_cpp_backend.py -- new helper
def h3_preferred_cuda_device(binary):
    """Largest-VRAM CUDA device from `sd-cli --list-devices`, or None to keep sd.cpp's default."""
    override = (os.environ.get("UNSLOTH_H3_GPU")
                or os.environ.get("UNSLOTH_DIFFUSION_GPU") or "").strip()
    if override:
        return override if not override.isdigit() else f"CUDA{override}"
    text = _sd_cpp_probe_output(binary, "--list-devices") if binary else None
    if text is None:
        return None
    sizes = {}
    for line in text.splitlines():
        m = re.search(r"Device\s+(\d+):.*?VRAM:\s*(\d+)\s*MiB", line)
        if m:
            sizes[int(m.group(1))] = int(m.group(2))
    names = [ln.split("\t", 1)[0].strip() for ln in text.splitlines() if "\t" in ln]
    cuda = [n for n in names if re.fullmatch(r"CUDA\d+", n.upper())]
    if len(cuda) < 2 or not sizes:
        return None
    best = max(cuda, key = lambda n: (sizes.get(int(n.upper().removeprefix("CUDA")), 0),
                                      -int(n.upper().removeprefix("CUDA"))))
    return best if sizes.get(int(best.upper().removeprefix("CUDA")), 0) else None

Applied at both call sites — sd_cpp_backend.py (image, where offload is built) and video.py (H3):

target = h3_preferred_cuda_device(binary)
if target and "--backend" not in offload:
    # --clip-on-cpu / --vae-on-cpu are the DEPRECATED spellings of te=cpu / vae=cpu. They must
    # win, or sd.cpp's last-wins parser lets the device pick silently undo low_vram.
    te  = "cpu" if "--clip-on-cpu" in offload else target
    vae = "cpu" if "--vae-on-cpu"  in offload else target
    offload += ("--backend", f"diffusion={target},te={te},vae={vae}")

B. Honour a device choice in diffusers. _cuda_or_rocm_target() returns a bare "cuda", so torch resolves ordinal 0. The fix is torch.cuda.set_device(), not an indexed string (see C):

# backend/core/inference/diffusion_device.py -- in _cuda_or_rocm_target(), before the
# capability/bf16 probes, since those are indexless too and would otherwise describe a
# different card than the one the weights land on.
ordinal = _select_cuda_ordinal(torch)   # largest total_memory, UNSLOTH_DIFFUSION_GPU overrides
if ordinal is not None:
    torch.cuda.set_device(ordinal)

This is the correct lever because diffusion_memory.py:257 calls torch.cuda.mem_get_info() with no argument and its own comment states it means the current device. Setting the current device therefore steers weight placement and the offload-policy budget together. Verified on the 12 GB + 16 GB box: mem_get_info flips from the 4070 Ti to the 5060 Ti, and torch.zeros(1, device="cuda").device becomes cuda:1.

Caveat: torch.cuda.set_device() is thread-local. It happens to be fine here because resolve_diffusion_device_target() is called on both the load path (diffusion.py:1083) and the generate path (diffusion.py:1890), so both worker threads get it — a proper fix should not rely on that coincidence.

C. Do not fix B by returning "cuda:N". This is the tempting one-liner and it silently breaks CUDA support, because the device string is compared by value in at least:

diffusion_device.py:34 (DiffusionDeviceTarget.is_cuda), diffusion_device.py:207, diffusion_memory.py:139, diffusion_memory.py:228 (memory policy), diffusion_speed.py:222 (speed flags), diffusion_attention.py:257 (attention backend), video.py:581, video.py:666, video.py:683, video.py:4252, sd_cpp_backend.py:1256.

Every one of those takes its non-CUDA branch when the string is "cuda:1", so the model still loads but with CUDA-specific optimisations quietly disabled.

D. MiniMax-H3 graph-cut flags, appended to the H3 native offload flags in video.py (see issue 2 above):

if sd_cpp_supports_graph_cut(binary):          # probes --help for --max-vram / --stream-layers
    native_offload += ["--max-vram", "-1", "--stream-layers"]

Not gated on the memory mode on purpose — auto and fast are what users reach first and are exactly the modes that OOM.

Activity

  1. danielhanchen commented on Aug 28, 2026

    @danielhanchen
    Member

    This should be fixed now - sorry on the delay - please update Unsloth Studio to the latest via curl -fsSL https://unsloth.ai/install.sh | sh for Linux, Mac, WSL or irm https://unsloth.ai/install.ps1 | iex for Windows - if it's not fixed yet, it'll be in the next Studio release - if it's still not working after that, please open another issue - appreciate it again!

    Image and video generation now honour your GPU selection, pinning the chosen device for the diffusion, text encoder and VAE backends, with the graph-cut VRAM flags passed through.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions