Skip to content

Studio: FLUX.3 prompt upsampling (Enhance prompt) through a llama.cpp sidecar - #14137

Merged
danielhanchen merged 73 commits into
mainfrom
studio-flux3-pup
Oct 18, 2026
Merged

danielhanchen merged 73 commits into
mainfrom
studio-flux3-pup

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Follows #13933 (FLUX.3 Image Klein, merged).

Why

FLUX.3 Image Klein is trained on long, explicit captions. Sent a short prompt as typed, it often draws broken bodies on unusual poses (backflips, handstands, tangled arms) and generic scenes. BFL ships a prompt upsampler for exactly this (black-forest-labs/flux-3-image-klein-pup, a Qwen3.5-9B fine-tune, Apache-2.0), and its model card says FLUX.3 "is not meant to run without a prompt upsampler in front of it". ComfyUI's official FLUX.3 templates run it by default. Studio currently drops that step and encodes the prompt as typed.

Same 16 prompts, same seeds and reference noise, 32 images per arm:

Arm Broken bodies
distilled, prompt as typed 3 (backflip on both seeds, one handstand)
distilled, upsampled caption 0
base (50 steps), prompt as typed 4 (headless handstand, tangled arms, two odd violin grips)
base (50 steps), upsampled caption 1 (odd violin angle)

As typed, "a gymnast doing a backflip" mostly renders a back-bend or walkover; upsampled, it renders a tucked backflip. Ordinary scenes (groups, walking, dinner) were already fine and stay fine.

What this adds

Backend (core/inference/flux3_prompt_upsampler.py)

  • The upsampler runs as a llama.cpp llama-server sidecar, modelled on the dictation (mtmd STT) sidecar: started on demand on an ephemeral loopback port, five minute keep-alive, unloaded early when VRAM is tight, and stopped at every training start, llama.cpp update, image unload and GPU handover to chat or video. Stop during a cold start cancels the server start. On a multi-account host it never starts beside another account's run. CUDA, ROCm, Metal and CPU all work through the same binary Studio already installs.
  • Weights come only from unsloth/flux-3-image-klein-pup-GGUF (Q4_K_M plus mmproj-F16.gguf for edits, 6.5 GB). UNSLOTH_FLUX3_UPSAMPLER_GGUF / _MMPROJ point at local files instead.
  • Prompts and sampling follow the ComfyUI FLUX.3 templates: BFL's t2i / i2i system prompts verbatim (sha256 pinned in a test, identical to diffusers' SYSTEM_PROMPTS), greedy decoding, thinking off, 3584 max tokens, presence penalty 1.5 for text-to-image and 0 for edits, repeat penalty 1.05 for distilled and 1.0 for base. Edits send the reference images (prepared as diffusers' prepare_reference) and the edit scaffold.
  • When the server supports penalize_prompt (server: add penalize_prompt to keep prompt tokens out of the penalty history llama.cpp#283), the penalties cover only generated tokens over the whole caption, which is what ComfyUI and BFL's reference do. Against an exact-semantics reference on 8 prompts this moves word similarity from 0.49 to 0.69 (the cross-runtime floor is about 0.7 to 0.8). Older servers keep their default window.
  • DiffusionGenerateRequest.enhance_prompt (default: on for FLUX.3 Klein, ignored elsewhere). Records keep prompt as typed and add enhanced_prompt (the caption encoded) and prompt_enhancement (applied / off / unavailable / failed). Generation never fails because of the upsampler: a missing download, missing binary or server error falls back to the prompt as typed, and a multi-GB download is never started implicitly.
  • Routes: GET /api/inference/images/prompt-upsampler/status, POST .../download, POST .../cancel, POST .../preview. /images/status gains supports_prompt_upsampler and prompt_upsampler_default; generate-progress reports an enhance phase.
  • Captions are cached per (prompt, variant, references), so a batch upsamples each distinct prompt once and a repeat costs nothing.
  • Fix in the shared sidecar download progress: huggingface_hub 1.18+ writes <etag>.<8 hex>.incomplete, which the byte counter missed, so the bar sat at 0% until the end. This also fixes the dictation model download bar.

Frontend (Images page)

  • "Enhance prompt" toggle under the prompt for FLUX.3 families only, on by default, remembered per family.
  • Download notice with size, progress and cancel when the upsampler is missing.
  • Preview: shows the caption with Copy and "Use as prompt" (puts the caption in the prompt and turns the toggle off, so it can be edited).
  • The Recipe popover shows the enhanced prompt and offers "Restore with the enhanced prompt", which reproduces the image exactly.

Evidence

End to end on a fresh install from this branch (B200, unsloth/flux-3-image-klein-FP8):

Check Result
status before download downloaded: false; generate falls back, prompt_enhancement: "unavailable"
download through the route 6,547,275,232 bytes in 44 s into the HF cache
preview 231-word caption, 12.2 s cold (includes llama-server start), 4.8 s for a new prompt warm
generate 1.0 to 1.5 s warm without enhancement, about 8 s with a new caption, 1.2 s with a cached one
restore (caption as prompt, enhance off, same seed) max abs pixel difference 0
edit (reference workflow, "make it night time") caption describes the actual source image
VRAM about 23 GB combined peak (DiT 13 to 16 GB, sidecar 6.2 GB text-only, 7.5 GB with the vision projector)
non-FLUX.3 family (Z-Image Turbo) no toggle; enhance_prompt: true passes through untouched

GGUF fidelity (llama.cpp b11696-mix-7baeb9a): the BF16 GGUF matches transformers' chat template token for token and only diverges at near-tie tokens (probability gaps 0.0015 to 0.041). Captions from Q4_K_M and Q8_0 rendered the hard poses with no anatomy difference from the BF16 captions.

Tests: tests/test_flux3_prompt_upsampler.py 73 passed; with the training VRAM, multi-model serving, managed engine, STT, GPU selection, GPU arbiter and diffusion route suites 777 passed. Frontend tests/image-*.test.ts 144 passed, tsc clean.

Not covered

  • Clicking Download in the UI (the download was driven through the route), cancel mid-download, the base variant end to end, edits with several reference images, and the unload-when-tight path (the card never ran tight).
  • macOS, Windows and AMD were not run; the sidecar uses the same llama-server binary and launch helpers as dictation.
  • Exact ComfyUI caption parity needs the penalize_prompt pin in the llama.cpp prebuilt; until then captions are valid but not word-for-word ComfyUI's.

UI

Images composer with unsloth/flux-3-image-klein-FP8 loaded, before (studio-flux3-klein, this PR's base) and after, with Preview clicked. After this PR there is an Enhance prompt switch (on by default for FLUX.3) and Preview opens the caption the upsampler wrote (237 words here) with Copy and Use as prompt. GET /api/inference/images/prompt-upsampler/status returns 404 before and 200 after.

Images composer before and after: Enhance prompt switch and the enhanced caption

danielhanchen and others added 30 commits October 15, 2026 13:14
Diffusers ships FLUX.3 only as Modular Diffusers blocks and the repos carry
modular_model_index.json instead of model_index.json. diffusion_flux3 builds
the components per subfolder and puts a DiffusionPipeline face over the
modular blocks, so placement, offload, the step callback, cancel and the
scheduler swap work the same as for every other family.

- flux.3-klein (16 steps, no CFG) and flux.3-klein-base (50 steps, CFG 3.5)
  families with up to 10 reference images through the reference workflow
- download plan reads only transformer/, text_encoder/, vae/ and the
  modular index (never the root BFL single file or variants/)
- the memory plan prices only component-depth weight files
- class gate: 0.42.0 minimum (unreleased); listing probes the module file
  since main and the PR branch report 0.41.0.dev0
- prompt upsampler repo (-pup) is not matched as an image model
- defaults, labels, bf16 size table, fixtures
FLUX.3 Image Klein support is open upstream as huggingface/diffusers#15046
(branch flux3-image in huggingface/diffusers, current main plus additive
FLUX.3 files). Re-enable diffusers-main.txt at that branch head with its
archive digest, the same route Qwen-Image-2.1 used before 0.41.0. A host
that cannot fetch it keeps the 0.41.0 release and only FLUX.3 is refused.

The pin tests now exercise release mode on a commented-out copy instead of
the shipped file, so they hold in either state.
… BFL seeds

- each reference image is scaled to 1 megapixel (Lanczos, aspect kept),
  as ComfyUI's ReferenceMultiLatent ["resize", 1] in the FLUX.3 templates
  does; diffusers alone only downsizes above 16 megapixels
- a seeded, sized request starts from the BFL reference's noise layout, so
  a Studio seed renders what the BFL CLI renders for it
- base defaults to ComfyUI's CFG template (25 steps, CFG 3.5); distilled
  stays at 16 steps (edit template and BFL; the t2i template's er_sde is
  not a sampler this backend runs)
…ed memory

- FamilyProfile.quant_exclude_tokens: name tokens left dense for every
  transformer-quant scheme (default empty, other families unchanged).
  FLUX.3 keeps modulations, timestep embedders, norm_out, the text-stream
  per-mode blocks and the text projection in bf16. Without it mxfp8 and
  nvfp4 crash at the first step (stride-0 modulation inputs) and int8 /
  fp8 lose the most quality.
- regional compile and CUDA graphs on for FLUX.3 (measured: no graph
  breaks, no recompiles across sizes).
- single file and GGUF denoisers assemble around the base's modular
  companions; the block graph follows the loaded denoiser. A GGUF FLUX.3
  reports uint8 as transformer.dtype (only fp32-kept QK norms are float),
  which the denoise block casts the latents to, so the compute dtype is
  pinned with an empty buffer.
- the other variant's checkpoint and BFL's own fp8r / nvfp4 packages are
  refused up front (the nvfp4 one would decode silently wrong through the
  ComfyUI NVFP4 loader).
- measured activation rows for the distilled checkpoint, and references
  charged at their measured ~0.7 GiB per megapixel instead of nothing.
…s nvfp4

torchao's MX and NVFP4 activation quantisers assert a contiguous input,
so a stride-0 broadcast (an adaLN fed temb.expand(B, S, D)) crashes at the
first denoise step. The shared post-quantisation hook now registers a
pre-hook on MX / NVFP4 Linears that makes the activation contiguous (a
no-op for contiguous inputs), and the scheme smoke probe also runs a
stride-0 broadcast, so a missing guard fails the probe instead of the
render. Measured on B200: without the guard the probe fails mxfp8 and
nvfp4, with it all four schemes pass.

FLUX.3 Klein denies nvfp4 (every keep-set measured 0.09-0.12 LPIPS), and
references are charged at 0.11 of the flat per-megapixel estimate (about
900 MiB per 1 MP reference with an int8 / fp8 denoiser).
Diffusers main moved to requires-python >= 3.11 (huggingface/diffusers#15030),
so the FLUX.3 build cannot install on Python 3.10. Raise the installer's and
the startup repair's main-build floor to 3.11 so 3.10 keeps the 0.41.0
release without a clone that can never succeed, and give a 3.10 user a
FLUX.3 refusal that names the Python requirement instead of a reinstall.
… assembles the modular pipeline

flux.3-klein lists unsloth/flux-3-image-klein-FP8 for int8 and fp8, mirroring
flux.2-klein. A GGUF pick with a transformer quant builds through _assemble_pipe,
which called from_pretrained on a modular pipeline class and returned a pipe with
no transformer; it now assembles FLUX.3 through load_flux3_pipeline.
…eme smoke probe as it was

The picker offers unsloth/flux-3-image-klein-GGUF next to the FLUX.2 klein
rows. The smoke probe goes back to its zero-row input only; the stride-0
broadcast probe is left for a separate change. The contiguous-input guard
on MX / NVFP4 Linears stays, since mxfp8 FLUX.3 needs it to render.
…lar local base, aliases

- generate runs each FLUX.3 image as its own chunk, so every image gets its
  own encode / denoise / decode phase and text-encoder release; renders are
  pixel identical.
- The pipeline face pairs a per-image negative prompt list with each split
  call instead of passing the whole list to every call.
- A GGUF / single-file FLUX.3 load accepts a local base with only
  modular_model_index.json.
- text_encoder_files / vae_file are refused for FLUX.3 up front; the
  supplied-component loader needs a model_index.json and was not used.
- The UI defaults cover the flux3-image-klein aliases the backend registers.

[skip ci]
… row until it is published

The FLUX.3 pipeline face now inherits Flux3LoraLoaderMixin (transformer-only)
when the installed Diffusers has it, so Studio's load_lora_weights /
set_adapters / unload_lora_weights calls work, eager and baked into an int8
build. The unsloth/flux-3-image-klein-GGUF picker row is removed until the
repo is uploaded.

[skip ci]
… the folders FLUX.3 loads

- The route preflight and begin_load read the pick's tensor names (the file
  on disk, a GGUF header range read, or the safetensors header) and refuse a
  distilled / base mismatch or a BFL quantized package before the resident
  pipeline is unloaded. The loader's own check stays as the backstop.
- Local FLUX.3 validation checks <root>/text_encoder, /transformer and /vae,
  the folders load_flux3_pipeline reads, instead of a modular spec's source
  repo, so a manifest pointing elsewhere is refused before loading.

[skip ci]
…pipelines, canonical keys, modular status

- A FLUX.3 GGUF / single file assembles from the staged companion dir when
  the prefetch resolved one, like every other assembly.
- A full FLUX.3 pipeline whose manifest names the other variant is refused
  before eviction (local folder, cached or fetched manifest), with a loader
  backstop on the resolved block graph for every FLUX.3 assembly.
- flux.3-klein / flux.3-klein-base get their recipes in both defaults tables,
  and the resident recipe falls back to the FLUX.3 family for an opaque path.
- The image status lists FLUX.3 in modular_families, so the family override
  admits an opaque modular folder.
…w list

Since 2026-10-16 the official FLUX.3 Klein manifests (distilled 2a70d1707a,
base 6d332ea733) list prompt_upsampler / prompt_upsampler_processor from the
separate ~19 GB flux-3-image-klein-pup repo. FLUX.3 image loads never read
them, but local validation required them as folders of the repo, so a local
or cached copy of the current revision was refused, and the media locality
check wanted the pup repo cached.

FLUX3_COMPONENT_FOLDERS now names exactly the components the loader reads
(text_encoder, tokenizer, transformer, vae); fixed-folder validation checks
those and skips any other manifest entry, and the locality check judges a
FLUX.3 manifest the same way. The download plan already fetches only the
three component folders, and the loader builds the modular pipeline from
its own components without reading the manifest's sources.

[skip ci]
… manifest; require every loaded folder

- The gated-base access probe (route preflight, load prefetch, download
  plan) looks for modular_model_index.json on a FLUX.3 base, so a cached
  gated repo with no usable token is recognised instead of refused.
- Restoring the released transformer shards after a failed prequant seed
  fetches the modular manifest, and the prefetch recognises it as the
  staged snapshot marker, so the dense fallback restores and loads.
- Fixed-folder validation checks every folder load_flux3_pipeline opens
  (text_encoder with its processor, transformer, vae; the transformer is
  skipped for a GGUF / single file), whether or not the manifest lists it,
  and nothing else.

[skip ci]
…scoped and staged by the modular manifest

- download_plan carries the FLUX.3 verdict (a single file / GGUF of the other
  variant or a BFL quantized package from its header, a pipeline of the other
  variant from its manifest) in incompatible_reason, so the Images page
  refuses at selection instead of staging the files the load then refuses.
- A FLUX.3 GGUF / single file stages only the folders the assembler opens
  (text_encoder, vae, transformer/config.json; the transformer shards only on
  the dense quant path) plus modular_model_index.json. Before, the official
  repo's variants/fp8r and variants/nvfp4 packages were staged and the
  manifest was not, so the staged snapshot was never recognised.

[skip ci]
- Single file / GGUF on the other variant's companions: the transformer config
  came from the companion repo, so a base file on the distilled repo (the base
  repo is gated, the TE and VAE are shared) built the flow-map target-time
  embedder and died on meta tensors. The family, already matched to the
  checkpoint by the variant check, now sets flow_map.
- The variant check refused BFL's official ComfyUI int8_convrot / nvfp4 files
  (black-forest-labs/flux-3-image-klein-comfy) as BFL variants/ packages. A
  file that declares ComfyUI quantization (.comfy_quant tensors or the
  _quantization_metadata header) now goes to the ComfyUI loader; the
  undeclared variants/ packages stay refused, local and Hub headers alike.
- The ComfyUI loader splits FLUX.3's fused <block>.qkv.weight into the
  q/k/v projections the diffusers converter expects (rows only, so int8
  scales and ConvRot stay exact).
BFL's ComfyUI base files are flux3_image_klein_{bf16,int8_convrot,nvfp4}
.safetensors: no "base" in the name, so the name tables matched the
distilled key and seeded 16 steps / CFG 1 for the undistilled base (25 / 3.5),
in the status defaults, the auto step-cache plan and the Images form. The
variant check has already matched the checkpoint to the family, so for
FLUX.3 the family goes first; other families keep names first.

[skip ci]
…hot switch, base prequant repo

- Local FLUX.3 validation checks an excluded transformer config-only instead of
  skipping it: the loader still builds the denoiser from <base>/transformer.
- The distilled FLUX.3 family uses its measured activation rows: every reference
  is resized to 1 MP and the request guard charges those pixels on top.
- Media auto-switch plans and loads a seeded FLUX.3 cache snapshot (no dense
  transformer shards) by its repo id, so the cached pre-quantized seed counts.
- flux.3-klein-base lists unsloth/flux-3-image-klein-base-FP8 for int8 and fp8.
  The INT8 file is BFL's ComfyUI int8_convrot denoiser, read through the
  ComfyUI quant loader; the FP8 file is Studio's own.

[skip ci]
…ense-cache probe scoped to transformer/

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Eviction, release and release_if of the DIFFUSION claim, and an admitted
image load replacing the model, now cancel active runs and stop the
server first. Every attempted enhancement binds the generation to its
model, and the preview digest cache is cleared once no preview is shown.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: bbe1541c3c

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit def3451 into main Oct 18, 2026
@danielhanchen
danielhanchen deleted the studio-flux3-pup branch October 18, 2026 20:44
Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
danielhanchen added a commit that referenced this pull request Oct 18, 2026
## Summary

`(Python 3.13, l-r)` fails on main at `6069a27a`, and on PRs based on it
such as #14151:

```
studio/backend/tests/test_log_budget.py::test_every_classified_path_is_in_a_scenario
AssertionError: these paths are classified in loggers/handlers.py but no scenario in tests/log_budget/session.py polls them, so their log volume is unmeasured:
    /api/inference/images/prompt-upsampler/status
```

#14137 (FLUX.3 prompt upsampling) added
`/api/inference/images/prompt-upsampler/status` to
`_QUIET_SUCCESS_PATHS` in `loggers/handlers.py`, with the note "Polled
by the Images page while the FLUX.3 prompt upsampler downloads". It did
not add the path to either log-budget scenario. The guard is right to
fail: every classified poll needs a cadence so the idle and busy
envelopes stay honest. The product is fine.

## Change

`studio/backend/tests/log_budget/session.py` adds the path to
`BUSY_POLLS` at `(1.0, "declared")`.

The cadence comes from `usePromptUpsamplerStatus` in
`studio/frontend/src/features/images/prompt-enhance-panel.tsx`:
- It reads the status once when the panel becomes active.
- After that it reads every 1000 ms only while `download.downloading` is
true.

It is therefore busy-only, at the same 1 s as the other
download-progress polls. `tests/studio/playwright_declared_polls.py`
reads the same `ALL_POLLS`, so the browser check knows the path too.

## Testing

- `studio/backend/tests/test_log_budget.py`: 8 passed. On main without
this change, `test_every_classified_path_is_in_a_scenario` fails with
the error above.
- `test_log_signal_floor.py` and `test_research_runs_hardening.py`,
which also import the scenario module: 328 passed.
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…upsampler tests (#14169)

## Summary

`(Python 3.13, a-k)` failed three of #14137's new FLUX.3 prompt
upsampler tests on #14151's run (base `def3451e`), on two different
xdist workers:

```
tests/test_flux3_prompt_upsampler.py::test_generated_only_penalties_follow_the_server[True]
tests/test_flux3_prompt_upsampler.py::test_generated_only_penalties_follow_the_server[False]
tests/test_flux3_prompt_upsampler.py::test_stop_during_server_start_cancels_the_start
core.inference.flux3_prompt_upsampler.UpsamplerUnavailableError: The image model no longer holds the GPU.
```

On their own the tests pass on main (93 passed, serially and with `-n
4`). They fail only after another test has run in the same process.
#14151 does not touch either file, so any PR whose worker draws this
order will hit it.

## Cause

`FluxPromptUpsampler.generate` starts the sidecar only while
`_image_model_owns_gpu()`, which reads `gpu_arbiter.current_owner()`
(image model or nobody). That arbiter is process-wide, and the upsampler
tests never pinned it.

I ran each `tests/test_[a-k]*` file that touches the arbiter in front of
`test_flux3_prompt_upsampler.py` in one process. Only
`test_gpu_selection.py` reproduces the failures, and it gives the same
three IDs. Tracing `gpu_arbiter._owner` around each test points at one
test:
`TestRouteErrors::test_inference_route_returns_400_for_invalid_gpu_ids`
(`None -> 'chat'`). It drives the real `/load` route, which claims the
GPU for CHAT through `acquire_for_request` before the stubbed backend
refuses `gpu_ids = [99]`. Nothing puts the arbiter back afterwards.

So the tests are what is wrong here: one leaks global state, the other
depends on it.

A failed chat load leaving CHAT claimed with nothing loaded is a
separate product question, which this PR does not change. I could not
find a failure path in `routes/inference.py` that calls
`release_chat_gpu_claim()`. It may be worth a look on its own.

## Change

Test only:
- **`test_gpu_selection.py`:** `TestRouteErrors.setUp` saves the
arbiter's module state (`_owner`, `_owner_epoch`, `_owner_account`,
`_prior_account`) and restores it with `addCleanup`. The route tests
therefore leave the arbiter as they found it.
- **`test_flux3_prompt_upsampler.py`:** the autouse `_clean` fixture
pins `gpu_arbiter._owner` to `None`, the fresh-start state those tests
assume. The tests about a different owner already set it themselves and
still do.

## Testing

`tests/test_gpu_selection.py tests/test_flux3_prompt_upsampler.py` in
one process, in that order:

| change | result |
|---|---|
| neither (main) | 3 failed, 194 passed: the three IDs above |
| only the upsampler pin | 197 passed |
| only the `TestRouteErrors` restore | 197 passed |
| both (this PR) | 197 passed |

`test_gpu_selection.py`, `test_flux3_prompt_upsampler.py` and
`test_gpu_arbiter.py` together with `-n 4` give 218 passed.
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…eset the startup budget to the build (#14168)

## Summary

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

```
over the startup budget: transfer 2005.9 KB > 2003.5 KB, raw 6665.4 KB > 6659.1 KB      (main at 2fee36f)
```

This PR takes two steps. It moves #14137's prompt upsampler client out
of the startup chunks, which is real growth with a lazy home. It then
resets both limits to the measured build. Main has gone over this budget
repeatedly, and the root of that is a shortfall in how the limits were
raised, which this corrects.

## Cause

**#14137 (FLUX.3 prompt upsampling).** The Images page is lazy
(`ImagesPage = lazy(...)` in `__root.tsx`), but `features/images/api.ts`
is not. Startup modules import it for other calls
(`loaded-models-api.ts`, `loaded-models-sources.ts`,
`use-media-companion-bytes.ts`). #14137 put the four upsampler calls
there, with value imports from `lib/prompt-enhance.ts`, so that module
joined the startup chunks. Only `prompt-enhance-panel.tsx`, inside the
lazy Images page, calls them.

**The limits themselves.** Each raise since #14073 was sized from its
own PR's delta and added to the previous limit. That previous limit
already sat below the build, starting at #14073:
- `475a02ac` measures 2,047,700 B transfer against the 2,047,608 B limit
#14073 set.
- By `2fee36ff` the gap is 6,500 B raw and 2,409 B transfer.

The raises since (#14072, #14075, #14110, #14108, #14113) each added
their delta, so the shortfall carried forward. CI agrees with my machine
to the byte: the first run of this PR read 1999.7 KB transfer on both.

## Change

- **New `features/images/prompt-upsampler-api.ts`:** holds
`getPromptUpsamplerStatus`, `startPromptUpsamplerDownload`,
`cancelPromptUpsamplerDownload` and `previewEnhancedPrompt`, moved
unchanged, with the same `parseJson` error handling.
- **`api.ts`:** now imports only the `PromptEnhancement` type from
`lib/prompt-enhance` (erased at build).
- **`prompt-enhance-panel.tsx`:** imports the calls from the new module.
- **No behavior change** in the app.
- **`check-bundle-budget.ts`:** both limits are reset to the measured
build plus the usual margin (160 B raw, 189 B transfer), with an entry
in the BUDGET comment block explaining why the reset is absolute rather
than by delta.
  - `rawBytes`: 6,819,206 (main after #14113) -> 6,825,885.
  - `transferBytes`: 2,051,727 -> 2,054,261.

## Testing

One machine and build, Node 24, exact byte totals from the budget
script, 95 chunks throughout:

| tree | raw B | transfer B |
|---|---|---|
| main `2fee36ff` | 6,825,378 | 2,053,999 |
| main `2fee36ff` + the move | 6,821,006 | 2,052,708 |
| main `78e5eefa4d` (adds #14113) + the move | 6,821,334 | 2,052,857 |
| + #14183 | 6,821,410 | 2,052,614 |
| + #14172 (one tooltip design) | 6,825,307 | 2,053,990 |
| this PR (main `b227654927`, adds #14184, + the move) | 6,825,725 |
2,054,072 |

- **The move saves:** 4,372 B raw and 1,291 B transfer.
- **#14113 adds:** 328 B raw and 149 B transfer on this build.
- **Landed while main was over, with no raise:** #14183 (+76 B raw, -243
B transfer), #14172 (+3,897 B raw, +1,376 B transfer, the shared tooltip
is in the eager shell) and #14184 (+418 B raw, +82 B transfer). This is
the treadmill the absolute reset stops: while main is red on this check,
growth lands unaccounted.
- **With the new limits:** `within budget (0.2 KB transfer, 0.2 KB raw
to spare)`.
- **`npm run typecheck`:** clean.
- **`bundle-budget-cli.test.ts`, `bundle-budget-closure.test.ts`,
`image-prompt-enhance.test.ts` and
`loaded-models-platform-matrix.test.ts`:** 74 passed.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
…ard (unslothai#14696)

## Studio: pin the FLUX.3 prompt upsampler to the native sd.cpp image
card

The Enhance prompt sidecar (unslothai#14137) finds the image model's card by
reading `placed_ordinal` off the active engine's state. The diffusers
state has that field. The native sd.cpp state (`_SdState`) does not: it
records its card as `physical_gpu_id`. So when FLUX.3 runs on native
sd.cpp, the upsampler always reads "no card":

```text
native physical_gpu_id: 1
_resident_cuda_ordinal(): None
_child_device_mask(...):  {}
```

On a host with more than one visible GPU, the on-demand launch then
starts llama-server with no device mask. llama.cpp's default splits
layers over every visible card, so the 6-7.5 GB sidecar can land on
cards the image model never claimed, and the free-memory probe
(`_accelerator_memory_mib(None)`) and the later `release_if_tight` read
the current device rather than the card the sidecar uses. The
speculative warm start already declined in this case ("placement"), but
the first enhanced generate still launched unpinned.

### Change

`_SdState` gains a read-only `placed_ordinal` property. It maps
`physical_gpu_id` back to the torch-visible ordinal through
`get_parent_visible_gpu_ids()`, which is the same list
`_resolved_server_physical_gpu_id` used to build the physical id. It
returns None when:

- `physical_gpu_id` is None (CPU, Metal, Vulkan, `--offload-to-cpu`,
automatic multi-GPU, one-shot mode), or
- the load used an `UNSLOTH_DIFFUSION_SD_CPP_DEVICE` off-torch card, or
- the id is not in the parent-visible list.

In all three cases the answer stays what it was before. Nothing assigns
`placed_ordinal` on an `_SdState`, and it is not a dataclass field, so
construction, `replace()` and equality are unchanged.

The upsampler and the segmentation helper both read `placed_ordinal`
through `getattr`, so both now see the native card. For the upsampler
that means `_child_device_mask` pins llama-server to the image model's
card (honouring a parent `CUDA_VISIBLE_DEVICES` / `HIP_VISIBLE_DEVICES`
mask), the memory probe reads that card, and the warm start no longer
declines a resolvable native placement. Single-GPU hosts are unchanged,
since `_child_device_mask` returns no mask when torch sees one card.

### Tests

New `studio/backend/tests/test_sd_cpp_upsampler_placement.py`:

- the upsampler reads the native card for an unmasked host (`[0, 1]`,
card 1 and card 0) and for a parent mask (`3,5`, physical 5 is ordinal
1), and None for an id outside the mask
- unresolved and off-torch native placements stay unplaced
- with `CUDA_VISIBLE_DEVICES=3,5` and two torch cards, the llama-server
child env becomes `CUDA_VISIBLE_DEVICES=5`

On main 4 of the 6 cases fail (`assert None == 1`, and `{} ==
{'CUDA_VISIBLE_DEVICES': '5'}` for the mask). With this change all 6
pass, and the existing `test_flux3_prompt_upsampler.py`,
`test_diffusion_segment.py`, `test_gpu_arbiter.py` and
`test_swap_kv_resume.py` pass unchanged.

### Not covered

- A real two-card run with FLUX.3 on native sd.cpp and the upsampler
GGUF was not done here. The tests run the real helpers against the
native state schema.
- A native load whose placement is unresolved (`--offload-to-cpu`,
automatic multi-GPU) still launches the sidecar unpinned on a multi-GPU
host, as before.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant