Skip to content

Studio: honour the GPU-layer split for DiffusionGemma loads - #7575

Merged
danielhanchen merged 24 commits into
unslothai:mainfrom
LeoBorcherding:fix/diffusion-gpu-layers-offload
Aug 1, 2026
Merged

danielhanchen merged 24 commits into
unslothai:mainfrom
LeoBorcherding:fix/diffusion-gpu-layers-offload

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #7574. Requires unslothai/unsloth-zoo#958, which adds the --ngl flag this PR passes —
that one should merge first, or a diffusion load on new Studio against an old zoo will fail
on an unrecognised argument.

load_model accepts gpu_memory_mode / gpu_layers, but the diffusion branch returned early
into _start_diffusion_server without forwarding them, then overwrote the recorded values with
auto / -1.

Two consequences: the runner always pinned every layer to the GPU, so a GGUF larger than VRAM
OOMed in cudaMalloc even with GPU layers set to 0; and /status reported auto regardless of
what the user picked, so the UI silently discarded the setting.

Change

Forward gpu_memory_mode / gpu_layers into _start_diffusion_server, emit --ngl in manual
mode, and record what was actually applied so /status and reload dedup agree with the running
child. _gpu_offload_active now reflects a CPU-only pick instead of being hardcoded True in
both places it was set. Auto mode is unchanged.

n_cpu_moe and tensor_split are still reset — the diffusion runner has no equivalent knob.

Performance note

The reporter measured ~6 tok/s against ~31 tok/s for non-diffusion Gemma-4-26B-A4B once
layers sit on CPU. Block diffusion is compute-bound rather than bandwidth-bound, so a CPU split
costs much more here than on an autoregressive model, and that may well be why the value was
pinned at 99 originally.

The default is therefore unchanged: only an explicit manual split alters behaviour, and it now
logs a warning so the tradeoff is visible rather than surprising. An OOM with no override is
still the wrong failure mode.

Tests

tests/studio/test_diffusion_gpu_layers_contract.py, source-level in the style of
test_llama_cpp_wall_clock_cap.py (importing the backend pulls in the whole studio stack): the
parameters are accepted, --ngl is emitted, gpu_layers >= 0 guards the falsy-zero case, the
call site forwards both, and the auto / -1 clobber is gone.

5 passed; scripts/verify_import_hoist.py PASS; scripts/run_ruff_format.py applied.

@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: 0c5f38bf33

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +5496 to +5497
self._gpu_memory_mode = gpu_memory_mode if manual_ngl is not None else "auto"
self._gpu_layers = manual_ngl if manual_ngl is not None else -1

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 Compare diffusion GPU-layer settings before deduping

Once diffusion loads record and apply gpu_memory_mode/gpu_layers here, the existing already-loaded guards also need to compare those fields for diffusion models. Both _request_matches_loaded_settings and _already_in_target_state still skip the GPU-memory comparison whenever is_diffusion is true, so changing the same loaded DiffusionGemma model from, for example, gpu_layers=0 to gpu_layers=20 is treated as already satisfied and no new shim is started with the new --ngl value.

Useful? React with 👍 / 👎.

Comment on lines +5420 to +5421
if manual_ngl is not None:
cmd += ["--ngl", str(manual_ngl)]

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 Gate --ngl on a compatible diffusion shim

When gpu_memory_mode=manual reaches this branch, Studio now always appends --ngl, but _find_diffusion_assets() normally launches the installed unsloth_zoo.diffusion_studio.shim and the package floor still allows older unsloth_zoo installs. In those environments the shim exits during argument parsing before health can pass, so a manual DiffusionGemma load fails outright instead of falling back or reporting an upgrade requirement; either bump/probe the shim version or only emit this flag when supported.

Useful? React with 👍 / 👎.

# and reload dedup don't report a previous GGUF's manual settings.
self._gpu_memory_mode = "auto"
self._gpu_layers = -1
self._gpu_offload_active = manual_ngl != 0

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 Bypass the training guard for zero-layer diffusion loads

For gpu_layers=0 this records the loaded diffusion runner as CPU-only, but the active-training preflight still receives only gpu_memory_mode and treats every diffusion GGUF as a single-GPU load before _start_diffusion_server() is called. With training active and insufficient free VRAM, the route returns 409 even though this exact zero-layer launch would not offload model layers, so the CPU-only workaround cannot be used during training.

Useful? React with 👍 / 👎.

load_model accepted gpu_memory_mode / gpu_layers but the diffusion branch
returned early without forwarding them, then overwrote the recorded values with
auto / -1. The runner pinned every layer to the GPU, so a GGUF larger than VRAM
OOMed in cudaMalloc even with GPU layers set to 0, and /status reported auto
regardless of what the user picked.

Forward the split to the shim as --ngl in manual mode and record what was
actually applied. Auto mode is unchanged.
@LeoBorcherding
LeoBorcherding force-pushed the fix/diffusion-gpu-layers-offload branch from 0c5f38b to 3253a5b Compare July 28, 2026 19:58

@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: 3253a5bcdb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

# and reload dedup don't report a previous GGUF's manual settings.
self._gpu_memory_mode = "auto"
self._gpu_layers = -1
self._gpu_offload_active = manual_ngl != 0

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 Avoid marking a GPU-visible diffusion runner CPU-only

When gpu_layers=0 on a GPU host, this marks the diffusion child as _gpu_offload_active=False, but the command above still passes a non-empty --gpu token because cpu_only only checks whether GPUs are visible. The training VRAM coordinator treats _gpu_offload_active is False as “holds no VRAM” and skips unloading such GGUF models before training, so a zero-layer DiffusionGemma runner can remain GPU-visible and steal memory from a subsequent training run. Either launch zero-layer diffusion with the CPU/empty GPU token or keep the residency flag conservative until the child is known not to use a GPU.

Useful? React with 👍 / 👎.

- Both already-loaded guards skipped the GPU-memory comparison for diffusion, so
  changing a loaded model from 10 layers to 8 deduped to 'already satisfied' and
  never restarted the shim. They now compare the EFFECTIVE --ngl via a shared
  _diffusion_manual_ngl helper, which also avoids a reload loop: the UI keeps a
  manual preference standing across a diffusion load, so comparing raw modes
  would reload forever.
- --ngl is now gated on _shim_supports_ngl. The unsloth_zoo floor still allows a
  shim without the flag, where argparse would exit before health and fail the
  load outright; that case logs an upgrade hint and drops the flag instead.
- gpu_layers=0 now CUDA-masks the child like a genuine CPU host. Previously it
  set _gpu_offload_active=False while still passing a real --gpu token, and the
  training VRAM coordinator trusts that flag to skip unloading, so a zero-layer
  runner could hold VRAM into a training run.

@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: b9aa7d633f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

# like a genuine CPU host. Leaving a real --gpu token would let the child
# hold a CUDA context while _gpu_offload_active reports False, and the
# training VRAM coordinator trusts that flag to skip unloading (P2).
cpu_only = self._effective_gpu_count() == 0 or manual_ngl == 0

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 Honor CPU masking for zero-layer diffusion GPU picks

When gpu_layers=0 is combined with an explicit GPU selection, this new cpu_only flag does not actually mask the child: _diffusion_gpu_arg() returns the selected gpu_ids[0] before it checks cpu_only, so the runner still receives --gpu <id> while _gpu_offload_active is recorded as false. Fresh evidence in this revision is that zero-layer requests now set cpu_only=True, but the unchanged helper still prioritizes explicit GPU picks, leaving the training VRAM coordinator free to skip unloading a GPU-visible diffusion runner.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
# and Unsloth mode both mean "runner default".
from core.inference.llama_cpp import _diffusion_manual_ngl
loaded_ngl = llama_backend.gpu_layers if llama_backend.gpu_layers >= 0 else None
if _diffusion_manual_ngl(request.gpu_memory_mode, request.gpu_layers) != loaded_ngl:

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 Avoid reloading unsupported diffusion splits forever

When the installed diffusion shim lacks --ngl, _start_diffusion_server() now drops the manual split and records the loaded runner as the default (gpu_layers=-1), but this dedup check still compares the raw request's effective split against None. In that older-shim environment, repeating the same manual request (for example gpu_layers=20) always returns false and restarts the runner even though the split cannot be honored; the fresh evidence is the new compatibility fallback that changes manual_ngl to None before recording state.

Useful? React with 👍 / 👎.

shimmyshimmer and others added 4 commits July 29, 2026 11:08
Follow-up to the layer-split plumbing in this PR. Four behaviours the split
introduced did not hold outside the CUDA happy path.

1. `_gpu_offload_active` was derived from `cpu_only`, which is
   `_effective_gpu_count() == 0`, which is `torch.cuda` and nothing else. That
   reads 0 on a Metal, Vulkan, Windows-HIP or Intel XPU host, all of which ship
   the visual server and will use the GPU, and none of which an empty
   `CUDA_VISIBLE_DEVICES` can mask (Vulkan selects with
   GGML_VK_VISIBLE_DEVICES; Metal has no CUDA runtime at all). The training VRAM
   coordinator treats `False` as "confirmed no VRAM" and skips the unload
   entirely, so a diffusion runner could survive into a training run holding
   memory. `False` is now claimed only for an explicit zero-layer split, which
   is the one case that keeps weights off every backend.

2. `_diffusion_gpu_arg` returned `sorted(gpu_ids)[0]` before it consulted
   `cpu_only`, so `gpu_layers=0` with a GPU picked still handed the child a real
   device while the residency flag said otherwise. A new `force_cpu` outranks the
   picker for a zero-layer request. `cpu_only` deliberately stays below it: it
   only means no device is visible to torch, and an explicit pick is still the
   better answer on a host whose GPU torch cannot see.

3. When the installed shim has no `--ngl` the launcher drops the split and
   records the default, but both dedup guards compared the raw request against
   that recorded default, so the same manual request mismatched forever and
   restarted the runner on every /load. `diffusion_requested_ngl` records what
   was asked for while `gpu_layers` keeps reporting what is running.

4. The active-training preflight never received `gpu_layers`, so a zero-layer
   diffusion load, which places no layers on any device, was still sized as a
   full single-GPU occupant and could be refused with 409. The guard now takes
   the layer count and returns early for that case, and its device probe mirrors
   the loader's override instead of checking only the torch GPU count.

`ValidateModelRequest` gains `gpu_layers` so the preflight sizes the load it is
gating, defaulting to -1 so a client that omits it behaves exactly as before.

Also parse the shim to detect `--ngl` rather than grepping for the literal
`"--ngl"`. The substring test reported support for a shim that merely mentions
the flag in a comment, which sends an argument argparse then rejects, and missed
a shim that quotes it differently, which silently drops the user's split. The
extension check is case-insensitive so a Windows `UNSLOTH_DG_SHIM` pointing at
SHIM.PY inspects the file that is actually about to be spawned.

Auto mode and the Auto slider are untouched: the child command line and the
recorded state are byte-identical to main on every OS and GPU backend.
Most of these assertions matched source text, so they passed on code that does
not work and failed on code that does. `test_zero_layers_masks_the_child_devices`
asserted the string `self._gpu_offload_active = not cpu_only` was present, which
is why the residency bug above went undetected, and which broke the moment that
line was corrected. Both dedup tests were satisfied by the identifier appearing
anywhere in the function, so for the route the import line alone passed them and
the comparison could have been deleted. The "no longer hardcodes auto" test was
two `not in` checks that also pass if the assignments are deleted outright.

They now drive the real functions: the device token for a zero-layer request
with and without an explicit pick, nine dedup transitions including the
unsupported-shim case, and the probe against declarations, comments, docstrings,
alternative quoting and an uppercase extension. The training-guard test checks
the signature and both call sites.

The fixture also left `studio/backend` on `sys.path` for the rest of the
session, shadowing generic top-level names (utils, state, models, hub, auth,
storage) for every later test in the same run; sibling files avoid this
deliberately. It is popped in a `finally` now.

16 tests to 35.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed three commits to this branch, plus a merge of current main.

The layer-split plumbing here is right, and the diagnosis in #7574 holds end to end: I confirmed env["NGL"] = "99" in visual_engine.py:151, that shim.py uses parse_args() so an unknown flag is fatal, and that the binary's own default is 0 with partial offload supported. What follows is about the paths outside the CUDA happy path.

I built a simulation harness that drives _start_diffusion_server with the process layer stubbed, so what gets asserted is the exact argv and environment the child would have received, across [Linux, WSL, macOS, Windows] x [NVIDIA CUDA, AMD ROCm, AMD HIP, Vulkan, Metal, Intel XPU, CPU] for every cell Unsloth ships the visual server for. Three real uv venv sandboxes with unsloth_zoo 2026.6.2, 2026.7.6 and the #958 branch pip-installed cover the compatibility side.

The one that is not in any review comment

_gpu_offload_active was derived from cpu_only, which is _effective_gpu_count() == 0, which is torch.cuda and nothing else. That reads 0 on a Metal, Vulkan, Windows-HIP or Intel XPU host, all of which ship the visual server and will use the GPU. training_vram.py:63 and :408 treat False as "confirmed to hold no VRAM" and skip unload_model() entirely, so a diffusion runner could survive into a training run still holding memory.

It fires on plain auto/-1, not just on a manual split, so on a Mac it would have affected every diffusion load. An empty CUDA_VISIBLE_DEVICES cannot mask those backends either: Vulkan selects devices with GGML_VK_VISIBLE_DEVICES, and Metal has no CUDA runtime involved at all.

False is now claimed only for an explicit zero-layer split, which is the one case that keeps weights off every backend.

The three open Codex P2s

_diffusion_gpu_arg returned the pick before checking cpu_only. manual/0 with GPU 3 and 1 selected produced --gpu 1 while the residency flag said False. A new force_cpu outranks the picker for a zero-layer request. cpu_only deliberately stays below it: it only means no device is visible to torch, and an explicit pick is still the better answer on a host whose GPU torch cannot see. I got this wrong on the first attempt by letting cpu_only outrank the picker too, and the matrix caught it.

Reload loop on an older shim. When the shim has no --ngl the launcher drops the split and records the default, but both guards compared the raw request against that recorded default, so the same manual request mismatched forever. Driving _already_in_target_state three times with an identical manual/20 gave [False, False, False], i.e. three restarts. diffusion_requested_ngl now records what was asked for while gpu_layers keeps reporting what is running, giving [True, True, True], and a genuine 20 -> 8 change still reloads.

409 during training. The preflight never received gpu_layers, so a zero-layer load, which places no layers anywhere, was sized as a full single-GPU occupant. The guard now takes the layer count and returns early for that case, and its device probe mirrors the loader's override instead of checking only the torch GPU count. This needed gpu_layers on ValidateModelRequest (10 tests fail without it, since the field did not exist) and one line in chat-api.ts; it defaults to -1, so a client that omits it behaves exactly as before.

Shim detection

The probe grepped for the literal "--ngl". That reports support for a shim that only mentions the flag in a comment, which sends an argument argparse then rejects, and misses a shim that quotes it differently, which silently drops the split. It parses the source and looks for an actual add_argument now, falling back to a substring scan only when the file will not parse. The extension test is case-insensitive so a Windows UNSLOTH_DG_SHIM pointing at SHIM.PY inspects the file that is about to be spawned rather than falling through to the installed package.

Tests

Most assertions matched source text, so they passed on code that does not work and failed on code that does. test_zero_layers_masks_the_child_devices asserted the string self._gpu_offload_active = not cpu_only was present, which is why the residency bug went undetected and which broke the moment that line was corrected. Both dedup tests were satisfied by the identifier appearing anywhere in the function, so for the route the import line alone passed them. They drive the real functions now, 16 tests to 35, and the fixture no longer leaves studio/backend on sys.path for the rest of the session.

Compatibility

All four upgrade orders launch a child that starts, verified by lifting each install's real argparse block out with ast and running it as a subprocess:

order sends --ngl child starts
neither upgraded no yes
zoo first, old Studio no yes
Studio first, old zoo no yes
both upgraded yes yes

Studio-first is the one that mattered, and against today's released zoo (2026.7.6, which is also the pyproject floor) the argv is byte-identical to main. A zoo upgrade mid-session is picked up on the next load without a restart, since the probe runs per launch. Zoo #958 needs no changes and can merge first as you suggested.

Auto mode is untouched: 45 of 45 non-manual launches are byte-identical to main on argv, offload flag and recorded state, in every cell.

Verification

10 simulations, 120 checks. Studio backend suite 11585 passed, 1 failed, that one being test_text_io_encoding[run.py] which fails identically on main (from #7577, unrelated). Repo studio tests 109 passed, ruff clean, verify_import_hoist clean, frontend typecheck and its 26 tests pass.

Your four red CI jobs were the stale-base bitsandbytes collection error that #7580 already fixed, not anything in this diff. The merge of main in this push clears them.

# Conflicts:
#	studio/backend/routes/inference.py

@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: a919fbddc5

ℹ️ 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 +4766 to +4768
diffusion_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers) if is_gguf else None
if is_gguf and diffusion_kind is not False and diffusion_ngl == 0:
return

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 Keep the training guard when zero-layer fallback is unsupported

When training is active and the installed diffusion shim lacks --ngl, a manual gpu_layers=0 request returns here without a VRAM check, but _start_diffusion_server() subsequently drops the unsupported split and launches the shim's default GPU-resident configuration. That load can contend with or OOM the active training job despite this guard treating it as CPU-only. Fresh evidence in this revision is the compatibility fallback that changes manual_ngl to None; only bypass the guard after confirming the resolved shim can actually apply zero layers.

Useful? React with 👍 / 👎.

Comment on lines +1751 to +1754
if len(shim_cmd) >= 2 and str(shim_cmd[-1]).lower().endswith(".py"):
candidates = [Path(shim_cmd[-1])]
else:
candidates = []

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 Probe the actual shim override regardless of its suffix

When UNSLOTH_DG_SHIM points to an extensionless or .pyw Python file, _find_diffusion_assets() accepts and launches that exact file, but this suffix check ignores it and instead probes the installed package or a sibling named shim.py. Consequently a capable custom shim may silently lose the requested layer split, or an incapable custom shim may receive --ngl and fail argument parsing. Fresh evidence in this revision is that the new source probe selects overrides only by a .py suffix even though the existing resolver accepts any file; probe shim_cmd[-1] whenever the command represents the file override.

Useful? React with 👍 / 👎.

@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: 8bed9acb0d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// Only 0 changes the verdict: a zero-layer DiffusionGemma split places no
// layers on any device, so validate must not refuse it during training when
// /load would accept it.
gpu_layers: payload.gpu_layers,

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 Pass GPU layers into validation call sites

Fresh evidence in this revision is that this new field is forwarded only if the caller supplies it, but the GGUF validation payloads in use-chat-model-runtime.ts and shared-composer.tsx still send gpu_memory_mode without the matching gpu_layers even though their subsequent /load calls pass loadGpuLayers/effectiveGpuLayers. For a manual DiffusionGemma load with gpu_layers=0 while training is active, /validate therefore defaults to -1 and can still return 409 before the /load path that would CPU-mask the runner is reached; add the same layer value to those validation payloads (and the auto-load preflight if it can load remembered manual splits).

Useful? React with 👍 / 👎.

Comment on lines +5772 to +5773
self._gpu_memory_mode = gpu_memory_mode if manual_ngl is not None else "auto"
self._gpu_layers = manual_ngl if manual_ngl is not None else -1

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 Preserve diffusion manual mode during hydration

Once this can report manual for a loaded DiffusionGemma, the frontend hydration helper still treats every diffusion response as mode-agnostic and skips adopting gpuMemoryMode when resp.is_diffusion is true (chat-runtime-store.ts:751-756). After a browser refresh/status hydration of a zero-layer diffusion runner, the store can keep the persisted auto mode while adopting gpuLayers=0; the next Apply/load then sends gpu_memory_mode=auto, so _diffusion_manual_ngl resolves to the runner default and reloads the model back onto GPU. Update the diffusion frontend hydration/persistence path together with this new backend echo.

Useful? React with 👍 / 👎.

Comment on lines +4844 to +4846
diffusion_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers) if is_gguf else None
if is_gguf and diffusion_kind is not False and diffusion_ngl == 0:
return

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 Account for diffusion splits in the training guard

Now that manual DiffusionGemma loads can pass a positive --ngl, only the zero-layer case is handled here; any positive split falls through to _estimate_gguf_required_gb, which sizes the whole GGUF and then compares that full footprint against one selected GPU. With training active and a request such as gpu_layers=20 for a model whose full GGUF exceeds the remaining VRAM but whose 20-layer offload fits, /validate or /load can still return 409 even though the launched runner would place the rest on CPU. Use diffusion_ngl to size the offloaded portion before applying the coexistence guard.

Useful? React with 👍 / 👎.

The merge push and the pre-commit.ci formatting push landed two minutes apart,
so the concurrency groups cancelled all 46 checks on this head before any of
them reported.
@danielhanchen

Copy link
Copy Markdown
Member

CI triage on fdafdf437. 36 green, 6 red, and none of the six are attributable to this diff. Details so they can be checked rather than taken on trust.

(Python 3.10 / 3.11 / 3.12 / 3.13) are all the same single assertion:

FAILED tests/test_text_io_encoding.py::test_text_io_names_its_encoding[run.py]
  run.py:805: subprocess(text = True) without encoding

studio/backend/run.py is not touched here. It fails identically on a clean origin/main checkout, and the offending line arrived in #7577.

Repo tests (CPU) is 3 failed, 745 passed, and all three are in unsloth_cli/tests/test_start.py:

test_start_rejects_invalid_gpu_memory_mode
test_hermes_resume_oneshot_rejects_usage_file[--usage-file]
test_hermes_resume_oneshot_rejects_usage_file[--usage-file=usage.json]

They assert on Click's error text and are getting the generic Usage: ... Try '--help' block instead. git diff origin/main...HEAD -- unsloth_cli is empty, so the code and the tests are byte-identical to main; all three pass locally on both this branch and a clean origin/main worktree against click 8.4.2. CI is resolving a newer click whose parameter-validation output differs. The first one names --gpu-memory-mode, which looks related to this PR but is the CLI's own flag parsing and is untouched here. Worth a separate look given #7598 only recently started running these in Backend CI.

Chat UI Tests is the floating live monitor geometry:

AssertionError: [ui] FAIL: content growth bottom inset: expected 884, got 932.0

932 - 884 is 48, exactly the height of the probe element the test appends, so the monitor is growing past its bottom inset instead of holding it. That assertion came in with #7579, which landed after the last green Mac Studio UI run on main (076c96572, 05:31), so main's own CI has not exercised it yet. The entire frontend delta on this branch against main is one JSON field in a fetch body:

       gpu_memory_mode: payload.gpu_memory_mode,
+      gpu_layers: payload.gpu_layers,
       n_parallel: payload.n_parallel,

There is no path from that to a pixel geometry assertion on a floating monitor.

For the record, locally against the merged tree: studio backend suite 12712 passed with the one run.py failure above, repo studio tests 109 passed, tests/studio/test_diffusion_gpu_layers_contract.py 35 passed, ruff clean, verify_import_hoist clean, frontend typecheck and its 26 tests pass, and the 10 simulations re-run green after the merge.

The two Re-trigger CI and merge commits are mine: the first push and the pre-commit.ci formatting push landed two minutes apart and the concurrency groups cancelled all 46 checks before any reported.

The training guard and validate path now reason about what the launcher will
actually run, not what was asked:

- The zero-layer bypass and the new positive-split scaling are gated on
  diffusion_split_supported(), a mirror of the launch gate. A split the shim
  cannot accept is guarded as the default GPU-resident configuration, so a
  manual/0 request against an old unsloth_zoo no longer skips the VRAM check
  while the child takes a whole GPU.
- A confirmed-diffusion positive split is sized as its GPU share
  (ngl/n_layers of the estimate) instead of the whole file, so gpu_layers=20
  during training no longer 409s a load that fits. Unknown layer count keeps
  the full, conservative estimate.
- _shim_supports_ngl keys on the argv shape instead of a .py suffix: an
  extensionless or .pyw UNSLOTH_DG_SHIM override is the file about to be
  spawned and is now the file probed.
- Both frontend validate call sites now send gpu_layers alongside
  gpu_memory_mode, so validate reaches the same verdict as the /load that
  follows it.
- Status hydration adopts gpuMemoryMode for a diffusion runner that reports
  manual (a split was actually applied); a diffusion auto response still
  leaves the standing preference alone, so the old no-loop behaviour holds.

@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: 52ce26443c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1776 to +1777
if extra_pythonpath:
candidates.append(Path(extra_pythonpath) / "shim.py")

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 Probe only the overridden shim file

When UNSLOTH_DG_SHIM points to a custom-named file, _find_diffusion_assets() executes that exact path and passes its directory as extra_pythonpath; appending <dir>/shim.py here means a sibling shim.py that supports --ngl can make the probe return true even if the override itself does not. Fresh evidence in this revision is this unconditional extra-PYTHONPATH candidate, which can still make manual DiffusionGemma loads append --ngl to an incompatible override and fail argparse instead of using the compatibility fallback.

Useful? React with 👍 / 👎.

// Only 0 changes the verdict: a zero-layer DiffusionGemma split places no
// layers on any device, so validate must not refuse it during training when
// /load would accept it.
gpu_layers: payload.gpu_layers,

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 gpu_layers in auto-load preflight

Fresh evidence in this revision is that chat-adapter.ts still computes effectiveGpuLayers and sends it to /load, but its background canAutoLoad validation payload only includes gpu_memory_mode; since this new serializer only forwards payload.gpu_layers when callers provide it, /api/inference/validate defaults to -1. A remembered manual DiffusionGemma split, especially gpu_layers=0 during active training, can therefore be rejected by validation before the follow-up load that would CPU-mask or partially offload it.

Useful? React with 👍 / 👎.

// Sized like the follow-up /load: without it a manual
// DiffusionGemma split is validated as a full-GGUF occupant
// and 409s during training even when the split fits.
gpu_layers: validateGpuLayers,

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 model-config loads to keep diffusion splits

When the pending load comes from the model-config page for a DiffusionGemma, withoutUnsupportedDiffusionSettings still resets gpuMemoryMode to auto and drops gpuLayers before pendingLoadConfig reaches this validation/load path (model-config-page.tsx:112-133, 988-1054), and the GPU controls are hidden for diffusion there. That means this new gpu_layers wiring is unreachable from the Studio model-settings flow: a configured 0-layer or partial split is validated and loaded as Auto/-1, so the model can still OOM despite the backend support.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and the only one of the seventeen still live at 6c53f07. The wiring lands but nothing can reach it from the model-settings flow: model-config-page.tsx:370 hides the GPU Memory row for diffusion, :418 hides the layer slider, and :131 strips the saved config back to auto/undefined before onRun, so pendingLoadConfig always arrives as auto.

Leaving it as an explicit follow-up rather than fixing it here, because unhiding those controls is a product decision, not a correctness one: the backend only honours --ngl when diffusion_split_supported() is true, so an exposed slider silently no-ops against a shim without the flag. Worth deciding alongside the unsloth-zoo#958 release.

# keep reporting reality (_gpu_layers), but the dedup guards have to compare
# like with like, or the same unsatisfiable request mismatches the recorded
# default forever and restarts the runner on every /load.
self._diffusion_requested_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers)

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 Recheck shim support before deduping fallback splits

When a manual DiffusionGemma load first runs with an old shim, manual_ngl is dropped but this records the unsatisfied request as diffusion_requested_ngl; after the user upgrades unsloth_zoo in the same Studio session, pressing Apply again with the same layer count still dedupes as already loaded instead of restarting with the now-supported --ngl. Store whether the split was actually supported, or make the dedup guard reload when current shim support has changed.

Useful? React with 👍 / 👎.

gpu_memory_mode: effectiveGpuMemoryMode,
// Sized like the load below: a manual DiffusionGemma split must
// not be validated as a full-GGUF occupant during training.
gpu_layers: effectiveGpuLayers,

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 Honor diffusion GPU splits in compare loads

For compare-pane loads, the code just above this payload still forces effectiveGpuMemoryMode to "auto" and effectiveGpuLayers to GPU_LAYERS_AUTO whenever resolvedIsDiffusion is true, so the newly forwarded gpu_layers value is always -1 for DiffusionGemma. A pane with a remembered/manual 0-layer or partial split is therefore validated and loaded as the default all-GPU runner, which can still OOM or be refused during training despite the backend split support.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at 839eb61, which dropped the resolvedIsDiffusion ? GPU_LAYERS_AUTO forcing.

Flagging a regression that removal introduced, now fixed in the commit above this reply: with the pin gone the fallback is an unguarded ownConfig.gpuLayers ?? compareLoadKnobs.gpuLayers, and DEFAULT_PER_MODEL_CONFIG defines neither gpuMemoryMode nor gpuLayers, so an unconfigured diffusion pane inherits the live store, i.e. whatever chat GGUF was loaded at Send. Set Manual + 12 layers on a normal GGUF, add a never-configured DiffusionGemma to compare, Send, and the runner gets --ngl 12. A standing 0 is worse: force_cpu masks the pane's devices. The pane's own split is still sent, only the inherited snapshot is refused.

…more call sites

- _shim_supports_ngl no longer consults a sibling shim.py next to a file
  override: the override itself is what argparse will run, and a capable
  sibling vouching for an incapable custom-named shim re-created the exact
  startup failure the probe exists to prevent. The extra_pythonpath
  parameter is gone; it could only ever name that sibling.
- A dropped split now un-sticks after a mid-session unsloth_zoo upgrade:
  both dedup guards re-probe shim support when the recorded state shows the
  ask was not applied, so an identical Apply finally reloads with --ngl.
  The probe only runs in that narrow state, keeping the no-loop behaviour
  against a shim that stays old.
- chat-adapter's background auto-load preflight now sends gpu_layers, the
  third validate call site: a remembered manual split (0 in particular) was
  still being sized as a full-GGUF occupant during training.
- Compare panes no longer force a diffusion pane to auto/-1: the runner
  honours the layer split now, so panes pass gpuMemoryMode/gpuLayers
  through like every other GGUF. MoE offload and tensor parallel stay
  forced off; the runner has no equivalent knobs.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed 52ce26443 and 839eb619e, addressing the five findings from the review of 8bed9acb0d / a919fbddc5 and then the five from the follow-up review of 52ce26443. Nine fixed, one deferred with rationale below.

Round on 8bed9acb0d / a919fbddc5 (fixed in 52ce26443)

  • Zero-layer bypass on an old shim: the training guard's early return and the split-scaled estimate are both gated on a new diffusion_split_supported(), which resolves the same shim assets as _start_diffusion_server and probes them. A split the launcher will drop is guarded as the default GPU-resident configuration.
  • Positive split sized as the whole file: a confirmed-diffusion manual split is sized as ngl/n_layers of the estimate, so gpu_layers=20 during training no longer 409s a load that fits. Unknown layer count (uncached remote GGUF) keeps the full, conservative estimate.
  • Probe suffix check: _shim_supports_ngl keys on the argv shape (-m module form vs file override) instead of a .py suffix, so an extensionless or .pyw UNSLOTH_DG_SHIM is the exact file probed.
  • Validate call sites: use-chat-model-runtime.ts and shared-composer.tsx now send gpu_layers with gpu_memory_mode.
  • Hydration: the store adopts gpuMemoryMode for a diffusion runner reporting manual; a diffusion auto response still leaves the standing preference alone, keeping the no-loop behaviour.

Round on 52ce26443 (fixed in 839eb619e)

  • Sibling shim.py vouching for a custom override: the probe no longer consults extra_pythonpath; a file override is probed as the exact file argparse will run, nothing else. The parameter is gone since it could only ever name that sibling.
  • Dedup sticking after a mid-session zoo upgrade: both guards re-probe shim support when the recorded state shows the ask was not applied, so an identical Apply reloads and finally applies --ngl. The probe runs only in that narrow dropped-split state, so the no-loop behaviour against a shim that stays old holds (covered by test_zoo_upgrade_reloads_a_dropped_split).
  • Third validate call site: chat-adapter's background auto-load preflight now sends gpu_layers, so a remembered manual split (0 in particular) is no longer sized as a full-GGUF occupant during training.
  • Compare panes forcing diffusion to auto: panes now pass gpuMemoryMode/gpuLayers through like every other GGUF; MoE offload and tensor parallel stay forced off since the runner has no equivalent knobs.

Deferred: model-config page still strips diffusion splits

The finding is correct: withoutUnsupportedDiffusionSettings resets a remembered split to Auto on the config-page load path, and that page hides the GPU Memory controls for diffusion entirely. But the stripper is threaded through the page's baseline/dirty math, save/forget persistence, the fixed-layer context pin, and the Vulkan-pick reconciliation, and unhiding the controls is a product decision about what that page should expose for diffusion. Doing it as a strip-removal inside this PR risks the settings surface Daniel just reworked. Proposing it as a follow-up; the chat settings sheet path (which the reporter validated) and compare panes now both honour splits.

Confirmation from the reporter

The reporter installed both branches on the failing machine (RTX 4050 laptop, 6 GB VRAM, Ubuntu, unsloth 2026.7.5 + unsloth_zoo 2026.7.6) and confirms the manual split now loads the model, with the CPU-offload warning showing.

Tests 35 → 48. Ruff, verify_import_hoist, and the frontend typecheck are clean.

@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: 839eb619e8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// still honors the user's choice. But "manual" means a layer split was
// actually applied (#7574): adopt it, or a refresh hydrates the store back
// to the persisted "auto" while the runner is serving a manual split.
...(resp.is_diffusion && mode !== "manual" ? {} : { gpuMemoryMode: mode }),

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 Preserve diffusion layer count after shim fallback

When an older diffusion shim drops a manual split, the backend responds with gpu_memory_mode="auto"/gpu_layers=-1 while keeping the requested diffusion_requested_ngl internally so a same request can be applied after a mid-session unsloth_zoo upgrade. Fresh evidence here is that this adoption path preserves only gpuMemoryMode; the non-manual branch above resets gpuLayers to -1 when load/status responses are applied, so after the upgrade the next Apply sends manual/-1 instead of the original split and the backend re-probe cannot ever emit --ngl for it. Preserve the standing layer count for diffusion auto fallbacks too, or echo the requested split.

Useful? React with 👍 / 👎.

LeoBorcherding and others added 3 commits July 29, 2026 18:45
When an older shim drops a manual split, the backend reports auto/-1 (what
ran) while keeping the ask in diffusion_requested_ngl. Hydration preserved
the standing gpuMemoryMode for that response but still reset the editable
gpuLayers to Auto, so the next Apply sent manual/-1 and the ask could never
be applied, even after the unsloth_zoo upgrade that adds --ngl. The
non-manual reset now skips gpuLayers for diffusion, mirroring the standing
mode; loaded baselines and the MoE/split knobs still reset.
main pinned a diffusion compare pane to auto/-1:

    const effectiveGpuMemoryMode =
      resolvedIsDiffusion ? "auto" : (ownConfig.gpuMemoryMode ?? compareLoadKnobs.gpuMemoryMode);

This PR removed the pin so a pane's own saved split can be honoured, but the
replacement is an unguarded ?? chain and DEFAULT_PER_MODEL_CONFIG defines neither
gpuMemoryMode nor gpuLayers. An unconfigured diffusion pane therefore falls
through to compareLoadKnobs, which is a snapshot of the live store, i.e. whatever
chat GGUF was loaded at Send, whose layer count is bounded by that model.

Repro in one session: set Manual + 12 layers on a normal chat GGUF, open compare,
add a never-configured DiffusionGemma, Send. The runner launches with --ngl 12. A
standing 0 is worse: force_cpu masks the pane's devices and it runs entirely on
CPU without being asked. No diffusion UI can show or clear the inherited value,
because the mode row and the layer slider are hidden for diffusion.

The pane's OWN split is still sent, so the feature this PR adds is intact; only
the inherited snapshot is refused. nCpuMoe and tensorParallel two lines below
already guard on resolvedIsDiffusion the same way.

The rule moves to a dependency-free module so it can be unit-tested: the frontend
runner is node --experimental-strip-types with no @/ alias resolution, so
chat-runtime-store.ts is not importable from a test. GPU_LAYERS_AUTO moves with
it and is re-exported, so every existing import path keeps working.
…plit

The zero-layer bypass used `diffusion_kind is not False`, which also exempts an
UNCLASSIFIED GGUF. _classify_diffusion_gguf returns None whenever the header is
unreadable and the name lacks the family, so an uncached HF-repo GGUF loaded at
manual/0 while training is active skipped the VRAM estimate entirely.

That is unsafe for an ordinary GGUF: --gpu-layers 0 is not zero VRAM when a
device pin, surviving tensor mode, an mmproj or a GPU drafter keeps it resident,
which is exactly what LlamaCppBackend._zero_offload_keeps_gpu_visible exists to
report. The scaling block sixty lines below already refuses an unknown
classification for the same reason, and says so in its comment, so the two were
contradicting each other.

A DiffusionGemma the user actually downloaded classifies True either by name or
by header, so nothing this PR adds is lost.

Adds two behavioural cases: a confirmed diffusion split at ngl 0 still bypasses,
an unclassified GGUF at ngl 0 still raises 409. The second fails against the old
condition.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

The compare pane re-probes only when sel.isDiffusion is undefined, but the
model-config page collapsed an inconclusive probe to a definite false before
handing it to onRun:

  classifiedIsDiffusion = isDiffusion ? true : stagedDims?.isDiffusion

For an uncached GGUF whose name carries no family that is false, which flows
through the selection into the pane, skips the re-probe, and leaves
diffusionUnknown false. The pane then inherits the other model's manual layer
count, which /load applies once the downloaded header turns out to be diffusion.
Same leak as the last fix, through a different entry point.

resolveStagedDiffusionClassification keeps the answer tri-state, so an
inconclusive probe stays undefined and the pane's existing preflight re-probes
and learns diffusion_unknown. A conclusive answer is unchanged in both
directions, and the page's own resolvedIsDiffusion still tests === true, so no
GPU control changes visibility.
@danielhanchen

Copy link
Copy Markdown
Member

@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: f77342fdc3

ℹ️ 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 +4948 to +4949
required_override_gb = _scale_diffusion_required_gb(
required_override_gb, diffusion_ngl, _gguf_layer_count(config)

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 Scale uncached diffusion splits before applying the guard

For an uncached Hugging Face DiffusionGemma GGUF, _estimate_gguf_required_gb can obtain the remote file size, but _gguf_layer_count(config) returns None because it only reads a locally cached file; _scale_diffusion_required_gb consequently keeps the full estimate. With training active, a positive manual split that would fit is therefore still rejected with 409 until the model has already been downloaded. Fresh evidence beyond the earlier positive-split report is that the new scaling path explicitly falls back to the full footprint when this local-only layer probe cannot resolve the remote model.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and the reasoning is sharper than the code's own comment. I confirmed both halves: _gguf_layer_count documents itself as "or None (remote / unreadable)" and only stats a local path, and _scale_diffusion_required_gb returns required_gb untouched when not n_layers. The block's comment only anticipated an unknown classification, but diffusion_kind is True also holds for an uncached model matched by name, so confirmed-diffusion plus None layer count is a real combination that keeps the full footprint.

I am not fixing it here, deliberately.

Scaling needs a true layer count. The only way to get one for a model that is not on disk is a remote GGUF header read, which this codebase has no helper for (read_gguf_staged_dims is local-only), and adding range-request header parsing inside the training guard is a much larger and riskier change than this PR should carry. The alternative, scaling by an assumed layer count, is worse than the current behaviour: guessing low would under-reserve and let a diffusion load OOM an active training run, whereas the present behaviour fails safe by refusing a load that might not fit.

It is also not a regression. Before this PR there was no diffusion scaling at all, so an uncached model with a positive split sized as the full file and 409'd exactly as it does now. This PR strictly improves the cached case and leaves the uncached case where it was.

So: a real limitation, worth a follow-up once a remote header probe exists, but not a defect this PR introduces or should grow to cover.

// DROPPING a manual split (the ask lives in diffusion_requested_ngl).
// Resetting the slider would turn that ask into manual/-1, unapplyable
// even after the unsloth_zoo upgrade that adds --ngl.
...(resp.is_diffusion ? {} : { gpuLayers: GPU_LAYERS_AUTO }),

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 Echo dropped diffusion splits during status hydration

When an old shim drops a manual split and the browser is refreshed, the new store starts with gpuLayers=-1, while /status reports only the applied Auto/-1 state; omitting gpuLayers from this patch merely preserves that new default rather than recovering the backend's _diffusion_requested_ngl. After the shim is upgraded, the next load therefore sends manual/-1 instead of the original count, so the dedup retry intended to apply the newly supported split cannot run. Fresh evidence beyond the earlier fallback-hydration report is that this fix preserves only existing in-memory state and adds no requested-split field to the response.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct on the facts. I checked: diffusion_requested_ngl is a backend property read in exactly one place (routes/inference.py, the dedup comparison) and appears on no response model, so the store comment pointing at it describes something the browser genuinely cannot see. After a refresh the in-memory count is gone and /status reports only the applied Auto/-1, so the post-upgrade re-apply has nothing to re-apply.

I am leaving this one for @LeoBorcherding to decide rather than fixing it unilaterally, because the fix is new public API surface, not a correction.

Recovering the ask means adding a requested-split field to InferenceStatusResponse (and LoadResponse for the load path) plus hydration logic to adopt it. That is a small diff but it is wire surface whose only purpose is a transient window: it exists solely for a shim without --ngl, which stops happening once unsloth-zoo#958 ships. It also fails safe today, the runner serves Auto rather than a wrong split, and the recovery still works without a refresh since the in-memory value survives.

Worth noting the reachability too: the GPU controls are hidden for diffusion in the model-config UI, so a manual diffusion split cannot be entered from that flow at all right now (see the earlier thread on that). Until that product question is settled, the split this would recover mostly cannot be set in the first place.

Happy to add the field if you would rather close the loop inside this PR.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed after all, in 528e778: on reflection this is a completeness gap in a mechanism this PR introduced, not a product question, so it should not have been left to you.

LoadResponse and InferenceStatusResponse now carry diffusion_requested_ngl, and recoverDroppedDiffusionSplit restores it during hydration, re-asserting manual mode so the next Apply re-sends the count. Zero is preserved as the real CPU-only ask rather than read as absent, and an applied split (mode === "manual") is left authoritative so nothing is recovered over it.

Both fields default to None and the frontend reads them optionally, so a backend without them behaves exactly as before.

Six new cases in studio/frontend/tests/gpu-placement.test.ts plus two wiring tests in tests/studio/test_diffusion_gpu_layers_contract.py. The wiring pair asserts both response models declare the field and that every response reporting is_diffusion from the backend also reports the ask, so a future response site that forgets it reddens. Both fail against the previous code.

@danielhanchen

Copy link
Copy Markdown
Member

Round 7 triage. Both new items are correct; neither is being fixed in this PR, and I want the reasoning on the record rather than implied by silence.

Uncached diffusion split keeps the full footprint (routes/inference.py:4949). Confirmed: _gguf_layer_count only stats a local path, and _scale_diffusion_required_gb returns the estimate untouched when the count is None. The sharp part of the catch is that diffusion_kind is True also holds for an uncached model matched by name, so confirmed-diffusion with an unknown layer count is reachable, which the block's comment did not anticipate.

Not fixed because scaling needs a real layer count, and the only source for a model that is not on disk is a remote GGUF header read that this codebase has no helper for. Assuming a count instead would be worse than the current behaviour: guessing low would under-reserve and let a diffusion load OOM an active training run, where today it fails safe by refusing. It is also not a regression, since before this PR there was no diffusion scaling at all and the uncached case sized as the full file exactly as it does now.

Requested split not recoverable after a refresh (chat-runtime-store.ts:751). Confirmed: diffusion_requested_ngl is read in exactly one place server-side and is on no response model, so the comment pointing at it describes something the browser cannot reach.

Left for @LeoBorcherding to decide, because the fix is new public API surface rather than a correction: it means adding a requested-split field to InferenceStatusResponse and LoadResponse plus hydration to adopt it. That surface exists only for a shim without --ngl, which stops happening once unslothai/unsloth-zoo#958 ships, it fails safe today, and the recovery already works without a refresh. It also interacts with the open question on this PR about the diffusion GPU controls being hidden in the model-config UI: while they are hidden, the split this would recover largely cannot be set in the first place. Say the word and I will add the field.

Both are worth follow-ups; I do not think either should grow this PR further.

Verification at f77342fdc: staging CI green and closed (backend 9/9; ubuntu + macos-14 + windows + Playwright 13/13), tests/studio/ 2148 passed, frontend 50/50, typecheck clean, ruff clean.

Separately, Repo tests (CPU) is red on main itself for a reason outside this PR: tests/sh/test_tauri_retry_failure_context.sh fails on two assertions about explicit exits bypassing the setup failure helpers. #7644 fixes that and unblocks the job for every open PR.

A shim without --ngl cannot apply a manual split: the runner reports Auto while
the backend keeps the ask in _diffusion_requested_ngl. That value never reached
the client, so the recovery only worked while the in-memory store survived. After
a browser refresh the store starts at Auto and /status reports Auto, the ask is
gone, and the next Apply sends manual/-1 -- which the retry that exists to apply
the split after an unsloth_zoo upgrade can never turn back into the original
count.

LoadResponse and InferenceStatusResponse now carry diffusion_requested_ngl, and
recoverDroppedDiffusionSplit restores it during hydration, re-asserting manual
mode so the next Apply can re-send the count. Zero is preserved as the real
CPU-only ask it is.

Both fields default to None and the frontend reads them optionally, so a backend
without them behaves exactly as before.
@danielhanchen

Copy link
Copy Markdown
Member

@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: 04410ce724

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Outdated
diffusion_gpu = LlamaCppBackend._diffusion_gpu_arg(
requested_gpu_ids,
cpu_only = LlamaCppBackend._effective_gpu_count() == 0,
force_cpu = diffusion_ngl == 0,

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 Keep unknown zero-layer GGUFs in the guard

When diffusion_kind is None (for example an uncached/renamed GGUF whose header cannot be read yet), a manual gpu_layers=0 request skips the confirmed-diffusion early return above but still passes force_cpu=true here. That makes _diffusion_gpu_arg return an empty token, and can_load_chat_during_training treats an empty single_device_gpu as CPU-only and allows the load; if the downloaded GGUF turns out to be an ordinary model, llama-server can still keep GPU memory visible with --gpu-layers 0 via a device pin, mmproj, drafter, or tensor state while training is active. Gate this CPU token on diffusion_kind is True, or avoid passing a single-device CPU token for unknown GGUFs so they stay conservatively estimated.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and this one is squarely my miss: I hardened the early return to is True in an earlier round and left the sibling force_cpu on the same condition. Fixed in 4a01247.

I traced the consequence you describe rather than taking it on the summary. routes/training_vram.py short-circuits an empty single_device_gpu:

token = str(single_device_gpu).strip()
if not token:
    return True, {"mode": "single_device", "reason": "cpu_only"}

so an unclassified GGUF at manual/0 was allowed during training unconditionally, on an assumption that only holds for a confirmed diffusion model. The comment above the early return already states why it does not hold: a device pin, tensor mode, mmproj or a GPU drafter keeps an ordinary GGUF resident at --gpu-layers 0.

I dropped force_cpu at that call site rather than gating it on diffusion_kind is True. Reaching it with ngl == 0 now implies an unclassified GGUF, because the confirmed case returns above, so the gated flag could only ever evaluate False and would have been dead code. The picker chooses a device instead and the load stays conservatively sized.

Worth flagging why the existing test_zero_layer_unclassified_gguf_still_hits_the_training_guard did not catch this: it stubs can_load_chat_during_training, so the empty-token branch never executes, and it asserted only that the guard was reached. The new test asserts the token it was reached with, and fails against the previous code with single_device_gpu was ''.

The confirmed-diffusion early return was hardened to `is True`, but the
force_cpu on the _diffusion_gpu_arg call sixty lines below still keyed off
`diffusion_ngl == 0` alone. An unclassified GGUF therefore skipped the early
return, as intended, and then handed the guard an empty device token anyway.
can_load_chat_during_training reads an empty single_device_gpu as a CPU-only
runner and returns True unconditionally, so the load was allowed during training
on an assumption that only holds for a real diffusion model. The comment above
the early return already gives the reason it does not: a device pin, tensor
mode, mmproj or a GPU drafter keeps an ordinary GGUF resident at --gpu-layers 0.

Drop force_cpu at this call site rather than gating it. Reaching it with ngl 0
now implies an unclassified GGUF, since the confirmed case returns above, so the
flag could only ever be False. The picker then chooses a device and the load
stays conservatively sized.

The existing unclassified-zero test could not catch this: it stubs can_load, so
the empty-token branch never ran, and it asserted only that the guard was
reached. The new test asserts the token it was reached with.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4a0124741a

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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: be076635ad

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

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Merged current main in. No conflicts; the diff against main is the same 17 files as before.

Reporter confirmation from #7574: adrir ran this branch together with unslothai/unsloth-zoo#958 on the affected machine (RTX 4050 laptop, 6 GB VRAM, native Ubuntu, unsloth 2026.7.5 / unsloth_zoo 2026.7.6 baseline) and the manual split loads the model with the offload warning showing.

CI triage on the pre-merge head be076635, since the six red are worth checking rather than taking on trust. All six reproduce on main at c670340e or are infra:

  • Backend CI py3.10-3.13 (4 jobs) are one shared pair of assertions in tests/test_setup_llama_cpp_backend.py (test_explicit_vulkan_prebuilt_failure_does_not_change_backend, test_explicit_vulkan_source_build_fails_closed). Identical failures on main run 30576158948. This branch touches no installer scripts.
  • Core (HF=latest + TRL=latest): tests/utils/test_packing.py::test_enable_sample_packing, AttributeError: '_DummyTrainer' object has no attribute 'data_collator'. Also red on main run 30576159010.
  • Windows Unsloth UI CI is not a test failure. Both suites logged PASS comprehensive UI flow and PASS extra UI flow; the job died on the actions/upload-artifact step with no output. Same workflow passed on 6c53f078 and edde8dcc. The push above re-runs it.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@LeoBorcherding LeoBorcherding self-assigned this Jul 31, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Studio UI: before / after

This PR changes 10 frontend files, so here is what that does and does not do to the rendered UI. Two fully isolated Studios via UNSLOTH_STUDIO_HOME, main on :8901 and this branch on :8902, sharing one HF cache, driven headless with Playwright against the real unsloth/diffusiongemma-26B-A4B-it-GGUF (Q4_K_M) and unsloth/gemma-3-270m-it-GGUF (UD-Q4_K_XL).

Why there is no visible change for a diffusion model

ordinary GGUF vs DiffusionGemma

Left is an ordinary GGUF, right is DiffusionGemma, both on this branch. The GPU Memory row between Tensor Parallelism and GPUs is present on the left and absent on the right, because model-config-page.tsx hides both the mode row and the layer slider for diffusion:

:371   <div className={isDiffusion ? "hidden" : ROW_CLASS}>   // mode row
:419   {!isDiffusion && isManual && (                          // layer slider

GpuMemorySettings is the only component that renders them, and both the model-config page and the chat sidebar route through it. So the store changes in this PR feed controls that are hidden exactly when they would differ. That is the same product question already open on this PR: the backend wiring lands, but no diffusion split can be entered from this flow while the controls are hidden.

Diffusion model, before vs after

diffusion before after

Pixel diff: 34 differing pixels out of 900,000, max per-channel delta 10, zero pixels above delta 40. That is anti-aliasing noise, not content.

Ordinary GGUF, before vs after

normal before after

Pixel diff: 82 differing pixels, of which 31 exceed delta 40. Those 31 are a 2x16 px vertical bar at x=766-767 that is background in one shot and #242424 / #4486C6 in the other: a blinking text caret in the Parallel Slots input, caught in different blink phases. Content is identical (32768, f16, auto).

What these shots do NOT cover

The one genuinely user-visible behaviour change is not shown here: a compare pane loading an uncached GGUF now uses Auto placement instead of inheriting the active model's Manual + N layers, because an undownloaded GGUF comes back diffusion_unknown and must not be treated as ordinary. Capturing that needs a two-model compare run with real loads, which I did not do.

@danielhanchen
danielhanchen merged commit eb92c60 into unslothai:main Aug 1, 2026
46 of 49 checks passed
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.

[Bug] DiffusionGemma: GPU-layer setting is ignored, hardcoded NGL=99 forces a full-VRAM load

3 participants