Skip to content

Studio Images: SDXL prompt weighting, CLIP skip, CFG rescale and variation seeds - #14562

Merged
danielhanchen merged 31 commits into
mainfrom
studio-images-sdxl-controls
Oct 22, 2026
Merged

danielhanchen merged 31 commits into
mainfrom
studio-images-sdxl-controls

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Refs #10695

Four generation controls for SDXL checkpoints on the diffusers engine. Most of these requests come from people bringing Civitai SDXL models over from AUTOMATIC1111 / Forge:

  1. Prompt weighting with AUTOMATIC1111 syntax: (word:1.2), (word), [word], \( \) \[ \] \\ escapes, and BREAK. Prompts past 75 CLIP tokens are now encoded in 75-token chunks instead of being cut off at 77.
  2. CLIP skip, using AUTOMATIC1111 numbering.
  3. CFG rescale (cfg_rescale), which passes through as diffusers guidance_rescale.
  4. Variation seed and variation strength (AUTOMATIC1111 subseeds), plus a Vary button.

All four are off by default, and off sends exactly the pipeline call that runs today, with one intended exception: a prompt longer than 75 CLIP tokens is now chunked instead of silently truncated. They only show up when the loaded model supports them.

Behaviour

Prompt weighting

  • The parser follows modules/prompt_parser.py parse_prompt_attention in stable-diffusion-webui (commit 82a973c). That repo is AGPL-3.0, the same licence as Studio, but the code here is a rewrite, not a copy.
  • Tokenization and chunking follow modules/sd_hijack_clip.py tokenize_line / process_tokens:
    • each chunk is <bos> + 75 tokens + <eos>;
    • when a chunk fills up, the tokens after a comma in its last 20 tokens move to the next chunk;
    • everything after the first <eos> uses the tokenizer's pad id, which for SDXL's OpenCLIP tokenizer is !, as in webui.
  • Emphasis is webui's default Original from modules/sd_emphasis.py: each token's output is scaled by its weight, then the chunk is rescaled back to its unweighted mean. The pooled embedding comes from the first chunk, unweighted.
  • If either side uses CFG, positive and negative are padded to the same chunk count with empty-prompt chunks (webui pad_cond_uncond), because diffusers runs both branches in one batch.
  • An empty negative prompt still gives zero negatives (force_zeros_for_empty_prompt), the same as the pipeline today.
  • It engages only when parsing changes the text (brackets, escapes, BREAK) or the prompt is longer than 75 CLIP tokens (counted after maybe_convert_prompt, as encode_prompt tokenizes). A shorter plain prompt never reaches the new code and goes through the pipeline's own encode_prompt, so it renders bit-identically.
  • Layer selection is diffusers' own indexing, so (fox:1.0) renders bit-identically to fox.
  • prompt_weighting: false reads brackets as literal text; a long prompt still chunks (webui's "None" emphasis).
  • A malformed weight such as (cat:1.2.3) stays literal text, parentheses included (webui raises on it).
  • Encoding stops at 32 chunks (2400 tokens) and logs a warning; webui and ComfyUI have no limit, so this only bounds what one request can make the encoder do. Tokenizing and chunking stop at the cap too, and at most 76800 characters of a prompt are read, so a huge API prompt costs no more than one at the cap.
  • Textual inversion tokens are expanded per fragment with the pipeline's maybe_convert_prompt.

CLIP skip

The UI and API use AUTOMATIC1111 numbering, where 1 means the model's own layer.

  • diffusers: StableDiffusionXLPipeline.encode_prompt reads hidden_states[-(clip_skip + 2)] ("SDXL always indexes from the penultimate layer"). StableDiffusionPipeline.encode_prompt reads hidden_states[-(clip_skip + 1)] and then applies final_layer_norm.
  • webui-forge reads hidden_states[-max(N, minimal_clip_skip)], with minimal_clip_skip=2 for SDXL (backend/diffusion_engine/sdxl.py) and 1 for SD 1.x. AUTOMATIC1111 keeps SDXL on the penultimate layer unless sdxl_clip_l_skip is set.
  • On SDXL the skip moves CLIP-L and OpenCLIP-G together. This matches ComfyUI's CLIPSetLastLayer: comfy/sdxl_clip.py SDXLClipModel.set_clip_options passes the layer to both clip_l and clip_g. Forge does the same (StableDiffusionXL.set_clip_skip sets both text engines), and so does diffusers' encode_prompt(clip_skip=...). AUTOMATIC1111's sdxl_clip_l_skip option, off by default, skips CLIP-L only.
  • So AUTOMATIC1111 N maps to diffusers max(N, 2) - 2 on SDXL (None for 1 and 2) and N - 1 on SD 1.x. On SDXL, "Clip skip 2" (common on Pony / Illustrious cards) is the default, and 1 and 2 render the same. A naive N - 1 would change every Pony / Illustrious render.
  • Values above 2 on SDXL go through the same encoder as prompt weighting, not through the pipeline's clip_skip argument. diffusers' SDXL encode_prompt applies clip_skip to the positive prompt only: a non-empty negative is always read at hidden_states[-2]. AUTOMATIC1111 and Forge apply the skip to the prompt and the negative alike.
  • The maximum is capped at the shallower text encoder's depth, which the status reports.

CFG rescale

  • Passed through as guidance_rescale to StableDiffusionXLPipeline.__call__, which applies rescale_noise_cfg (arXiv 2305.08891, section 3.4) after the guided combination.
  • The default is 0. For v-prediction checkpoints, the hint shows 0.7, the paper's value, but nothing defaults to it: the NoobAI-XL V-Pred 1.0 and 0.75s cards recommend CFG 4 to 5 and Euler, and neither names a rescale value.
  • Workflows whose pipeline has no guidance_rescale (ControlNet) refuse a non-zero value. On the Images page, Create with a ControlNet engaged does not send it, and the CFG rescale slider is disabled with the reason.

Variation seed

  • Follows modules/rng.py ImageRNG.first and slerp in stable-diffusion-webui: the seed's noise is slerped toward the variation seed's noise by the strength, per image, using webui's formula including its nearly-parallel branch.
  • The base noise is still drawn by the pipeline's own prepare_latents from the request's generator, so the generator advances exactly as before and ancestral samplers get the same per-step noise. Only the initial latent changes.
  • Strength 0 is today's render. Strength 1 is exactly the render of the variation seed.
  • In a batch, every image keeps the seed and image i uses variation_seed + i (webui all_subseeds), so a batch gives variations of one image.
  • Text to image and ControlNet only. Img2img and inpaint take their noise from the source image, so they refuse it. The Images page shows the variation controls and sends their fields only on Create.
  • Vary restores the selected image's settings (the exact caption it ran with, size, guidance, LoRAs and these controls) and re-runs its seed with a fresh variation seed at strength 0.15, so the result keeps that image's composition even when the form held something else. It is offered for a text-to-image image made with the loaded model, and disabled with the reason when the current load cannot apply part of that recipe (its LoRAs on a load without LoRA support, or a recorded CLIP skip, CFG rescale or prompt weighting off the load does not offer). It is also disabled for an image that already used a variation seed: its noise was a blend of two seeds, which a fresh variation of its base seed would not keep. It also needs the image to come off the exact loaded build: the engine, model kind, checkpoint file, transformer and text-encoder quants, attention backend, step cache and the LoRAs baked in at load time (compared as a set) recorded with it must match the current load, since a different build turns the same seed into a different picture. An image whose record predates those fields (no engine recorded) cannot be checked, so Vary stays disabled for it with that reason; gallery records now include the recorded engine for this. AUTOMATIC1111 users typically use 0.05 to 0.3. Fooocus' Vary buttons are img2img at denoise 0.5 / 0.85, which is a different mechanism.

Gating and API

  • /api/inference/images/status reports sd_controls: prompt_weighting, clip_skip {min, max, default, same_as_default_through}, cfg_rescale {min, max, default, recommended}, variation_seed, vary_strength and prediction_type. It is null for every non-SDXL family and for the native and MLX engines. Status also reports baked_loras, the adapter ids baked into the transformer at load time (as the gallery record names them), empty when none were baked.
  • The Images page shows the controls in the Advanced section only when sd_controls is present. Each control has a tooltip, and the Vary button shows only on Create with a selected text-to-image image from the loaded model.
  • POST /api/inference/images/generate takes the optional fields prompt_weighting, clip_skip (1 to 12, AUTOMATIC1111 numbering), cfg_rescale (0 to 1), variation_seed (0 to 2^32 - 1) and variation_strength (0 to 1). Omitting them all is today's request.
  • A FLUX, Qwen or other non-SDXL load returns a 400 that names the controls. Weight syntax there is still literal text. The native and MLX engines also return a 400 for a non-default value.
  • The recipe, gallery record and PNG parameters record what ran, using webui infotext names: Variation seed, Variation seed strength, Clip skip, plus CFG rescale. Restore brings the values back. The record's prompt_weighting is true when weight syntax was applied and false when the request turned weighting off, so restoring a literal-prompt image keeps Prompt weighting off. On the native sd.cpp engine, which always reads (word:1.2) syntax, restoring or importing such an image names "prompt weighting off" as not applied. Restoring a gallery image onto a load that lacks a recorded CLIP skip, CFG rescale or variation seed (for example the same SDXL repo on the native engine), or would clamp it, names those too instead of reporting a full restore. A literal-prompt run also writes Emphasis: None into parameters, so A1111 and Forge replay it unweighted.

How this fits with #14508

#14508 (paste generation parameters) already parses A1111 / Forge Clip skip, CFG Rescale (and RescaleCFG, Forge's latent_modifier_rescale_cfg_phi), Variation seed and Variation seed strength, and listed them under "Not applied" because no request field existed yet. This branch is merged with main after it and fills that gap:

  • Pasting a parameters block, dropping an image, or loading a recipe now sets CLIP skip, CFG rescale, the variation seed and its strength in the SDXL controls. There is one parser (Studio Images: paste generation parameters, inpaint mask blur and only-masked area, seed buttons #14508's parseA1111Parameters) and one restore path (applyImportedRecipe into restoreSettings); the duplicate parser branch this PR had is gone.
  • The four keys moved from "parsed but not sent" (PENDING_RECIPE_KEYS) to restored keys. importNotApplied now takes the loaded model's sd_controls. It names only what that model lacks, a Clip skip above the model's maximum (as clamped), a CFG rescale outside [0, 1] or above the model's maximum (as clamped), a variation seed for img2img or inpaint (the backend refuses it there, so the import also clears it), and a variation seed or strength outside the request bounds (not 32-bit, or strength above 1), which is named and left off instead of becoming a random seed or a clamped strength. On a model without sd_controls the toast is the same as on main.
  • With prompt weighting available, pasted A1111 emphasis and escaped brackets are applied, so they are no longer reported as "passed as plain text".
  • A pasted Emphasis: None (webui skips the prompt parser) restores Prompt weighting off; on the native sd.cpp engine it is named as not applied.
  • The image's own parameters text uses the same key names, so pasting it back round-trips these controls.
  • Inpaint mask blur / Only masked (Studio Images: paste generation parameters, inpaint mask blur and only-masked area, seed buttons #14508) and these controls sit side by side in the request, the gallery record and generate(). A variation run keeps one base seed across runs, and that seed is the one "Reuse last seed" picks up.

How this fits with #14563

#14563 (per-generation Shift for flow-matching models, SDXL textual inversion embeddings) is merged into this branch. The two touch the same request, status, gallery record and restore code but different fields, so they combine side by side:

  • DiffusionGenerateRequest takes shift / base_shift / max_shift and the four SDXL controls; status carries shift_control, textual_inversion and sd_controls. Shift applies to flow-matching models and these controls to SDXL, so one model shows one set or the other.
  • On an SDXL checkpoint, the weighted encoder expands embedding tokens per fragment with the pipeline's maybe_convert_prompt, the same hook Studio Images: per-generation Shift for flow-matching models and SDXL textual inversion embeddings #14563's embeddings rely on, so a weighted prompt can name an embedding. This pair has not been run end to end on a real embedding file here.
  • Recipes record and restore both sets of keys; the import toast lists Shift values and missing embeddings next to the SDXL controls.
  • To keep the startup bundle within budget after the merge, the three Images-page-only calls (listDiffusionControlNets, moveGalleryImage, addGalleryImageToProject) moved out of api.ts (which the eager chat chunk carries) into images-page-api.ts, as Studio Images: per-generation Shift for flow-matching models and SDXL textual inversion embeddings #14563 did with embeddings-api.ts.

Compile and CUDA graphs

With the compiled U-Net and CUDA graphs on the tiny SDXL pipeline (speed default: channels_last, fused QKV, compiled, CUDA graphs), changing weights, clip skip, rescale or variation between renders compiled nothing new.

Prompts 2 to 4 of a probe that alternates weighted and plain prompts with and without a variation strength had 0 FX graph cache misses and 0 new graphs. Weighting and variation only change tensor values.

A prompt that now chunks to 154 or 231 tokens is a new text length for the U-Net and compiles once per chunk count. The same is true of any new text length.

Tests

  • tests/test_diffusion_sd_controls.py:
    • the parser checked against the webui doctests, plus escapes and BREAK;
    • chunking, comma backtrack and pad ids;
    • emphasis mean restoration;
    • CLIP skip mapping;
    • gating (FLUX refusal);
    • cfg_rescale to guidance_rescale passthrough;
    • slerp against webui's formula, its endpoints, and seed reproducibility;
    • prepare_latents restore;
    • request validation ranges;
    • the route refusing other engines;
    • infotext.
  • Against the real tiny SDXL pipeline, the weighted encoder at weight 1 matches encode_prompt bit for bit for positive, negative and both pooled embeddings, and CLIP skip matches encode_prompt(clip_skip=k). A plain prompt over 75 tokens is chunked (positive and negative padded to the same length); a shorter one is left to encode_prompt.
  • The SD 1.x layout (diffusers StableDiffusionPipeline.encode_prompt around a CLIP-L encoder) matches too, including A1111 "Clip skip 2" = diffusers clip_skip=1 (hidden_states[-2] plus final_layer_norm). On transformers 5, diffusers' own SD 1.x clip_skip branch reads text_encoder.text_model, which transformers 5 removed; the encoder here handles both layouts.
  • frontend/tests/images-sd-controls.test.ts: request fields, gating and recipe restore. One new test pastes an A1111 block with Clip skip 3, CFG Rescale 0.7 and Variation seed 99 @ 0.3 and checks that it restores into the controls, that SDXL reports nothing as not applied, that a model without the controls still names all three, that a Clip skip over the maximum is reported as clamped, and that an img2img variation is named.
  • Studio Images: paste generation parameters, inpaint mask blur and only-masked area, seed buttons #14508's tests were updated where their anchors moved: image-metadata.test.ts (a newer recipe's cfg_rescale restores, and is named only without the control), image-paste-parameters.test.ts (the importNotApplied call passes sd_controls) and image-seed-inpaint-steps.test.ts (the run seed holds still while varying).
  • frontend/tests/images-sd-controls.test.ts also covers Vary restoring the selected image's recipe (and only for a text-to-image image from the loaded model), the sd.cpp literal-prompt warning, out-of-bounds imported variation values, and Vary staying disabled for an image from a different or unrecorded build (including a different baked LoRA set, attention backend or step cache). backend/tests/test_diffusion_backend.py covers baked_loras in the loaded and unloaded status and the status response model.
  • After merging main with Studio Images: per-generation Shift for flow-matching models and SDXL textual inversion embeddings #14563 (38d2124):
    • Frontend, node --experimental-strip-types --test "tests/**/*.test.ts": 13406 tests, 13405 passed, 0 failed, 1 skipped. node scripts/typecheck.mjs --tests is clean, the build passes, and npm run bundle:check is within budget (0.1 KB transfer to spare).
    • Backend: this PR's and Studio Images: per-generation Shift for flow-matching models and SDXL textual inversion embeddings #14563's files plus the Images suites (diffusion backend, routes, sampler, ControlNet, inpaint mask, LoRA, image gallery, generate-image tool, flow shift, Shift override, embeddings, saved-image metadata, model validation and more): 1996 passed, 3 skipped, 1 failed. The failure, test_diffusion_backend.py::test_mirrored_base_still_trips_the_flux2_shape_guard, fails the same way on origin/main (no gguf module in the test venv), so it is not from this PR.
  • Real backend (load_pipeline + generate on hf-internal-testing/tiny-stable-diffusion-xl-pipe), compared with main on the same GPU and seed:
    • plain prompts with and without a negative, a batch and a second seed are pixel-identical to main;
    • (fox:1.0), CLIP skip 2, rescale 0 and variation strength 0 are pixel-identical to the plain render;
    • variation strength 1 toward seed 12 equals the seed 12 render;
    • weights, CLIP skip 3, rescale 0.7 and strength 0.3 all change the image, and repeat bit-identically.

Screenshots

Before is the merge base (5ab5419), after is this PR (6bb2918), each a separate install.sh --local Studio on the same GPU with the tiny random-weight SDXL pipeline (hf-internal-testing/tiny-stable-diffusion-xl-pipe) loaded, so the images themselves are noise.

Advanced panel on an SDXL load. After adds Prompt weighting, CLIP skip, CFG rescale and Variation strength under Live preview; before has none of them.

Advanced panel: SD controls added

A plain SDXL image selected. After shows Vary next to Generate, enabled, with its tooltip; before has no Vary.

Vary enabled on a plain SDXL image

An image that already used a variation seed (strength 0.3) selected. Vary is disabled and the tooltip says why.

Vary disabled: image already used a variation seed

An image generated on a load with text_encoder_quant=fp8, selected after reloading without it. Vary is disabled and the tooltip names the differing part of the build (text encoder quant).

Vary disabled: image from a different build

Pasting an A1111 infotext with (sloth astronaut:1.2), Clip skip: 2, CFG Rescale: 0.7, Variation seed: 42 and Variation seed strength: 0.3. Before warns that prompt emphasis, CFG rescale 0.7 and variation seed 42 (strength 0.3) were not applied; after there is no such warning (the remaining toasts, about the juggernautXL_v9 checkpoint name and the restore, are the same on both sides).

Paste: not-applied warning gone

The Advanced panel after that paste. After reads CLIP skip 2, CFG rescale 0.7, Variation strength 0.3 and Variation seed 42; before has nowhere to put them.

Paste: SD controls filled from the infotext

After only: a tiny FLUX.1 pipeline (hf-internal-testing/tiny-flux-pipe) loaded on this PR. Status reports no sd_controls, so none of the controls and no Vary button appear.

FLUX.1 load on this PR: no SD controls

…eeds on the Images page

AUTOMATIC1111 prompt syntax ((word:1.2), (word), [word], escapes, BREAK) with
75-token chunking and mean-restored emphasis, CLIP skip in A1111 numbering
(SDXL 1 and 2 = the penultimate layer the model already reads), CFG rescale
via diffusers guidance_rescale, and A1111 variation seeds (slerp of the
initial noise) with a Vary button. All off by default; a plain prompt keeps
the pipeline's own encode path and renders bit-identically. Gated on the
status sd_controls capability, refused for other families and engines.

Refs #10695
…_rescale

A plain prompt longer than 75 CLIP tokens now takes the chunked encoder
instead of being truncated at 77; shorter plain prompts still go through
encode_prompt unchanged. The request, recipe and status field is cfg_rescale
(diffusers guidance_rescale underneath), matching the parameter import.
SD 1.x layer selection is checked against StableDiffusionPipeline, and the
final_layer_norm lookup handles transformers 5's flattened CLIPTextModel.

Refs #10695
…ontrols

Conflicts kept both sides: the inpaint mask fields and the SDXL controls sit side
by side in the request, the gallery record, the route kwargs and generate().
A variation run keeps one base seed across runs (runBaseSeed), which also feeds
Reuse last seed.

Pasted or dropped A1111 Clip skip, CFG Rescale and Variation seed now restore
into the SDXL controls: they leave PENDING_RECIPE_KEYS, the duplicate parser
branch is dropped in favour of #14508's, and importNotApplied takes the loaded
model's sd_controls so only controls it lacks are named. Prompt weighting counts
as reading A1111 emphasis. A variation seed for img2img / inpaint is named and
cleared, since the backend refuses it there.
@danielhanchen danielhanchen self-assigned this Oct 21, 2026
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-22T01:46:35.482521Z
We couldn’t complete this review. Comment @codex review to try again.
6bb2918 New commits
🔒 Security Review ⚠️ Failed 2026-10-21T20:39:02.268342Z
We couldn’t complete this review. Comment @codex security review to try again.
870e58c PR opened
ℹ️ About Codex in GitHub

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

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

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

@chatgpt-codex-connector

Copy link
Copy Markdown

The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fa8cd6c363

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +227 to +230
if clip_skip is None:
z = out.hidden_states[-2]
else:
z = out.hidden_states[-(clip_skip + 2)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Apply SDXL clip skip only to the CLIP-L encoder

For SDXL CLIP-skip values of 3 or more, _encode_texts invokes this branch for both encoder pairs, causing the OpenCLIP-G encoder to select an earlier hidden state too. The A1111/Forge convention this control claims to implement keeps CLIP-G on its penultimate layer and applies the extra skip only to CLIP-L, so imported Pony/Illustrious-style settings above the default produce different conditioning than advertised. The skip needs to be selected per encoder rather than shared by both.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Keeping this as is. ComfyUI's CLIPSetLastLayer moves both encoders: comfy/sdxl_clip.py SDXLClipModel.set_clip_options passes the layer to clip_l and clip_g. Forge does the same (backend/diffusion_engine/sdxl.py set_clip_skip sets both text engines, each reading hidden_states[-max(N, 2)]). Only AUTOMATIC1111 limits it to CLIP-L, and only behind its sdxl_clip_l_skip option, which is off by default. Studio follows ComfyUI and Forge; c657d4b says so in the module docstring and the description now cites it.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

# Conflicts:
#	studio/backend/core/inference/diffusion.py
#	studio/backend/models/inference.py
#	studio/backend/routes/inference.py
#	studio/frontend/src/features/images/api.ts
#	studio/frontend/src/features/images/images-page.tsx
#	studio/frontend/src/features/images/lib/image-metadata.ts
…pi chunk

Keeps the startup bundle within budget after merging main.
…s as not applied

A recipe with a variation seed past 32 bits, a negative or fractional seed, or a
strength above 1 no longer restores silently as a random seed or a clamped
strength: the variation is left off and the import toast names it.
…ngine

A gallery image or recipe made with prompt weighting off cannot replay literally
on sd.cpp, which always reads (word:1.2) syntax. Restoring it there now names
prompt weighting off as not applied instead of dropping the choice silently.
Vary now restores the selected gallery image's settings (its exact caption,
size, guidance, LoRAs and controls) and generates once the restored form has
rendered, so the variation keeps that image's composition. It is offered only
for a text-to-image image made with the loaded model.

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

This comment was marked as resolved.

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

This comment was marked as resolved.

Compare the engine, model kind, checkpoint file and transformer and text
encoder quants recorded with the image against the loaded status, and
block Vary with a reason when they differ or the record predates them.
Serve the recorded engine in gallery records so the check can read it.

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

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e3bf450f66

ℹ️ 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 pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
@danielhanchen
danielhanchen merged commit d277aa6 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the studio-images-sdxl-controls branch October 22, 2026 07:24
danielhanchen added a commit that referenced this pull request Oct 22, 2026
Refs #10695 (item 6: compare grid).

## What

A **Compare grid** on the Images page, modelled on AUTOMATIC1111's X/Y/Z
plot. It renders the same prompt across up to three axes and lays the
results out as one labelled grid image.

- **Axes**: X, Y, and an optional Z. Z produces one grid per value.
- **Axis types are gated on what the loaded model exposes**:
  - Seed and Steps
  - CFG, unless the model is distilled to a fixed guidance
  - Sampler and Schedule type, only where the sampler picker exists
- Shift (SD3-style) or Base / Max shift (FLUX-style), when status
reports a shift control
- LoRA weight, one axis per active LoRA row, when the load can apply
LoRA
  - Prompt S/R
- Clip skip, CFG rescale, Var. seed and Var. strength. These appear only
once status reports `sd_controls` (#14562). Nothing here has to change
when that lands.
- **Value syntax follows A1111** (`scripts/xyz_grid.py`,
`process_axis`):
  - Comma or newline separated lists, with CSV quoting
- `1-5`, `10-30 (+10)`, `1-10 [4]` (evenly spaced; truncated on integer
axes)
  - Sampler values match either the id or the A1111 label
- Seed `-1` is fixed to one random seed per value, unless "Keep -1 for
seeds" is on
- Two small differences from A1111: a descending range keeps its end
(`5-1` is 5..1), and a decimal step may omit its sign.
- **Options**:
  - Draw legend, Keep -1 for seeds, grid margin, and Swap X/Y.
- A grid is capped at 64 cells. Past that, the panel says how many cells
the axes make, and Generate grid is disabled.
- **Progress**: the generation overlay reads `Cell 3/9: Steps: 20,
Sampler: Euler`, and the panel counts finished cells.
- **Result**:
  - A dialog shows each grid with a Download PNG button.
- The PNG carries an A1111-style `parameters` chunk: the shared recipe
plus `Script: X/Y/Z plot, X Type, X Values, ...`.
- Every cell is also saved to the gallery with its own recipe, so any
cell can be restored or reused.

## How

- **Each cell is one request through the existing generate endpoint,
sent from the page's own Generate loop.** `handleGenerate` reads the run
from a ref, so a grid keeps the same behaviour as a normal Generate:
Stop, live progress, the lost-response recovery, the gallery merge and
the error toasts. The only edits inside the loop are:
  - the run count
  - wrapping the request body in `compareRequest(...)`
  - one `onImages` callback
- **No backend batch endpoint.** A grid cell is a full denoise taking
seconds, against a few ms of JSON round trip. Batching seeds or prompts
through `seeds` / `prompts` would change the denoiser's batch size,
which costs a compile and a graph capture per distinct size. The other
axes (steps, CFG, sampler, shift) cannot share a batch anyway.
- **Cells run at batch size 1 with one shared seed** (A1111 `fix_seed`).
The prompt enhancer is off for every cell, so a per-cell rewrite cannot
confound the comparison.
- **Run order**: A1111 nests z, y, x, and moves costly axes to the outer
loop (`AxisOption.cost`). On top of that, values of a costly axis run
grouped by shape class:
  - CFG on vs off, i.e. whether the unconditional pass runs
  - LoRA weight 0 vs above 0
  - each Prompt S/R text

So the denoiser changes shape at most once per class, and no cell needs
a model reload. Cells are placed in the grid by index, so the run order
does not affect the layout.
- **Code layout and startup bundle**: the new code lives in
`src/features/images/compare/` (values parser, axes / plan, run object,
grid layout and drawing, panel). The Images page imports it statically,
and the page is already its own lazy chunk, so none of it is on the
startup path. `bundle:check` is unchanged from main: 6,718.1 KB raw /
2,023.3 KB transfer, 97 chunks. A nested `import()` of the panel was
measured too: rolldown split startup-shared modules out of their chunks,
giving +3 startup chunks and putting the budget over by 1.2 KB transfer.

## Tests

- New `tests/images-compare-grid.test.ts`, 19 tests:
  - A1111 list / range / count syntax and errors
- Capability gating, including the #14562 SD controls and the ControlNet
exclusion for CFG rescale
  - The 64-cell cap and duplicate-axis checks
- Per-cell requests: batch 1, seeds, sampler plus schedule fallback,
negative prompt re-derived from CFG, Prompt S/R in both prompts, LoRA
weight 0 dropping the adapter, enhancer off
  - Run order: one CFG on/off switch, Prompt S/R outermost
  - The run object and Z slices
- Grid layout (A1111 font size and bands, legend off, Z title, shrink to
the canvas limit)
- The PNG `parameters` chunk read back through the existing metadata
reader
  - The page wiring
- `tests/image-prompt-enhance.test.ts`: its source anchor now matches
the wrapped `generateDiffusionImage(` call.
- `npm run typecheck`, `npm run build`, `npm run bundle:check` (within
budget) and all `tests/image*.test.ts` / `tests/images*.test.ts` pass
(379). ESLint reports nothing new in `images-page.tsx`, and nothing in
the new files.

## GPU run

Measured on a B200 shared with other jobs, so timings are indicative
only. The harness drives Studio's `DiffusionBackend` with the exact
requests the shipped planner builds, in its order, after three warm-up
renders of the form's settings. It counts the deltas in `torch._dynamo`
unique graphs and recompiles, inductor FX cache misses, and Studio's
CUDA graph capture counter.

| Model | Grid | Cells wall | Recompiles | New graphs | CUDA graph
captures |
|---|---|---|---|---|---|
| Z-Image-Turbo (UI defaults: compiled + CUDA graphs), 1024x1024 | Shift
1, 3, 6 x Steps 4, 8, 12 | 10.4 s for 9 cells | 0 | 0 | 0 |
| tiny SDXL (compiled + CUDA graphs) | Euler, Euler a, DPM++ 2M x Steps
10, 20, 30 | 73.5 s (70.5 s of it one compile) | 0 | 1 | 1 |

The single SDXL compile and capture is the first DPM++ 2M cell. It is
not caused by the grid. `DPMSolverMultistepScheduler` hands the UNet
int64 timesteps, while Euler and Euler a hand it float32, so the first
DPM++ render in a process traces and captures once for the new input
dtype. Later DPM++ cells reuse it. A plain Generate that switches to
DPM++ hits the same cost. Casting the timestep to one dtype in front of
the compiled denoiser would remove it, which is left for a follow-up.

Grid from the planner's own requests (Z-Image-Turbo, Shift 1 / 3 / 6 x
Steps 4 / 8 / 12, one seed), downscaled:

![Z-Image-Turbo Shift x Steps
grid](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14624/grid_q-075d866a93ee.png)

## Not covered

- The grid in this PR's GPU run was drawn with PIL from the planner's
own layout. The in-browser canvas path, and the panel itself, were
exercised by typecheck, build and the unit tests, but not by a
Playwright run.
- No real SDXL checkpoint was loaded. The sampler axis was measured on
the tiny SDXL pipe.
- "Generate anyway" after a memory refusal on a grid cell retries one
normal Generate, not the rest of the grid.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant