Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: fix FLUX.3 workflows, controls, LoRAs and download progress (#14312)

oobaboogab32d54408779
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index dc7ba61d178..7c1978bf850 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -409,15 +409,47 @@ logger = get_logger(__name__)
_ZERO_THRESHOLD_NEGATIVE_PROMPT_FAMILIES = frozenset(("z-image", KREA2_FAMILY_NAME))
+def _negative_prompt_guidance_threshold(family: DiffusionFamily) -> Optional[float]:
+ """The guidance above which Studio passes a negative prompt; None when guidance does not gate it. Studio's rule,
+ not the guider's: diffusers also runs CFG below 1, steering toward the negative prompt."""
+ if family.cfg_kwarg == "true_cfg_scale":
+ return 1.0
+ if family.cfg_kwarg == "guidance_scale":
+ return 0.0 if family.name in _ZERO_THRESHOLD_NEGATIVE_PROMPT_FAMILIES else 1.0
+ return None
+
+
+def _refuse_weight_change_on_streamed_graph(state: Any) -> None:
+ """Recapturing a block-streamed graph after a LoRA weight change fails, and the eager fallback then fails every
+ later generate, so such a load keeps its baked weights until a reload."""
+ handles = getattr(state, "cuda_graphs", ()) or ()
+ if any(getattr(getattr(h, "placement", None), "mode", None) == "group" for h in handles):
+ raise ValueError(
+ "This load streams the transformer through GPU memory, so its LoRA weights are fixed until the "
+ "model is reloaded. Reload the model with the new adapter weights."
+ )
+
+
+def _guidance_supported(state: Any) -> bool:
+ """FLUX.2 klein base and distilled share a family; Flux2KleinPipeline turns guidance off on ``is_distilled``."""
+ if not state.family.uses_guidance:
+ return False
+ config = getattr(getattr(state, "pipe", None), "config", None)
+ return not (
+ state.family.name == "flux.2-klein" and bool(getattr(config, "is_distilled", False))
+ )
+
+
+def _live_preview_available(state: Any) -> bool:
+ from .diffusion_preview import preview_available
+ return preview_available(getattr(state.family, "name", None), getattr(state, "device", None))
+
+
def _negative_prompt_engaged(family: DiffusionFamily, guidance: float) -> bool:
if not family.uses_negative_prompt:
return False
- if family.cfg_kwarg == "true_cfg_scale":
- return float(guidance) > 1.0
- if family.cfg_kwarg == "guidance_scale":
- threshold = 0.0 if family.name in _ZERO_THRESHOLD_NEGATIVE_PROMPT_FAMILIES else 1.0
- return float(guidance) > threshold
- return True
+ threshold = _negative_prompt_guidance_threshold(family)
+ return threshold is None or float(guidance) > threshold
# Every `import diffusers` below is lazy, so this runs first. On Windows ROCm both reach an absent distributed
@@ -11223,10 +11255,10 @@ class DiffusionBackend:
) -> None:
"""Generation-time LoRA handling for a torchao-quantized pipe. The adapters (if any) were
baked at load time, before quantize_ + compile, so the module topology is immutable here.
- Allowed without a reload: weight tweaks on the baked set and disabling everything (scale
- 0 reproduces the quantized base exactly; set_adapters is value-level, so torch.compile
- guards absorb it). Anything that would change topology raises a clean 400 telling the
- client to reload with the new selection."""
+ Allowed without a reload: weight tweaks on the baked set and disabling any of it (scale 0
+ reproduces the quantized base exactly; set_adapters is value-level, so torch.compile guards
+ absorb it). Anything that would change topology raises a clean 400 telling the client to
+ reload with the new selection."""
if not quant_baked:
if not specs:
return # no adapters baked, none requested
@@ -11238,6 +11270,7 @@ class DiffusionBackend:
# Disable every baked adapter: scale 0 reproduces the quantized base exactly.
names = [n for (n, _p, _w) in current]
if any(w != 0 for (_n, _p, w) in current):
+ _refuse_weight_change_on_streamed_graph(state)
pipe.set_adapters(names, adapter_weights = [0.0] * len(names))
pipe._unsloth_loras = tuple((n, p, 0.0) for (n, p, _w) in current)
# Adapter scales are Python values read inside the LoRA forward, so a graph bakes them in.
@@ -11249,20 +11282,29 @@ class DiffusionBackend:
hf_token = state.hf_token,
cancel = cancel,
)
- if desired == current:
- return
- if [(n, p) for (n, p, _w) in desired] == [(n, p) for (n, p, _w) in current]:
- pipe.set_adapters(
- [n for (n, _p, _w) in desired],
- adapter_weights = [w for (_n, _p, w) in desired],
+ # Requests drop zero-weight rows, so ``desired`` is the active subset of the bake. Match by file: names
+ # are deduplicated per resolved set, so a subset can rename an adapter. Omitted adapters run at 0.
+ wanted: dict[str, list[float]] = {}
+ for _n, path, weight in desired:
+ wanted.setdefault(path, []).append(weight)
+ updated = tuple(
+ (name, path, wanted[path].pop(0) if wanted.get(path) else 0.0)
+ for (name, path, _w) in current
+ )
+ if any(wanted.values()):
+ raise ValueError(
+ "The LoRA selection changed, but a quantized (int8/fp8) transformer bakes its "
+ "adapters at load time. Reload the model with the new adapter selection."
)
- pipe._unsloth_loras = desired
- cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
+ if updated == current:
return
- raise ValueError(
- "The LoRA selection changed, but a quantized (int8/fp8) transformer bakes its "
- "adapters at load time. Reload the model with the new adapter selection."
+ _refuse_weight_change_on_streamed_graph(state)
+ pipe.set_adapters(
+ [n for (n, _p, _w) in updated],
+ adapter_weights = [w for (_n, _p, w) in updated],
)
+ pipe._unsloth_loras = updated
+ cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
@staticmethod
def _reset_step_cache(pipe: Any) -> None:
@@ -12799,6 +12841,9 @@ class DiffusionBackend:
# Workflows the loaded family supports, so the UI can gate its tabs.
"workflows": _family_workflows(state.family),
"supports_negative_prompt": state.family.uses_negative_prompt,
+ "negative_prompt_min_guidance": _negative_prompt_guidance_threshold(state.family),
+ "supports_guidance": _guidance_supported(state),
+ "supports_live_preview": _live_preview_available(state),
"prompt_hint": state.family.prompt_hint,
"samplers": sampler_options(getattr(state.pipe, "scheduler", None)),
"conditioning": conditioning_capabilities(
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index ba3e0884516..1f165a24fcb 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -89,6 +89,8 @@ class DiffusionFamily:
cfg_kwarg: str = "guidance_scale"
# False when the diffusers pipeline ignores a negative prompt; the native engine decides on its own.
uses_negative_prompt: bool = True
+ # False when the diffusers pipeline takes no guidance (FLUX.3 distilled); FLUX.2 klein is per checkpoint.
+ uses_guidance: bool = True
# One or two sentences on how this family reads prompts; None when it has no quirks.
prompt_hint: Optional[str] = None
# The pipe attribute holding the denoiser: ``pipe.transformer`` for DiT families, ``pipe.unet`` for SDXL.
@@ -511,6 +513,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
# Every keep-set measured 0.09-0.12 LPIPS against bf16 on NVFP4, as did BFL's own nvfp4 package. A passing
# NVFP4 gate record for a base still lifts it.
scheme_deny = frozenset({"nvfp4"}),
+ # The FLUX.2 VAE and the same 2x2 packed 128-channel tokens, so FLUX.2's fitted map applies.
+ preview_factors = "flux2",
),
pipeline_class = "Flux3ModularPipeline",
# Same layout as the distilled repo. The INT8 file is BFL's own ComfyUI int8_convrot denoiser
@@ -563,6 +567,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
# Every keep-set measured 0.09-0.12 LPIPS against bf16 on NVFP4, as did BFL's own nvfp4 package. A passing
# NVFP4 gate record for a base still lifts it.
scheme_deny = frozenset({"nvfp4"}),
+ # The FLUX.2 VAE and the same 2x2 packed 128-channel tokens, so FLUX.2's fitted map applies.
+ preview_factors = "flux2",
),
pipeline_class = "Flux3DistilledModularPipeline",
# Pre-quantized distilled denoisers (both schemes in one repo, as FLUX.2 klein), built with the keep-list above;
@@ -572,6 +578,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
("fp8", "unsloth/flux-3-image-klein-FP8"),
),
uses_negative_prompt = False,
+ uses_guidance = False,
transformer_class = "Flux3Transformer2DModel",
# Qwen3-VL-4B pre-cast fp8, the int8 ConvRot encoder's fallback (diffusion_te_prequant.TE_INT8_CONVROT_FILES).
te_prequant_repos = (("fp8", "text_encoder", "unsloth/flux-3-image-klein-FP8"),),
diff --git a/studio/backend/core/inference/diffusion_preview.py b/studio/backend/core/inference/diffusion_preview.py
index 8064c534886..6b0fc7a0748 100644
--- a/studio/backend/core/inference/diffusion_preview.py
+++ b/studio/backend/core/inference/diffusion_preview.py
@@ -62,6 +62,17 @@ def preview_wanted(requested: Optional[bool]) -> bool:
return True if requested is None else bool(requested)
+def preview_available(family: Optional[str], device: Any) -> bool:
+ """Mirrors ``LatentPreviewer.create``: kill switch off, a fitted map, and CUDA (no event to poll elsewhere)."""
+ if not env_enabled() or factors_for(family) is None:
+ return False
+ try:
+ import torch
+ return torch.device(device).type == "cuda" and torch.cuda.is_available()
+ except Exception: # noqa: BLE001 - a status read must never fail on this
+ return False
+
+
@functools.lru_cache(maxsize = 64)
def factors_for(family: Optional[str]) -> Optional[LatentRGB]:
"""Cached so a family keeps one object, and its device copy is uploaded once per process."""
diff --git a/studio/backend/core/inference/flux3_prompt_upsampler.py b/studio/backend/core/inference/flux3_prompt_upsampler.py
index 65b5760932c..6d84aff1c9d 100644
--- a/studio/backend/core/inference/flux3_prompt_upsampler.py
+++ b/studio/backend/core/inference/flux3_prompt_upsampler.py
@@ -146,6 +146,84 @@ SYSTEM_PROMPTS = {
"\n"
"Output only the instruction."
),
+ "t2i_bbox": (
+ "You are the prompt upsampler of a text-to-image model. Plan the full image the user's short request implies and "
+ "output ONE structured caption on a single line: the global caption paragraph, one space, then ONE JSON array, "
+ "the element table that places every cited element with a bounding box in the image to be generated. Output "
+ "nothing else (no Markdown fences, commentary or refusals); visualize the concept of a non-image input. The "
+ 'request may begin with a "TARGET CANVAS: W:H" line: compose for that canvas and never mention it. Boxes live on '
+ "a 0-1000 grid stretched onto the canvas: an element of physical width-to-height ratio a gets an x-span of about "
+ "y-span x a x H/W.\n"
+ "\n"
+ "Planning: keep every explicit subject, attribute, count, spatial constraint, style cue and "
+ "piece of wording, and decide everything left open as ONE concrete composition that the caption and the table "
+ 'both describe. Without a stated style plan an actual photograph and open with the medium convention ("Full-color '
+ 'outdoor photograph, ...", "Studio photograph, ..."); add camera optics only when asked for; do not invent names, '
+ "brands, logos or celebrities; drop appraisal and sales vocabulary.\n"
+ "\n"
+ "The table: one row per distinct object, "
+ "person, animal, building or salient region the caption mentions and one per coherent text block; no rows for "
+ "style, lighting or atmosphere. Structured layouts (tables, grids, calendars, keyboards, charts, maps, posters, "
+ "pages) decompose into their regions, each row carrying that region's complete verbatim content; more than about "
+ "ten interchangeable items become one collection row giving the exact count and arrangement, while items whose "
+ 'positions matter keep a row each. Row keys, in order: "id", "bbox", "desc". id: the bare class noun plus an '
+ "index numbered left to right, then top to bottom, from 1 (person_1, dog_2); a text block is its two-letter "
+ "language code plus _Text_ plus an index (En_Text_1); one entity is one row and ids are unique. bbox: [y_min, "
+ "x_min, y_max, x_max] as integers from 0 to 1000, top-left origin, clamped at the borders, with plausible "
+ "relative sizes and a small margin around text. desc: one self-contained paragraph in the generative voice that "
+ 'opens with the element\'s identity (never "the X"): shape, material, colors, state and markings, but no position. '
+ "People in focus get the richest desc: ethnicity, gender, age range, skin tone, build, hair, face, each garment, "
+ "accessories, pose and expression. A text row carries its complete wording verbatim in double quotes, with line "
+ "breaks as \\n, plus its typography.\n"
+ "\n"
+ "The global caption: one flowing paragraph in the generative voice (medium "
+ "first, then scene, lighting, camera and frame-relative layout; no quality judgments) that names each table "
+ 'element at identity level at its first mention and cites it with its id in its own angle brackets: "a wicker '
+ 'table <table_1> holding a tiered stand <stand_1>". Cite every table id and no other; appearance detail and text '
+ "content live in the descs; no coordinates. Text-dense documents are laid out region by region with every visible "
+ "text transcribed verbatim at a readable size (cut content rather than shrink type), and a grid quotes every "
+ "visible cell. All prose is English; only quoted text keeps its language.\n"
+ "\n"
+ "Output only the caption and the table."
+ ),
+ "i2i_bbox": (
+ "You are the annotation system an image-editing model was trained on. You see the source image(s), attached in "
+ "order as ref_image_0, ref_image_1, ..., and the user's editing instruction; the edited target image does not "
+ "exist yet. Determine the edit precisely, imagine the target consistently with the source, and write the record "
+ "its annotator would have written, on one line: the instruction paragraph, one space, then ONE JSON array. Output "
+ "nothing else.\n"
+ "\n"
+ 'The paragraph: English, instruction voice ("Change the ...", "Remove the ...", or "Create a '
+ 'photograph of ..." when the references are drawn into a new frame), never observer phrasing and never a '
+ "comparison with the target. Cite every involved object, person or text block at its first mention with its table "
+ 'id in its own angle brackets ("remove the delivery van <van_1>"), every table id exactly once and no other id; '
+ 'cite a reference image by its token when content is taken from it ("the cup <cup_1> from <ref_image_1>"). End '
+ "states (new color, new text in quotes, pose, degree) live in the paragraph, static appearance in the descs; no "
+ "coordinates. An editing instruction closes with one compact clause that everything else stays identical to the "
+ "source.\n"
+ "\n"
+ 'The table, rows {"id", "from", "src_bbox", "tgt_bbox", "desc"}: one row per edited, removed, added, '
+ "moved or anchoring item, plus the scene or background when it is itself changed or preserved; no rows for "
+ "untouched scenery. id: a lowercase class noun plus an index (person_1, cup_2) numbered left to right, then top "
+ 'to bottom; text blocks are En_Text_1 and so on; ids are unique. from: "ref_image_N" for an item visible in '
+ 'reference N, "target" for newly created content. src_bbox is the item\'s box in its from-image and null for '
+ "target rows; tgt_bbox is its box in the imagined result and null for removed items; moved or resized items carry "
+ "both; new items are sized like similar objects in the frame. Boxes are [y_min, x_min, y_max, x_max] integers "
+ "from 0 to 1000, top-left origin, tight around objects, with 5 to 15 units of margin around text. A row may also "
+ "carry src_bbox_1stage and tgt_bbox_1stage, a first-pass estimate of the same boxes. desc: one English paragraph "
+ "of the item's static appearance in its from-image (for target rows, its decided appearance), opening with its "
+ "identity; people get the richest descs (ethnicity, gender, age range, skin tone, hair, face, garments, "
+ "accessories, pose, expression); text rows quote their text verbatim.\n"
+ "\n"
+ "State only decided facts: visible in the "
+ "source, demanded by the instruction, or a concrete default needed to realize it. Settle whether the edit targets "
+ "one instance, all of a class or several; land every magnitude on a concrete value; include visible knock-on "
+ "effects; added objects are new objects at real-world size; a zoom-in names the neighbors it excludes; an "
+ "outpainting keeps the source whole and continues it in the same medium. Everything the instruction does not "
+ "involve stays identical to the source.\n"
+ "\n"
+ "Output only the paragraph and the table."
+ ),
}
# The user turn of an edit: the reference images, then this text.
I2I_SCAFFOLD = (
@@ -153,6 +231,12 @@ I2I_SCAFFOLD = (
"User request: {instruction}\n"
"Output the caption."
)
+# The same for a layout edit (``i2i_bbox``), from BFL's flux3/pup.py.
+I2I_BBOX_SCAFFOLD = (
+ "Reference images follow in attachment order: ref_image_0, ref_image_1, ...\n"
+ "User editing instruction: {instruction}\n"
+ "Decide the edit, imagine the target image, and output the annotation record."
+)
# ── sampling (ComfyUI FLUX.3 templates) ─────────────────────────────────────────────────────────────────────────────
MAX_NEW_TOKENS = 3584
@@ -348,16 +432,22 @@ def build_chat_payload(
references: Optional[list[bytes]] = None,
*,
edit: Optional[bool] = None,
+ locked: Optional[list[dict]] = None,
) -> dict:
"""The /v1/chat/completions body. ``references`` are prepared JPEGs; ``edit`` forces the edit prompt without
- images (a missing mmproj runs an edit text-only)."""
+ images (a missing mmproj runs an edit text-only). ``locked`` box rows select the layout prompts
+ (``t2i_bbox`` / ``i2i_bbox``) and wrap ``prompt`` in BFL's locked-annotation request."""
if variant not in VARIANTS:
raise ValueError(f"variant must be one of {', '.join(VARIANTS)}")
references = list(references or [])
edit = bool(references) if edit is None else bool(edit)
mode = "i2i" if edit else "t2i"
+ system_key = f"{mode}_bbox" if locked else mode
+ if locked:
+ prompt = layout_request(prompt, locked)
if edit:
import base64
+
content: list[dict] = [
{
"type": "image_url",
@@ -367,13 +457,14 @@ def build_chat_payload(
}
for ref in references
]
- content.append({"type": "text", "text": I2I_SCAFFOLD.format(instruction = prompt)})
+ scaffold = I2I_BBOX_SCAFFOLD if locked else I2I_SCAFFOLD
+ content.append({"type": "text", "text": scaffold.format(instruction = prompt)})
else:
content = [{"type": "text", "text": prompt}]
repeat_penalty, presence_penalty = PENALTIES[(mode, variant)]
return {
"messages": [
- {"role": "system", "content": SYSTEM_PROMPTS[mode]},
+ {"role": "system", "content": SYSTEM_PROMPTS[system_key]},
{"role": "user", "content": content},
],
**_BASE_SAMPLING,
@@ -396,6 +487,179 @@ def clean_caption(text: Optional[str]) -> str:
return text
+# ── layout captions (bounding boxes) ────────────────────────────────────────────────────────────────────────────────
+# Adapted from BFL's src/flux3/bbox.py (black-forest-labs/flux-3-image-klein at bfc8889a, Apache-2.0). Boxes arrive
+# inside the prompt: "<caption> [rows]", rows {"id", "bbox": [y_min, x_min, y_max, x_max] on 0-1000, "desc"} (edits:
+# "from", "src_bbox", "tgt_bbox"). The plain t2i / i2i prompts forbid ids and coordinates and would drop them.
+BOX_CANVAS = 1000
+_BOX_ID = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
+
+
+def split_box_table(text: str) -> tuple[str, Optional[list]]:
+ """(caption, rows) for the JSON list closing the text, if any. Not a regex: descs may hold brackets."""
+ for i in range(len(text) - 1, -1, -1):
+ if text[i] == "[":
+ try:
+ rows = json.loads(text[i:])
+ except json.JSONDecodeError:
+ continue
+ if isinstance(rows, list):
+ return text[:i].rstrip(), rows
+ return text.strip(), None
+
+
+def valid_canvas_box(box: Any) -> Optional[list]:
+ """The box if it is a well-formed [y_min, x_min, y_max, x_max] on the 0-1000 canvas, else None."""
+ if not isinstance(box, (list, tuple)) or len(box) != 4:
+ return None
+ if any(
+ isinstance(v, bool) or not isinstance(v, (int, float)) or v != v or abs(v) == float("inf")
+ for v in box
+ ):
+ return None
+ y1, x1, y2, x2 = box
+ # max <= 1 means 0-1 coordinates, not the 0-1000 canvas
+ if (
+ y1 < 0
+ or x1 < 0
+ or y2 <= y1
+ or x2 <= x1
+ or y2 > BOX_CANVAS
+ or x2 > BOX_CANVAS
+ or max(box) <= 1
+ ):
+ return None
+ return list(box)
+
+
+def detect_box_table(prompt: str) -> Optional[tuple[str, list[dict]]]:
+ """(caption, rows) when ``prompt`` ends in a box table of only box rows (not a caption ending in "[SALE]")."""
+ text, rows = split_box_table(prompt)
+ if not rows or not all(
+ isinstance(row, dict)
+ and isinstance(row.get("id"), str)
+ and _BOX_ID.fullmatch(row["id"])
+ and any(valid_canvas_box(row.get(key)) for key in ("bbox", "src_bbox", "tgt_bbox"))
+ for row in rows
+ ):
+ return None
+ locked = re.fullmatch(
+ r"ORIGINAL PROMPT:\n(.*?)\n\nLOCKED BOUNDING-BOX ANNOTATIONS .*", text, re.S
+ )
+ return (locked.group(1) if locked else text), rows
+
+
+def is_finished_layout_caption(prompt: str) -> bool:
+ """Every box id cited as <id> in the caption: an upsampler answer, which BFL's generate.py sends as it is."""
+ found = detect_box_table(prompt)
+ return found is not None and all(f"<{row['id']}>" in found[0] for row in found[1])
+
+
+def layout_request(prompt: str, rows: list[dict]) -> str:
+ return (
+ f"ORIGINAL PROMPT:\n{prompt.strip()}\n\n"
+ "LOCKED BOUNDING-BOX ANNOTATIONS ([y_min, x_min, y_max, x_max] on a 0-1000 canvas, with (0, 0) at "
+ "the top-left). This is an authoritative JSON list of dictionaries; preserve every supplied identity, "
+ f"provenance value, null, and coordinate exactly:\n{json.dumps(rows, ensure_ascii = False)}"
+ )
+
+
+def _valid_added_row(row: Any, caption: str) -> Optional[dict]:
+ if not isinstance(row, dict):
+ return None
+ row_id, desc = row.get("id"), row.get("desc")
+ if (
+ not isinstance(row_id, str)
+ or not _BOX_ID.fullmatch(row_id)
+ or f"<{row_id}>" not in caption
+ or not isinstance(desc, str)
+ or not desc.strip()
+ ):
+ return None
+ if (box := valid_canvas_box(row.get("bbox"))) is not None:
+ return {"id": row_id, "bbox": box, "desc": desc.strip()}
+ origin, src, tgt = row.get("from"), row.get("src_bbox"), row.get("tgt_bbox")
+ src_box = valid_canvas_box(src) if src is not None else None
+ tgt_box = valid_canvas_box(tgt) if tgt is not None else None
+ if (
+ not isinstance(origin, str)
+ or not re.fullmatch(r"ref_image_\d+|target", origin)
+ or (src is not None and src_box is None)
+ or (tgt is not None and tgt_box is None)
+ or (src_box is None and tgt_box is None)
+ or (origin == "target") == (src_box is not None)
+ ):
+ return None
+ return {
+ "id": row_id,
+ "from": origin,
+ "src_bbox": src_box,
+ "tgt_bbox": tgt_box,
+ "desc": desc.strip(),
+ }
+
+
+def _first_valid_box(row: dict) -> Optional[list]:
+ for key in ("bbox", "tgt_bbox", "src_bbox"):
+ if (box := valid_canvas_box(row.get(key))) is not None:
+ return box
+ return None
+
+
+def _box_iou(a: list, b: list) -> float:
+ inter = max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(0, min(a[3], b[3]) - max(a[1], b[1]))
+ union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
+ return inter / union if union > 0 else 0.0
+
+
+def reconcile_layout_caption(text: str, locked: list[dict]) -> str:
+ """The upsampler's answer with the user's boxes re-imposed. A row re-planning a locked box under its own id
+ (IoU >= 0.9) takes the locked id, in the rows and the caption's citations; the locked rows are kept verbatim with
+ the upsampler's description; rows it added follow if they are valid."""
+ caption, rows = split_box_table(text)
+ rows = rows or []
+ locked_ids = {row["id"] for row in locked}
+ row_ids = {row.get("id") for row in rows if isinstance(row, dict)}
+ renamed: dict = {}
+ for lock in locked:
+ lock_box = _first_valid_box(lock)
+ if lock["id"] in row_ids or lock_box is None:
+ continue
+ for row in rows:
+ if not isinstance(row, dict) or row.get("id") in renamed or row.get("id") in locked_ids:
+ continue
+ box = _first_valid_box(row)
+ if box is not None and _box_iou(box, lock_box) >= 0.9:
+ renamed[row["id"]] = lock["id"]
+ break
+ for row in rows:
+ if isinstance(row, dict) and row.get("id") in renamed:
+ row["id"] = renamed[row["id"]]
+ for old, new in renamed.items():
+ caption = caption.replace(f"<{old}>", f"<{new}>")
+ by_id = {
+ row.get("id"): row
+ for row in rows
+ if isinstance(row, dict) and isinstance(row.get("id"), str)
+ }
+ out = []
+ for lock in locked:
+ desc = by_id.get(lock["id"], {}).get("desc")
+ out.append(
+ {
+ **lock,
+ "desc": desc.strip()
+ if isinstance(desc, str) and desc.strip()
+ else lock.get("desc", ""),
+ }
+ )
+ for row in rows:
+ added = _valid_added_row(row, caption)
+ if added is not None and added["id"] not in {r["id"] for r in out}:
+ out.append(added)
+ return f"{caption} {json.dumps(out, ensure_ascii = False)}"
+
+
# ── weights on disk ─────────────────────────────────────────────────────────────────────────────────────────────────
@dataclass(frozen = True)
class _UpsamplerSpec:
@@ -1490,7 +1754,10 @@ def upsample(
sidecar: Optional[PromptUpsamplerSidecar] = None,
) -> str:
"""The caption for ``prompt`` (cached). Raises UpsamplerUnavailableError when nothing can run, a cancel as
- UpsamplerCancelledError, and anything else the server does. An empty caption returns ``prompt``."""
+ UpsamplerCancelledError, and anything else the server does. An empty caption returns ``prompt``, as does a
+ finished layout caption, which the image model takes as it is."""
+ if is_finished_layout_caption(prompt):
+ return prompt
binary = find_llama_server_binary()
if binary is None:
raise UpsamplerUnavailableError("llama.cpp (llama-server) is not installed.")
@@ -1508,7 +1775,10 @@ def upsample(
)
else:
references = prepare_references(reference_images)
- payload = build_chat_payload(prompt, variant, references, edit = edit)
+ # A box table in the prompt switches to the layout prompts with its rows locked (BFL's bbox.plan).
+ found = detect_box_table(prompt)
+ request, locked = found if found is not None else (prompt, None)
+ payload = build_chat_payload(request, variant, references, edit = edit, locked = locked)
key = (prompt, variant, edit, references_hash(references), model)
cached = _cache_get(key)
if cached is not None:
@@ -1525,6 +1795,8 @@ def upsample(
if not text:
logger.warning("flux3.prompt_upsampler: empty caption; using the prompt as typed")
return prompt
+ if locked:
+ text = reconcile_layout_caption(text, locked)
_cache_put(key, text)
return text
@@ -1582,6 +1854,11 @@ def enhance_for_generation(
for index, prompt in enumerate(distinct):
if cancel_event.is_set():
raise UpsamplerCancelledError("Cancelled.")
+ if is_finished_layout_caption(prompt):
+ # Already an upsampler caption with its box table: rewriting it would only drop the boxes.
+ outcome.statuses[prompt] = STATUS_OFF
+ _advance(tracked)
+ continue
systemic = None
try:
caption = upsample(
diff --git a/studio/backend/core/inference/mlx_diffusion_backend.py b/studio/backend/core/inference/mlx_diffusion_backend.py
index 91f793e7e1b..63cda6b808f 100644
--- a/studio/backend/core/inference/mlx_diffusion_backend.py
+++ b/studio/backend/core/inference/mlx_diffusion_backend.py
@@ -1281,9 +1281,9 @@ class MlxDiffusionBackend:
conditioning["reference_resolutions"] = []
conditioning["notes"] = []
try:
- negative = bool(self._rt().supports_guidance(state.model))
+ guided = bool(self._rt().supports_guidance(state.model))
except Exception: # noqa: BLE001
- negative = False
+ guided = False
return {
"loaded": True,
"repo_id": state.repo_id,
@@ -1317,7 +1317,11 @@ class MlxDiffusionBackend:
},
"supports_lora": False,
"supports_controlnet": False,
- "supports_negative_prompt": negative,
+ "supports_negative_prompt": guided,
+ # CFG, and with it the negative prompt, engages only above guidance 1 (cache_text_encodings, generate).
+ "negative_prompt_min_guidance": 1.0 if guided else None,
+ "supports_guidance": guided,
+ "supports_live_preview": False,
"prompt_hint": state.family.prompt_hint,
"workflows": ["txt2img"],
"conditioning": conditioning,
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index c98c395fe6a..7dda3573a91 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -2592,6 +2592,13 @@ def _map_guidance(
return cfg, None
+def _negative_prompt_guidance_threshold(fam: DiffusionFamily) -> Optional[float]:
+ """sd.cpp drops a negative prompt unless _map_guidance gives cfg > 1; embedded-guidance families never use one."""
+ if fam.name in _EMBEDDED_GUIDANCE_FAMILIES:
+ return None
+ return 0.0 if fam.name == "z-image" else 1.0
+
+
def _assert_shards_beside_index(kind: str, path: str) -> None:
"""sd-cli resolves a ``*.safetensors.index.json`` encoder's shards relative to the index, so every shard it names
must sit in the same snapshot directory. The shards are fetched as their own assets, which normally lands them
@@ -4991,6 +4998,10 @@ class SdCppDiffusionBackend:
),
"supports_controlnet": False,
"supports_negative_prompt": state.family.name not in _EMBEDDED_GUIDANCE_FAMILIES,
+ "negative_prompt_min_guidance": _negative_prompt_guidance_threshold(state.family),
+ # Every family maps guidance to sd.cpp's cfg or embedded guidance (_map_guidance). No denoise previews.
+ "supports_guidance": True,
+ "supports_live_preview": False,
"prompt_hint": state.family.prompt_hint,
# "server" = resident sd-server (load once); "oneshot" = legacy per-image sd-cli.
"native_mode": state.mode,
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 65e84bd7dea..331b32be408 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -5667,6 +5667,22 @@ class DiffusionStatusResponse(BaseModel):
"(drives the Negative prompt field). False for FLUX and Ideogram 4 on diffusers, and "
"for FLUX.1 / Kontext / FLUX.2-dev on the native engine.",
)
+ negative_prompt_min_guidance: Optional[float] = Field(
+ None,
+ description = "The guidance Studio passes a negative prompt above (1 for classifier-free guidance, 0 "
+ "for Z-Image and Krea 2 on diffusers); null when guidance does not gate it. Drives the Negative prompt hint.",
+ )
+ supports_guidance: bool = Field(
+ True,
+ description = "Whether the loaded model reads the guidance value on this engine (drives the Guidance "
+ "control). False on diffusers for FLUX.3 Klein (distilled), whose pipeline has no guidance, and for "
+ "distilled FLUX.2 klein checkpoints, which Flux2KleinPipeline runs without it.",
+ )
+ supports_live_preview: bool = Field(
+ True,
+ description = "Whether generations on this load can stream live denoise previews (drives the Live preview "
+ "switch). False on the native and MLX engines and for families without a fitted preview map.",
+ )
prompt_hint: Optional[str] = Field(
None,
description = "How the loaded model reads prompts, in one or two sentences; null when "
diff --git a/studio/backend/tests/fixtures/diffusion_family_data_freeze.json b/studio/backend/tests/fixtures/diffusion_family_data_freeze.json
index 9cde1a53043..3daa6adeae7 100644
--- a/studio/backend/tests/fixtures/diffusion_family_data_freeze.json
+++ b/studio/backend/tests/fixtures/diffusion_family_data_freeze.json
@@ -1292,7 +1292,7 @@
"zero_row": []
},
"page": "image",
- "preview_key": null,
+ "preview_key": "flux2",
"te_int8_effective": "fp8"
},
"flux.3-klein-base": {
@@ -1415,7 +1415,7 @@
"zero_row": []
},
"page": "image",
- "preview_key": null,
+ "preview_key": "flux2",
"te_int8_effective": "fp8"
},
"hidream-i1": {
@@ -3650,6 +3650,8 @@
"flux.1-kontext": "flux1",
"flux.2-dev": "flux2",
"flux.2-klein": "flux2",
+ "flux.3-klein": "flux2",
+ "flux.3-klein-base": "flux2",
"hunyuanvideo-1.5": "hv15",
"hunyuanvideo-1.5-720p": "hv15",
"ltx-2": "ltx2",
diff --git a/studio/backend/tests/test_diffusion_control_capabilities.py b/studio/backend/tests/test_diffusion_control_capabilities.py
new file mode 100644
index 00000000000..12641471c55
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_control_capabilities.py
@@ -0,0 +1,91 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""What the Images page is told about the loaded model's Guidance, Negative prompt and Live preview controls: each
+status field must agree with what the engine actually does with the value."""
+
+from __future__ import annotations
+
+import pytest
+
+from core.inference import diffusion, diffusion_preview, sd_cpp_backend
+from core.inference.diffusion_families import _FAMILIES
+
+
[email protected]("fam", _FAMILIES, ids = lambda f: f.name)
+def test_diffusers_negative_threshold_is_where_the_negative_prompt_engages(fam):
+ threshold = diffusion._negative_prompt_guidance_threshold(fam)
+ if not fam.uses_negative_prompt:
+ assert not diffusion._negative_prompt_engaged(fam, 10.0)
+ elif threshold is None:
+ assert diffusion._negative_prompt_engaged(fam, 0.0)
+ else:
+ assert not diffusion._negative_prompt_engaged(fam, threshold)
+ assert diffusion._negative_prompt_engaged(fam, threshold + 0.5)
+
+
[email protected]("fam", _FAMILIES, ids = lambda f: f.name)
+def test_native_negative_threshold_is_where_sd_cpp_runs_cfg(fam):
+ # sd.cpp drops the negative prompt unless _map_guidance gives a cfg above 1.
+ threshold = sd_cpp_backend._negative_prompt_guidance_threshold(fam)
+ if threshold is None:
+ assert fam.name in sd_cpp_backend._EMBEDDED_GUIDANCE_FAMILIES
+ return
+ assert sd_cpp_backend._map_guidance(fam, threshold)[0] <= 1.0
+ assert sd_cpp_backend._map_guidance(fam, threshold + 0.5)[0] > 1.0
+
+
+def test_flux3_thresholds_are_one():
+ by_name = {f.name: f for f in _FAMILIES}
+ for name in ("flux.3-klein", "flux.3-klein-base"):
+ assert sd_cpp_backend._negative_prompt_guidance_threshold(by_name[name]) == 1.0
+ assert diffusion._negative_prompt_guidance_threshold(by_name["flux.3-klein-base"]) == 1.0
+
+
+def test_only_the_distilled_flux3_graph_ignores_guidance_as_a_family():
+ # Flux3DistilledModularPipeline has no guider, so diffusion_flux3._set_guidance drops the value.
+ assert [f.name for f in _FAMILIES if not f.uses_guidance] == ["flux.3-klein"]
+
+
+ "family, is_distilled, expected",
+ [
+ ("flux.3-klein", False, False),
+ ("flux.3-klein-base", False, True),
+ # Flux2KleinPipeline.do_classifier_free_guidance is False whenever config.is_distilled.
+ ("flux.2-klein", True, False),
+ ("flux.2-klein", False, True),
+ # Krea 2 Turbo's is_distilled only moves the scheduler shift; it still runs CFG.
+ ("krea-2", True, True),
+ ],
+)
+def test_guidance_support_follows_the_loaded_checkpoint(family, is_distilled, expected):
+ from types import SimpleNamespace
+
+ fam = next(f for f in _FAMILIES if f.name == family)
+ state = SimpleNamespace(
+ family = fam, pipe = SimpleNamespace(config = SimpleNamespace(is_distilled = is_distilled))
+ )
+ assert diffusion._guidance_supported(state) is expected
+
+
[email protected]("name", ["flux.3-klein", "flux.3-klein-base", "flux.2-klein"])
+def test_flux3_has_a_live_preview_map_like_flux2(name, monkeypatch):
+ import torch
+
+ monkeypatch.delenv(diffusion_preview.PREVIEW_ENV, raising = False)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ assert diffusion_preview.factors_for(name) == diffusion_preview.factors_for("flux.2-klein")
+ assert diffusion_preview.preview_available(name, "cuda")
+ assert not diffusion_preview.preview_available(name, "cpu")
+ monkeypatch.setenv(diffusion_preview.PREVIEW_ENV, "0")
+ assert not diffusion_preview.preview_available(name, "cuda")
+
+
+def test_a_family_without_a_map_has_no_live_preview(monkeypatch):
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ without = [f.name for f in _FAMILIES if diffusion_preview.factors_for(f.name) is None]
+ assert without, "every family has a map; drop this test"
+ assert not diffusion_preview.preview_available(without[0], "cuda")
diff --git a/studio/backend/tests/test_diffusion_lora.py b/studio/backend/tests/test_diffusion_lora.py
index 65443be3246..29cfd81319b 100644
--- a/studio/backend/tests/test_diffusion_lora.py
+++ b/studio/backend/tests/test_diffusion_lora.py
@@ -405,6 +405,77 @@ def test_diffusers_apply_rejects_unsupported_quant():
assert pipe.loaded == [] # rejected before touching the pipe
+def test_baked_quant_pipe_disables_any_subset_of_its_adapters(monkeypatch):
+ # Turning one of two baked adapters off arrives as the other alone: a weight change, not a new selection.
+ # Every alias collides here, so a subset resolves to other names than the bake: adapters match by file.
+ import threading
+
+ monkeypatch.setattr(
+ dl,
+ "resolve_specs",
+ lambda specs, **_: [
+ dl.ResolvedLora(i, "style", f"/{i}.safetensors", "safetensors", w) for i, w in specs
+ ],
+ )
+ b = _backend()
+ pipe = _FakePipe()
+ state = _fake_state(pipe, quant = "int8")
+ pipe._unsloth_loras = b._resolve_lora_set(
+ [("styleA", 1.0), ("styleB", 1.0)], family = "flux.1", hf_token = None
+ )
+ pipe._unsloth_loras_baked = True
+ assert [n for (n, _p, _w) in pipe._unsloth_loras] == ["style", "style_2"]
+
+ b._apply_loras(state, [("styleA", 1.0), ("styleB", 0.0)], threading.Event())
+ assert pipe.active == (["style", "style_2"], [1.0, 0.0])
+ b._apply_loras(state, [("styleB", 0.5)], threading.Event())
+ assert pipe.active == (["style", "style_2"], [0.0, 0.5])
+ b._apply_loras(state, [("styleB", 1.0), ("styleA", 0.7)], threading.Event())
+ assert pipe.active == (["style", "style_2"], [0.7, 1.0])
+ assert pipe.loaded == [] # never reloaded or re-attached
+ # A file the bake does not hold still needs a reload with the new selection.
+ with pytest.raises(ValueError, match = "Reload the model with the new adapter selection"):
+ b._apply_loras(state, [("styleA", 1.0), ("styleC", 1.0)], threading.Event())
+ assert pipe.active == (["style", "style_2"], [0.7, 1.0])
+
+
[email protected]("mode, refused", [("group", True), ("resident", False), ("model", False)])
+def test_baked_weights_stay_fixed_under_a_block_streamed_graph(monkeypatch, mode, refused):
+ # Resetting a block-streamed graph for new LoRA scales left every later generate failing. Refuse the change.
+ import threading
+
+ monkeypatch.setattr(
+ dl,
+ "resolve_specs",
+ lambda specs, **_: [
+ dl.ResolvedLora(i, dl.sanitize_alias(i), f"/{i}.safetensors", "safetensors", w)
+ for i, w in specs
+ ],
+ )
+ b = _backend()
+ pipe = _FakePipe()
+ state = _fake_state(pipe, quant = "int8")
+ state.cuda_graphs = (
+ types.SimpleNamespace(placement = types.SimpleNamespace(mode = mode), reset = lambda: None),
+ )
+ pipe._unsloth_loras = b._resolve_lora_set(
+ [("styleA", 1.0), ("styleB", 1.0)], family = "flux.1", hf_token = None
+ )
+ pipe._unsloth_loras_baked = True
+ baked = pipe._unsloth_loras
+ # The baked weights themselves never touch the graph.
+ b._apply_loras(state, [("styleA", 1.0), ("styleB", 1.0)], threading.Event())
+ for loras in ([("styleA", 1.0)], [("styleA", 0.5), ("styleB", 1.0)], []):
+ if refused:
+ with pytest.raises(ValueError, match = "Reload the model with the new adapter weights"):
+ b._apply_loras(state, loras, threading.Event())
+ assert pipe._unsloth_loras == baked and pipe.active is None
+ else:
+ b._apply_loras(state, loras, threading.Event())
+ if not refused:
+ assert pipe.active == (["styleA", "styleB"], [0.0, 0.0])
+
+
def test_diffusers_apply_rejects_gguf_adapter(monkeypatch):
# A .gguf adapter (discoverable in the shared catalog) cannot load on the diffusers engine, so it is a clean 400 before touching the pipe.
import threading
diff --git a/studio/backend/tests/test_flux3_prompt_upsampler.py b/studio/backend/tests/test_flux3_prompt_upsampler.py
index ce260dd6b19..9b5255ffec8 100644
--- a/studio/backend/tests/test_flux3_prompt_upsampler.py
+++ b/studio/backend/tests/test_flux3_prompt_upsampler.py
@@ -37,11 +37,15 @@ def _clean(monkeypatch):
# diffusers SYSTEM_PROMPTS at d42ebf9c6e.
_T2I_SHA = "8b235a421bce2213d11ada01f5a1244443dd72303ffbb4cc9e5a0d8b0de5ab6f"
_I2I_SHA = "95cec384d5b6d341caa9fb3f2c7ca45ee80c2364b3a95d4044aebf976f6dd3bf"
+_T2I_BBOX_SHA = "5f513d8ce5838732919f9e645507aa20ff373e88bf93132c768e063c9db3151f"
+_I2I_BBOX_SHA = "9ad10f947e401337cf155cac0518cc428159ef16f2f029f48aae2aaab8380a5e"
def test_system_prompts_are_bfls_verbatim():
assert hashlib.sha256(pup.SYSTEM_PROMPTS["t2i"].encode()).hexdigest() == _T2I_SHA
assert hashlib.sha256(pup.SYSTEM_PROMPTS["i2i"].encode()).hexdigest() == _I2I_SHA
+ assert hashlib.sha256(pup.SYSTEM_PROMPTS["t2i_bbox"].encode()).hexdigest() == _T2I_BBOX_SHA
+ assert hashlib.sha256(pup.SYSTEM_PROMPTS["i2i_bbox"].encode()).hexdigest() == _I2I_BBOX_SHA
@pytest.mark.parametrize(
@@ -1713,3 +1717,93 @@ def test_release_route_cancels_a_warm_start_and_stops_an_idle_server(routes, mon
assert r.status_code == 200 and r.json() == {"released": True, "cancelled_warm": True}
# Non-blocking: a request still using the server keeps it.
assert calls == ["cancel", ("unload", False)]
+
+
+# ── layout captions (bounding boxes) ────────────────────────────────────────────────────────────────────────────────
+# A finished caption: every box id is cited as <id> (BFL's generate.py sends it to the DiT as it is).
+_FINISHED = (
+ "A white canvas with a red circle <circle_1> upper left and a blue square <square_1> lower right. "
+ '[{"id": "circle_1", "bbox": [100, 100, 400, 400], "desc": "solid red circle"}, '
+ '{"id": "square_1", "bbox": [600, 600, 900, 900], "desc": "solid blue square"}]'
+)
+# A request with boxes (BFL examples/inputs/balloons_boxes.json on the 0-1000 canvas): no id is cited yet.
+_REQUEST = (
+ "hot-air balloons over a green valley at sunrise "
+ '[{"id": "obj_1", "bbox": [80, 60, 480, 380], "desc": "a red and yellow striped hot-air balloon"}]'
+)
+
+
+ "prompt, finished, boxes",
+ [
+ (_FINISHED, True, True),
+ (_REQUEST, False, True),
+ ("A poster that reads [SALE]", False, False),
+ ('A list ["a", "b"]', False, False),
+ # 0-1 coordinates are not the 0-1000 canvas.
+ ('x <o_1> [{"id": "o_1", "bbox": [0.1, 0.1, 0.4, 0.4], "desc": "d"}]', False, False),
+ ],
+)
+def test_box_table_detection(prompt, finished, boxes):
+ assert pup.is_finished_layout_caption(prompt) is finished
+ assert (pup.detect_box_table(prompt) is not None) is boxes
+
+
+def test_a_finished_layout_caption_skips_the_upsampler(runnable):
+ assert pup.upsample(_FINISHED) == _FINISHED
+ out = pup.enhance_for_generation([_FINISHED], family_name = "flux.3-klein", enhance_prompt = None)
+ assert runnable.calls == []
+ # Used as it is, which is what enhancement off records, not a failed rewrite.
+ assert (
+ out.status == "off"
+ and out.encoded(_FINISHED) == _FINISHED
+ and out.caption_for(_FINISHED) is None
+ )
+
+
+def test_a_box_request_uses_the_layout_prompt_and_keeps_the_boxes(runnable):
+ def reply(payload):
+ # The upsampler re-plans obj_1 under its own id and adds a row; reconcile restores the locked box and id.
+ return (
+ "Full-color photograph with a balloon <balloon_1> and the sun <sun_1>. "
+ '[{"id": "balloon_1", "bbox": [82, 58, 478, 381], "desc": "A striped balloon."}, '
+ '{"id": "sun_1", "bbox": [470, 455, 535, 525], "desc": "A low sun."}]'
+ )
+
+ runnable.reply = reply
+ caption = pup.upsample(_REQUEST, variant = "base")
+ payload = runnable.calls[0]["payload"]
+ assert payload["messages"][0]["content"] == pup.SYSTEM_PROMPTS["t2i_bbox"]
+ text = payload["messages"][1]["content"][0]["text"]
+ assert text.startswith(
+ "ORIGINAL PROMPT:\nhot-air balloons over a green valley at sunrise\n\nLOCKED"
+ )
+ assert '"bbox": [80, 60, 480, 380]' in text
+ assert caption == (
+ "Full-color photograph with a balloon <obj_1> and the sun <sun_1>. "
+ '[{"id": "obj_1", "bbox": [80, 60, 480, 380], "desc": "A striped balloon."}, '
+ '{"id": "sun_1", "bbox": [470, 455, 535, 525], "desc": "A low sun."}]'
+ )
+
+
+def test_a_box_edit_uses_the_layout_edit_prompt(runnable):
+ pup.upsample(_REQUEST, reference_images = [_png_url()])
+ content = runnable.calls[0]["payload"]["messages"][1]["content"]
+ assert runnable.calls[0]["payload"]["messages"][0]["content"] == pup.SYSTEM_PROMPTS["i2i_bbox"]
+ assert content[0]["type"] == "image_url"
+ assert content[-1]["text"].startswith(
+ "Reference images follow in attachment order: ref_image_0"
+ )
+ assert "User editing instruction: ORIGINAL PROMPT:" in content[-1]["text"]
+
+
+def test_a_renamed_row_matches_the_first_valid_locked_box():
+ # detect_box_table accepts a row with any valid box, so a malformed bbox beside a valid tgt_bbox is locked.
+ locked = pup.detect_box_table(
+ 'Two balloons [{"id": "obj_1", "bbox": [100, 200], "from": "target", '
+ '"tgt_bbox": [100, 100, 500, 400], "desc": "red balloon"}]'
+ )[1]
+ answer = 'A red balloon <obj_9>. [{"id": "obj_9", "bbox": [100, 100, 500, 400], "desc": "A red balloon."}]'
+ caption, rows = pup.split_box_table(pup.reconcile_layout_caption(answer, locked))
+ assert caption == "A red balloon <obj_1>."
+ assert [row["id"] for row in rows] == ["obj_1"] and rows[0]["desc"] == "A red balloon."
diff --git a/studio/backend/tests/test_mlx_diffusion_backend.py b/studio/backend/tests/test_mlx_diffusion_backend.py
index e9ee3c9c2e7..6018ee4da47 100644
--- a/studio/backend/tests/test_mlx_diffusion_backend.py
+++ b/studio/backend/tests/test_mlx_diffusion_backend.py
@@ -215,6 +215,20 @@ def test_load_then_status_and_guards(env):
assert calls["dense_bits"] == 4
[email protected]("guided, threshold", [(False, None), (True, 1.0)])
+def test_status_reports_the_guidance_controls(env, monkeypatch, guided, threshold):
+ from models.inference import DiffusionStatusResponse
+
+ backend, runtime, _calls = env
+ monkeypatch.setattr(runtime, "supports_guidance", lambda model: guided)
+ _load(backend)
+ status = DiffusionStatusResponse(**backend.status())
+ assert status.supports_guidance is guided and status.supports_negative_prompt is guided
+ # generate() only passes a negative prompt above guidance 1.
+ assert status.negative_prompt_min_guidance == threshold
+ assert status.supports_live_preview is False
+
+
def test_conversion_is_cached_across_loads(env):
backend, runtime, calls = env
_load(backend)
diff --git a/studio/frontend/src/features/hub/download-manager/staged-download-progress.ts b/studio/frontend/src/features/hub/download-manager/staged-download-progress.ts
new file mode 100644
index 00000000000..68f0eb7e316
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/staged-download-progress.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Pure logic only (no "@/" imports) so node:test can load it directly.
+
+/** Bytes of the entry's missing files transferred so far. A job resuming an earlier attempt counts cached files too,
+ * against a scope-wide `expectedBytes`; that excess over `entryBytes` is the cached part and comes off the reading.
+ * A held sample (`measuredTransfer: false`, see `resolveProgressUpdate`) carries the previous run's bytes beside the
+ * new run's total, so it keeps `previous`, the last measured result for this entry. */
+export function stagedEntryTransferredBytes(
+ entryBytes: number,
+ progress:
+ | { expectedBytes: number; downloadedBytes: number; measuredTransfer?: boolean }
+ | null
+ | undefined,
+ previous = 0,
+): number {
+ const missing = Math.max(0, entryBytes);
+ if (!progress) {
+ return 0;
+ }
+ if (progress.measuredTransfer === false) {
+ return Math.min(missing, Math.max(0, previous));
+ }
+ const cached = Math.max(0, progress.expectedBytes - missing);
+ return Math.min(missing, Math.max(0, progress.downloadedBytes - cached));
+}
diff --git a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
index a8d73b1278e..4771ea23588 100644
--- a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
+++ b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
@@ -24,6 +24,8 @@ export interface DownloadJobProgress {
expectedBytes: number;
downloadedBytes: number;
fraction: number;
+ /** False when the last poll held `downloadedBytes` over from the previous reading (`resolveProgressUpdate`). */
+ measuredTransfer?: boolean;
}
export interface DownloadJob {
@@ -227,6 +229,7 @@ export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {
expectedBytes: active.expectedBytes,
downloadedBytes: active.downloadedBytes,
fraction: active.fraction,
+ measuredTransfer: active.measuredTransfer !== false,
}
: null,
[active],
diff --git a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
index afa51d67f17..b11dfa7f153 100644
--- a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
+++ b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
@@ -16,6 +16,7 @@ import {
publishStagedQueue,
useStagedDownloadQueues,
} from "./staged-download-queue";
+import { stagedEntryTransferredBytes } from "./staged-download-progress";
import { useRepoDownload } from "./use-repo-download";
/** Total progress for the plan ID returned by `stage()`. */
@@ -228,9 +229,23 @@ export function useStagedDownload({
}, []);
const remainingBytes = (queue ?? []).reduce((sum, entry) => sum + Math.max(0, entry.bytes), 0);
+ // The last measured reading of the current entry, kept through a held sample (a transport switch or retry).
+ const [lastMeasured, setLastMeasured] = useState<{
+ entry: StagedDownloadEntry | null;
+ bytes: number;
+ }>({ entry: null, bytes: 0 });
+ const previousBytes = current && lastMeasured.entry === current ? lastMeasured.bytes : 0;
const currentBytes = current
- ? Math.min(Math.max(0, current.bytes), job.progress?.downloadedBytes ?? 0)
+ ? stagedEntryTransferredBytes(current.bytes, job.progress, previousBytes)
: 0;
+ if (
+ current &&
+ job.progress &&
+ job.progress.measuredTransfer !== false &&
+ (lastMeasured.entry !== current || lastMeasured.bytes !== currentBytes)
+ ) {
+ setLastMeasured({ entry: current, bytes: currentBytes });
+ }
const downloadedBytes = queue ? Math.max(0, staged.bytes - remainingBytes) + currentBytes : 0;
const totalBytes = queue ? staged.bytes : 0;
const plan = staged.plan;
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index cd32864e451..753cb64f53b 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -87,6 +87,12 @@ export interface DiffusionStatus {
// Whether the loaded model can apply a ControlNet. Diffusers only, for families with a ControlNet pipeline.
supports_controlnet?: boolean;
supports_negative_prompt?: boolean;
+ // The guidance a negative prompt is used above; null when guidance does not gate it, absent on older backends.
+ negative_prompt_min_guidance?: number | null;
+ // False when the loaded model ignores guidance on this engine (FLUX.3 distilled on diffusers).
+ supports_guidance?: boolean;
+ // False when this load streams no denoise previews (native engine, families without a preview map).
+ supports_live_preview?: boolean;
// One or two sentences on how the loaded model reads prompts; null when it has no tip.
prompt_hint?: string | null;
// "default" first; empty or absent = no choice (flow models, native / MLX engines, older backend).
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index cfb46c84cfe..1c812e821fa 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -757,6 +757,7 @@ function SliderField({
max,
step,
onChange,
+ disabled,
}: {
label: string;
hint?: ReactNode;
@@ -765,6 +766,7 @@ function SliderField({
max: number;
step: number;
onChange: (v: number) => void;
+ disabled?: boolean;
}) {
return (
<ParamSlider
@@ -776,6 +778,7 @@ function SliderField({
max={max}
step={step}
onChange={onChange}
+ disabled={disabled}
/>
);
}
@@ -2089,6 +2092,20 @@ export function ImagesPage({
const controlnetSupported = Boolean(status?.loaded && status?.supports_controlnet);
const controlnetCapable = !external && controlnetSupported;
const negativeCapable = !external && status?.supports_negative_prompt !== false;
+ // A model that reads no guidance here runs at its default, which the request and recipe then carry.
+ const guidanceFixed = !external && status?.loaded === true && status.supports_guidance === false;
+ const effectiveGuidance = guidanceFixed
+ ? (status?.generation_defaults?.guidance ?? DEFAULT_GEN.guidance)
+ : guidance;
+ // The guidance a negative prompt needs: 0 with no model loaded or on an older backend, the old rule.
+ const negativeMinGuidance =
+ status?.loaded && status.negative_prompt_min_guidance !== undefined
+ ? status.negative_prompt_min_guidance
+ : 0;
+ const negativeEngaged =
+ negativeCapable && (negativeMinGuidance === null || effectiveGuidance > negativeMinGuidance);
+ const livePreviewUnavailable =
+ !external && status?.loaded === true && status.supports_live_preview === false;
const samplerOptions = (!external && status?.loaded ? status.samplers : null) ?? NO_SAMPLERS;
// The checkpoint, not residentDefaults: community SDXL files all share the SDXL base repo.
const samplerModelKey = status?.loaded ? `${status.repo_id ?? ""}|${status.gguf_filename ?? ""}` : "";
@@ -3537,11 +3554,14 @@ export function ImagesPage({
}, []);
const applyEditSource = useCallback(
(dataUrl: string) => {
+ // FLUX.2 klein and FLUX.3 edit through Reference; without this fallback the source lands hidden on Create.
const target: WorkflowId | null = isWorkflowEnabled("edit", supported)
? "edit"
: isWorkflowEnabled("transform", supported)
? "transform"
- : null;
+ : isWorkflowEnabled("reference", supported)
+ ? "reference"
+ : null;
if (target) setWorkflow(target);
handleInitChange(dataUrl);
if (target === "edit") {
@@ -3550,6 +3570,8 @@ export function ImagesPage({
toast.success("Image added to Transform", {
description: "The loaded model cannot follow edit instructions, so it redraws the image from your prompt.",
});
+ } else if (target === "reference") {
+ toast.success("Image added to Reference. Describe the change and hit Generate.");
} else {
toast.info("Image set as the source", {
description: "The loaded model cannot edit images. Load an edit model, then pick Edit.",
@@ -4971,12 +4993,11 @@ export function ImagesPage({
res = await generateDiffusionImage({
prompt: prompt.trim(),
// Only send a negative prompt when guidance uses it, so the recipe does not record one the model ignored.
- negative_prompt:
- negativeCapable && guidance > 0 ? negativePrompt.trim() || undefined : undefined,
+ negative_prompt: negativeEngaged ? negativePrompt.trim() || undefined : undefined,
width: w,
height: h,
steps,
- guidance,
+ guidance: effectiveGuidance,
// Offset runs by the batch size: the native engine seeds image j at seed+j, so a +1 offset
// would regenerate batch-mates.
seed: baseSeed + i * batchSize,
@@ -5083,7 +5104,7 @@ export function ImagesPage({
setGenStep(null);
setStopping(false);
}
- }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeCapable, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, multiImageEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);
+ }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeEngaged, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, width, height, steps, effectiveGuidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, multiImageEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);
// Stop the in-flight generation. Latch FIRST, so a multi-run request stops even if the POST
// races the run that is already finishing.
@@ -5453,11 +5474,16 @@ export function ImagesPage({
<div className="flex items-center justify-between">
<span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">
Live preview
- <InfoHint>Show a rough preview of the image while it denoises. Costs no measurable speed and never changes the final image.</InfoHint>
+ <InfoHint>
+ {livePreviewUnavailable
+ ? "The loaded model shows no preview while it denoises on this engine."
+ : "Show a rough preview of the image while it denoises. Costs no measurable speed and never changes the final image."}
+ </InfoHint>
</span>
<Switch
- checked={livePreview}
+ checked={livePreview && !livePreviewUnavailable}
onCheckedChange={(on) => setLivePreviewOff(!on)}
+ disabled={livePreviewUnavailable}
aria-label="Live preview"
/>
</div>
@@ -6103,7 +6129,11 @@ export function ImagesPage({
onChange={setNegativePrompt}
open={negativeOpen}
onOpenChange={setNegativeOpen}
- hint="What to steer the image away from. Only used when guidance is above 0."
+ hint={
+ negativeMinGuidance === null
+ ? "What to steer the image away from."
+ : `What to steer the image away from. Only used when guidance is above ${negativeMinGuidance}.`
+ }
/>
)}
{!external && !loraCapable && offersNativeLoraReload(status) && (
@@ -6286,12 +6316,17 @@ export function ImagesPage({
</div>
<SliderField
label="Guidance"
- hint="Controls how strongly the model follows the prompt. Start with the selected model's default; distilled models may require low or zero guidance."
- value={guidance}
+ hint={
+ guidanceFixed
+ ? "The loaded model is distilled to run without guidance, so this value has no effect and stays at its default."
+ : "Controls how strongly the model follows the prompt. Start with the selected model's default; distilled models may require low or zero guidance."
+ }
+ value={effectiveGuidance}
min={0}
max={15}
step={0.5}
onChange={setGuidance}
+ disabled={guidanceFixed}
/>
</>
)}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index 1c315fd8770..c3a5910632a 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -3068,7 +3068,7 @@ export function HubModelPicker({
onBrowseHub,
onConfigureConnection,
onModelsChange,
- onConfigure,
+ onConfigure: onConfigureProp,
deleteDisabled = false,
section = "downloaded",
sectionToggle,
@@ -3152,6 +3152,8 @@ export function HubModelPicker({
const tasks = task ? (typeof task === "string" ? [task] : task) : [];
return tasks.some((entry) => DIFFUSION_TASKS.has(entry));
}, [task]);
+ // Run settings is the chat load form, which the Images and Video pages never read.
+ const onConfigure = diffusionLoad ? undefined : onConfigureProp;
const audioTaskPicker = taskFilterHasAudio(task);
// What the backend actually holds, not the dropdown highlight: an image or video load evicts
// the chat model and leaves the pick untouched, so rows kept a "Loaded" badge with nothing
diff --git a/studio/frontend/tests/staged-download-cached-progress.test.ts b/studio/frontend/tests/staged-download-cached-progress.test.ts
new file mode 100644
index 00000000000..f31d470a1fb
--- /dev/null
+++ b/studio/frontend/tests/staged-download-cached-progress.test.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+registerBundlerResolver();
+const { stagedEntryTransferredBytes } = await import(
+ "../src/features/hub/download-manager/staged-download-progress.ts"
+);
+
+const GB = 1e9;
+// The FLUX.3 Balanced plan: 11.1 GB of missing transformer shards in a 16.7 GB file scope whose encoder and VAE
+// (5.6 GB) are already cached. A job resuming a cancelled attempt measures the whole scope.
+const missing = 11.1 * GB;
+const scope = 16.7 * GB;
+
+test("cached files in the job's scope do not count as staged progress", () => {
+ assert.equal(
+ stagedEntryTransferredBytes(missing, {
+ expectedBytes: scope,
+ downloadedBytes: 5.6 * GB,
+ }),
+ 0,
+ );
+ const halfway = stagedEntryTransferredBytes(missing, {
+ expectedBytes: scope,
+ downloadedBytes: 5.6 * GB + missing / 2,
+ });
+ assert.ok(Math.abs(halfway - missing / 2) < 1, String(halfway));
+ // The reading that showed "11 GB of 11 GB, 100%" while the panel had 15 GB of 17 GB.
+ const late = stagedEntryTransferredBytes(missing, {
+ expectedBytes: scope,
+ downloadedBytes: 15 * GB,
+ });
+ assert.ok(late < missing && Math.abs(late - 9.4 * GB) < 1, String(late));
+ assert.equal(
+ stagedEntryTransferredBytes(missing, {
+ expectedBytes: scope,
+ downloadedBytes: scope,
+ }),
+ missing,
+ );
+});
+
+test("an entry whose scope is all missing keeps the plain reading", () => {
+ assert.equal(
+ stagedEntryTransferredBytes(100, {
+ expectedBytes: 100,
+ downloadedBytes: 40,
+ }),
+ 40,
+ );
+ // A job still seeded with the plan's own total.
+ assert.equal(
+ stagedEntryTransferredBytes(100, { expectedBytes: 0, downloadedBytes: 40 }),
+ 40,
+ );
+ assert.equal(
+ stagedEntryTransferredBytes(100, {
+ expectedBytes: 80,
+ downloadedBytes: 90,
+ }),
+ 90,
+ );
+ assert.equal(
+ stagedEntryTransferredBytes(100, {
+ expectedBytes: 100,
+ downloadedBytes: 140,
+ }),
+ 100,
+ );
+ assert.equal(stagedEntryTransferredBytes(100, null), 0);
+});
+
+test("a held sample keeps the last measured reading instead of pricing it against the new total", () => {
+ // A retry's first poll reports 0 bytes against a smaller total; the job holds the previous 3 GB beside it.
+ const held = { expectedBytes: 0.5 * GB, downloadedBytes: 3 * GB, measuredTransfer: false };
+ assert.equal(stagedEntryTransferredBytes(0.5 * GB, held), 0);
+ assert.equal(stagedEntryTransferredBytes(0.5 * GB, held, 0.2 * GB), 0.2 * GB);
+ assert.equal(stagedEntryTransferredBytes(0.5 * GB, held, 0.9 * GB), 0.5 * GB);
+ // A measured sample ignores `previous`.
+ assert.equal(
+ stagedEntryTransferredBytes(100, { expectedBytes: 100, downloadedBytes: 40, measuredTransfer: true }, 90),
+ 40,
+ );
+});