Repository navigation
Studio Images: SDXL prompt weighting, CLIP skip, CFG rescale and variation seeds - #14562
Conversation
…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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
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. |
[skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if clip_skip is None: | ||
| z = out.hidden_states[-2] | ||
| else: | ||
| z = out.hidden_states[-(clip_skip + 2)] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
… parses attention syntax
…ed on a model without it
# 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]
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]
…ld check [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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:  ## 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.
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:
(word:1.2),(word),[word],\(\)\[\]\\escapes, andBREAK. Prompts past 75 CLIP tokens are now encoded in 75-token chunks instead of being cut off at 77.cfg_rescale), which passes through as diffusersguidance_rescale.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
modules/prompt_parser.pyparse_prompt_attentionin 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.modules/sd_hijack_clip.pytokenize_line/process_tokens:<bos>+ 75 tokens +<eos>;<eos>uses the tokenizer's pad id, which for SDXL's OpenCLIP tokenizer is!, as in webui.Originalfrommodules/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.pad_cond_uncond), because diffusers runs both branches in one batch.force_zeros_for_empty_prompt), the same as the pipeline today.BREAK) or the prompt is longer than 75 CLIP tokens (counted aftermaybe_convert_prompt, asencode_prompttokenizes). A shorter plain prompt never reaches the new code and goes through the pipeline's ownencode_prompt, so it renders bit-identically.(fox:1.0)renders bit-identically tofox.prompt_weighting: falsereads brackets as literal text; a long prompt still chunks (webui's "None" emphasis).(cat:1.2.3)stays literal text, parentheses included (webui raises on it).maybe_convert_prompt.CLIP skip
The UI and API use AUTOMATIC1111 numbering, where 1 means the model's own layer.
StableDiffusionXLPipeline.encode_promptreadshidden_states[-(clip_skip + 2)]("SDXL always indexes from the penultimate layer").StableDiffusionPipeline.encode_promptreadshidden_states[-(clip_skip + 1)]and then appliesfinal_layer_norm.hidden_states[-max(N, minimal_clip_skip)], withminimal_clip_skip=2for SDXL (backend/diffusion_engine/sdxl.py) and 1 for SD 1.x. AUTOMATIC1111 keeps SDXL on the penultimate layer unlesssdxl_clip_l_skipis set.CLIPSetLastLayer:comfy/sdxl_clip.pySDXLClipModel.set_clip_optionspasses the layer to bothclip_landclip_g. Forge does the same (StableDiffusionXL.set_clip_skipsets both text engines), and so does diffusers'encode_prompt(clip_skip=...). AUTOMATIC1111'ssdxl_clip_l_skipoption, off by default, skips CLIP-L only.max(N, 2) - 2on SDXL (None for 1 and 2) andN - 1on SD 1.x. On SDXL, "Clip skip 2" (common on Pony / Illustrious cards) is the default, and 1 and 2 render the same. A naiveN - 1would change every Pony / Illustrious render.clip_skipargument. diffusers' SDXLencode_promptappliesclip_skipto the positive prompt only: a non-empty negative is always read athidden_states[-2]. AUTOMATIC1111 and Forge apply the skip to the prompt and the negative alike.CFG rescale
guidance_rescaletoStableDiffusionXLPipeline.__call__, which appliesrescale_noise_cfg(arXiv 2305.08891, section 3.4) after the guided combination.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
modules/rng.pyImageRNG.firstandslerpin 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.prepare_latentsfrom 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.variation_seed + i(webuiall_subseeds), so a batch gives variations of one image.enginefor 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/statusreportssd_controls:prompt_weighting,clip_skip {min, max, default, same_as_default_through},cfg_rescale {min, max, default, recommended},variation_seed,vary_strengthandprediction_type. It is null for every non-SDXL family and for the native and MLX engines. Status also reportsbaked_loras, the adapter ids baked into the transformer at load time (as the gallery record names them), empty when none were baked.sd_controlsis 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/generatetakes the optional fieldsprompt_weighting,clip_skip(1 to 12, AUTOMATIC1111 numbering),cfg_rescale(0 to 1),variation_seed(0 to 2^32 - 1) andvariation_strength(0 to 1). Omitting them all is today's request.parametersrecord what ran, using webui infotext names:Variation seed,Variation seed strength,Clip skip, plusCFG rescale. Restore brings the values back. The record'sprompt_weightingis 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 writesEmphasis: Noneintoparameters, so A1111 and Forge replay it unweighted.How this fits with #14508
#14508 (paste generation parameters) already parses A1111 / Forge
Clip skip,CFG Rescale(andRescaleCFG, Forge'slatent_modifier_rescale_cfg_phi),Variation seedandVariation 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:parseA1111Parameters) and one restore path (applyImportedRecipeintorestoreSettings); the duplicate parser branch this PR had is gone.PENDING_RECIPE_KEYS) to restored keys.importNotAppliednow takes the loaded model'ssd_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 withoutsd_controlsthe toast is the same as on main.Emphasis: None(webui skips the prompt parser) restores Prompt weighting off; on the native sd.cpp engine it is named as not applied.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:
DiffusionGenerateRequesttakesshift/base_shift/max_shiftand the four SDXL controls; status carriesshift_control,textual_inversionandsd_controls. Shift applies to flow-matching models and these controls to SDXL, so one model shows one set or the other.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.listDiffusionControlNets,moveGalleryImage,addGalleryImageToProject) moved out ofapi.ts(which the eager chat chunk carries) intoimages-page-api.ts, as Studio Images: per-generation Shift for flow-matching models and SDXL textual inversion embeddings #14563 did withembeddings-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:cfg_rescaletoguidance_rescalepassthrough;prepare_latentsrestore;encode_promptbit for bit for positive, negative and both pooled embeddings, and CLIP skip matchesencode_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 toencode_prompt.StableDiffusionPipeline.encode_promptaround a CLIP-L encoder) matches too, including A1111 "Clip skip 2" = diffusersclip_skip=1(hidden_states[-2]plusfinal_layer_norm). On transformers 5, diffusers' own SD 1.xclip_skipbranch readstext_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.image-metadata.test.ts(a newer recipe'scfg_rescalerestores, and is named only without the control),image-paste-parameters.test.ts(theimportNotAppliedcall passessd_controls) andimage-seed-inpaint-steps.test.ts(the run seed holds still while varying).frontend/tests/images-sd-controls.test.tsalso 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.pycoversbaked_lorasin the loaded and unloaded status and the status response model.node --experimental-strip-types --test "tests/**/*.test.ts": 13406 tests, 13405 passed, 0 failed, 1 skipped.node scripts/typecheck.mjs --testsis clean, the build passes, andnpm run bundle:checkis within budget (0.1 KB transfer to spare).test_diffusion_backend.py::test_mirrored_base_still_trips_the_flux2_shape_guard, fails the same way onorigin/main(noggufmodule in the test venv), so it is not from this PR.load_pipeline+generateonhf-internal-testing/tiny-stable-diffusion-xl-pipe), compared with main on the same GPU and seed:(fox:1.0), CLIP skip 2, rescale 0 and variation strength 0 are pixel-identical to the plain render;Screenshots
Before is the merge base (5ab5419), after is this PR (6bb2918), each a separate
install.sh --localStudio 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.
A plain SDXL image selected. After shows Vary next to Generate, enabled, with its tooltip; before has no Vary.
An image that already used a variation seed (strength 0.3) selected. Vary is disabled and the tooltip says why.
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).Pasting an A1111 infotext with
(sloth astronaut:1.2),Clip skip: 2,CFG Rescale: 0.7,Variation seed: 42andVariation 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).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.
After only: a tiny FLUX.1 pipeline (
hf-internal-testing/tiny-flux-pipe) loaded on this PR. Status reports nosd_controls, so none of the controls and no Vary button appear.