Skip to content

Studio Images: per-generation Shift for flow-matching models and SDXL textual inversion embeddings - #14563

Merged
danielhanchen merged 5 commits into
mainfrom
studio-images-shift-embeddings
Oct 21, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-images-shift-embeddings

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Refs #10695

Two of the missing Images generation controls: a per-generation Shift for flow-matching models and textual inversion embeddings (EasyNegative and friends) for SDXL. Both are optional; a request that sets neither runs exactly as before.

Shift

New optional request fields on POST /api/inference/images/generate: shift, base_shift, max_shift. Which ones a model takes follows the ComfyUI node a workflow for that model sets its shift with (comfy_extras/nodes_model_advanced.py):

Studio family ComfyUI node Request fields
Qwen-Image, Qwen-Image-Edit, Qwen-Image-Layered ModelSamplingAuraFlow (the templates patch it over the FLUX-type QwenImage) shift
Z-Image, Lumina 2, HiDream-I1, HunyuanImage 2.1 ModelSamplingSD3 / AuraFlow (ComfyUI ModelType.FLOW) shift
FLUX.1-schnell ModelSamplingSD3 (ComfyUI FluxSchnell is ModelType.FLOW) shift
FLUX.1-dev / Krea-dev, FLUX.1 Kontext, FLUX.2 klein / dev, FLUX.3 klein, Krea 2, Qwen-Image-2.1 ModelSamplingFlux (ComfyUI ModelType.FLUX) base_shift, max_shift
Ideogram 4, SDXL none (Ideogram 4 runs its own mu / std preset; SDXL is not flow matching) refused

The mapping, as ComfyUI computes it:

  • ModelSamplingSD3 / AuraFlow: sigma = shift * t / (1 + (shift - 1) * t) (comfy/model_sampling.py time_snr_shift). Studio sets that static shift on a copy of the loaded scheduler with dynamic shifting and the terminal stretch off, which is exactly what diffusers' FlowMatchEulerDiscreteScheduler.set_timesteps does in its static branch.
  • ModelSamplingFlux: mu = (w * h / 256) * mm + b with the line through (256, base_shift) and (4096, max_shift), then sigma = e^mu / (e^mu + 1/t - 1) (flux_time_shift). That curve is the static shift e^mu, so Studio resolves mu at the output size and applies e^mu the same way.

The override builds on the load-time ComfyUI shift Studio already applies (comfy_flow_shift + flow_shift_overrides), and its defaults are the values that load resolved:

  • ModelSamplingSD3 families report the loaded static shift (Qwen-Image 3.1, Z-Image 3.0, Lumina 2 6.0, ...).
  • ModelSamplingFlux families with a fixed mu (FLUX.1-dev / Kontext 1.15, Qwen-Image-2.1 0.69) report base = max = that mu. Dynamic ones (FLUX.2, Krea 2) report their scheduler's base / max shift.
  • A request that leaves one of base / max shift out takes the resolved value for it.
  • Sending the resolved value back keeps the loaded scheduler object: no rebuild, identical render.

Any other value builds a fresh scheduler from the loaded one's config for that call, restored in the same finally as the sampler swap. A checkpoint that ships its own sampling grid (sample_sigmas) keeps it: Shift is hidden and refused there, the same condition under which the load-time shift is skipped. Sending the wrong field for the loaded model, a value out of the node's range, or any shift to the native / MLX engine or an external connection is a 400.

The diffusion status gains shift_control: {node: "sd3", shift} (the loaded value, null when it depends on resolution) or {node: "flux", base_shift, max_shift}, or null. The Images page shows the Shift box(es) only when it is set, with the resolved values as placeholders, and a newly loaded checkpoint starts empty (its own schedule).

Textual inversion embeddings

  • Files go in <studio_home>/embeddings/diffusion, next to loras/diffusion. safetensors only (.pt is pickled).
  • GET /api/models/diffusion-embeddings?family= lists them (reads safetensors headers only): {id, trigger, kind, vectors, size_bytes} plus embeddings_dir.
  • As in AUTOMATIC1111, the filename stem is the trigger. Naming it in the prompt or negative prompt (any case, whole word, or ComfyUI's embedding:NAME) uses it for that generation. The longest name wins, so bad-hands-5 does not also fire bad.
  • Formats follow diffusers' load_textual_inversion docs: SDXL files carry clip_l for text_encoder / tokenizer and clip_g for text_encoder_2 / tokenizer_2. A single-tensor SD 1.x file is supported by the helper too, but Studio has no SD 1.x family yet, so only SDXL offers embeddings. A file meant for another model (wrong width) is skipped, like A1111 does, and reported in embeddings_skipped.
  • Applying one never reloads the pipeline and never mutates a loaded component. Each tokenizer is swapped for a copy that carries the new tokens (tok, tok_1, ... the diffusers multi-vector naming, so the pipeline's own maybe_convert_prompt expands them). Each CLIP input embedding is wrapped by a module that serves the new ids and calls the original nn.Embedding for every other id. After the generation the original objects go back. I did not use load_textual_inversion / unload_textual_inversion directly: they resize the embedding matrix, replace the module, and re-run enable_model_cpu_offload on an offloaded pipeline, which would fight Studio's own offload policies.
  • The in-memory prompt cache adds the applied embeddings (name + file fingerprint) to its key. The on-disk conditioning cache skips while embeddings are applied, as it already does for LoRA.
  • The Images page lists the embeddings for the loaded model, with buttons that add the trigger to the prompt or the negative prompt.

How this fits with #14508

#14508 (paste generation parameters) gave the Images page one parser and one restore path for A1111 / Forge text, Unsloth recipes and dropped images. That PR reported TI hashes entries as "textual inversion NAME" not applied, because Studio loaded no embeddings then. This branch is merged with main after it and wires both controls into that path:

  • Shift:
    • shift, base_shift and max_shift are restored recipe keys now. A gallery restore, a dropped Studio image, or a pasted recipe fills the Shift box(es).
    • A Shift: field in pasted parameters text is read as the static shift. The image's own parameters text now writes Shift: when a static shift was requested, so pasting it back restores it. Base / max shift have no infotext key and stay in the recipe chunk only.
    • A Shift the loaded model cannot take is named in the "not applied" toast: no Shift control, the other ComfyUI node's fields, or a value out of range.
  • Embeddings:
    • The parser keeps the TI hashes names. When the loaded model takes embeddings, the import checks them against the installed ones (file stem, any case). An installed embedding applies through the restored prompt and is not reported. A missing one is named "textual inversion NAME (not installed)".
    • On a model without embeddings, or when the lookup is superseded or the model changed in the meantime, the toast is the same as on main.
    • embeddings in a Studio recipe is informational (the prompt carries the triggers), so it is no longer reported as an unknown key.
  • Merge conflicts: the inpaint mask fields (Studio Images: paste generation parameters, inpaint mask blur and only-masked area, seed buttons #14508) and the Shift fields sit side by side in the request, the gallery record and generate().
  • Bundle budget: listDiffusionEmbeddings moved from api.ts (part of the eager chat chunk) to embeddings-api.ts, which only the Images page loads. Main has 0.0 KB transfer headroom and this keeps the startup bundle within budget.

Tests

  • tests/test_diffusion_shift_override.py:
    • the family-to-node table and the FLUX.1 schnell / dev variants;
    • mu against a transcription of ModelSamplingFlux.patch and against diffusers calculate_shift;
    • the built schedule against time_snr_shift and flux_time_shift on dynamic, dynamic + terminal and static scheduler configs;
    • UniPC flow_shift (HiDream);
    • validation, shift_control and its resolved defaults (fixed mu, dynamic config line), no rebuild at the resolved value, the route refusal on other engines, and the request bounds.
  • tests/test_diffusion_embeddings.py:
    • format classification, the listing, trigger matching and prompt rewriting;
    • nothing is touched without a trigger;
    • real tiny SD 1.x (hf-internal-testing/tinier-stable-diffusion-pipe) and SDXL (hf-internal-testing/tiny-stable-diffusion-xl-pipe) pipelines with a synthetic 3-vector file: the expanded ids land past the base vocabulary in each tokenizer, the negative encoding changes, the positive does not, the wrong-width file is skipped, and after restore every object is the original and the encoding is bit-identical;
    • the prompt cache key and the family gating.
  • Both new files fail to collect on the merge base (the symbols do not exist there) and pass here: 62 tests. One of them checks the new Shift: parameters-text field.
  • frontend/tests/images-shift-embeddings-import.test.ts (new) covers:
    • a pasted Shift: restoring into the box and being sent on a ModelSamplingSD3 model, and named on a ModelSamplingFlux model or one without the control;
    • a Studio recipe's base / max shift restoring, with the request bounds;
    • TI hashes names staying reported until an installed embedding matches;
    • the page wiring: the superseded or model-changed lookup, and the gallery restore filling Shift.
  • After merging main (head vs origin/main at 94a8bfa, same host):
    • Frontend, node --experimental-strip-types --test "tests/**/*.test.ts": head 13393 tests, 0 failures (1 skipped); main 13390 tests, 0 failures (1 skipped). node scripts/typecheck.mjs --tests is clean, npm run build passes, and npm run bundle:check is within budget.
    • Backend: this PR's two files plus the Images suites (inpaint mask, inpaint mask SDXL, diffusion backend, routes, sampler, SDXL, ControlNet, image gallery, generate-image tool, prompt / cond cache, control capabilities, saved-image metadata, OpenAI images route, more families, flow shift, model defaults), one process per file: head 1331 passed, 1 skipped, 1 failed; main 1269 passed, 1 skipped, 1 failed. The failure is the same test on both sides, test_diffusion_backend.py::test_mirrored_base_still_trips_the_flux2_shape_guard, so it was already failing before this PR.
  • The related existing suites have the same failing IDs (none) on base and head:
    • flow shift, comfy sigmas, sampler, prompt / cond cache, LoRA, backend, routes, ControlNet, FLUX.3, static skip, TE release, MLX and others;
    • 1112 + 943 tests each side.

Studio's real backend path (DiffusionBackend.load_pipeline + generate) on GPU, tiny pipelines, with the same seed:

Case Unset, base vs head Unset twice Override changes the image Back to unset after it Sigmas vs ComfyUI formula (max abs err)
FLUX.1 (tiny-flux-pipe), base 0.5 / max 3.0 identical identical yes identical 1.0e-7
Qwen-Image (tiny-qwenimage-pipe), shift 5 identical identical yes identical 2.0e-8
Qwen-Image-2.1 (tiny-qwenimage21-pipe), base = max = 1.0 identical identical yes identical 1.2e-7
Lumina 2 (tiny-lumina2-pipe), shift 2 identical identical yes identical 2.0e-8

These ran with speed_mode=off. Sending the reported default back (Qwen-Image shift 3.1, Qwen-Image-2.1 base = max = 0.69, FLUX.1 tiny base = max = 0) rendered identically to leaving it unset. The wrong field for each model (a single shift on a ModelSamplingFlux model, base_shift on a ModelSamplingSD3 one) was refused, and the loaded scheduler's class and config were unchanged afterwards.

SDXL (tiny-stable-diffusion-xl-pipe) Eager (off) Compiled (max)
Negative prompt naming a missing embedding, base vs head identical not comparable: two head processes already differ
Same prompt with a 4-vector EasyNeg.safetensors present image changes, embeddings: ["EasyNeg"] image changes, embeddings: ["EasyNeg"]
Wrong-width OtherModel.safetensors named embeddings_skipped: ["OtherModel"] embeddings_skipped: ["OtherModel"]
File removed, same prompt again, same process identical to the first image identical to the first image
New dynamo graphs over the 4 renders after the first n/a 0

The compiled SDXL row is speed_mode=max (regional compile + CUDA graphs on the U-Net). Rendering with an embedding, then without it, then the original prompt again added no dynamo graphs and logged no recompiles. The embedding only changes text-encoder inputs.

Not covered here

  • Shift on the native sd.cpp and MLX engines (refused with a 400 rather than ignored).
  • SD 1.x embeddings in the UI, until Studio has an SD 1.x family.
  • A1111 .pt embeddings (pickle).
  • Recording base / max shift and the embeddings in the A1111 parameters text. They are in the Unsloth recipe chunk. A static shift is written as Shift:.
  • ComfyUI graphs' ModelSamplingSD3 / ModelSamplingFlux nodes are not read on import yet.

…ual inversion embeddings for SDXL

Shift maps to the ComfyUI node each family's workflow uses: ModelSamplingSD3 / AuraFlow (one static
shift) for Qwen-Image, Z-Image, Lumina 2, HiDream, HunyuanImage 2.1 and FLUX.1-schnell, and
ModelSamplingFlux (base / max shift at the output size) for FLUX.1-dev / Kontext, FLUX.2, FLUX.3,
Krea 2 and Qwen-Image-2.1. The override builds a scheduler copy for that generation only; unset keeps
today's schedule.

Embeddings are .safetensors files in the Studio embeddings folder, triggered by their filename stem in
the prompt or negative prompt (A1111 semantics, plus ComfyUI's embedding:NAME). They are applied per
generation through tokenizer copies and a wrapper around each CLIP input embedding, then restored, so
the pipeline is never reloaded and the denoiser is untouched.
shift_control reports the loaded static shift, or base = max = the fixed mu for ModelSamplingFlux
families that resolved one, and a missing base / max shift takes that value. Sending the resolved value
keeps the loaded scheduler (no rebuild), and a checkpoint that ships its own sampling grid keeps it:
Shift is hidden and refused there, as the load-time ComfyUI shift is.
…embeddings

Conflicts kept both sides: the inpaint mask fields and the Shift fields sit side
by side in the request, the gallery record, the route kwargs and generate(); the
record copies all of them through one "set only" filter.

Pasted, dropped or restored parameters now set Shift: shift / base_shift /
max_shift are restored recipe keys, a `Shift:` infotext field is parsed (and
written into the image's parameters text), and the import names a Shift the
loaded model cannot take. TI hashes names are matched against the installed
embeddings when the loaded model takes them: an installed one applies through
the restored prompt, a missing one is named "(not installed)".

listDiffusionEmbeddings moves out of api.ts into embeddings-api.ts so the eager
chat chunk stays inside the startup bundle budget.
@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 ✅ Completed 2026-10-21T20:45:32.129573Z f512ca4 Manual request
🔒 Security Review ⚠️ Failed 2026-10-21T20:39:03.040564Z
We couldn’t complete this review. Comment @codex security review to try again.
6a599bd 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.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f512ca4d19

ℹ️ About Codex in GitHub

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

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

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

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

@danielhanchen
danielhanchen merged commit 38d2124 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-images-shift-embeddings branch October 21, 2026 21:29
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…o its own build (#14571)

Main is over the startup bundle budget, so "Frontend build + bundle
sanity" fails for any PR built on it:

```
over the startup budget: transfer 2023.3 KB > 2023.3 KB
```

Exact bytes, one machine, Node 24, measured with the checker's own sums:

| build | raw | transfer | transfer budget |
|---|---|---|---|
| before #14508 (`94a8bfacb3^`) | 6,878,900 | 2,071,669 | 2,071,693 |
| `94a8bfacb3` (#14508) | 6,878,900 | 2,071,672 | 2,071,693 |
| before #14563 (`38d21245d0^`) | 6,879,325 | 2,071,834 | 2,071,816 |
| main `5ab80ffdb4` | 6,879,345 | 2,071,823 | 2,071,816 |

#14524 raised the transfer budget to exactly its own measured build
("transfer set to the measured build"), leaving zero headroom. Next to
the other frontend changes that landed around it, the startup set
compresses a few bytes larger (+18 B before #14563, +7 B now). Neither
PR added a large import; the limit simply had no room.

## Change

`transferBytes` is set to the measured main build + 189 B (2,072,012),
the same headroom used for earlier raises, with a comment recording the
measurement. `rawBytes` is unchanged: it is already 244 B above the
measured 6,879,345.

## Testing

- Main build at `5ab80ffdb4` with main's budget: `over the startup
budget`.
- Same build with this budget: `within budget (0.2 KB transfer, 0.2 KB
raw to spare)`.
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…ation seeds (#14562)

## 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 (#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 (#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
#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 #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.
- #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 #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 #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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14562/pr14562_advanced_controls-a15208c0dc2e.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14562/pr14562_vary_enabled-a726dfe93543.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14562/pr14562_vary_disabled_variation-80bcae637c50.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14562/pr14562_vary_disabled_build-b6f3a22ba4cd.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14562/pr14562_paste_toast-a30a89c3f82b.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14562/pr14562_paste_fields-3ce8e49303d3.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14562/pr14562_flux_after_no_controls-b477f67b8249.png)

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant