Skip to content

Studio Images: per-load engine choice for GGUF picks (native sd.cpp for LoRA) - #14232

Merged
danielhanchen merged 9 commits into
mainfrom
studio-images-engine-choice
Oct 19, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
studio-images-engine-choice

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Closes #9295.

Summary

On a GPU host a GGUF image model always loads on diffusers, and a GGUF run as-is there cannot take a LoRA, so Studio hides the LoRA controls. The native sd.cpp engine applies LoRAs to the same GGUF, but a GPU host could only reach it through UNSLOTH_DIFFUSION_ENGINE. This adds an engine pick per load.

Backend

  • /images/load and /images/download-plan take engine: auto (default, unchanged), diffusers or sd_cpp. It applies to that load only, and UNSLOTH_DIFFUSION_ENGINE still wins over it.
  • A pick the engine cannot serve is refused with a 400 before anything is unloaded, never swapped for the other engine:
    • native for a non-GGUF kind
    • native for a family without sd.cpp assets
    • native with no runnable binary
    • diffusers without the pipeline class
  • Switching engines goes through the existing safe unload.
  • Status adds engine_forced, native_engine_eligible, lora_via_native, and a resolved.engine provenance entry (Auto vs explicit, with the reason).

Frontend

  • Images Advanced has an Engine select (Auto / Diffusers / Native (sd.cpp)), shown for a loaded GGUF the native engine can run, with the usual provenance badge.
  • The choice is remembered per checkpoint once a load lands with it, and recalled for that checkpoint's next load. A refused pick is never replayed.
  • When a GGUF runs as-is on diffusers (no LoRA) and native would apply LoRAs, a note under the prompt offers "Reload with native engine", which reloads the same pick with engine=sd_cpp.
  • The hint covers the tradeoffs: native applies LoRAs and usually needs less VRAM, but has no torch.compile or quantised fast paths and is often slower on CUDA.

With precision on Auto a GPU host already loads the full base as dense int8, which bakes LoRAs in at load, so the note only appears when the GGUF runs as-is (precision Off).

Screenshots

FLUX.2 klein 4B GGUF loaded as-is on diffusers. The note under the prompt that offers the native reload:

Prompt column before and after

The Engine select in Advanced, with its provenance badge:

Advanced panel before and after

Testing

  • Backend: test_diffusion_engine_router.py gains cases for the field, env precedence, refusals before unload, status eligibility and provenance. Router, MLX router, load-contract and routes suites: 579 passed.
  • Frontend: tests/image-engine-choice.test.ts (7 tests); image and diffusion suites 291/291; tsc --noEmit -p . and scripts/typecheck.mjs --tests clean.
  • End to end through the real /images routes: one CUDA GPU, FLUX.2 klein 4B Q4_K_M GGUF, 512x512, 4 steps, seed 7, sd.cpp master-968 CUDA prebuilt, LoRA adirik/pixel-art-lora-flux.2-klein-4B.
Load engine supports_lora lora_via_native resolved.engine load gen (2nd) LoRA gen
Auto, precision Off (GGUF as-is) diffusers false true auto 50.6 s 0.3 s 400 (unsupported)
engine=sd_cpp sd_cpp true false explicit 12.0 s 0.9 s 200, 1.6 s
Auto again diffusers false true auto 37.2 s
Auto, precision Auto (dense int8) diffusers true false auto 63.4 s 0.7 s 400 (bake at load)
engine=sd_cpp sd_cpp true false explicit 41.5 s 2.1 s 200, 3.3 s
  • The native LoRA applies: mean absolute pixel difference vs the same seed without it is 28.86 (0-255), and the next generation without the LoRA matches the no-LoRA image exactly.
  • Refusals: native for a pipeline pick returns 400 "The native sd.cpp engine loads GGUF models only."; an unknown engine returns 422.
  • Timings are single runs on a shared GPU, not a speed comparison.

Not covered: the CPU sd.cpp bundle on a GPU host (one managed sd.cpp install per host, so a CPU pick would replace the CUDA build), and Mac / Windows / ROCm runs.

A GGUF on a GPU host always loads on diffusers, which applies no LoRA to the
GGUF weights; the native sd.cpp engine does, but was reachable only through
UNSLOTH_DIFFUSION_ENGINE. Loads now carry an optional engine pick.

- /images/load and /images/download-plan take engine (auto | diffusers |
  sd_cpp), honoured for that load only. Auto is the default and unchanged;
  UNSLOTH_DIFFUSION_ENGINE still wins over a pick.
- A pick the engine cannot serve (native for a non-GGUF kind or a family
  without sd.cpp assets, native with no runnable binary, diffusers without
  the pipeline class) is refused with a 400 before anything is unloaded,
  never swapped for the other engine. Switching goes through _activate's
  unload.
- Status reports engine_forced, native_engine_eligible, lora_via_native and
  a resolved["engine"] provenance entry.
- Images Advanced gets an Engine select (Auto / Diffusers / Native (sd.cpp))
  for loaded GGUFs native can run, remembered per checkpoint once a load
  lands with it. Where LoRA is hidden on a diffusers GGUF but native applies
  it, a note offers Reload with native engine.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T13:49:24.682329Z 048d7f8 New commits
🔒 Security Review ⚠️ Failed 2026-10-19T09:42:49.528162Z bea7ed2 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 492ce2151b

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

common case: a fresh CPU host.
"""
if mlx_selection(fam, model_kind = model_kind, gguf_filename = gguf_filename)[0]:
requested = _requested_engine(engine)

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 Refuse unavailable native picks during planning

When engine="sd_cpp" is requested on a host with no runnable native binary and installation is disabled, predict_engine() computes requested but ultimately returns diffusers because native_available is false. Consequently, /images/download-plan succeeds with a diffusers plan and may stage multiple gigabytes, while the subsequent load deterministically raises the native-binary refusal. The planning path should reject this explicit request instead of silently planning for the engine that the load will not use.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 64b241f. predict_engine now raises the same refusal selection gives for an explicit native pick it cannot honour (no runnable binary with installs off, or a refused pick per refuse_engine_pick), so /images/download-plan answers 400 instead of planning diffusers files. Test: test_the_plan_refuses_a_native_pick_the_load_would_refuse.

Comment on lines +649 to +651
active = _select_and_activate_engine(fam, **kwargs)
with _lock:
_engine_pick = _requested_engine(kwargs.get("engine"))

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 Record the engine choice only after the load lands

This records the new request's provenance immediately after engine selection, before admission, begin_load_on(), or the background load reaching ready. On a same-engine reload the previous model can therefore remain loaded while a later arbiter/preflight/load failure leaves _engine_pick describing the failed request; concurrent selections can also overwrite it out of order after _activate() releases the transition lock. Status then attributes the resident model to the wrong explicit engine choice, and the frontend persists that incorrect choice for the checkpoint.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 64b241f. Selection no longer records the pick. The load route calls note_engine_pick() only after engine.begin_load() accepted the load, inside begin_load_on's lock, so a refused or failed admission never relabels the resident model and concurrent loads record in start order. Tests: test_selection_alone_does_not_relabel_the_resident_model, test_the_engine_pick_is_recorded_only_once_the_engine_accepted_the_load.

return _activate(ENGINE_DIFFUSERS, f"non-GGUF load ({model_kind}) requires diffusers")

forced, sd_cpp_pref, mps_enabled = _engine_config()
forced, sd_cpp_pref, mps_enabled = _engine_config(engine)

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 the native-engine disable flag for per-load picks

When UNSLOTH_DIFFUSION_SD_CPP=0 is set and a request supplies engine="sd_cpp", _engine_config(engine) turns the request into forced == sd_cpp, so prefer_native becomes true and the disable check is bypassed. This lets an API/UI request install and execute the native backend even though the documented environment knob disables that route; only UNSLOTH_DIFFUSION_ENGINE=sd_cpp, the higher-priority administrator force setting, should override the disable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 64b241f. refuse_engine_pick refuses an explicit sd_cpp pick while UNSLOTH_DIFFUSION_SD_CPP disables the native route; only UNSLOTH_DIFFUSION_ENGINE=sd_cpp still wins, as before. Test: test_a_native_pick_honours_the_native_disable (refuse, predict and select).

Comment on lines +4060 to +4063
const l =
lastLoad.current ??
(status?.loaded && status.model_kind === "gguf" && status.repo_id && status.gguf_filename
? { repoId: status.repo_id, kind: "gguf" as const, filename: status.gguf_filename, displayRepoId: status.display_repo_id ?? undefined }

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 Reload the GGUF currently reported by status

If another client or API load replaces the resident model while this page still has a non-null lastLoad.current, the native-LoRA note is rendered for the new status but this null-coalescing expression always selects the stale page-initiated model. Clicking “Reload with native engine” then unexpectedly swaps back to the old checkpoint rather than reloading the GGUF named by the note; use lastLoad.current only when it matches the current status, as the generation recall path already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 64b241f. The reload target comes from nativeReloadTarget(lastLoad, status): the page's last load only when its repo, kind and file match what status reports as resident, else the resident model from status. Test in image-engine-choice.test.ts.

fam = detect_family("", override = status.get("family"))
except Exception: # noqa: BLE001 -- an unknown family reads as not eligible
fam = None
native_eligible = fam is not None and family_sd_cpp_supported(fam)

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 Exclude custom-component loads from native eligibility

A diffusers GGUF loaded with text_encoder_file or vae_file is marked native-eligible solely from its family, so the UI exposes both the Native select and the LoRA reload note. Reapply/reload preserves those component fields via currentLoadAdvanced, but both /images/download-plan and /images/load unconditionally reject them through _refuse_native_component_files, making every offered native action fail with a 400 for this supported load configuration. Eligibility should account for status.component_files, or the native action must deliberately omit the incompatible overrides.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 64b241f. engine_choice_status only reports native_engine_eligible (and lora_via_native) when the load has no separate component files, matching the plan and load refusals, so neither the Engine select nor the LoRA note appears for those loads. Test: test_component_file_loads_are_not_native_eligible.

Comment on lines +3187 to +3189
if (engineSeed !== `${loadedEngineKey}|${loadedEngine}`) {
setEngineSeed(`${loadedEngineKey}|${loadedEngine}`);
setEngineChoice(loadedEngine);

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 Reset an engine selection after its load is refused

After a native Reapply is refused before the old model is unloaded, the status refresh reports the same model and the same loaded auto provenance, so engineSeed is unchanged and this reseeding block does not restore engineChoice; it remains sd_cpp. The next Reapply therefore silently submits the refused choice again even though it was intentionally not persisted, contradicting the guarantee that a refused pick is not replayed. The failure path needs to restore the resident model's loadedEngineChoice or invalidate this seed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 64b241f. A refused load clears the Engine select's seed, so it reseeds from the resident build's own choice instead of keeping the refused pick.

// will run: without the token a gated base plans no companion, and without the controls it
// stages shards the load never opens.
hf_token: hfApiToken(getHfToken()),
engine: engineFor(repoId, opts, advanced),

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 Snapshot the engine used to build a staged plan

The download plan computes its engine from the mutable engineSelection ref, but the LoadAdvanced snapshot retained in pendingStagedLoad does not contain that effective engine, so the eventual handleLoad call computes it again. If the currently loaded GGUF is reselected and the user changes its Engine select while the staged download is running, the plan can be built for diffusers and the load run on sd.cpp, or vice versa; the loader then fetches missing companion assets outside the download manager or stages large files it never uses. Store the resolved engine in the staged snapshot and send that identical value to both requests.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 64b241f. loadOrStage writes the resolved engine into the advanced snapshot before planning, and the plan request and the staged load both read that one value, so a later change to the select cannot split them.

…an, record the pick after the load lands

- predict_engine refuses an explicit sd_cpp pick the load would refuse (no runnable binary, install disabled)
- an explicit sd_cpp pick honours UNSLOTH_DIFFUSION_SD_CPP=0; only UNSLOTH_DIFFUSION_ENGINE=sd_cpp overrides it
- the engine pick provenance is recorded once the engine accepted the load, not at selection
- loads with separate text-encoder / VAE files are not native-eligible
- the native LoRA reload targets the resident GGUF, not a stale page load
- a refused load reseeds the Engine select from the resident build
- a staged pick snapshots its resolved engine for both the plan and the load

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 64b241f6e0

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

void handleLoad(
l.repoId,
{ kind: l.kind, filename: l.filename, displayRepoId: l.displayRepoId },
{ ...currentLoadAdvanced(l.repoId), engine: "sd_cpp" },

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 Omit diffusers precision from native reloads

When the resident GGUF was loaded with an explicit diffusers-only precision such as text_encoder_quant="fp8", currentLoadAdvanced() preserves that setting here while forcing engine="sd_cpp". The load route then rejects the request in _assert_native_precision_unset, so clicking “Reload with native engine” returns a 409 instead of enabling LoRA. Clear the transformer/text-encoder precision fields, or otherwise normalize native-incompatible advanced settings, for this action.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8678a64. An explicit native load now drops what the native routes refuse before it is sent: nativeLoadAdvanced() clears transformer_quant, text_encoder_quant, text_encoder_file and vae_file for an sd_cpp pick (not when the server pins diffusers, where the pick is ignored). It runs at the top of handleLoad and of the download-plan request, so Reload with native engine, Engine=Native plus Reapply, and staged loads all send the same normalized settings. LoRAs and the other settings are kept. Test: a native load drops the precision and component files the native routes refuse.

Comment on lines +2945 to +2947
if (loaded.loaded && loaded.model_kind === "gguf") {
const key = engineModelKey(loaded.repo_id, loaded.gguf_filename);
setEngineChoices((all) => withEngineChoice(all, key, loadedEngineChoice(loaded)));

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 Persist engine choices when resuming a completed load

The per-checkpoint choice is saved only in this load-poll ready branch. If the page unmounts while a daemon load is running and is reopened after it finishes, the mount path refreshes status but does not call pollLoadProgress() because the phase is already ready, so the successful explicit choice is never written to engineChoices/localStorage. After another checkpoint is loaded, returning to this one therefore falls back to Auto; persist the resolved choice whenever a current loaded status is accepted, not only when this poll observes the transition.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8678a64. setStatusIfNewest, the single place the page accepts a status, now runs rememberLoadedEngine(): an explicit resolved.engine (source explicit, with its requested engine) is saved under the loaded GGUF, so a load that finished while the page was closed is remembered. Auto, unloaded and non-GGUF statuses neither write nor clear, and an unchanged choice causes no write. Test: an explicit choice is persisted from any accepted loaded status, not only the poll's ready branch.

…ce from any loaded status

- an explicit native load (the LoRA reload note, or Engine=Native + Reapply) drops the explicit precision and
  separate text-encoder / VAE files the native routes refuse, in both the load and its download plan
- the per-checkpoint explicit engine choice is recorded from every accepted loaded status, so a load that
  finished while the page was closed is remembered too

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8678a6431f

ℹ️ 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 +162 to +163
if (!key || !isPick(choice) || choices[key] === choice) return choices;
return withEngineChoice(choices, key, choice);

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 Clear stale picks when status reports Auto

When a checkpoint has a stored explicit choice and is later loaded with Auto while this page is closed, the first accepted status after reopening reaches this branch with choice === "auto" and leaves the old localStorage entry intact. After another checkpoint becomes resident, selecting the original checkpoint makes engineFor() reuse that stale explicit choice, so a model whose latest load was Auto unexpectedly reloads with the older engine. Treat Auto as a value that removes the stored entry here, just as the load-progress ready path does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e7ae5a0. An accepted loaded status that reports Auto now removes the stored explicit choice for that checkpoint, so the latest load wins, as the ready path does. Test: a resident load that reports Auto clears the stored explicit choice.

Comment on lines +4082 to +4086
void handleLoad(
l.repoId,
{ kind: l.kind, filename: l.filename, displayRepoId: l.displayRepoId },
{ ...currentLoadAdvanced(l.repoId), engine: "sd_cpp" },
);

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 Stage native-reload companion assets before loading

When the resident GGUF was loaded through diffusers and the native-only VAE or text-encoder assets are not cached, this calls handleLoad directly instead of going through loadOrStage. The sd.cpp backend consequently fetches those potentially multi-gigabyte companions inline, outside the download manager, even though the new engine-specific planning path exists precisely because diffusers and native require different files. Route this engine-changing reload through the plan/staging flow with the pinned sd_cpp snapshot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e7ae5a0. Reload with native engine now goes through loadOrStage with the sd_cpp choice already in the snapshot, so the plan stages the native VAE and text encoders through the download manager and the staged load reuses that snapshot. An engine-changing Reapply from the Engine select takes the same path (reapplyChangesEngine); a same-engine Reapply still loads directly. Test: an engine-changing reload is planned and staged, a same-engine Reapply loads directly.

Comment on lines +5173 to +5175
{!external && engineSelectVisible(status) && (
<AdvancedSelect
label="Engine"

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 Provide a reload target for resident GGUF engine changes

When the page opens after a GGUF was loaded elsewhere or while the page was unmounted, lastLoad.current remains null because the resident seeding logic only creates a Reapply target for pipelines. This newly displayed Engine select can therefore be changed, but the Reapply button remains hidden (canReapply is false and the model is not a pipeline), so the selection has no way to take effect unless the separate LoRA-specific native action happens to be shown. Seed a GGUF reload target from status.repo_id and status.gguf_filename, or hide/disable the control until such a target exists.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e7ae5a0. residentReloadTarget(status) gives a resident GGUF a reload target from its repo id and file (pipelines as before; none for a load with separate component files, which status cannot reproduce), the seeding effect uses it, and Reapply shows whenever such a target exists. Test: a resident GGUF the page did not load gets a Reapply target from status.

…or a resident GGUF

- a resident load that reports Auto clears the stored explicit choice for that checkpoint (latest load wins)
- the native LoRA reload and an engine-changing Reapply go through the download plan, so the other
  engine's companion files are staged by the download manager instead of fetched inline by the load
- a resident GGUF the page did not load gets a Reapply target from status (repo id + file), so an
  Engine change on it can take effect; not for builds with separate component files

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e7ae5a0f29

ℹ️ 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 thread studio/backend/routes/inference.py Outdated
**_component_file_kwargs(request),
)
# Only once the engine accepted the load, so a refused pick never relabels the resident model.
note_engine_pick(request.engine)

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 Commit engine provenance only after the background load lands

For a same-engine reload, begin_load() only starts the daemon and can deliberately keep the previous _state resident while assets are fetched, but this immediately replaces the router-global provenance. If the worker then fails before tearing down or publishing the new state—for example on an asset or binary error—status continues reporting the old checkpoint with the failed request's engine choice, which the frontend persists for that checkpoint. The fresh post-fix evidence is that both backend worker error paths preserve _state on such pre-commit failures, so associate the pick with the committed model state or update it only when the worker reaches ready.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e2de630. The route now only stores the pick as pending with the engine and its state object at load start; it moves into the recorded pick once that engine publishes a new, non-None state, checked on every status read and before the next load is noted. A worker that fails before publishing keeps the old state and the old pick, and a teardown leaves nothing to label. Test: test_the_engine_pick_commits_only_when_the_background_load_lands.

Comment on lines +4085 to +4087
const l = lastLoad.current;
if (l) void handleLoad(l.repoId, { kind: l.kind, filename: l.filename, displayRepoId: l.displayRepoId });
}, [handleLoad]);
if (!l) return;
const opts = { kind: l.kind, filename: l.filename, displayRepoId: l.displayRepoId };

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 Reapply the checkpoint currently reported by status

When this page previously loaded checkpoint A and another client replaces it with checkpoint B, the status refresh updates the Engine select for B but the resident-seeding effect leaves the non-null lastLoad.current pointing at A. This handler then evaluates reapplyChangesEngine against B while passing A to loadOrStage or handleLoad, so clicking Reapply—particularly after changing B's engine—unexpectedly swaps back to A. Resolve the target against the current status as the adjacent native-reload path already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e2de630. reapplyTarget(last, status) uses the page's own last load only while it is still the resident model, else the checkpoint status reports (residentReloadTarget), and null when status cannot rebuild it, so Reapply never swaps back to a stale pick. Test: Reapply resolves its target against the checkpoint status reports.

Comment on lines +142 to +143
if (engine !== "sd_cpp" || (forced && forced !== "sd_cpp")) return advanced;
return { ...advanced, transformer_quant: undefined, text_encoder_quant: undefined, text_encoder_file: undefined, vae_file: undefined };

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 Normalize loads pinned to the native engine

When UNSLOTH_DIFFUSION_ENGINE=sd_cpp is set and the per-load choice is Auto or Diffusers, the actual engine is native but engine here is not sd_cpp, so the native-incompatible precision and component fields are returned unchanged. Those controls remain available while unloaded (and text-encoder/component controls remain available on a loaded native model), causing download plans and Reapply/model loads to be rejected by _assert_native_precision_unset or _refuse_native_component_files even though the server pin deterministically selects sd.cpp. Treat forced === "sd_cpp" as a native load regardless of the ignored per-load choice.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e2de630. nativeLoadAdvanced treats a GGUF load as native when the server pins UNSLOTH_DIFFUSION_ENGINE=sd_cpp as well as for an explicit sd_cpp pick, and strips the same diffusers-only fields; non-GGUF loads are never stripped since the router keeps them on diffusers. Test: a load the server pins to sd_cpp is normalised like an explicit native pick, GGUF only.

Comment on lines +183 to +187
status.model_kind === "gguf" &&
status.gguf_filename &&
Object.keys(status.component_files ?? {}).length === 0
) {
return { repoId: status.repo_id, kind: "gguf", filename: status.gguf_filename, displayRepoId };

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 the resident GGUF's base repository on Reapply

When the page adopts a GGUF loaded through the API with an explicit nondefault base_repo, this helper offers Reapply because there are no separate component files, but the returned target omits the effective base repository reported by status. Both the ordinary Reapply and native-reload paths subsequently send no base_repo, so the backend resolves the family's default instead and may fetch or load different text encoders, VAE, or configuration from the resident build. Carry status.base_repo through the reload target and request, or withhold the action when the build cannot be reconstructed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e2de630. Reload targets built from status carry status.base_repo, and the load and plan requests send it as base_repo, so Reapply and the native reload keep the resident GGUF's base. Ordinary picks never set it. Test: a reload from status keeps the resident GGUF's base repo, on the load and the plan.

…pply what status reports

- the engine pick provenance is committed only once the started load publishes a new state on its
  engine, so a background load that fails before publishing never relabels the resident model
- Reapply resolves its target against the current status, so a model another client loaded is
  reloaded instead of the page's stale pick
- a GGUF load the server pins to sd_cpp (UNSLOTH_DIFFUSION_ENGINE) drops the same precision and
  component fields as an explicit native pick
- a reload built from status carries the resident GGUF's base repo to the load and the plan
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e2de63020d

ℹ️ 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 thread studio/backend/routes/inference.py Outdated
Comment on lines +51284 to +51286
# Only once the engine accepted the load, committed when it lands, so a refused or failed pick never
# relabels the resident model.
note_engine_pick(request.engine, engine)

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 Snapshot provenance before starting the load worker

When a cached load finishes between engine.begin_load() starting its daemon thread and this call, note_engine_pick() snapshots the newly published _state as the pre-load state; _settle_engine_pick_locked() then waits forever for another distinct state and status continues reporting the previous request's engine choice. The fresh evidence in the current code is that each begin_load() calls .start() before returning, so capture the old state before launching the worker or associate provenance with the load token.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cdb965. The route snapshots the engine's loaded state before begin_load starts the worker and passes it to note_engine_pick, which also commits at once if the load already landed, so a cached load that publishes before begin_load returns still records its pick. Tests: test_a_load_that_publishes_before_begin_load_returns_still_commits_its_pick, plus the load-contract ordering check.

Comment on lines +153 to +155
const native = gguf && (forced ? forced === "sd_cpp" : engine === "sd_cpp");
if (!native) return advanced;
return { ...advanced, transformer_quant: undefined, text_encoder_quant: undefined, text_encoder_file: undefined, vae_file: undefined };

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 diffusers options when the native pin falls back

When UNSLOTH_DIFFUSION_ENGINE=sd_cpp is set but no runnable native binary exists, or the family lacks native support, the router deliberately falls back to diffusers (the backend even tests the missing-binary case). This condition nevertheless treats the pin as proof that the load will be native and removes explicit precision and component files from both the plan and load, so the fallback silently builds a different diffusers configuration. Normalize only after the effective engine is known, or make the server pin fail instead of falling back.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cdb965. nativeLoadAdvanced now strips only for an explicit sd_cpp pick on a GGUF with no server pin, which the router either runs natively or refuses. Under UNSLOTH_DIFFUSION_ENGINE=sd_cpp the options are kept, so a fallback to diffusers builds the load that was asked for; an explicit precision that really runs native is refused as before this PR. Test: a server pin never strips options.

Comment on lines +3441 to +3443
// A refused load keeps the resident model and its provenance, so the seed would not move: reseed the
// Engine select from the resident build rather than replay the refused pick on the next Reapply.
setEngineSeed("");

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 Reset failed engine picks on worker errors

This resets the Engine select only when the initial POST fails. If the POST succeeds but the background worker reports phase === "error" before replacing the resident state—for example during an asset fetch—the error branch restores lastLoad and refreshes the unchanged resident status without clearing engineSeed; because the seed is unchanged, the failed explicit pick remains selected and the next Reapply submits it again. The fresh evidence is that the current load-progress error branch has no corresponding seed reset.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cdb965. The load-progress error branch reseeds the Engine select from the resident build, as the refused-start path does.

Comment on lines 50723 to 50726
gpu_ordinal = gpu_ordinal,
gguf_filename = request.gguf_filename,
engine = request.engine,
)

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 Validate native precision while training is active

When training is active on a GPU host and a caller explicitly requests engine="sd_cpp", this new argument makes the planner select the native backend, but the surrounding not training guard skips _assert_native_precision_unset. A request that also pins transformer_quant or text_encoder_quant therefore receives and may stage a valid-looking native download plan even though /images/load deterministically rejects the same fields once training ends. Keep the allocation-heavy diffusers probe gated, but run the native value-only refusal regardless of training.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5cdb965. The download plan runs the native precision check for any non-diffusers planner regardless of training; only the diffusers availability probe still waits for training to end. Test: test_the_native_plan_refuses_an_explicit_precision_while_training_runs.

…options under a pin

- the load route snapshots the engine's loaded state before begin_load starts the worker, so a
  cached load that publishes before begin_load returns still commits its engine pick
- the download plan runs the value-only native precision refusal while training is active too;
  only the diffusers GPU probe waits for training
- a server pin (UNSLOTH_DIFFUSION_ENGINE) never strips precision or component files: its sd_cpp
  route falls back to diffusers when native cannot run the pick
- a background load that fails reseeds the Engine select, like a refused start

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5cdb965659

ℹ️ 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 +1098 to +1100
native_eligible = (
fam is not None and family_sd_cpp_supported(fam) and not status.get("component_files")
)

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 Hide native actions when the native route is disabled

When UNSLOTH_DIFFUSION_SD_CPP=0 and a supported GGUF is resident on diffusers, this still reports both native_engine_eligible and potentially lora_via_native as true because it ignores the disable setting. The Images page consequently offers the Native engine selector and “Reload with native engine,” but either action sends engine=sd_cpp and is deterministically rejected by refuse_engine_pick() with a 400. Include the native-disable policy when computing these capabilities so the UI does not advertise an unusable action.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in aab6b5a. engine_choice_status now reports native_engine_eligible and lora_via_native false while UNSLOTH_DIFFUSION_SD_CPP disables the native route, using the same rule as refuse_engine_pick (UNSLOTH_DIFFUSION_ENGINE=sd_cpp still overrides it, as for the load), so the page no longer offers Native or the native reload there. Test: test_the_native_disable_hides_the_native_actions.

…route is disabled

UNSLOTH_DIFFUSION_SD_CPP=0 refuses an explicit native pick unless the server pins sd_cpp, so the
status no longer reports native_engine_eligible / lora_via_native for it.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: aab6b5a778

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

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

[skip ci]
@danielhanchen
danielhanchen merged commit 6ccf0e4 into main Oct 19, 2026
@danielhanchen
danielhanchen deleted the studio-images-engine-choice branch October 19, 2026 13:49
danielhanchen added a commit that referenced this pull request Oct 19, 2026
## Summary

Main is over the startup bundle budget again, by 189 B raw, so `Frontend
build + bundle sanity` fails on every PR based on it:

```
over the startup budget: raw 6682.2 KB > 6682.0 KB      (main at 6ccf0e4)
```

#14258 set both limits to the measured build plus a 160 B raw / 189 B
transfer margin. #11937 (a setting to hide the macOS menu bar icon) then
added 349 B raw / 78 B transfer to the startup chunks, and merged
without raising them.

## Cause

#11937 adds strings to `i18n/locales/en.ts`, which ships in the startup
chunks, and entries to the settings search index (`settings-search.ts`,
`dialog-search-index.ts`). That is small real growth. I measured each
commit since #14258 on its own:

| tree | raw B | transfer B |
|---|---|---|
| `46e4f50bea` (#14258) | 6,842,183 | 2,060,321 |
| `2b20770c91` (+ #11937) | 6,842,532 | 2,060,399 |
| `f5e91f1ca5` (+ #14223) | 6,842,532 | 2,060,421 |
| main `6ccf0e4e74` (+ #14232) | 6,842,532 | 2,060,400 |

#14223 and #14232 add no raw bytes. #14021 and #14263 change no frontend
code.

## Change

- **`check-bundle-budget.ts`:** a BUDGET comment entry for #11937, and
both limits moved to the measured build at main plus the same margin:
  - `rawBytes`: 6,842,343 -> 6,842,692.
  - `transferBytes`: 2,060,510 -> 2,060,589.

## Testing

One machine and build, Node 24, exact byte totals from the budget
script, 96 chunks.

- **Main against the old limits:** `over the startup budget: raw 6682.2
KB > 6682.0 KB`.
- **With this change:** `within budget (0.2 KB transfer, 0.2 KB raw to
spare)`.
danielhanchen added a commit that referenced this pull request Oct 19, 2026
… stub (#14269)

## Summary

`Chat UI Tests (extra)` fails on main at `c708b1d727` (run 39268175533)
and on every PR based on it, in the `Image text encoder precision
regression (Playwright)` step:

```
File "tests/studio/playwright_image_text_encoder.py", line 233, in main
    with page.expect_request(
playwright._impl._errors.TimeoutError: Timeout 30000ms exceeded while waiting for event "request"
```

Every later step in that job is skipped (25 steps), so the shard
currently checks nothing past this point.

## Cause

#14232 (per-load engine choice for GGUF picks) changed what Reapply
reloads. `reapplyTarget` in `features/images/lib/engine-choice.ts` uses
the page's last pick only while it still matches the resident model:
same repo, kind and `gguf_filename`. Otherwise it falls back to the
checkpoint that status reports, which for a GGUF needs a
`gguf_filename`.

The test's stub `/api/inference/images/status` reported `model_kind:
"gguf"` with no `gguf_filename`. The real `status()` always carries it
(`diffusion.py`, `"gguf_filename": state.gguf_filename`). So in the
test, Reapply had no target and never sent `/api/inference/images/load`.
The product behaves correctly against the real backend, and the stub had
drifted from the contract.

Bisected locally against a stubbed build (vite preview of
`studio/frontend`, same script, same chromium):

| commit | result |
|---|---|
| `f5e91f1ca5` (before #14232) | Passed |
| `6ccf0e4e74` (#14232) | TimeoutError at line 233 |
| main `4ea4c758dc` | TimeoutError at line 233 |

## Change

Test-only, `tests/studio/playwright_image_text_encoder.py`:

- **Stub status:** it now echoes the loaded file, `gguf_filename =
loads[-1].get("gguf_filename")`, as the backend's status does.
- **New check:** a GGUF load request without `gguf_filename` is recorded
as a page error, and the script already asserts there are none. It
records rather than raises inside the route handler, which would leave
the request hanging.

## Testing

Same local setup, all three variants the workflow runs:

- `applied`: Passed: planned and pinned precision, four explicit modes,
fallback reseeding and default omission
- `PW_COMPLETION_FIRST=1`: Passed (same)
- `PW_DECLINE=1`: Passed: a declined encoder precision reseeds to Dense
(bf16)

Not covered here: the 25 steps after this one that the failure skipped
on main. This PR's `Chat UI Tests (extra)` run is the first chance they
run again since #14232, and several need the real Studio backend.
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…14272)

## Summary

`Frontend build + bundle sanity` fails its `Typecheck` step (`npm run
typecheck`, tests included) on PRs based on current main (seen on
#14245):

```
tests/image-engine-choice.test.ts(305,48): error TS2339: Property 'baseRepo' does not exist on type '{ repoId: string; kind?: ...; filename?: ...; } | { repoId: string; kind: "gguf"; filename: string; displayRepoId?: string; baseRepo?: string; }'.
tests/image-mask-from-text.test.ts(246,30): error TS2345: Argument of type '"drawImage"' is not assignable to parameter of type 'never'.
tests/image-mask-from-text.test.ts(246,61): error TS2345: Argument of type '"putImageData"' is not assignable to parameter of type 'never'.
```

Reproduced on main `6c159816c5` with `node scripts/typecheck.mjs
--tests` (TypeScript 7.0.2, as CI). The product code typechecks. Both
errors are in tests:

- **`image-engine-choice.test.ts` (from #14232):**
`nativeReloadTarget(null, gguf)?.baseRepo`. With `null` as the last
load, `T` falls back to its constraint, which has no `baseRepo`, so one
branch of the return union lacks the property.
- **`image-mask-from-text.test.ts` (from #14235):**
`assert.deepEqual(calls, [])` from `node:assert/strict` is an assertion
signature. It narrows `calls` to `never[]`, so the later
`calls.includes("drawImage")` no longer typechecks.

## Change

Test-only:

- **`image-engine-choice.test.ts`:** `nativeReloadTarget<{ repoId:
string; baseRepo?: string }>(null, gguf)?.baseRepo`. This names `T`, so
the status-built branch, the one that carries `baseRepo`, is what is
read. The assertion is unchanged.
- **`image-mask-from-text.test.ts`:** `assert.equal(calls.length, 0)` in
place of `assert.deepEqual(calls, [])`. It asserts the same thing
without the narrowing, with a comment saying why.

## Testing

- **`node scripts/typecheck.mjs --tests`:** clean (exit 0), from the
three errors above on main.
- **`node --experimental-strip-types --test` on both files:** 30 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.

Studio Images: expose native sd.cpp for GGUF LoRA inference

1 participant