Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(upscale): build the refine pass from Generation's family pipelines (#10306)
Josh Corbettc5fa56e727df
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdxindex ba2180be03..8c089cb909 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx@@ -332,12 +332,16 @@ weights instead of being merged into them.- An older version of InvokeAI registered MOSS-Image LoRAs as Z-Image LoRAs or as unknown models. Select one in theModel Manager and use **Re-identify model**.+## Upscaling++The [Upscale panel](/users-guide/image-generation/upscale/) refines with MOSS-Image, enabled LoRAs included. Its+MOSS-Image tab lists the components and defaults the detail pass uses.+## Limitations- ComfyUI scaled and unscaled fp8, other torchao layouts, torchao fp8 mixed with ComfyUI-quantized layers, nvfp4, w4a8 and ComfyUI-GGUF `Q8_CR`/`Q4_CR` transformers are refused at install (see [Installing](#installing)).- ControlNet, reference images and seamless tiling are not available.- Regional guidance places boxes in a layout; it has no regional negative prompts or regional reference images.-- MOSS-Image is not offered in the [Upscale panel](/users-guide/image-generation/upscale/).## Workflow nodesdiff --git a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdxindex 708b825dd3..2246ce3b29 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx@@ -197,7 +197,7 @@ Each upscaler has a native scale, such as 4× for 4x-UltraSharp. In Model only m| 4× | Runs 2× 2 times | Runs 4× once || 8× | Runs 2× 3 times | Runs 4× 2 times, then resizes to 8× |-When **Scale** equals the native scale the note is left out. A 1× model (a restoration model) keeps the input size, so **Scale** has no effect. In Refine mode the panel shows no native scale. FLUX.1, FLUX.2, Z-Image, Anima, Krea-2 and Qwen Image resize the upscaler's result to **Scale** before the detail pass; SD1.5 and SDXL keep the upscaler's size, so with a 1× model their result stays at the source size.+When **Scale** equals the native scale the note is left out. In Model only mode a 1× model (a restoration model) keeps the input size, so **Scale** has no effect. In Refine mode the panel shows no native scale: every main model (SD1.5, SDXL, FLUX.1, FLUX.2, Z-Image, Anima, Krea-2, Qwen Image and MOSS-Image) resizes the upscaler's result to **Scale** before the detail pass, so a 1× model's result still comes out at **Scale**.A Model only result's metadata is the source image's metadata plus the upscaler and the **Scale**, so **Recall** on it restores how the source was made.diff --git a/docs/src/content/docs/contributing/new-model-integration.mdx b/docs/src/content/docs/contributing/new-model-integration.mdxindex ce9e1c31a0..d1105cb703 100644--- a/docs/src/content/docs/contributing/new-model-integration.mdx+++ b/docs/src/content/docs/contributing/new-model-integration.mdx@@ -860,6 +860,8 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor`FamilyGraph` requires each fact field, but its types do not prove that a nullable fact is present for the family's capabilities or that a node reference names the right node. Verify that the new base and every graph-changing variant participate in `generateGraphCases` (`graphCoverage.testing.ts`), which derives its bases from `SUPPORTED_GENERATE_BASES`. Extend `SHAPE_OVERRIDES` and `CANDIDATE_VARIANTS` as needed, and update the per-base expectations in `graph.test.ts`'s `family graph facts` tests. Those tests check the facts against emitted VAE, UNet, denoise and conditioning wiring.+ Upscale refines with the same builder. A family in `IMAGE_TO_IMAGE_PIPELINES` is split into a pipeline, `buildZImagePipeline(input: FamilyPipelineInput, extras)`, which builds the loader, LoRAs, encoders, denoise and decode from the narrow `FamilyPipelineSettings`, and the Generate builder, which passes references, PiD and enhancers through the pipeline's hooks and adds metadata once the pipeline returns. `UPSCALE_ARCHITECTURES` is type-checked against that table, so supporting Upscale means the split plus an Upscale entry for its own choices (tile ControlNet, schedulers, defaults).+Validation that only one architecture needs belongs in `getModelFamilyValidationReasons` (`baseGenerationPolicies.ts`).4. **Component pickers** (encoder, VAE, Diffusers component source)@@ -878,7 +880,7 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor5. **Canvas**- Name the encode node in the builder's `latents` record (step 3). Leave it `null` only when the architecture has no image-to-latents node.- - If the architecture uses the `strength^0.2` denoising-start curve, add it to `canvasDenoisingStart`.+ - Record how its denoise clips `denoising_start` in `getDenoisingStartClipping` (`baseGenerationPolicies.ts`). Clipping by sigma value gives Canvas the `strength^0.2` curve; a node that clips by step index also records its sigmas and rounding, which Upscale aims Creativity with.- Add a case to `BASE_CASES` in `canvas/compileCanvasGraph.test.ts`.6. **Recall** (`src/workbench/image-actions/`)diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex 7a85b192f9..c3268e7ba1 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -114,6 +114,7 @@ Feature interfaces stay ordinary module interfaces unless two adapters add lever- Models and Nodes: production event/transport adapters. Their sinks (model-load activity, node execution) are injected into Queue's runtime at the App composition root; Queue runtime tests use doubles.- Models owns the served architecture table and its VAE pairing question. Generation maps the table onto its own policy; the Generate VAE picker, validator and compiler and Related Models' VAE links ask the same question, so pairings change only in the backend's `VaeFacet`. Pure cores read it through `features/models/architectures`; it loads on demand, off the Launchpad startup graph ([features/models/README.md](src/features/models/README.md#architecture-table)).- Gallery, Generation, Workflow, Upscale keep compilation and UI seams internal until a feature ticket shows another independent adapter. Workbench image actions also stay internal, not a shallow Image Feature.+- Generation's family pipeline is the exception, with two adapters: Canvas grafts its image modes onto the `FamilyGraph` a Generate builder returns, and Upscale builds its detail pass from `buildImageToImagePipeline` (`features/generation/graph.ts`) and adds only its own prefix, tile control and metadata. Generate-only extras reach a pipeline as hooks Upscale's entry cannot pass.- Gallery picker and media slots read a narrow `GalleryHost`: gallery scope, notifications, optional Gallery-widget reveal. Workbench derives it from the Gallery UI adapter. Launchpad's model manager has no workbench and supplies its own.- Gallery media shown outside the Gallery widget (workflow fields, outputs, picker tiles) opens the shared item menu through `useGalleryItemContextMenu` (`features/gallery/react`), which calls the Gallery UI adapter's stable `openItemContextMenu`. App fetches the item only when the surface has none and loads the menu with the lazy image-actions bridge; only the newest request in the active project opens, and the user's next click or Escape drops one still loading. A `GalleryHost` host has no item menu and keeps the browser's.- Media slots accept dragged gallery items only inside `GalleryDragScope`, provided by the workbench shell with its drag context. Widget dialog hosts and the Launchpad sit outside it.@@ -127,7 +128,7 @@ Feature interfaces stay ordinary module interfaces unless two adapters add lever| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Models, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution || Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope, offline graph export and widget contribution || Workflow | Workflow document, validation, compilation, preview/editor/library and explicit publication; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution |-| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |+| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue/Generation interfaces; value/validation reads, submission command and widget contribution || Intermediates | Per-project intermediates read models, cleanup previews/operations and the Settings section that manages them; Workbench settings, project menus, account administration | Platform plus Identity's public session/capability reads; query keys, read models, the focus intent, the browser hold lease and the `settingsContribution` metadata whose loader owns the section body |Launchpad retains visited sections with React Activity. Inactive view observers and registrations disconnect while account-owned jobs continue; returning reattaches the view under its Query refetch policy. Home and Projects refetch on every reveal; other queries refetch when stale. Intermediates search commits its bounded pending debounce while hidden so its retained input and query agree on reveal. Removed sections unmount. The authenticated route's account lifetime owns the entire Launchpad, so account changes discard visited view state.diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 7be6c71106..4d894ce28d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -3,7 +3,11 @@ import type {GenerationModelTaxonomyType as ModelTaxonomyType,PromptHistoryItem,} from '@features/generation/core/contracts';-import type { BaseGenerationConfig, GuidanceLabel } from '@features/generation/core/generationConfig';+import type {+ BaseGenerationConfig,+ GuidanceLabel,+ NegativePromptUsage,+} from '@features/generation/core/generationConfig';import { getArchitectureGenerationConfig } from '@features/generation/core/architectureGenerationConfig';import {@@ -356,6 +360,10 @@ export const coerceSchedulerForGraph = (}};+/** Whether a local model's denoise reads a negative prompt: always, only above CFG 1, or never. */+export const getNegativePromptUsage = (model: GenerateModelConfig | undefined): NegativePromptUsage =>+ getBaseGenerationConfig(model).negativePrompt.usage;+export const getPromptPolicy = (model: GenerateModelConfig | undefined,settings: Pick<GenerateSettings, 'cfgScale' | 'negativePromptEnabled'>@@ -1108,7 +1116,7 @@ const hasFlux2EncoderSource = (ctx: ComponentPolicyContext): boolean =>/** The saved component source the FLUX.2 loader can use: its VAE always, its encoder unless a standalone one is set. */export const getFlux2ComponentSource = (model: MainModelConfig,- settings: GenerateSettings+ settings: Pick<GenerateSettings, 'componentSourceModel' | 'mistralEncoderModel' | 'qwen3EncoderModel'>): MainModelConfig | undefined => {const source = settings.componentSourceModel;@@ -3631,3 +3639,101 @@ export const getGenerateInvocationIssues = (...(models ? getGenerationModelAvailabilityIssues(model, values, models) : []),];};++// How each denoise node clips `denoising_start`: Canvas picks its strength curve by it, Upscale translates Creativity.++/** A start `s` enters at sigma `1 - s`, whatever the shift. */+interface SigmaClipping {+ kind: 'sigma';+}++/** Clips by step index, so a start enters noisier; `test_upscale_index_clipped_starts.py` pins these schedules. */+export interface StepClipping {+ kind: 'step';+ /** Noisiest first, without the final 0. */+ sigmas: (model: Pick<MainModelConfig, 'variant'>, size: { width: number; height: number }, steps: number) => number[];+ /** `int(start * steps)`, or Python's half-to-even `int(round(start * steps))`. */+ rounding: 'floor' | 'round';+}++export type DenoisingStartClipping = SigmaClipping | StepClipping;++/** First `steps` sigmas of a flow schedule shifted by `shift`, without the final 0 (diffusers: shift = exp(mu)). */+const shiftedSigmas = (shift: number, steps: number): number[] =>+ Array.from({ length: steps }, (_, index) => {+ const t = 1 - index / steps;++ return (shift * t) / (1 + (shift - 1) * t);+ });++/** `mu` on a line through two token counts, one token per 16x16 pixels, held at the line's upper end. */+const tokenFitMu = (+ { width, height }: { width: number; height: number },+ fit: { minSeqLen: number; maxSeqLen: number; baseShift: number; maxShift: number }+): number => {+ const seqLen = Math.min(Math.floor(width / 16) * Math.floor(height / 16), fit.maxSeqLen);+ const slope = (fit.maxShift - fit.baseShift) / (fit.maxSeqLen - fit.minSeqLen);++ return seqLen * slope + fit.baseShift - slope * fit.minSeqLen;+};++/** `z_image_denoise.Z_IMAGE_SHIFT_FIT`, held at the fit's 4096-token end since the clamp (#378). */+const Z_IMAGE_SHIFT_FIT = { baseShift: 0.5, maxSeqLen: 4096, maxShift: 1.15, minSeqLen: 256 };++/** `ANIMA_SHIFT`: Anima's schedule is shifted by a constant, not by resolution. */+const ANIMA_SCHEDULE_SHIFT = 3;++/** `krea2/sampling_utils.py`: Turbo's fixed mu and Raw's token-count fit; anything not Raw counts as distilled. */+const KREA2_DISTILLED_MU = 1.15;+const KREA2_SHIFT_FIT = { baseShift: 0.5, maxSeqLen: 6400, maxShift: 1.15, minSeqLen: 256 };++/** `qwen_image_denoise`'s scheduler: mu 0.5 at 256 tokens to 0.9 at 8192, held at the end, stretched to 0.02. */+const QWEN_IMAGE_SHIFT_FIT = { baseShift: 0.5, maxSeqLen: 8192, maxShift: 0.9, minSeqLen: 256 };+const QWEN_IMAGE_SHIFT_TERMINAL = 0.02;++/** As diffusers' FlowMatchEulerDiscreteScheduler builds them, including `stretch_shift_to_terminal`. */+const qwenImageSigmas = (size: { width: number; height: number }, steps: number): number[] => {+ const shifted = shiftedSigmas(Math.exp(tokenFitMu(size, QWEN_IMAGE_SHIFT_FIT)), steps);+ const scale = (1 - (shifted[steps - 1] ?? 0)) / (1 - QWEN_IMAGE_SHIFT_TERMINAL);++ return shifted.map((sigma) => 1 - (1 - sigma) / scale);+};++const SIGMA_CLIPPING: SigmaClipping = { kind: 'sigma' };++// The step schedules assume the node's default shift. Upscale sends no shift; Canvas can, so it reads only `kind`.+const DENOISING_START_CLIPPING: Partial<Record<string, DenoisingStartClipping>> = {+ anima: {+ kind: 'step',+ rounding: 'floor',+ sigmas: (_model, _size, steps) => shiftedSigmas(ANIMA_SCHEDULE_SHIFT, steps),+ },+ flux: SIGMA_CLIPPING,+ flux2: SIGMA_CLIPPING,+ flux3: SIGMA_CLIPPING,+ 'krea-2': {+ kind: 'step',+ rounding: 'round',+ sigmas: (model, size, steps) =>+ shiftedSigmas(+ Math.exp(model.variant === 'krea2_base' ? tokenFitMu(size, KREA2_SHIFT_FIT) : KREA2_DISTILLED_MU),+ steps+ ),+ },+ 'moss-image': SIGMA_CLIPPING,+ 'qwen-image': { kind: 'step', rounding: 'round', sigmas: (_model, size, steps) => qwenImageSigmas(size, steps) },+ 'sd-3': SIGMA_CLIPPING,+ 'z-image': {+ kind: 'step',+ rounding: 'floor',+ sigmas: (_model, size, steps) => shiftedSigmas(Math.exp(tokenFitMu(size, Z_IMAGE_SHIFT_FIT)), steps),+ },+};++/** Null where neither rule applies (SD clips scheduler timesteps); the start is then passed as is. */+export const getDenoisingStartClipping = (+ model: Pick<GenerateModelConfig, 'base' | 'type'>+): DenoisingStartClipping | null =>+ model.type !== 'external_image_generator' && Object.hasOwn(DENOISING_START_CLIPPING, model.base)+ ? (DENOISING_START_CLIPPING[model.base] ?? null)+ : null;diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex 072cdac916..bc431b6cb8 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -6,6 +6,7 @@ import type { FamilyGraph, FamilyLatentSpace } from '@features/generation/core/fimport type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';import {+ getDenoisingStartClipping,getGenerationValidationReasons,hasEnabledKrea2EditReferences,} from '@features/generation/core/baseGenerationPolicies';@@ -55,17 +56,12 @@ import {import { type CanvasSize, resolveCanvasProcessingSize } from './canvasProcessingSize';import { isAnimaInpaintAdapterModel } from './controlValidation';-/** SD-3, FLUX, FLUX.2, FLUX.3 and MOSS-Image start at 1 - strength^0.2; FLUX Fill at 0; others at 1 - strength. */+/** Sigma-clipping families start at 1 - strength^0.2; FLUX Fill at 0; others at 1 - strength. */const canvasDenoisingStart = (model: GenerateModelConfig, strength: number): number => {if (isFluxFillModel(model)) {return 0;}- const usesOptimizedCurve =- model.base === 'sd-3' ||- model.base === 'flux' ||- model.base === 'flux2' ||- model.base === 'flux3' ||- model.base === 'moss-image';+ const usesOptimizedCurve = getDenoisingStartClipping(model)?.kind === 'sigma';return 1 - strength ** (usesOptimizedCurve ? 0.2 : 1);};diff --git a/invokeai/frontend/webv2/src/features/generation/core/familyGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/familyGraph.tsindex 8cda6b48a3..b2b2c848ee 100644--- a/invokeai/frontend/webv2/src/features/generation/core/familyGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/familyGraph.ts@@ -1,4 +1,5 @@import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';+import type { GenerateSettings, MainModelConfig, VaeModelConfig } from '@features/generation/core/types';/** A node output that feeds an input: the node and its output field. */export interface GraphOutput {@@ -8,8 +9,9 @@ export interface GraphOutput {/*** A family builder's graph with the facts callers compose over. Canvas grafts image encodes, masks, control and- * regional conditioning onto the nodes the builder names here, so it neither guesses node ids nor scans edges for these- * facts. The `seed` and `canvas_output` ids stay shared contracts outside this record.+ * regional conditioning onto the nodes the builder names here, and Upscale feeds its enlarged frame through `latents`+ * into `denoise`, so neither guesses node ids nor scans edges for these facts. The `seed` and output ids stay shared+ * contracts outside this record.*/export interface FamilyGraph {graph: BackendGraphContract;@@ -53,3 +55,47 @@ export interface FamilyConditioning {*/fluxReduxCollector: BackendInvocationContract | null;}++/** The settings a pipeline reads; widening it fails Upscale's build until Upscale maps the new field. */+export type FamilyPipelineSettings = Pick<+ GenerateSettings,+ | 'cfgRescaleMultiplier'+ | 'cfgScale'+ | 'clipEmbedModel'+ | 'clipSkip'+ | 'componentSourceModel'+ | 'loras'+ | 'mistralEncoderModel'+ | 'qwen35EncoderModel'+ | 'qwen3EncoderModel'+ | 'qwen3VLEncoderModel'+ | 'qwenVLEncoderModel'+ | 'scheduler'+ | 'steps'+ | 't5EncoderModel'+ | 'vae'+ | 'vaePrecision'+>;++/** Prompts, seed, loader, LoRAs, encoders, denoise and decode; Generate-only additions cannot be asked for here. */+export interface FamilyPipelineInput {+ model: MainModelConfig;+ settings: FamilyPipelineSettings;+ /** The size the denoise runs at, already on the family's grid. */+ denoiseSize: { width: number; height: number };+ /** Where the denoise enters its schedule, in the denoise node's own terms (see `getDenoisingStartClipping`). */+ denoisingStart: number;+ useCpuNoise: boolean;+ output: { id: string; isIntermediate: boolean };+ /** Tiles the decode where the node has the switch; null decodes whole. The caller tiles its own encode. */+ vaeTileSize: number | null;+ /** SD only: tiled multi-diffusion denoise, which takes one conditioning per side and so has no `conditioning`. */+ multiDiffusion: { tileSize: number; tileOverlap: number } | null;+}++/** A family graph plus the decode node whose image is the result. */+export interface FamilyPipeline extends FamilyGraph {+ output: BackendInvocationContract;+ /** The VAE model handed to the loader; null where the graph decodes with a bundled or source model's VAE. */+ vaeModel: VaeModelConfig | null;+}diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex c009855c44..1ba2e7ae53 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -13,7 +13,14 @@ import type {} from './types';import { getDefaultGenerateSettings, type SupportedGenerateBase } from './baseGenerationPolicies';-import { compileGenerateGraph, getFamilyGraphBuilder, GRAPH_BUILDERS, resolveGenerateSeed } from './graph';+import {+ buildImageToImagePipeline,+ compileGenerateGraph,+ getFamilyGraphBuilder,+ GRAPH_BUILDERS,+ type ImageToImagePipelineBase,+ resolveGenerateSeed,+} from './graph';import {fullyFilledSettingsFor,generateGraphCases,@@ -765,6 +772,73 @@ describe('getFamilyGraphBuilder', () => {});});+describe('buildImageToImagePipeline', () => {+ // What only another feature asks for: a partial pass, its own output node, tiled VAE ends and SD's tiled denoise.+ it.each([+ ['sd-1', 'tiled_multi_diffusion_denoise_latents', true],+ ['sdxl', 'tiled_multi_diffusion_denoise_latents', true],+ ['flux', 'flux_denoise', true],+ ['flux2', 'flux2_denoise', true],+ ['z-image', 'z_image_denoise', true],+ // `anima_l2i` has no tiling switch: it tiles on its own.+ ['anima', 'anima_denoise', false],+ ['krea-2', 'krea2_denoise', true],+ ['qwen-image', 'qwen_image_denoise', true],+ ['moss-image', 'moss_image_denoise', true],+ ] as const satisfies readonly (readonly [ImageToImagePipelineBase, string, boolean])[])(+ 'builds the %s pass the input asks for',+ (base, denoiseType, decodeTiles) => {+ const { shape } = generateGraphCases.find((testCase) => testCase.base === base)!;+ const { model, settings } = satisfiedSettingsFor(base, shape);+ const sd = base === 'sd-1' || base === 'sdxl';+ const pipeline = buildImageToImagePipeline({+ denoiseSize: { height: 768, width: 1024 },+ denoisingStart: 0.4,+ model,+ multiDiffusion: sd ? { tileOverlap: 64, tileSize: 512 } : null,+ output: { id: 'pass_output', isIntermediate: true },+ settings,+ useCpuNoise: true,+ vaeTileSize: 640,+ });+ const { nodes } = pipeline.graph;++ expect(pipeline.output).toBe(nodes.pass_output);+ expect(nodes.canvas_output).toBeUndefined();+ expect(nodes.pass_output).toMatchObject({ is_intermediate: true, use_cache: false });+ expect(pipeline.denoise).toMatchObject({ denoising_end: 1, denoising_start: 0.4, type: denoiseType });+ if (decodeTiles) {+ expect(nodes.pass_output).toMatchObject({ tile_size: 640, tiled: true });+ } else {+ expect(nodes.pass_output).not.toHaveProperty('tiled');+ }+ if (sd) {+ expect(pipeline.denoise).toMatchObject({ tile_height: 512, tile_overlap: 64, tile_width: 512 });+ // The tiled denoise takes one conditioning per side, so there are no collectors to graft onto.+ expect(pipeline.conditioning).toBeNull();+ }+ }+ );++ it('refuses a family without an image-to-image pipeline', () => {+ const { shape } = generateGraphCases.find((testCase) => testCase.base === 'wan')!;+ const { model, settings } = satisfiedSettingsFor('wan', shape);++ expect(() =>+ buildImageToImagePipeline({+ denoiseSize: { height: 768, width: 1024 },+ denoisingStart: 0,+ model,+ multiDiffusion: null,+ output: { id: 'pass_output', isIntermediate: false },+ settings,+ useCpuNoise: false,+ vaeTileSize: null,+ })+ ).toThrow(/no image-to-image pipeline/);+ });+});+describe('family graph facts', () => {const projectSettings = { useCpuNoise: true, useNsfwChecker: false, useWatermark: false };const build = (model: MainModelConfig, settings: GenerateSettings) =>diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex ba18bf0d5d..b72858cdde 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -7,7 +7,7 @@ import type {import { SEED_MAX } from '@platform/core/seed';-import type { FamilyGraph } from './familyGraph';+import type { FamilyGraph, FamilyPipeline, FamilyPipelineInput } from './familyGraph';import type {CompiledGenerateGraph,ComponentModelConfig,@@ -77,12 +77,12 @@ import { addSDXLRefinerStage, getRefinerMetadata } from './sdxlRefinerGraph';import { getEffectiveIdeogram4Sampling } from './settings';const getCompatibleComponentSource = (- settings: GenerateSettings,+ settings: Pick<GenerateSettings, 'componentSourceModel'>,model: MainModelConfig): MainModelConfig | undefined => getCompatibleDiffusersComponentSource(model, settings.componentSourceModel);// The picker's rule, not a copy of it: a base list here once dropped a VAE the picker offered.-const getCompatibleVae = (settings: GenerateSettings, model: MainModelConfig) =>+const getCompatibleVae = (settings: Pick<GenerateSettings, 'vae'>, model: MainModelConfig) =>settings.vae && isVaeCompatibleWithGenerateModel(model, settings.vae) ? settings.vae : null;/** Filter stale optional selections that required-slot validation skips. */@@ -252,7 +252,10 @@ const addFluxKontextReferenceImages = (return prevCollect;};-const getDiffusersSource = (settings: GenerateSettings, model: MainModelConfig): MainModelConfig | undefined =>+const getDiffusersSource = (+ settings: Pick<GenerateSettings, 'componentSourceModel'>,+ model: MainModelConfig+): MainModelConfig | undefined =>getCompatibleComponentSource(settings, model) ?? (isBundledMainForBase(model.base)(model) ? model : undefined);const requireComponent = <T extends ComponentModelConfig | null>(value: T, label: string): NonNullable<T> => {@@ -380,18 +383,224 @@ export const addWanLoraLoaders = (return source;};-const buildSDGraph = (+type GenerateGraphBuilder = (settings: GenerateSettings,model: MainModelConfig,outputIsIntermediate: boolean,projectSettings: GenerationProjectSettings-): FamilyGraph => {+) => FamilyGraph;++/** What a decode hook is handed: the latents to decode, the VAE and what PiD conditions its decode on. */+interface DecodeSources {+ denoise: BackendInvocationContract;+ positivePrompt: BackendInvocationContract;+ seed: BackendInvocationContract;+ vaeSource?: BackendInvocationContract;+ vaeField?: string;+}++/** Builds the decode in place of the plain VAE decode and returns the result node. */+type DecodeBuilder = (graph: BackendGraphContract, sources: DecodeSources) => BackendInvocationContract;++/** Generate-only hooks: splices run inside the pipeline; the rest keep Generate's edge order, which collects follow. */+interface PipelineExtras {+ /** Literal fields the denoise node gains: FLUX DyPE, a schedule shift, MOSS-Image's skip layers, HiDiffusion. */+ denoiseFields?: Record<string, unknown>;+ /** The decode Generate builds instead of the VAE decode: PiD. */+ decode?: DecodeBuilder;+}++/** Positive conditioning passed through Generate's enhancers on its way to the collector. */+type ConditioningHook = (+ graph: BackendGraphContract,+ conditioning: BackendInvocationContract,+ seed: BackendInvocationContract+) => BackendInvocationContract;++const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({+ negativePrompt: addNode(graph, { id: 'negative_prompt', type: 'string' }),+ positivePrompt: addNode(graph, { id: 'positive_prompt', type: 'string' }),+ seed: addNode(graph, { id: 'seed', type: 'integer' }),+});++const addImageOutputNode = (graph: BackendGraphContract, type: string, outputIsIntermediate: boolean) =>+ addNode(graph, { id: 'canvas_output', is_intermediate: outputIsIntermediate, type, use_cache: false });++/** A pipeline's output node without its edges, for families that wire it as they go. */+const addPipelineOutputNode = (+ graph: BackendGraphContract,+ input: FamilyPipelineInput,+ type: string,+ { tiles }: { tiles: boolean }+) =>+ addNode(graph, {+ id: input.output.id,+ is_intermediate: input.output.isIntermediate,+ type,+ use_cache: false,+ ...(tiles ? vaeTilingFields(input) : {}),+ });++/** The switch a VAE node with tiling takes, when the input asks for it. */+const vaeTilingFields = (input: FamilyPipelineInput) =>+ input.vaeTileSize === null ? {} : { tile_size: input.vaeTileSize, tiled: true };++/** A pass from 0 sends no range, so Generate's graph is unchanged; Canvas sets the range itself. */+const partialDenoisingRange = (input: FamilyPipelineInput) =>+ input.denoisingStart === 0 ? {} : { denoising_end: 1, denoising_start: input.denoisingStart };++const addVaeDecode = (+ graph: BackendGraphContract,+ output: { id: string; isIntermediate: boolean; tiling: Record<string, unknown> },+ {+ denoise,+ l2iProps,+ l2iType,+ vaeField = 'vae',+ vaeSource,+ }: Omit<DecodeSources, 'positivePrompt' | 'seed'> & { l2iType: string; l2iProps?: Record<string, unknown> }+): BackendInvocationContract => {+ const node = addNode(graph, {+ id: output.id,+ is_intermediate: output.isIntermediate,+ type: l2iType,+ use_cache: false,+ ...l2iProps,+ ...output.tiling,+ });++ if (vaeSource) {+ addEdge(graph, vaeSource, vaeField, node, 'vae');+ }+ addEdge(graph, denoise, 'latents', node, 'latents');++ return node;+};++/** The pipeline's decode: the extra's where Generate passes one, else the VAE decode the input asks for. */+const addPipelineDecode = (+ graph: BackendGraphContract,+ input: FamilyPipelineInput,+ decode: DecodeBuilder | undefined,+ {+ l2iProps,+ l2iType,+ ...sources+ }: DecodeSources & {+ l2iType: string;+ /** Extra props for the VAE decode node; a decode hook builds its own. */+ l2iProps?: Record<string, unknown>;+ }+): BackendInvocationContract =>+ decode+ ? decode(graph, sources)+ : addVaeDecode(+ graph,+ { id: input.output.id, isIntermediate: input.output.isIntermediate, tiling: vaeTilingFields(input) },+ { ...sources, l2iProps, l2iType }+ );++/** Generate's decode hook: PiD where it is on; otherwise none, and the pipeline decodes with the VAE. */+const getGenerateDecode = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean+): DecodeBuilder | undefined =>+ shouldUsePidDecode(settings, model.base)+ ? (graph, sources) => addPidDecode({ ...sources, base: model.base, graph, outputIsIntermediate, settings })+ : undefined;++/** Both decode branches return canvas_output for metadata attachment. */+const addDecodeOutput = ({+ graph,+ settings,+ model,+ l2iType,+ l2iProps,+ denoise,+ positivePrompt,+ seed,+ vaeSource,+ vaeField = 'vae',+ outputIsIntermediate,+}: {+ graph: BackendGraphContract;+ settings: GenerateSettings;+ model: MainModelConfig;+ l2iType: string;+ /** Extra props for the ordinary decode node; ignored by the PiD chain, which has its own. */+ l2iProps?: Record<string, unknown>;+ denoise: BackendInvocationContract;+ positivePrompt: BackendInvocationContract;+ seed: BackendInvocationContract;+ vaeSource?: BackendInvocationContract;+ vaeField?: string;+ outputIsIntermediate: boolean;+}): BackendInvocationContract =>+ getGenerateDecode(+ settings,+ model,+ outputIsIntermediate+ )?.(graph, {+ denoise,+ positivePrompt,+ seed,+ vaeField,+ vaeSource,+ }) ??+ addVaeDecode(+ graph,+ { id: 'canvas_output', isIntermediate: outputIsIntermediate, tiling: {} },+ { denoise, l2iProps, l2iType, vaeField, vaeSource }+ );++/** Native PiD denoises at one quarter of the requested target dimensions. */+const getDenoiseSize = (settings: GenerateSettings, model: MainModelConfig): { width: number; height: number } =>+ // Use the model-native grid for divided dimensions, not the UI's PiD-scaled grid.+ getPidDenoiseSize(settings, model.base, getGenerationDimensions(model).grid);++/** The pipeline a Generate run asks for: the whole schedule, decoded whole into `canvas_output`. */+const toGeneratePipelineInput = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings,+ denoiseSize: { width: number; height: number }+): FamilyPipelineInput => ({+ denoiseSize,+ denoisingStart: 0,+ model,+ multiDiffusion: null,+ output: { id: 'canvas_output', isIntermediate: outputIsIntermediate },+ settings,+ useCpuNoise: projectSettings.useCpuNoise,+ vaeTileSize: null,+});++interface SdPipelineExtras extends PipelineExtras {+ /** The denoise's start and end, which the SDXL refiner splits. */+ denoisingRange?: { denoising_start: number; denoising_end: number };+ /** Seamless tiling, which wraps the UNet and the VAE the graph decodes with. */+ seamless?: { seamless_x: boolean; seamless_y: boolean } | null;+ /** Runs once the denoise is wired and returns the node whose latents are decoded: the refiner's, when it runs. */+ afterDenoise?: (+ graph: BackendGraphContract,+ nodes: {+ denoise: BackendInvocationContract;+ negativePrompt: BackendInvocationContract;+ positivePrompt: BackendInvocationContract;+ seamless: BackendInvocationContract | null;+ }+ ) => BackendInvocationContract;+}++const buildSdPipeline = (input: FamilyPipelineInput, extras: SdPipelineExtras = {}): FamilyPipeline => {+ const { model, multiDiffusion, settings } = input;const graph: BackendGraphContract = { edges: [], id: createId(`${model.base}_graph`), nodes: {} };const modelLoaderType = model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader';const compelType = getCompelPromptNodeType(model.base);const activeLoras = getActiveCompatibleLoras(settings, model);const scheduler = coerceSchedulerForGraph(model, settings.scheduler);- const supportsHiDiffusion = model.base === 'sd-1' || model.base === 'sdxl';const positivePrompt = addNode(graph, { id: 'positive_prompt', type: 'string' });const negativePrompt = addNode(graph, { id: 'negative_prompt', type: 'string' });@@ -399,52 +608,38 @@ const buildSDGraph = (const modelLoader = addNode(graph, { id: 'model_loader', model, type: modelLoaderType });const posCond = addNode(graph, { id: 'pos_cond', type: compelType });const negCond = addNode(graph, { id: 'neg_cond', type: compelType });- const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });- const negCondCollect = addNode(graph, { id: 'neg_cond_collect', type: 'collect' });- const sdDenoiseSize = getDenoiseSize(settings, model);+ // The multi-diffusion denoise takes one conditioning per side, not a collected list.+ const posCondCollect = multiDiffusion ? null : addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCondCollect = multiDiffusion ? null : addNode(graph, { id: 'neg_cond_collect', type: 'collect' });const noise = addNode(graph, {- height: sdDenoiseSize.height,+ height: input.denoiseSize.height,id: 'noise',type: 'noise',- use_cpu: projectSettings.useCpuNoise,- width: sdDenoiseSize.width,+ use_cpu: input.useCpuNoise,+ width: input.denoiseSize.width,});const denoise = addNode(graph, {cfg_rescale_multiplier: settings.cfgRescaleMultiplier,cfg_scale: settings.cfgScale,- ...getBaseDenoisingRange(settings, model, 0),+ ...(extras.denoisingRange ?? { denoising_end: 1, denoising_start: input.denoisingStart }),id: 'denoise_latents',- ...(supportsHiDiffusion+ ...extras.denoiseFields,+ scheduler,+ steps: settings.steps,+ ...(multiDiffusion? {- hidiffusion: settings.hiDiffusionEnabled,- hidiffusion_raunet: settings.hiDiffusionRauNetEnabled,- hidiffusion_window_attn: settings.hiDiffusionWindowAttentionEnabled,- ...(settings.hiDiffusionEnabled- ? {- hidiffusion_auto_ratios: settings.hiDiffusionT1Ratio === null && settings.hiDiffusionT2Ratio === null,- hidiffusion_t1_ratio: settings.hiDiffusionT1Ratio ?? 0,- hidiffusion_t2_ratio: settings.hiDiffusionT2Ratio ?? 0,- }- : {}),+ tile_height: multiDiffusion.tileSize,+ tile_overlap: multiDiffusion.tileOverlap,+ tile_width: multiDiffusion.tileSize,}: {}),- scheduler,- steps: settings.steps,- type: 'denoise_latents',+ type: multiDiffusion ? 'tiled_multi_diffusion_denoise_latents' : 'denoise_latents',});const vaeOverride = getCompatibleVae(settings, model);const vaeLoader = vaeOverride? addNode(graph, { id: 'vae_loader', type: 'vae_loader', vae_model: vaeOverride }): null;- const seamless =- settings.seamlessXAxis || settings.seamlessYAxis- ? addNode(graph, {- id: 'seamless',- seamless_x: settings.seamlessXAxis,- seamless_y: settings.seamlessYAxis,- type: 'seamless',- })- : null;+ const seamless = extras.seamless ? addNode(graph, { id: 'seamless', ...extras.seamless, type: 'seamless' }) : null;let unetSource: BackendInvocationContract = seamless ?? modelLoader;let clipSource: BackendInvocationContract = modelLoader;let clip2Source: BackendInvocationContract | undefined;@@ -486,10 +681,15 @@ const buildSDGraph = (addEdge(graph, clipSource, 'clip', negCond, 'clip');}- addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');- addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');- addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');- addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ if (posCondCollect && negCondCollect) {+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ } else {+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ }addEdge(graph, seed, 'value', noise, 'seed');// Seamless wrapping covers both the selected UNet and overridden VAE.@@ -500,26 +700,84 @@ const buildSDGraph = (addEdge(graph, unetSource, 'unet', denoise, 'unet');addEdge(graph, noise, 'noise', denoise, 'noise');- const ipAdapterCollector = addIPAdapterReferenceImages(graph, settings, model, denoise);- // Validation rejects PiD alongside a refiner, so the refiner always feeds the ordinary VAE decode.- const refiner = getActiveRefiner(settings, model);- const refinerDenoise = refiner- ? addSDXLRefinerStage({ denoise, graph, model, negativePrompt, positivePrompt, refiner, seamless, settings })- : null;+ const decoded = extras.afterDenoise?.(graph, { denoise, negativePrompt, positivePrompt, seamless }) ?? denoise;const vaeSource = seamless ?? vaeLoader ?? modelLoader;- const output = addDecodeOutput({- denoise: refinerDenoise ?? denoise,- graph,+ const output = addPipelineDecode(graph, input, extras.decode, {+ denoise: decoded,l2iProps: { fp32: settings.vaePrecision === 'fp32' },l2iType: 'l2i',- model,- outputIsIntermediate,positivePrompt,seed,- settings,vaeSource,});+ return {+ conditioning:+ posCondCollect && negCondCollect+ ? {+ fluxReduxCollector: null,+ ipAdapterCollector: null,+ negative: { collector: negCondCollect, node: negCond },+ positive: posCond,+ positiveCollector: posCondCollect,+ }+ : null,+ denoise,+ denoiseSize: input.denoiseSize,+ graph,+ latents: {+ encodeType: 'i2l',+ fp32: settings.vaePrecision === 'fp32',++ unet: { field: 'unet', node: unetSource },+ vae: { field: 'vae', node: vaeSource },+ },+ layoutPrompt: null,+ output,+ vaeModel: vaeOverride,+ };+};++const buildSDGraph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const supportsHiDiffusion = model.base === 'sd-1' || model.base === 'sdxl';+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ // Validation rejects PiD alongside a refiner, so the refiner always feeds the ordinary VAE decode.+ const refiner = getActiveRefiner(settings, model);+ let ipAdapterCollector = null as BackendInvocationContract | null;+ const pipeline = buildSdPipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, getDenoiseSize(settings, model)),+ {+ afterDenoise: (graph, { denoise, negativePrompt, positivePrompt, seamless }) => {+ ipAdapterCollector = addIPAdapterReferenceImages(graph, settings, model, denoise);++ return refiner+ ? addSDXLRefinerStage({ denoise, graph, model, negativePrompt, positivePrompt, refiner, seamless, settings })+ : denoise;+ },+ decode: getGenerateDecode(settings, model, outputIsIntermediate),+ denoiseFields: supportsHiDiffusion+ ? {+ hidiffusion: settings.hiDiffusionEnabled,+ hidiffusion_raunet: settings.hiDiffusionRauNetEnabled,+ hidiffusion_window_attn: settings.hiDiffusionWindowAttentionEnabled,+ ...(settings.hiDiffusionEnabled+ ? {+ hidiffusion_auto_ratios: settings.hiDiffusionT1Ratio === null && settings.hiDiffusionT2Ratio === null,+ hidiffusion_t1_ratio: settings.hiDiffusionT1Ratio ?? 0,+ hidiffusion_t2_ratio: settings.hiDiffusionT2Ratio ?? 0,+ }+ : {}),+ }+ : {},+ denoisingRange: getBaseDenoisingRange(settings, model, 0),+ seamless:+ settings.seamlessXAxis || settings.seamlessYAxis+ ? { seamless_x: settings.seamlessXAxis, seamless_y: settings.seamlessYAxis }+ : null,+ }+ );+ const { graph, output } = pipeline;+addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings, {...(supportsHiDiffusion? {@@ -538,97 +796,11 @@ const buildSDGraph = (addReferenceImageMetadata(graph, settings);return {- conditioning: {- fluxReduxCollector: null,- ipAdapterCollector,- negative: { collector: negCondCollect, node: negCond },- positive: posCond,- positiveCollector: posCondCollect,- },- denoise,- denoiseSize: { height: noise.height, width: noise.width },- graph,- latents: {- encodeType: 'i2l',- fp32: settings.vaePrecision === 'fp32',- unet: { field: 'unet', node: unetSource },- vae: { field: 'vae', node: vaeSource },- },- layoutPrompt: null,+ ...pipeline,+ conditioning: pipeline.conditioning && { ...pipeline.conditioning, ipAdapterCollector },};};-const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({- negativePrompt: addNode(graph, { id: 'negative_prompt', type: 'string' }),- positivePrompt: addNode(graph, { id: 'positive_prompt', type: 'string' }),- seed: addNode(graph, { id: 'seed', type: 'integer' }),-});--const addImageOutputNode = (graph: BackendGraphContract, type: string, outputIsIntermediate: boolean) =>- addNode(graph, { id: 'canvas_output', is_intermediate: outputIsIntermediate, type, use_cache: false });--/** Both decode branches return canvas_output for metadata attachment. */-const addDecodeOutput = ({- graph,- settings,- model,- l2iType,- l2iProps,- denoise,- positivePrompt,- seed,- vaeSource,- vaeField = 'vae',- outputIsIntermediate,-}: {- graph: BackendGraphContract;- settings: GenerateSettings;- model: MainModelConfig;- l2iType: string;- /** Extra props for the ordinary decode node; ignored by the PiD chain, which has its own. */- l2iProps?: Record<string, unknown>;- denoise: BackendInvocationContract;- positivePrompt: BackendInvocationContract;- seed: BackendInvocationContract;- vaeSource?: BackendInvocationContract;- vaeField?: string;- outputIsIntermediate: boolean;-}): BackendInvocationContract => {- if (shouldUsePidDecode(settings, model.base)) {- return addPidDecode({- base: model.base,- denoise,- graph,- outputIsIntermediate,- positivePrompt,- seed,- settings,- vaeField,- vaeSource,- });- }-- const output = addNode(graph, {- id: 'canvas_output',- is_intermediate: outputIsIntermediate,- type: l2iType,- use_cache: false,- ...l2iProps,- });-- if (vaeSource) {- addEdge(graph, vaeSource, vaeField, output, 'vae');- }- addEdge(graph, denoise, 'latents', output, 'latents');-- return output;-};--/** Native PiD denoises at one quarter of the requested target dimensions. */-const getDenoiseSize = (settings: GenerateSettings, model: MainModelConfig): { width: number; height: number } =>- // Use the model-native grid for divided dimensions, not the UI's PiD-scaled grid.- getPidDenoiseSize(settings, model.base, getGenerationDimensions(model).grid);-const buildSD3Graph = (settings: GenerateSettings,model: MainModelConfig,@@ -728,12 +900,8 @@ const getFluxDypeFields = (};};-const buildFluxGraph = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-): FamilyGraph => {+const buildFluxPipeline = (input: FamilyPipelineInput, extras: PipelineExtras = {}) => {+ const { model, settings } = input;const graph: BackendGraphContract = { edges: [], id: createId('flux_graph'), nodes: {} };const { positivePrompt, seed } = addPromptAndSeedNodes(graph);const hasBundledComponents = isSelfContainedSDNQFlux1Pipeline(model);@@ -759,29 +927,23 @@ const buildFluxGraph = (: modelLoader;const posCond = addNode(graph, { id: 'pos_cond', type: 'flux_text_encoder' });const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });- const denoiseSize = getDenoiseSize(settings, model);- const dype = getFluxDypeFields(settings);const denoise = addNode(graph, {denoising_end: 1,- denoising_start: 0,+ denoising_start: input.denoisingStart,guidance: settings.cfgScale,- height: denoiseSize.height,+ height: input.denoiseSize.height,id: 'denoise_latents',num_steps: settings.steps,scheduler,type: 'flux_denoise',- width: denoiseSize.width,- ...dype,+ width: input.denoiseSize.width,+ ...extras.denoiseFields,});- const output = addDecodeOutput({+ const output = addPipelineDecode(graph, input, extras.decode, {denoise,- graph,l2iType: 'flux_vae_decode',- model,- outputIsIntermediate,positivePrompt,seed,- settings,vaeSource: modelLoader,});@@ -793,46 +955,57 @@ const buildFluxGraph = (addEdge(graph, positivePrompt, 'value', posCond, 'prompt');addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');- addEdge(graph, graph.nodes.seed, 'value', denoise, 'seed');+ addEdge(graph, seed, 'value', denoise, 'seed');++ return {+ components: { clipEmbedModel, t5EncoderModel },+ conditioning: {+ fluxReduxCollector: null,+ ipAdapterCollector: null,+ negative: null,+ positive: posCond,+ positiveCollector: posCondCollect,+ },+ denoise,+ denoiseSize: input.denoiseSize,+ graph,+ latents: { encodeType: 'flux_vae_encode', vae: { field: 'vae', node: modelLoader } },+ layoutPrompt: null,+ output,+ vaeModel,+ };+};++const buildFluxGraph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const dype = getFluxDypeFields(settings);+ const pipeline = buildFluxPipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, getDenoiseSize(settings, model)),+ { decode: getGenerateDecode(settings, model, outputIsIntermediate), denoiseFields: dype }+ );+ const { components, denoise, graph, output, vaeModel } = pipeline;+// Generation validation has checked that the enabled Kontext references belong to this model.addFluxKontextReferenceImages(graph, settings, denoise, 'flux_kontext_reference_image');const ipAdapterCollector = addIPAdapterReferenceImages(graph, settings, model, denoise);const fluxReduxCollector = addFluxReduxReferenceImages(graph, settings, model, denoise);addMetadata(graph, output, settings, model, 'flux_txt2img', projectSettings, {- clip_embed_model: clipEmbedModel ?? undefined,+ clip_embed_model: components.clipEmbedModel ?? undefined,guidance: settings.cfgScale,...dype,// Recorded even when off, so recall can restore it over a preset the panel has since turned on.dype_preset: settings.fluxDypePreset,- scheduler,- t5_encoder: t5EncoderModel ?? undefined,+ scheduler: coerceSchedulerForGraph(model, settings.scheduler),+ t5_encoder: components.t5EncoderModel ?? undefined,vae: vaeModel ?? undefined,...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),});addReferenceImageMetadata(graph, settings);- return {- conditioning: {- fluxReduxCollector,- ipAdapterCollector,- negative: null,- positive: posCond,- positiveCollector: posCondCollect,- },- denoise,- denoiseSize: { height: denoise.height, width: denoise.width },- graph,- latents: { encodeType: 'flux_vae_encode', vae: { field: 'vae', node: modelLoader } },- layoutPrompt: null,- };+ return { ...pipeline, conditioning: { ...pipeline.conditioning, fluxReduxCollector, ipAdapterCollector } };};-const buildFlux2Graph = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-): FamilyGraph => {+const buildFlux2Pipeline = (input: FamilyPipelineInput, extras: PipelineExtras = {}) => {+ const { model, settings } = input;const isDev = model.variant === 'dev';const sourceModel = getFlux2ComponentSource(model, settings);const hasBundledComponents = isBundledFlux2Main(model) || sourceModel;@@ -854,7 +1027,7 @@ const buildFlux2Graph = (}const graph: BackendGraphContract = { edges: [], id: createId('flux2_graph'), nodes: {} };- const { positivePrompt } = addPromptAndSeedNodes(graph);+ const { positivePrompt, seed } = addPromptAndSeedNodes(graph);const scheduler = coerceSchedulerForGraph(model, settings.scheduler);const activeLoras = getActiveCompatibleLoras(settings, model);const modelLoader = addNode(@@ -891,28 +1064,24 @@ const buildFlux2Graph = (type: isDev ? 'flux2_dev_text_encoder' : 'flux2_klein_text_encoder',});const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });- const flux2DenoiseSize = getDenoiseSize(settings, model);+ // CFG stays off: the slider drives the guidance [dev] is distilled on, which Klein ignores.const denoise = addNode(graph, {cfg_scale: 1,denoising_end: 1,- denoising_start: 0,+ denoising_start: input.denoisingStart,guidance: settings.cfgScale,- height: flux2DenoiseSize.height,+ height: input.denoiseSize.height,id: 'denoise_latents',num_steps: settings.steps,scheduler,type: 'flux2_denoise',- width: flux2DenoiseSize.width,+ width: input.denoiseSize.width,});- const output = addDecodeOutput({+ const output = addPipelineDecode(graph, input, extras.decode, {denoise,- graph,l2iType: 'flux2_vae_decode',- model,- outputIsIntermediate,positivePrompt,- seed: graph.nodes.seed,- settings,+ seed,vaeSource: modelLoader,});@@ -925,23 +1094,15 @@ const buildFlux2Graph = ();addEdge(graph, modelLoader, 'max_seq_len', posCond, 'max_seq_len');addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ // The denoise normalizes the latents with this VAE's BatchNorm statistics.addEdge(graph, modelLoader, 'vae', denoise, 'vae');addEdge(graph, positivePrompt, 'value', posCond, 'prompt');addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');- addEdge(graph, graph.nodes.seed, 'value', denoise, 'seed');- addFluxKontextReferenceImages(graph, settings, denoise, 'flux2_reference_image');- addMetadata(graph, output, settings, model, 'flux2_txt2img', projectSettings, {- ...(isDev- ? { mistral_encoder: mistralEncoderModel ?? undefined }- : { qwen3_encoder: qwen3EncoderModel ?? undefined, qwen3_source: sourceModel }),- scheduler,- vae: vaeModel ?? undefined,- ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),- });- addReferenceImageMetadata(graph, settings);+ addEdge(graph, seed, 'value', denoise, 'seed');return {+ components: { mistralEncoderModel, qwen3EncoderModel, sourceModel },conditioning: {fluxReduxCollector: null,ipAdapterCollector: null,@@ -950,13 +1111,36 @@ const buildFlux2Graph = (positiveCollector: posCondCollect,},denoise,- denoiseSize: { height: denoise.height, width: denoise.width },+ denoiseSize: input.denoiseSize,graph,latents: { encodeType: FLUX2_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },layoutPrompt: null,+ output,+ vaeModel,};};+const buildFlux2Graph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const pipeline = buildFlux2Pipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, getDenoiseSize(settings, model)),+ { decode: getGenerateDecode(settings, model, outputIsIntermediate) }+ );+ const { components, denoise, graph, output, vaeModel } = pipeline;++ addFluxKontextReferenceImages(graph, settings, denoise, 'flux2_reference_image');+ addMetadata(graph, output, settings, model, 'flux2_txt2img', projectSettings, {+ ...(model.variant === 'dev'+ ? { mistral_encoder: components.mistralEncoderModel ?? undefined }+ : { qwen3_encoder: components.qwen3EncoderModel ?? undefined, qwen3_source: components.sourceModel }),+ scheduler: coerceSchedulerForGraph(model, settings.scheduler),+ vae: vaeModel ?? undefined,+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),+ });+ addReferenceImageMetadata(graph, settings);++ return pipeline;+};+const buildCogView4Graph = (settings: GenerateSettings,model: MainModelConfig,@@ -1078,12 +1262,13 @@ const buildErnieImageGraph = (};};-const buildQwenImageGraph = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-): FamilyGraph => {+interface QwenImagePipelineExtras extends PipelineExtras {+ /** Literal fields each text encoder gains: Generate's encoder quantization. */+ encoderFields?: Record<string, unknown>;+}++const buildQwenImagePipeline = (input: FamilyPipelineInput, extras: QwenImagePipelineExtras = {}) => {+ const { model, settings } = input;const sourceModel = getCompatibleComponentSource(settings, model);const hasBundledComponents = model.format === 'diffusers' || sourceModel;const vaeModel = getCompatibleVae(settings, model);@@ -1112,33 +1297,25 @@ const buildQwenImageGraph = ('qwen_vl_encoder',]): modelLoader;- // The encoders default to `none`, so only an actual quantization choice reaches the graph.- const encoderQuantization =- settings.qwenImageEncoderQuantization === 'none' ? {} : { quantization: settings.qwenImageEncoderQuantization };- const posCond = addNode(graph, { id: 'pos_cond', type: 'qwen_image_text_encoder', ...encoderQuantization });+ const posCond = addNode(graph, { id: 'pos_cond', type: 'qwen_image_text_encoder', ...extras.encoderFields });const negCond = useCfg- ? addNode(graph, { id: 'neg_cond', type: 'qwen_image_text_encoder', ...encoderQuantization })+ ? addNode(graph, { id: 'neg_cond', type: 'qwen_image_text_encoder', ...extras.encoderFields }): null;- const qwenDenoiseSize = getDenoiseSize(settings, model);const denoise = addNode(graph, {cfg_scale: settings.cfgScale,- height: qwenDenoiseSize.height,+ ...partialDenoisingRange(input),+ height: input.denoiseSize.height,id: 'denoise_latents',- // Null keeps the node's dynamic shift; a value fixes the schedule (3 for the Lightning LoRAs).- ...(settings.qwenImageShift === null ? {} : { shift: settings.qwenImageShift }),+ ...extras.denoiseFields,steps: settings.steps,type: 'qwen_image_denoise',- width: qwenDenoiseSize.width,+ width: input.denoiseSize.width,});- const output = addDecodeOutput({+ const output = addPipelineDecode(graph, input, extras.decode, {denoise,- graph,l2iType: 'qwen_image_l2i',- model,- outputIsIntermediate,positivePrompt,seed,- settings,vaeSource: modelLoader,});@@ -1156,6 +1333,36 @@ const buildQwenImageGraph = (}addEdge(graph, seed, 'value', denoise, 'seed');++ return {+ components: { sourceModel },+ conditioning: null,+ denoise,+ denoiseSize: input.denoiseSize,+ graph,+ latents: { encodeType: QWEN_IMAGE_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },+ layoutPrompt: null,+ output,+ positiveEncoder: posCond,+ vaeModel,+ };+};++const buildQwenImageGraph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const pipeline = buildQwenImagePipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, getDenoiseSize(settings, model)),+ {+ decode: getGenerateDecode(settings, model, outputIsIntermediate),+ // Null keeps the node's dynamic shift; a value fixes the schedule (3 for the Lightning LoRAs).+ denoiseFields: settings.qwenImageShift === null ? {} : { shift: settings.qwenImageShift },+ // The encoders default to `none`, so only an actual quantization choice reaches the graph.+ encoderFields:+ settings.qwenImageEncoderQuantization === 'none' ? {} : { quantization: settings.qwenImageEncoderQuantization },+ }+ );+ const { components, denoise, graph, output, positiveEncoder: posCond, vaeModel } = pipeline;+ // The VAE the graph decodes with, which encodes the edit reference too.+ const vae = pipeline.latents.vae;const qwenReferenceImages =model.variant === 'edit' ? getEnabledReferenceImages(settings.referenceImages, 'qwen_image_reference_image') : [];@@ -1195,12 +1402,12 @@ const buildQwenImageGraph = (});addEdge(graph, refImageNode, 'image', refI2l, 'image');- addEdge(graph, modelLoader, 'vae', refI2l, 'vae');+ addEdge(graph, vae.node, vae.field, refI2l, 'vae');addEdge(graph, refI2l, 'latents', denoise, 'reference_latents');}}addMetadata(graph, output, settings, model, 'qwen_image_txt2img', projectSettings, {- qwen_image_component_source: sourceModel,+ qwen_image_component_source: components.sourceModel,qwen_image_quantization: settings.qwenImageEncoderQuantization,qwen_image_qwen_vl_encoder: settings.qwenVLEncoderModel ?? undefined,qwen_image_shift: settings.qwenImageShift ?? 'auto',@@ -1210,22 +1417,16 @@ const buildQwenImageGraph = (});addReferenceImageMetadata(graph, settings);- return {- conditioning: null,- denoise,- denoiseSize: { height: denoise.height, width: denoise.width },- graph,- latents: { encodeType: QWEN_IMAGE_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },- layoutPrompt: null,- };+ return pipeline;};-const buildZImageGraph = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-): FamilyGraph => {+interface ConditionedPipelineExtras extends PipelineExtras {+ /** Passes the positive conditioning through Generate's enhancers before its collector. */+ positiveConditioning?: ConditioningHook;+}++const buildZImagePipeline = (input: FamilyPipelineInput, extras: ConditionedPipelineExtras = {}) => {+ const { model, settings } = input;const sourceModel = getDiffusersSource(settings, model);const qwen3EncoderModel =settings.qwen3EncoderModel && isZImageQwen3Encoder(settings.qwen3EncoderModel) ? settings.qwen3EncoderModel : null;@@ -1258,51 +1459,33 @@ const buildZImageGraph = (const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'z_image_text_encoder' }) : null;const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;- const zImageDenoiseSize = getDenoiseSize(settings, model);const denoise = addNode(graph, {denoising_end: 1,- denoising_start: 0,+ denoising_start: input.denoisingStart,guidance_scale: settings.cfgScale,- height: zImageDenoiseSize.height,+ height: input.denoiseSize.height,id: 'denoise_latents',scheduler,- // Null keeps the node's size-derived shift.- ...(settings.zImageShift === null ? {} : { shift: settings.zImageShift }),+ ...extras.denoiseFields,steps: settings.steps,type: 'z_image_denoise',- width: zImageDenoiseSize.width,+ width: input.denoiseSize.width,});- const output = addDecodeOutput({+ const output = addPipelineDecode(graph, input, extras.decode, {denoise,- graph,l2iType: 'z_image_l2i',- model,- outputIsIntermediate,positivePrompt,seed,- settings,vaeSource: modelLoader,});addEdge(graph, loraSource, 'transformer', denoise, 'transformer');addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');+ // The denoise encodes a control image itself, with this VAE.addEdge(graph, modelLoader, 'vae', denoise, 'vae');addEdge(graph, positivePrompt, 'value', posCond, 'prompt');- // Zero strength would be a no-op node, so it is left out like Krea-2's enhancer.- if (settings.zImageSeedVarianceEnabled && settings.zImageSeedVarianceStrength > 0) {- const seedVariance = addNode(graph, {- id: 'seed_variance_enhancer',- randomize_percent: settings.zImageSeedVarianceRandomizePercent,- strength: settings.zImageSeedVarianceStrength,- type: 'z_image_seed_variance_enhancer',- });-- addEdge(graph, seed, 'value', seedVariance, 'seed');- addEdge(graph, posCond, 'conditioning', seedVariance, 'conditioning');- addEdge(graph, seedVariance, 'conditioning', posCondCollect, 'item');- } else {- addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');- }+ const positiveConditioning = extras.positiveConditioning?.(graph, posCond, seed) ?? posCond;+ addEdge(graph, positiveConditioning, 'conditioning', posCondCollect, 'item');addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');if (negCond && negCondCollect) {@@ -1313,19 +1496,9 @@ const buildZImageGraph = (}addEdge(graph, seed, 'value', denoise, 'seed');- addMetadata(graph, output, settings, model, 'z_image_txt2img', projectSettings, {- qwen3_encoder: qwen3EncoderModel ?? undefined,- qwen3_source: sourceModel,- scheduler,- vae: vaeModel ?? undefined,- z_image_seed_variance_enabled: settings.zImageSeedVarianceEnabled,- z_image_seed_variance_randomize_percent: settings.zImageSeedVarianceRandomizePercent,- z_image_seed_variance_strength: settings.zImageSeedVarianceStrength,- z_image_shift: settings.zImageShift ?? 'auto',- ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),- });return {+ components: { qwen3EncoderModel, sourceModel },conditioning: {fluxReduxCollector: null,ipAdapterCollector: null,@@ -1334,19 +1507,60 @@ const buildZImageGraph = (positiveCollector: posCondCollect,},denoise,- denoiseSize: { height: denoise.height, width: denoise.width },+ denoiseSize: input.denoiseSize,graph,latents: { encodeType: 'z_image_i2l', vae: { field: 'vae', node: modelLoader } },layoutPrompt: null,+ output,+ vaeModel,};};-const buildAnimaGraph = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-): FamilyGraph => {+const buildZImageGraph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const pipeline = buildZImagePipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, getDenoiseSize(settings, model)),+ {+ decode: getGenerateDecode(settings, model, outputIsIntermediate),+ // Null keeps the node's size-derived shift.+ denoiseFields: settings.zImageShift === null ? {} : { shift: settings.zImageShift },+ // Zero strength would be a no-op node, so it is left out like Krea-2's enhancer.+ positiveConditioning:+ settings.zImageSeedVarianceEnabled && settings.zImageSeedVarianceStrength > 0+ ? (graph, conditioning, seed) => {+ const seedVariance = addNode(graph, {+ id: 'seed_variance_enhancer',+ randomize_percent: settings.zImageSeedVarianceRandomizePercent,+ strength: settings.zImageSeedVarianceStrength,+ type: 'z_image_seed_variance_enhancer',+ });++ addEdge(graph, seed, 'value', seedVariance, 'seed');+ addEdge(graph, conditioning, 'conditioning', seedVariance, 'conditioning');++ return seedVariance;+ }+ : undefined,+ }+ );+ const { components, graph, output, vaeModel } = pipeline;++ addMetadata(graph, output, settings, model, 'z_image_txt2img', projectSettings, {+ qwen3_encoder: components.qwen3EncoderModel ?? undefined,+ qwen3_source: components.sourceModel,+ scheduler: coerceSchedulerForGraph(model, settings.scheduler),+ vae: vaeModel ?? undefined,+ z_image_seed_variance_enabled: settings.zImageSeedVarianceEnabled,+ z_image_seed_variance_randomize_percent: settings.zImageSeedVarianceRandomizePercent,+ z_image_seed_variance_strength: settings.zImageSeedVarianceStrength,+ z_image_shift: settings.zImageShift ?? 'auto',+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),+ });++ return pipeline;+};++const buildAnimaPipeline = (input: FamilyPipelineInput) => {+ const { model, settings } = input;const vaeModel = requireComponent(getCompatibleVae(settings, model), 'Anima VAE');const qwen3EncoderModel = requireComponent(settings.qwen3EncoderModel && isAnimaQwen3Encoder(settings.qwen3EncoderModel) ? settings.qwen3EncoderModel : null,@@ -1381,16 +1595,17 @@ const buildAnimaGraph = (const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;const denoise = addNode(graph, {denoising_end: 1,- denoising_start: 0,+ denoising_start: input.denoisingStart,guidance_scale: settings.cfgScale,- height: settings.height,+ height: input.denoiseSize.height,id: 'denoise_latents',scheduler,steps: settings.steps,type: 'anima_denoise',- width: settings.width,+ width: input.denoiseSize.width,});- const output = addImageOutputNode(graph, 'anima_l2i', outputIsIntermediate);+ // `anima_l2i` has no tiling switch: it tiles on its own once an untiled decode would take most of the card.+ const output = addPipelineOutputNode(graph, input, 'anima_l2i', { tiles: false });addEdge(graph, loraSource, 'transformer', denoise, 'transformer');addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');@@ -1415,31 +1630,47 @@ const buildAnimaGraph = (addEdge(graph, seed, 'value', denoise, 'seed');addEdge(graph, denoise, 'latents', output, 'latents');- const ipAdapterCollector = addIPAdapterReferenceImages(graph, settings, model, denoise);- addMetadata(graph, output, settings, model, 'anima_txt2img', projectSettings, {- qwen3_encoder: qwen3EncoderModel,- ...(qwen35EncoderModel ? { qwen3_5_encoder: qwen35EncoderModel } : {}),- scheduler,- vae: vaeModel,- });- addReferenceImageMetadata(graph, settings);return {+ components: { qwen35EncoderModel, qwen3EncoderModel },conditioning: {fluxReduxCollector: null,- ipAdapterCollector,+ ipAdapterCollector: null,negative: negCond && negCondCollect ? { collector: negCondCollect, node: negCond } : null,positive: posCond,positiveCollector: posCondCollect,},denoise,- denoiseSize: { height: denoise.height, width: denoise.width },+ denoiseSize: input.denoiseSize,graph,latents: { encodeType: 'anima_i2l', vae: { field: 'vae', node: modelLoader } },layoutPrompt: null,+ output,+ vaeModel,};};+const buildAnimaGraph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const pipeline = buildAnimaPipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, {+ height: settings.height,+ width: settings.width,+ })+ );+ const { components, denoise, graph, output, vaeModel } = pipeline;+ const ipAdapterCollector = addIPAdapterReferenceImages(graph, settings, model, denoise);++ addMetadata(graph, output, settings, model, 'anima_txt2img', projectSettings, {+ qwen3_encoder: components.qwen3EncoderModel,+ ...(components.qwen35EncoderModel ? { qwen3_5_encoder: components.qwen35EncoderModel } : {}),+ scheduler: coerceSchedulerForGraph(model, settings.scheduler),+ vae: vaeModel,+ });+ addReferenceImageMetadata(graph, settings);++ return { ...pipeline, conditioning: { ...pipeline.conditioning, ipAdapterCollector } };+};+/** Each reference reaches encoder and denoise in the same order; chained collects keep it, a single one would not. */const addKrea2EditReferences = (graph: BackendGraphContract,@@ -1490,19 +1721,19 @@ const addKrea2EditReferences = (}};-const buildKrea2Graph = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-): FamilyGraph => {+interface Krea2PipelineExtras extends ConditionedPipelineExtras {+ /** The GGUF encoder's vision tower for edit references; the loader refuses one beside any other encoder. */+ visionTower?: ComponentModelConfig | null;+}++const buildKrea2Pipeline = (input: FamilyPipelineInput, extras: Krea2PipelineExtras = {}) => {+ const { model, settings } = input;const isDiffusers = model.format === 'diffusers';const vaeModel = getCompatibleVae(settings, model);const qwen3VlEncoderModel = getCompatibleComponent(settings.qwen3VLEncoderModel, isQwen3Vl4bEncoder);- // The loader refuses a tower beside any other encoder, so a stale pick is never sent.const qwen3VlVisionTowerModel =qwen3VlEncoderModel && isGgufQwen3Vl4bEncoder(qwen3VlEncoderModel)- ? getCompatibleComponent(settings.qwen3VLVisionTowerModel, isQwen3Vl4bVisionTower)+ ? getCompatibleComponent(extras.visionTower ?? null, isQwen3Vl4bVisionTower): null;if (!isDiffusers) {@@ -1533,30 +1764,26 @@ const buildKrea2Graph = (const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'krea2_text_encoder' }) : null;const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;+ // `krea2_denoise` picks its own shift, fixed for Turbo and by size for Raw, so the graph sends none.const denoise = addNode(graph, {cfg_scale: settings.cfgScale,- height: settings.height,+ ...partialDenoisingRange(input),+ height: input.denoiseSize.height,id: 'denoise_latents',steps: settings.steps,type: 'krea2_denoise',- width: settings.width,+ width: input.denoiseSize.width,});// Krea-2 decodes with the Qwen-Image VAE, so it reuses that family's latents-to-image node.- const output = addImageOutputNode(graph, 'qwen_image_l2i', outputIsIntermediate);+ const output = addPipelineOutputNode(graph, input, 'qwen_image_l2i', { tiles: true });addEdge(graph, loraSource, 'transformer', denoise, 'transformer');addEdge(graph, loraSource, 'qwen3_vl_encoder', posCond, 'qwen3_vl_encoder');addEdge(graph, modelLoader, 'vae', output, 'vae');addEdge(graph, positivePrompt, 'value', posCond, 'prompt');- const positiveConditioningSource = addKrea2ConditioningEnhancers({- conditioning: posCond,- graph,- idPrefix: 'krea2',- seed,- settings,- });- addEdge(graph, positiveConditioningSource, 'conditioning', posCondCollect, 'item');+ const positiveConditioning = extras.positiveConditioning?.(graph, posCond, seed) ?? posCond;+ addEdge(graph, positiveConditioning, 'conditioning', posCondCollect, 'item');addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');if (negCond && negCondCollect) {@@ -1568,6 +1795,41 @@ const buildKrea2Graph = (addEdge(graph, seed, 'value', denoise, 'seed');addEdge(graph, denoise, 'latents', output, 'latents');++ return {+ components: { loadsLoras: activeLoras.length > 0, qwen3VlEncoderModel, qwen3VlVisionTowerModel },+ conditioning: {+ fluxReduxCollector: null,+ ipAdapterCollector: null,+ negative: negCond && negCondCollect ? { collector: negCondCollect, node: negCond } : null,+ positive: posCond,+ positiveCollector: posCondCollect,+ },+ denoise,+ denoiseSize: input.denoiseSize,+ graph,+ latents: { encodeType: QWEN_IMAGE_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },+ layoutPrompt: null,+ output,+ vaeModel,+ };+};++const buildKrea2Graph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const pipeline = buildKrea2Pipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, {+ height: settings.height,+ width: settings.width,+ }),+ {+ positiveConditioning: (graph, conditioning, seed) =>+ addKrea2ConditioningEnhancers({ conditioning, graph, idPrefix: 'krea2', seed, settings }),+ visionTower: settings.qwen3VLVisionTowerModel,+ }+ );+ const { components, conditioning, denoise, graph, output, vaeModel } = pipeline;+ // The VAE the graph decodes with, which encodes the references too.+ const vaeSource = pipeline.latents.vae.node;// Validation keeps edit and style references apart; the denoise refuses the two together.const editReferenceImages = getEnabledReferenceImages(settings.referenceImages, 'krea2_edit_reference_image').flatMap(({ config }) => (config.image ? [toImageField(config.image)] : [])@@ -1582,15 +1844,15 @@ const buildKrea2Graph = (// Only an edit LoRA trained with `kv_cache` reads the cache; without one the stored switch is kept but not sent.const referenceKvCache =- editReferenceImages.length > 0 && activeLoras.length > 0 ? settings.krea2ReferenceKvCache : undefined;+ editReferenceImages.length > 0 && components.loadsLoras ? settings.krea2ReferenceKvCache : undefined;if (editReferenceImages.length > 0) {addKrea2EditReferences(graph, {denoise,- prompts: negCond ? [posCond, negCond] : [posCond],+ prompts: conditioning.negative ? [conditioning.positive, conditioning.negative.node] : [conditioning.positive],referenceImages: editReferenceImages,referenceKvCache,- vaeSource: modelLoader,+ vaeSource,});} else if (styleReference?.config.image) {const styleReferenceNode = addNode(graph, {@@ -1603,7 +1865,7 @@ const buildKrea2Graph = (width: settings.width,});- addEdge(graph, modelLoader, 'vae', styleReferenceNode, 'vae');+ addEdge(graph, vaeSource, 'vae', styleReferenceNode, 'vae');addEdge(graph, styleReferenceNode, 'style_reference', denoise, 'style_reference');}addMetadata(graph, output, settings, model, 'krea2_txt2img', projectSettings, {@@ -1615,26 +1877,13 @@ const buildKrea2Graph = (krea2_seed_variance_strength: settings.krea2SeedVarianceStrength,...(styleReference ? { krea2_style_strength: styleReference.config.styleStrength } : {}),...(referenceKvCache === undefined ? {} : { krea2_reference_kv_cache: referenceKvCache }),- qwen3_vl_encoder: qwen3VlEncoderModel ?? undefined,- qwen3_vl_vision_tower: qwen3VlVisionTowerModel ?? undefined,+ qwen3_vl_encoder: components.qwen3VlEncoderModel ?? undefined,+ qwen3_vl_vision_tower: components.qwen3VlVisionTowerModel ?? undefined,vae: vaeModel ?? undefined,});addReferenceImageMetadata(graph, settings);- return {- conditioning: {- fluxReduxCollector: null,- ipAdapterCollector: null,- negative: negCond && negCondCollect ? { collector: negCondCollect, node: negCond } : null,- positive: posCond,- positiveCollector: posCondCollect,- },- denoise,- denoiseSize: { height: denoise.height, width: denoise.width },- graph,- latents: { encodeType: QWEN_IMAGE_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },- layoutPrompt: null,- };+ return pipeline;};const buildQwenImage21Graph = (@@ -1773,12 +2022,16 @@ const addQwenImage21ReferenceImages = (addEdge(graph, latentsCollect, 'collection', nodes.denoise, 'reference_latents');};-const buildMossImageGraph = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-): FamilyGraph => {+interface MossImagePipelineExtras extends PipelineExtras {+ /** The node whose text the positive encoder reads instead of the prompt: Generate's layout prompt. */+ positivePromptSource?: (+ graph: BackendGraphContract,+ positivePrompt: BackendInvocationContract+ ) => BackendInvocationContract;+}++const buildMossImagePipeline = (input: FamilyPipelineInput, extras: MossImagePipelineExtras = {}) => {+ const { model, settings } = input;// The filter drops a stale Qwen3.5 4B pick left over from Anima-3.8B, which shares the setting.const isDiffusers = model.format === 'diffusers';const vaeModel = getCompatibleVae(settings, model);@@ -1809,28 +2062,23 @@ const buildMossImageGraph = (: modelLoader;const posCond = addNode(graph, { id: 'pos_cond', type: 'moss_image_text_encoder' });const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'moss_image_text_encoder' }) : null;- const denoiseSize = getDenoiseSize(settings, model);const denoise = addNode(graph, {cfg_scale: settings.cfgScale,denoising_end: 1,- denoising_start: 0,- height: denoiseSize.height,+ denoising_start: input.denoisingStart,+ height: input.denoiseSize.height,id: 'denoise_latents',steps: settings.steps,type: 'moss_image_denoise',- uncond_skip_layers: [...settings.mossImageUncondSkipLayers],- width: denoiseSize.width,+ ...extras.denoiseFields,+ width: input.denoiseSize.width,});// MOSS-Image denoises into the FLUX.2 VAE's raw latent layout, so it decodes, and PiD-decodes, as FLUX.2 does.- const output = addDecodeOutput({+ const output = addPipelineDecode(graph, input, extras.decode, {denoise,- graph,l2iType: 'flux2_vae_decode',- model,- outputIsIntermediate,positivePrompt,seed,- settings,vaeSource: modelLoader,});@@ -1838,16 +2086,8 @@ const buildMossImageGraph = (// The denoise node reads the VAE's BatchNorm statistics, which define the latent space it works in.addEdge(graph, modelLoader, 'vae', denoise, 'vae');addEdge(graph, modelLoader, 'qwen3_5_encoder', posCond, 'qwen3_5_encoder');- // Compiles a layout draft and canvas `regions` at run time; batch prompt variation still flows via `positive_prompt`.- const layoutPrompt = addNode(graph, {- height: denoiseSize.height,- id: 'layout_prompt',- regions: [],- type: 'moss_image_layout_prompt',- width: denoiseSize.width,- });- addEdge(graph, positivePrompt, 'value', layoutPrompt, 'prompt');- addEdge(graph, layoutPrompt, 'value', posCond, 'prompt');+ const promptSource = extras.positivePromptSource?.(graph, positivePrompt) ?? positivePrompt;+ addEdge(graph, promptSource, 'value', posCond, 'prompt');addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');if (negCond) {@@ -1857,25 +2097,57 @@ const buildMossImageGraph = (}addEdge(graph, seed, 'value', denoise, 'seed');++ return {+ components: { qwen35EncoderModel },+ conditioning: null,+ denoise,+ denoiseSize: input.denoiseSize,+ graph,+ latents: { encodeType: FLUX2_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },+ layoutPrompt: null as BackendInvocationContract | null,+ output,+ vaeModel,+ };+};++const buildMossImageGraph: GenerateGraphBuilder = (settings, model, outputIsIntermediate, projectSettings) => {+ const denoiseSize = getDenoiseSize(settings, model);+ let layoutPrompt = null as BackendInvocationContract | null;+ const pipeline = buildMossImagePipeline(+ toGeneratePipelineInput(settings, model, outputIsIntermediate, projectSettings, denoiseSize),+ {+ decode: getGenerateDecode(settings, model, outputIsIntermediate),+ denoiseFields: { uncond_skip_layers: [...settings.mossImageUncondSkipLayers] },+ // Compiles a layout draft and canvas `regions` at run time; batch prompt variation flows via `positive_prompt`.+ positivePromptSource: (graph, positivePrompt) => {+ layoutPrompt = addNode(graph, {+ height: denoiseSize.height,+ id: 'layout_prompt',+ regions: [],+ type: 'moss_image_layout_prompt',+ width: denoiseSize.width,+ });+ addEdge(graph, positivePrompt, 'value', layoutPrompt, 'prompt');++ return layoutPrompt;+ },+ }+ );+ const { components, graph, output, vaeModel } = pipeline;+addMetadata(graph, output, settings, model, 'moss_image_txt2img', projectSettings, {moss_image_uncond_skip_layers: [...settings.mossImageUncondSkipLayers],- qwen3_5_encoder: qwen35EncoderModel ?? undefined,+ qwen3_5_encoder: components.qwen35EncoderModel ?? undefined,vae: vaeModel ?? undefined,...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),});const metadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');- if (metadata) {+ if (metadata && layoutPrompt) {addEdge(graph, layoutPrompt, 'value', metadata, 'moss_image_layout_prompt');}- return {- conditioning: null,- denoise,- denoiseSize: { height: denoise.height, width: denoise.width },- graph,- latents: { encodeType: FLUX2_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },- layoutPrompt,- };+ return { ...pipeline, layoutPrompt };};const buildFlux3Graph = (@@ -2233,13 +2505,6 @@ export const buildExternalGraph = (return graph;};-type GenerateGraphBuilder = (- settings: GenerateSettings,- model: MainModelConfig,- outputIsIntermediate: boolean,- projectSettings: GenerationProjectSettings-) => FamilyGraph;-export const GRAPH_BUILDERS = {'sd-1': buildSDGraph,'sd-2': buildSDGraph,@@ -2260,6 +2525,32 @@ export const GRAPH_BUILDERS = {wan: buildWanGraph,} satisfies Record<SupportedGenerateBase, GenerateGraphBuilder>;+/** The families Upscale's detail pass can run: Generate's pipeline builders, called without Generate's extras. */+const IMAGE_TO_IMAGE_PIPELINES = {+ anima: buildAnimaPipeline,+ flux: buildFluxPipeline,+ flux2: buildFlux2Pipeline,+ 'krea-2': buildKrea2Pipeline,+ 'moss-image': buildMossImagePipeline,+ 'qwen-image': buildQwenImagePipeline,+ 'sd-1': buildSdPipeline,+ sdxl: buildSdPipeline,+ 'z-image': buildZImagePipeline,+} satisfies Partial<Record<SupportedGenerateBase, (input: FamilyPipelineInput) => FamilyPipeline>>;++export type ImageToImagePipelineBase = keyof typeof IMAGE_TO_IMAGE_PIPELINES;++/** A family's image pipeline as another feature asks for it; throws for a family that has none. */+export const buildImageToImagePipeline = (input: FamilyPipelineInput): FamilyPipeline => {+ const { base } = input.model;++ if (!Object.hasOwn(IMAGE_TO_IMAGE_PIPELINES, base)) {+ throw new Error(`${input.model.name} has no image-to-image pipeline.`);+ }++ return IMAGE_TO_IMAGE_PIPELINES[base as ImageToImagePipelineBase](input);+};+/** The builder for a base, or null. Own keys only: a base from the API must not reach `Object.prototype` members. */export const getFamilyGraphBuilder = (base: string): GenerateGraphBuilder | null =>Object.hasOwn(GRAPH_BUILDERS, base) ? GRAPH_BUILDERS[base as SupportedGenerateBase] : null;diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.tsindex 8a9cf186c3..a55d3f8b61 100644--- a/invokeai/frontend/webv2/src/features/generation/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts@@ -3,10 +3,13 @@ export {addLoraCollectionLoader,addTransformerLoraCollectionLoader,addWanLoraLoaders,+ buildImageToImagePipeline,compileGenerateGraph,FLUX_REDUX_INFLUENCE,+ type ImageToImagePipelineBase,resolveGenerateSeed,} from './core/graph';+export type { FamilyPipelineSettings } from './core/familyGraph';export {addEdge,addNode,diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 04b832eb10..52a9790cab 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -55,6 +55,8 @@ export {createReferenceImageId,getCompatibleReferenceImages,getDefaultGenerateSettings,+ getDenoisingStartClipping,+ type StepClipping,addReferenceImages,getDefaultComponentSlotPolicies,isDefaultVaeLoaded,@@ -68,6 +70,7 @@ export {getGenerateInvocationIssues,getGenerationModelAvailabilityReasons,getGenerationUiPolicy,+ getNegativePromptUsage,getPromptHistoryRecallPatch,getReferenceImageRoom,getSchedulerOptions,@@ -126,6 +129,7 @@ export {isFlux2Qwen3EncoderForModel,isMossImageQwen35Encoder,isQwen3Vl4bEncoder,+ isSelfContainedSDNQFlux1Pipeline,isVaeAcceptedByBase,isVaeCompatibleWithGenerateModel,isZImageQwen3Encoder,diff --git a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.jsonindex d9648dcced..16b5f9aa19 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json@@ -68,6 +68,7 @@"flux_model_loader max_seq_len flux_text_encoder t5_max_seq_len","flux_model_loader t5_encoder flux_lora_collection_loader t5_encoder","flux_model_loader transformer flux_lora_collection_loader transformer",+ "flux_model_loader vae flux_denoise controlnet_vae","flux_model_loader vae flux_vae_decode vae","flux_model_loader vae flux_vae_encode vae","flux_text_encoder conditioning collect item",@@ -75,8 +76,10 @@"i2l latents tiled_multi_diffusion_denoise_latents latents","img_resize height core_metadata height","img_resize image anima_i2l image",+ "img_resize image controlnet image","img_resize image flux2_vae_encode image","img_resize image flux_vae_encode image",+ "img_resize image i2l image","img_resize image qwen_image_i2l image","img_resize image z_image_control image","img_resize image z_image_i2l image",@@ -122,6 +125,7 @@"qwen_image_lora_collection_loader transformer qwen_image_denoise transformer","qwen_image_model_loader qwen_vl_encoder qwen_image_lora_collection_loader qwen_vl_encoder","qwen_image_model_loader transformer qwen_image_lora_collection_loader transformer",+ "qwen_image_model_loader vae qwen_image_denoise vae","qwen_image_model_loader vae qwen_image_i2l vae","qwen_image_model_loader vae qwen_image_l2i vae","qwen_image_text_encoder conditioning qwen_image_denoise negative_conditioning",@@ -151,13 +155,7 @@"string value sdxl_compel_prompt style","string value z_image_text_encoder prompt","tiled_multi_diffusion_denoise_latents latents l2i latents",- "unsharp_mask height core_metadata height",- "unsharp_mask height noise height",- "unsharp_mask image controlnet image",- "unsharp_mask image i2l image","unsharp_mask image img_resize image",- "unsharp_mask width core_metadata width",- "unsharp_mask width noise width","z_image_control control z_image_denoise control","z_image_denoise latents z_image_l2i latents","z_image_i2l latents z_image_denoise latents",@@ -180,6 +178,7 @@"controlnet","core_metadata","i2l",+ "img_resize","integer","l2i","lora_collection_loader",@@ -198,6 +197,7 @@"controlnet","core_metadata","i2l",+ "img_resize","integer","l2i","lora_selector",@@ -644,6 +644,7 @@},"flux_denoise": {"inputs": [+ "controlnet_vae","latents","positive_text_conditioning","seed",@@ -798,6 +799,9 @@"vae"],"literalInputs": {+ "cfg_scale": [+ 1+ ],"denoising_end": [1],@@ -1328,11 +1332,12 @@},"noise": {"inputs": [- "height",- "seed",- "width"+ "seed"],"literalInputs": {+ "height": [+ 400+ ],"is_intermediate": [true],@@ -1341,6 +1346,9 @@],"use_cpu": [true+ ],+ "width": [+ 808]},"outputs": [@@ -1353,7 +1361,8 @@"negative_conditioning","positive_conditioning","seed",- "transformer"+ "transformer",+ "vae"],"literalInputs": {"cfg_scale": [@@ -1609,6 +1618,9 @@"unet"],"literalInputs": {+ "cfg_rescale_multiplier": [+ 0+ ],"cfg_scale": [2],@@ -1663,9 +1675,7 @@]},"outputs": [- "height",- "image",- "width"+ "image"]},"z_image_control": {diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.tsindex fd42858725..f1d9886e46 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts@@ -14,6 +14,7 @@ import {getZImageTileControlValues,} from './graph';import { createDefaultUpscaleWidgetValues, normalizeUpscaleWidgetValues } from './settings';+import { CASES, valuesForCase } from './upscaleGraphCoverage.testing';const model = (key: string, type: string, base: string, name = key): ModelConfig => ({base,@@ -76,48 +77,53 @@ describe('compileUpscaleGraph', () => {});});- it.each(['sd-1', 'sdxl'] as const)('compiles the legacy %s topology with fixed batch ids', (base) => {- const compiled = compileUpscaleGraph(createValues(base), 'gallery', { useCpuNoise: true });- const { edges, nodes } = compiled.backendGraph;+ it.each(['sd-1', 'sdxl'] as const)(+ 'runs the %s pass in tiles behind the Spandrel prefix, anchored by the ControlNet pair, with fixed batch ids',+ (base) => {+ const compiled = compileUpscaleGraph(createValues(base), 'gallery', { useCpuNoise: true });+ const { edges, nodes } = compiled.backendGraph;- expect(compiled.positivePromptNodeId).toBe('positive_prompt');- expect(compiled.negativePromptNodeId).toBe('negative_prompt');- expect(compiled.seedNodeId).toBe('seed');- expect(compiled.outputNodeId).toBe('upscale_output');- expect(nodes.spandrel_autoscale).toMatchObject({- fit_to_multiple_of_8: true,- image: { image_name: 'input.png' },- scale: 4,- type: 'spandrel_image_to_image_autoscale',- });- expect(nodes.tiled_multidiffusion_denoise_latents).toMatchObject({- cfg_scale: 2,- scheduler: 'kdpm_2',- steps: 30,- tile_height: 1024,- tile_overlap: 128,- tile_width: 1024,- });- expect(nodes.tiled_multidiffusion_denoise_latents?.denoising_start).toBeCloseTo(0.499);- expect(nodes.upscale_output).toMatchObject({ is_intermediate: false, tiled: true, type: 'l2i' });- expect(nodes.noise?.use_cpu).toBe(true);- expect(nodes.controlnet_1).toMatchObject({ control_weight: 0.625, end_step_percent: 0.55 });- expect(nodes.controlnet_2).toMatchObject({ begin_step_percent: 0.55, control_weight: 0.21375 });- expect(nodes.core_metadata).toMatchObject({- creativity: 0,- structure: 0,- tile_overlap: 128,- tile_size: 1024,- upscale_scale: 4,- });- expect(- hasEdge(edges, 'controlnet_collector', 'collection', 'tiled_multidiffusion_denoise_latents', 'control')- ).toBe(true);- expect(hasEdge(edges, 'positive_prompt', 'value', 'pos_cond', 'prompt')).toBe(true);- expect(hasEdge(edges, 'vae_loader', 'vae', 'upscale_output', 'vae')).toBe(true);- expect(Object.values(nodes).some((node) => node.type.includes('lora_collection_loader'))).toBe(true);- expect(base === 'sdxl' ? nodes.clip_skip : nodes.clip_skip?.type).toBe(base === 'sdxl' ? undefined : 'clip_skip');- });+ expect(compiled.positivePromptNodeId).toBe('positive_prompt');+ expect(compiled.negativePromptNodeId).toBe('negative_prompt');+ expect(compiled.seedNodeId).toBe('seed');+ expect(compiled.outputNodeId).toBe('upscale_output');+ expect(nodes.spandrel_autoscale).toMatchObject({+ fit_to_multiple_of_8: true,+ image: { image_name: 'input.png' },+ scale: 4,+ type: 'spandrel_image_to_image_autoscale',+ });+ expect(nodes.unsharp_2).toMatchObject({ radius: 2, strength: 60, type: 'unsharp_mask' });+ expect(hasEdge(edges, 'spandrel_autoscale', 'image', 'unsharp_2', 'image')).toBe(true);+ expect(hasEdge(edges, 'unsharp_2', 'image', 'fit_to_grid', 'image')).toBe(true);+ expect(nodes.denoise_latents).toMatchObject({+ cfg_scale: 2,+ scheduler: 'kdpm_2',+ steps: 30,+ tile_height: 1024,+ tile_overlap: 128,+ tile_width: 1024,+ type: 'tiled_multi_diffusion_denoise_latents',+ });+ expect(nodes.denoise_latents?.denoising_start).toBeCloseTo(0.499);+ expect(nodes.i2l).toMatchObject({ fp32: true, tile_size: 1024, tiled: true, type: 'i2l' });+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);+ expect(hasEdge(edges, 'i2l', 'latents', 'denoise_latents', 'latents')).toBe(true);+ expect(nodes.upscale_output).toMatchObject({ is_intermediate: false, tile_size: 1024, tiled: true, type: 'l2i' });+ expect(nodes.noise?.use_cpu).toBe(true);+ expect(nodes.controlnet_1).toMatchObject({ control_weight: 0.625, end_step_percent: 0.55 });+ expect(nodes.controlnet_2).toMatchObject({ begin_step_percent: 0.55, control_weight: 0.21375 });+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'controlnet_1', 'image')).toBe(true);+ expect(hasEdge(edges, 'controlnet_collector', 'collection', 'denoise_latents', 'control')).toBe(true);+ expect(nodes.core_metadata).toMatchObject({+ creativity: 0,+ structure: 0,+ tile_overlap: 128,+ tile_size: 1024,+ upscale_scale: 4,+ });+ }+ );it('marks only Canvas-destination output intermediate', () => {expect(@@ -137,7 +143,7 @@ describe('compileUpscaleGraph', () => {const nodes = compileUpscaleGraph(values, 'gallery', { useCpuNoise: false }, 'cuda', { prompt: 'source' }).backendGraph.nodes;- expect(nodes.tiled_multidiffusion_denoise_latents).toBeDefined();+ expect(nodes.denoise_latents?.type).toBe('tiled_multi_diffusion_denoise_latents');expect(nodes.core_metadata).toMatchObject({ creativity: 0, type: 'core_metadata' });expect(nodes.core_metadata).not.toHaveProperty('prompt');});@@ -290,76 +296,6 @@ const createFluxValues = (options: { withEncoders?: boolean } = {}) => {};};-describe('compileUpscaleGraph for FLUX.1', () => {- it('drives the second pass with flux nodes and tiles both VAE ends', () => {- const { edges, nodes } = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.model_loader).toMatchObject({ type: 'flux_model_loader' });- expect(nodes.model_loader?.t5_encoder_model).toMatchObject({ key: 't5' });- expect(nodes.model_loader?.clip_embed_model).toMatchObject({ key: 'clip' });- expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'flux_vae_encode' });- expect(nodes.upscale_output).toMatchObject({ tile_size: 1024, tiled: true, type: 'flux_vae_decode' });- expect(nodes.denoise_latents).toMatchObject({ guidance: 2, num_steps: 30, type: 'flux_denoise' });- expect(nodes.denoise_latents?.denoising_start).toBeCloseTo(0.499);- expect(hasEdge(edges, 'i2l', 'latents', 'denoise_latents', 'latents')).toBe(true);- expect(hasEdge(edges, 'pos_cond_collect', 'collection', 'denoise_latents', 'positive_text_conditioning')).toBe(- true- );- expect(Object.values(nodes).some((node) => node.type.includes('lora_collection_loader'))).toBe(true);- });-- it('fits the frame to the grid flux_denoise accepts, instead of whatever Spandrel rounded to', () => {- // Spandrel floors 203x101 at 4x to 808x400; 808 is not a multiple of 16, which `flux_denoise` requires.- const { edges, nodes } = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.fit_to_grid).toMatchObject({ height: 400, type: 'img_resize', width: 800 });- expect(nodes.denoise_latents).toMatchObject({ height: 400, width: 800 });- expect(hasEdge(edges, 'unsharp_2', 'image', 'fit_to_grid', 'image')).toBe(true);- expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);- expect(Number(nodes.denoise_latents?.width) % 16).toBe(0);- expect(Number(nodes.denoise_latents?.height) % 16).toBe(0);- });-- it('leaves the SD path on the size Spandrel produced, which is already the grid it needs', () => {- const { nodes } = compileUpscaleGraph(createValues('sd-1'), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.fit_to_grid).toBeUndefined();- });-- it('resizes a frame the scale already puts on the grid, because a 1x model makes Spandrel ignore the scale', () => {- const { edges, nodes } = compileUpscaleGraph(- { ...createFluxValues(), inputImage: { height: 1024, image_name: 'input.png', width: 1024 }, scale: 2 },- 'gallery',- { useCpuNoise: true }- ).backendGraph;-- expect(nodes.fit_to_grid).toMatchObject({ height: 2048, width: 2048 });- expect(nodes.denoise_latents).toMatchObject({ height: 2048, width: 2048 });- expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);- });-- it('wires no ControlNet, because FLUX.1 has no tile model to anchor with', () => {- const { nodes } = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(Object.values(nodes).some((node) => node.type === 'controlnet')).toBe(false);- expect(nodes.controlnet_collector).toBeUndefined();- });-- it('names the pass without claiming a multi-diffusion that does not run', () => {- const flux = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true });- const sd = compileUpscaleGraph(createValues('sd-1'), 'gallery', { useCpuNoise: true });-- expect(flux.graph.label).not.toContain('multi-diffusion');- expect(sd.graph.label).toContain('multi-diffusion');- });-- it('refuses to compile without the text encoders the loader demands', () => {- expect(() =>- compileUpscaleGraph(createFluxValues({ withEncoders: false }), 'gallery', { useCpuNoise: true })- ).toThrow(/T5 encoder/);- });-});-const withVariant = (config: ModelConfig, variant: string): ModelConfig => ({ ...config, variant }) as ModelConfig;const createZImageValues = (options: { tileControlNet?: boolean; cfgScale?: number } = {}) => {@@ -385,115 +321,6 @@ const createZImageValues = (options: { tileControlNet?: boolean; cfgScale?: numb};};-describe('compileUpscaleGraph for Z-Image', () => {- it('drives the second pass with z-image nodes, tiles both VAE ends and fits the 16px grid', () => {- const { edges, nodes } = compileUpscaleGraph(createZImageValues(), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.model_loader).toMatchObject({ type: 'z_image_model_loader' });- expect(nodes.model_loader?.qwen3_encoder_model).toMatchObject({ key: 'qwen3-4b' });- expect(nodes.model_loader?.vae_model).toMatchObject({ key: 'fluxvae' });- expect(nodes.model_loader?.qwen3_source_model).toBeUndefined();- expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'z_image_i2l' });- expect(nodes.upscale_output).toMatchObject({ tile_size: 1024, tiled: true, type: 'z_image_l2i' });- // 203x101 at 4x: Spandrel gives 808x400, and z_image_denoise takes multiples of 16 only.- expect(nodes.fit_to_grid).toMatchObject({ height: 400, width: 800 });- expect(nodes.denoise_latents).toMatchObject({- guidance_scale: 1,- height: 400,- steps: 30,- type: 'z_image_denoise',- width: 800,- });- expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);- expect(hasEdge(edges, 'i2l', 'latents', 'denoise_latents', 'latents')).toBe(true);- expect(hasEdge(edges, 'pos_cond_collect', 'collection', 'denoise_latents', 'positive_conditioning')).toBe(true);- expect(Object.values(nodes).some((node) => node.type === 'z_image_lora_collection_loader')).toBe(true);- });-- it('gives the negative prompt a branch exactly where CFG runs an unconditional pass, as Generate does', () => {- const turbo = compileUpscaleGraph(createZImageValues(), 'gallery', { useCpuNoise: true }).backendGraph;- const withCfg = compileUpscaleGraph(createZImageValues({ cfgScale: 4 }), 'gallery', { useCpuNoise: true });- const switchedOff = compileUpscaleGraph(- { ...createZImageValues({ cfgScale: 4 }), negativePromptEnabled: false },- 'gallery',- { useCpuNoise: true }- ).backendGraph;-- expect(turbo.nodes.neg_cond).toBeUndefined();- expect(switchedOff.nodes.neg_cond).toMatchObject({ type: 'z_image_text_encoder' });- expect(- hasEdge(withCfg.backendGraph.edges, 'neg_cond_collect', 'collection', 'denoise_latents', 'negative_conditioning')- ).toBe(true);- expect(hasEdge(withCfg.backendGraph.edges, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(- true- );- expect(hasEdge(turbo.edges, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(false);- });-- it('anchors to the enlarged frame with a tiled control encode when a tile ControlNet is chosen', () => {- const { edges, nodes } = compileUpscaleGraph(- { ...createZImageValues({ tileControlNet: true }), structure: 0 },- 'gallery',- { useCpuNoise: true }- ).backendGraph;-- expect(nodes.tile_control).toMatchObject({- begin_step_percent: 0,- control_model: { key: 'tile' },- tile_size: 1024,- tiled: true,- type: 'z_image_control',- });- expect(nodes.tile_control?.control_context_scale).toBeCloseTo(0.65);- expect(nodes.tile_control?.end_step_percent).toBeCloseTo(0.75);- expect(hasEdge(edges, 'fit_to_grid', 'image', 'tile_control', 'image')).toBe(true);- expect(hasEdge(edges, 'tile_control', 'control', 'denoise_latents', 'control')).toBe(true);- expect(hasEdge(edges, 'model_loader', 'vae', 'denoise_latents', 'vae')).toBe(true);- });-- it('runs without a ControlNet when none is chosen', () => {- const { nodes } = compileUpscaleGraph(createZImageValues(), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.tile_control).toBeUndefined();- expect(Object.values(nodes).some((node) => node.type === 'z_image_control')).toBe(false);- });-- it('spans Structure from a light early nudge to holding the whole pass', () => {- expect(getZImageTileControlValues(-10)).toEqual({- beginStepPercent: 0,- controlContextScale: expect.closeTo(0.3),- endStepPercent: expect.closeTo(0.5),- });- expect(getZImageTileControlValues(10)).toEqual({- beginStepPercent: 0,- controlContextScale: expect.closeTo(1),- endStepPercent: expect.closeTo(1),- });- });-- it('keeps an encoder the architecture does not read out of the graph and its metadata', () => {- const staleT5 = { base: 'any', key: 'stale-t5', name: 'stale-t5', type: 't5_encoder' } as never;- const { nodes } = compileUpscaleGraph({ ...createZImageValues(), t5EncoderModel: staleT5 }, 'gallery', {- useCpuNoise: true,- }).backendGraph;-- expect(JSON.stringify(nodes)).not.toContain('stale-t5');- });-- it('lets a Diffusers install supply its own encoder and VAE', () => {- const diffusers = { ...model('main', 'main', 'z-image'), format: 'diffusers' } as ModelConfig;- const values = {- ...createDefaultUpscaleWidgetValues([diffusers, model('spandrel', 'spandrel_image_to_image', 'any')]),- inputImage: { height: 64, image_name: 'input.png', width: 64 },- };- const { nodes } = compileUpscaleGraph(values, 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.model_loader?.qwen3_source_model).toMatchObject({ key: 'main' });- expect(nodes.model_loader?.qwen3_encoder_model).toBeUndefined();- expect(nodes.model_loader?.vae_model).toBeUndefined();- });-});-const createAnimaValues = (variant = 'anima_qwen3') => {const models = [withVariant(model('main', 'main', 'anima'), variant),@@ -512,34 +339,6 @@ const createAnimaValues = (variant = 'anima_qwen3') => {};};-describe('compileUpscaleGraph for Anima', () => {- it('drives the second pass with anima nodes at the size it states', () => {- const { edges, nodes } = compileUpscaleGraph(createAnimaValues(), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.model_loader).toMatchObject({ type: 'anima_model_loader' });- expect(nodes.model_loader?.qwen3_encoder_model).toMatchObject({ key: 'qwen3-06b' });- expect(nodes.model_loader?.vae_model).toMatchObject({ key: 'qwenvae' });- expect(nodes.model_loader?.qwen3_5_encoder_model).toBeUndefined();- expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'anima_i2l' });- expect(nodes.upscale_output).toMatchObject({ type: 'anima_l2i' });- // anima_denoise takes multiples of 8, so 808x400 needs no rounding -- but the size is a literal.- expect(nodes.fit_to_grid).toMatchObject({ height: 400, width: 808 });- expect(nodes.denoise_latents).toMatchObject({ height: 400, type: 'anima_denoise', width: 808 });- expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);- expect(Object.values(nodes).some((node) => node.type.includes('control'))).toBe(false);- });-- it('hands Anima-3.8B the Qwen3.5 encoder its connector reads', () => {- const { edges, nodes } = compileUpscaleGraph(createAnimaValues('anima_qwen35'), 'gallery', {- useCpuNoise: true,- }).backendGraph;-- expect(nodes.model_loader?.qwen3_5_encoder_model).toMatchObject({ key: 'qwen35' });- expect(hasEdge(edges, 'model_loader', 'qwen3_5_encoder', 'pos_cond', 'qwen3_5_encoder')).toBe(true);- expect(nodes.core_metadata?.qwen3_5_encoder).toMatchObject({ key: 'qwen35' });- });-});-const createKrea2Values = (variant: 'krea2_turbo' | 'krea2_base', format = 'gguf_quantized') => {const models = [{ ...withVariant(model('main', 'main', 'krea-2'), variant), format } as ModelConfig,@@ -557,44 +356,6 @@ const createKrea2Values = (variant: 'krea2_turbo' | 'krea2_base', format = 'gguf};};-describe('compileUpscaleGraph for Krea-2', () => {- it('drives the second pass with krea2 nodes and the Qwen-Image VAE, tiled at both ends', () => {- const { edges, nodes } = compileUpscaleGraph(createKrea2Values('krea2_base'), 'gallery', {- useCpuNoise: true,- }).backendGraph;-- expect(nodes.model_loader).toMatchObject({ type: 'krea2_model_loader' });- expect(nodes.model_loader?.qwen3_vl_encoder_model).toMatchObject({ key: 'qwen3vl-4b' });- expect(nodes.model_loader?.vae_model).toMatchObject({ key: 'qwenvae' });- expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'qwen_image_i2l' });- expect(nodes.upscale_output).toMatchObject({ tile_size: 1024, tiled: true, type: 'qwen_image_l2i' });- // 203x101 at 4x: Spandrel gives 808x400, and krea2_denoise takes multiples of 16 only.- expect(nodes.denoise_latents).toMatchObject({- cfg_scale: 5.5,- height: 400,- steps: 30,- type: 'krea2_denoise',- width: 800,- });- expect(nodes.denoise_latents).not.toHaveProperty('scheduler');- expect(nodes.denoise_latents).not.toHaveProperty('shift');- expect(nodes.core_metadata).toMatchObject({ qwen3_vl_encoder: { key: 'qwen3vl-4b' }, scheduler: 'euler' });- expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);- expect(hasEdge(edges, 'i2l', 'latents', 'denoise_latents', 'latents')).toBe(true);- expect(hasEdge(edges, 'neg_cond_collect', 'collection', 'denoise_latents', 'negative_conditioning')).toBe(true);- expect(hasEdge(edges, 'model_loader', 'qwen3_vl_encoder', 'pos_cond', 'qwen3_vl_encoder')).toBe(true);- });-- it('runs Turbo at CFG 1 without the unconditional branch it would not use', () => {- const { nodes } = compileUpscaleGraph(createKrea2Values('krea2_turbo'), 'gallery', {- useCpuNoise: true,- }).backendGraph;-- expect(nodes.denoise_latents?.cfg_scale).toBe(1);- expect(nodes.neg_cond).toBeUndefined();- });-});-const createFlux2Values = (variant: string, format = 'checkpoint') => {const models = [{ ...withVariant(model('main', 'main', 'flux2'), variant), format } as ModelConfig,@@ -617,71 +378,6 @@ const createFlux2Values = (variant: string, format = 'checkpoint') => {};};-describe('compileUpscaleGraph for FLUX.2', () => {- it('drives Klein with its own nodes, the guidance and the VAE statistics, tiled at both ends', () => {- const { edges, nodes } = compileUpscaleGraph(createFlux2Values('klein_4b'), 'gallery', {- useCpuNoise: true,- }).backendGraph;-- expect(nodes.model_loader).toMatchObject({- qwen3_encoder_model: { key: 'qwen3-4b' },- type: 'flux2_klein_model_loader',- vae_model: { key: 'flux2vae' },- });- expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'flux2_vae_encode' });- expect(nodes.upscale_output).toMatchObject({ tile_size: 1024, tiled: true, type: 'flux2_vae_decode' });- // 203x101 at 4x: Spandrel gives 808x400; flux2_denoise takes multiples of 16. A new Klein runs its served 4 steps.- expect(nodes.denoise_latents).toMatchObject({- guidance: 4,- height: 400,- num_steps: 4,- scheduler: 'euler',- type: 'flux2_denoise',- width: 800,- });- expect(nodes.denoise_latents).not.toHaveProperty('cfg_scale');- expect(nodes.neg_cond).toBeUndefined();- expect(nodes.core_metadata).toMatchObject({ guidance: 4, qwen3_encoder: { key: 'qwen3-4b' } });- expect(nodes.core_metadata).not.toHaveProperty('cfg_scale');- expect(hasEdge(edges, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(false);- expect(hasEdge(edges, 'model_loader', 'vae', 'denoise_latents', 'vae')).toBe(true);- expect(hasEdge(edges, 'model_loader', 'max_seq_len', 'pos_cond', 'max_seq_len')).toBe(true);- expect(hasEdge(edges, 'pos_cond_collect', 'collection', 'denoise_latents', 'positive_text_conditioning')).toBe(- true- );- expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);- expect(nodes.pos_cond).toMatchObject({ type: 'flux2_klein_text_encoder' });- expect(Object.values(nodes).some((node) => node.type === 'flux2_klein_lora_collection_loader')).toBe(true);- });-- it('hands Klein 9B the 8B encoder it was trained on', () => {- const { nodes } = compileUpscaleGraph(createFlux2Values('klein_9b_base'), 'gallery', {- useCpuNoise: true,- }).backendGraph;-- expect(nodes.model_loader?.qwen3_encoder_model).toMatchObject({ key: 'qwen3-8b' });- });-- it('drives [dev] with its Mistral encoder, never the Ministral, and records it', () => {- const { edges, nodes } = compileUpscaleGraph(createFlux2Values('dev', 'gguf_quantized'), 'gallery', {- useCpuNoise: true,- }).backendGraph;- const loraLoader = Object.entries(nodes).find(([, node]) => node.type === 'flux2_dev_lora_collection_loader');-- expect(nodes.model_loader).toMatchObject({- mistral_encoder_model: { key: 'mistral' },- type: 'flux2_dev_model_loader',- });- expect(nodes.model_loader).not.toHaveProperty('qwen3_encoder_model');- expect(nodes.pos_cond).toMatchObject({ type: 'flux2_dev_text_encoder' });- expect(loraLoader).toBeDefined();- expect(hasEdge(edges, loraLoader![0], 'mistral_encoder', 'pos_cond', 'mistral_encoder')).toBe(true);- expect(hasEdge(edges, 'model_loader', 'max_seq_len', 'pos_cond', 'max_seq_len')).toBe(true);- expect(nodes.core_metadata).toMatchObject({ mistral_encoder: { key: 'mistral' } });- expect(nodes.core_metadata).not.toHaveProperty('qwen3_encoder');- });-});-const createQwenImageValues = (options: { cfgScale?: number; format?: string } = {}) => {const models = [{ ...withVariant(model('main', 'main', 'qwen-image'), 'generate'), format: options.format ?? 'gguf_quantized' },@@ -701,88 +397,194 @@ const createQwenImageValues = (options: { cfgScale?: number; format?: string } =};};-describe('compileUpscaleGraph for Qwen Image', () => {- it('drives the second pass with qwen_image nodes, tiled at both ends, on the shift the node picks', () => {- const { edges, nodes } = compileUpscaleGraph(createQwenImageValues(), 'gallery', {- useCpuNoise: true,- }).backendGraph;+const compileCoverageCase = (label: string) => {+ const testCase = CASES.find((candidate) => candidate.label === label);- expect(nodes.model_loader).toMatchObject({- qwen_vl_encoder_model: { key: 'qwen-vl' },- type: 'qwen_image_model_loader',- vae_model: { key: 'qwenvae' },- });- expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'qwen_image_i2l' });- expect(nodes.upscale_output).toMatchObject({ tile_size: 1024, tiled: true, type: 'qwen_image_l2i' });- expect(nodes.denoise_latents).toMatchObject({- cfg_scale: 4,- height: 400,- steps: 30,- type: 'qwen_image_denoise',- width: 800,- });- expect(nodes.denoise_latents).not.toHaveProperty('shift');- expect(nodes.denoise_latents).not.toHaveProperty('scheduler');- expect(hasEdge(edges, 'pos_cond', 'conditioning', 'denoise_latents', 'positive_conditioning')).toBe(true);- expect(hasEdge(edges, 'neg_cond', 'conditioning', 'denoise_latents', 'negative_conditioning')).toBe(true);- expect(nodes.pos_cond_collect).toBeUndefined();- const loraLoaderId = Object.entries(nodes).find(- ([, node]) => node.type === 'qwen_image_lora_collection_loader'- )?.[0];- expect(loraLoaderId).toBeDefined();- expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', loraLoaderId ?? '', 'qwen_vl_encoder')).toBe(true);- expect(hasEdge(edges, loraLoaderId ?? '', 'qwen_vl_encoder', 'pos_cond', 'qwen_vl_encoder')).toBe(true);- expect(hasEdge(edges, loraLoaderId ?? '', 'qwen_vl_encoder', 'neg_cond', 'qwen_vl_encoder')).toBe(true);- expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', 'neg_cond', 'qwen_vl_encoder')).toBe(false);- expect(nodes.core_metadata).toMatchObject({- cfg_scale: 4,- qwen_image_qwen_vl_encoder: { key: 'qwen-vl' },- scheduler: 'euler',- });+ if (!testCase) {+ throw new Error(`No coverage case ${label}`);+ }++ return compileUpscaleGraph(valuesForCase(testCase).values, 'gallery', { useCpuNoise: true }).backendGraph;+};++describe('the frame the pass encodes', () => {+ it('fits the frame to the grid flux_denoise accepts, instead of whatever Spandrel rounded to', () => {+ // Spandrel's autoscale floors to a multiple of 8; `flux_denoise` declares multiple_of=16 and+ // raises on anything else -- after the upscale has already been paid for. The 203x101 fixture+ // at 4x is exactly that case: Spandrel gives 808x400, and 808 is not a multiple of 16.+ const { edges, nodes } = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true }).backendGraph;++ expect(nodes.fit_to_grid).toMatchObject({ height: 400, type: 'img_resize', width: 800 });+ expect(nodes.denoise_latents).toMatchObject({ height: 400, width: 800 });+ expect(hasEdge(edges, 'unsharp_2', 'image', 'fit_to_grid', 'image')).toBe(true);+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);});- it('takes the encoder straight from the model loader without LoRAs', () => {- const { edges, nodes } = compileUpscaleGraph({ ...createQwenImageValues(), loras: [] }, 'gallery', {- useCpuNoise: true,- }).backendGraph;+ it.each([+ ['FLUX.1', () => createFluxValues(), 'denoise_latents'],+ // SD's noise is sized as a literal too, so a frame the upscaler left small would not match it.+ ['SD1.5', () => createValues('sd-1'), 'noise'],+ ] as const)(+ 'resizes a %s frame the scale already puts on the grid, because a 1x model makes Spandrel ignore the scale',+ (_label, create, sizedNode) => {+ const { edges, nodes } = compileUpscaleGraph(+ { ...create(), inputImage: { height: 1024, image_name: 'input.png', width: 1024 }, scale: 2 },+ 'gallery',+ { useCpuNoise: true }+ ).backendGraph;++ expect(nodes.fit_to_grid).toMatchObject({ height: 2048, width: 2048 });+ expect(nodes[sizedNode]).toMatchObject({ height: 2048, width: 2048 });+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);+ }+ );- expect(Object.values(nodes).some((node) => node.type === 'qwen_image_lora_collection_loader')).toBe(false);- expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', 'pos_cond', 'qwen_vl_encoder')).toBe(true);- expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', 'neg_cond', 'qwen_vl_encoder')).toBe(true);+ it.each(CASES.map(({ label }) => label))(+ 'tiles both VAE ends of the %s pass where its nodes have the switch',+ (label) => {+ const { nodes } = compileCoverageCase(label);++ expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true });+ // `anima_l2i` has no switch: it tiles on its own once an untiled decode would take most of the card.+ if (nodes.upscale_output?.type === 'anima_l2i') {+ expect(nodes.upscale_output).not.toHaveProperty('tiled');+ } else {+ expect(nodes.upscale_output).toMatchObject({ tile_size: 1024, tiled: true });+ }+ }+ );++ it('names the pass without claiming a multi-diffusion that does not run', () => {+ const flux = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true });+ const sd = compileUpscaleGraph(createValues('sd-1'), 'gallery', { useCpuNoise: true });++ expect(flux.graph.label).not.toContain('multi-diffusion');+ expect(sd.graph.label).toContain('multi-diffusion');});- it('wires the negative prompt only above CFG 1, where the node runs an unconditional pass', () => {- const { edges, nodes } = compileUpscaleGraph(createQwenImageValues({ cfgScale: 1 }), 'gallery', {+ it('refuses to compile without the text encoders the loader demands', () => {+ expect(() =>+ compileUpscaleGraph(createFluxValues({ withEncoders: false }), 'gallery', { useCpuNoise: true })+ ).toThrow(/T5 encoder/);+ });+});++describe("the family pipeline Upscale runs Generation's way", () => {+ // Upscale keeps its own persisted field names; each must reach the loader input the family reads, and its record.+ it.each([+ ['flux', 't5_encoder_model', 't5', 't5_encoder'],+ ['flux', 'clip_embed_model', 'clip', 'clip_embed_model'],+ ['z-image', 'qwen3_encoder_model', 'qwen3-4b', 'qwen3_encoder'],+ ['anima-3.8b', 'qwen3_encoder_model', 'qwen3-06b', 'qwen3_encoder'],+ ['anima-3.8b', 'qwen3_5_encoder_model', 'qwen35', 'qwen3_5_encoder'],+ ['krea-2-raw', 'qwen3_vl_encoder_model', 'qwen3vl-4b', 'qwen3_vl_encoder'],+ ['flux2-dev', 'mistral_encoder_model', 'mistral', 'mistral_encoder'],+ ['flux2-klein-9b', 'qwen3_encoder_model', 'qwen3-8b', 'qwen3_encoder'],+ ['moss-image', 'qwen3_5_encoder_model', 'qwen35-9b', 'qwen3_5_encoder'],+ ['qwen-image', 'qwen_vl_encoder_model', 'qwen-vl', 'qwen_image_qwen_vl_encoder'],+ ])('hands the %s loader its %s, and records it', (label, loaderField, key, metadataKey) => {+ const { nodes } = compileCoverageCase(label);++ expect(nodes.model_loader?.[loaderField]).toMatchObject({ key });+ expect(nodes.core_metadata?.[metadataKey]).toMatchObject({ key });+ });++ it('records the VAE the loader used, not one a self-contained SDNQ FLUX.1 ignores', () => {+ const values = createFluxValues();+ const submodels = Object.fromEntries(+ ['transformer', 'vae', 'text_encoder', 'tokenizer', 'text_encoder_2', 'tokenizer_2'].map((name) => [name, {}])+ );+ const sdnq = { ...values.model, format: 'sdnq_quantized', submodels } as UpscaleWidgetValues['model'];+ const separate = compileUpscaleGraph(values, 'gallery', { useCpuNoise: true }).backendGraph.nodes;+ const bundled = compileUpscaleGraph({ ...values, model: sdnq }, 'gallery', { useCpuNoise: true }).backendGraph+ .nodes;++ expect(values.vae).toMatchObject({ key: 'fluxvae' });+ expect(separate.model_loader?.vae_model).toMatchObject({ key: 'fluxvae' });+ expect(separate.core_metadata?.vae).toMatchObject({ key: 'fluxvae' });+ expect(bundled.model_loader?.vae_model).toBeUndefined();+ expect(bundled.core_metadata?.vae).toBeUndefined();+ });++ it('keeps an encoder the architecture does not read out of the graph and its metadata', () => {+ // A T5 picked while FLUX was selected stays in the widget for when FLUX comes back.+ const staleT5 = { base: 'any', key: 'stale-t5', name: 'stale-t5', type: 't5_encoder' } as never;+ const { nodes } = compileUpscaleGraph({ ...createZImageValues(), t5EncoderModel: staleT5 }, 'gallery', {useCpuNoise: true,}).backendGraph;- expect(nodes.neg_cond).toBeUndefined();- expect(hasEdge(edges, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(false);+ expect(JSON.stringify(nodes)).not.toContain('stale-t5');+ });++ it.each(['z-image', 'qwen-image'])(+ 'sends the %s pass no schedule shift, which would move the schedule Creativity is translated against',+ (label) => {+ expect(compileCoverageCase(label).nodes.denoise_latents).not.toHaveProperty('shift');+ }+ );++ it('loads an enabled MOSS-Image LoRA into the transformer the pass denoises with, and records it', () => {+ const { edges, nodes } = compileCoverageCase('moss-image');+ const [loaderId] =+ Object.entries(nodes).find(([, node]) => node.type === 'moss_image_lora_collection_loader') ?? [];++ expect(loaderId).toBeDefined();+ expect(hasEdge(edges, 'model_loader', 'transformer', loaderId ?? '', 'transformer')).toBe(true);+ expect(hasEdge(edges, loaderId ?? '', 'transformer', 'denoise_latents', 'transformer')).toBe(true);+ expect(nodes.core_metadata?.loras).toEqual([{ model: expect.objectContaining({ key: 'moss-lora' }), weight: 1 }]);});});-describe('compileUpscaleGraph for a Diffusers install', () => {- it.each([- {- base: 'Krea-2',- encoder: 'qwen3_vl_encoder_model',- values: () => ({ ...createKrea2Values('krea2_turbo', 'diffusers'), vae: null }),- },- {- base: 'FLUX.2',- encoder: 'qwen3_encoder_model',- values: () => ({ ...createFlux2Values('klein_4b', 'diffusers'), vae: null }),- },- {- base: 'Qwen Image',- encoder: 'qwen_vl_encoder_model',- values: () => ({ ...createQwenImageValues({ format: 'diffusers' }), vae: null }),- },- ])('lets a $base Diffusers install supply its own $encoder and VAE', ({ encoder, values }) => {- const { nodes } = compileUpscaleGraph(values(), 'gallery', { useCpuNoise: true }).backendGraph;-- expect(nodes.model_loader?.[encoder]).toBeUndefined();- expect(nodes.model_loader?.vae_model).toBeUndefined();+describe('tile control', () => {+ it('wires no ControlNet where the architecture has none', () => {+ const { nodes } = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true }).backendGraph;++ expect(Object.values(nodes).some((node) => node.type === 'controlnet')).toBe(false);+ expect(nodes.controlnet_collector).toBeUndefined();+ });++ it('anchors Z-Image to the enlarged frame with a tiled control encode when a tile ControlNet is chosen', () => {+ const { edges, nodes } = compileUpscaleGraph(+ { ...createZImageValues({ tileControlNet: true }), structure: 0 },+ 'gallery',+ { useCpuNoise: true }+ ).backendGraph;++ // The control image is encoded inside the denoise at the frame's full size; untiled, that is+ // the encode the i2l node is tiled to avoid.+ expect(nodes.tile_control).toMatchObject({+ begin_step_percent: 0,+ control_model: { key: 'tile' },+ tile_size: 1024,+ tiled: true,+ type: 'z_image_control',+ });+ expect(nodes.tile_control?.control_context_scale).toBeCloseTo(0.65);+ expect(nodes.tile_control?.end_step_percent).toBeCloseTo(0.75);+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'tile_control', 'image')).toBe(true);+ expect(hasEdge(edges, 'tile_control', 'control', 'denoise_latents', 'control')).toBe(true);+ // The denoise encodes the control image itself, with the VAE the pass decodes with.+ expect(hasEdge(edges, 'model_loader', 'vae', 'denoise_latents', 'vae')).toBe(true);+ });++ it('runs Z-Image without a ControlNet when none is chosen', () => {+ const { nodes } = compileUpscaleGraph(createZImageValues(), 'gallery', { useCpuNoise: true }).backendGraph;++ expect(nodes.tile_control).toBeUndefined();+ expect(Object.values(nodes).some((node) => node.type === 'z_image_control')).toBe(false);+ });++ it('spans Structure from a light early nudge to holding the whole pass', () => {+ expect(getZImageTileControlValues(-10)).toEqual({+ beginStepPercent: 0,+ controlContextScale: expect.closeTo(0.3),+ endStepPercent: expect.closeTo(0.5),+ });+ expect(getZImageTileControlValues(10)).toEqual({+ beginStepPercent: 0,+ controlContextScale: expect.closeTo(1),+ endStepPercent: expect.closeTo(1),+ });});});@@ -861,9 +663,7 @@ describe('schedulers on the upscale pass', () => {const { nodes } = compileUpscaleGraph({ ...createBaseValues(), scheduler: stored }, 'gallery', {useCpuNoise: true,}).backendGraph;- const denoise = nodes.denoise_latents ?? nodes.tiled_multidiffusion_denoise_latents;-- expect([denoise?.scheduler, nodes.core_metadata?.scheduler]).toEqual([runs, runs]);+ expect([nodes.denoise_latents?.scheduler, nodes.core_metadata?.scheduler]).toEqual([runs, runs]);});});@@ -915,6 +715,37 @@ describe('upscale metadata', () => {expect(loaded).toEqual([[values.loras[0]!.model.key, 0.7]]);expect(recorded).toEqual(loaded);});++ it.each([+ ['Z-Image at CFG 1', () => createZImageValues(), false],+ ['Z-Image at CFG 4', () => createZImageValues({ cfgScale: 4 }), true],+ // Switched off, the prompt still gets its branch and the queue fills it with an empty string, so CFG runs at+ // the value the slider and the metadata show.+ [+ 'Z-Image at CFG 4 with the negative prompt off',+ () => ({ ...createZImageValues({ cfgScale: 4 }), negativePromptEnabled: false }),+ true,+ ],+ ['Qwen Image at CFG 1', () => createQwenImageValues({ cfgScale: 1 }), false],+ ['Krea-2 Raw at CFG 5.5', () => createKrea2Values('krea2_base'), true],+ ['FLUX.2', () => createFlux2Values('klein_4b'), false],+ ['SD1.5', () => createValues('sd-1'), true],+ ] as const)('records the negative prompt of %s exactly when the pass encodes one', (_label, create, reads) => {+ // The pipeline builds the negative branch by its own rule; the metadata must record the prompt on the same terms.+ const { edges, nodes } = compileUpscaleGraph(create(), 'gallery', { useCpuNoise: true }).backendGraph;++ expect(nodes.neg_cond !== undefined).toBe(reads);+ expect(hasEdge(edges, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(reads);+ });++ it('records the slider as guidance for a family that reads no negative prompt, and as CFG elsewhere', () => {+ const metadataFor = (values: UpscaleWidgetValues) =>+ compileUpscaleGraph(values, 'gallery', { useCpuNoise: true }).backendGraph.nodes.core_metadata;++ expect(metadataFor(createFlux2Values('klein_4b'))).toMatchObject({ guidance: 4 });+ expect(metadataFor(createFlux2Values('klein_4b'))).not.toHaveProperty('cfg_scale');+ expect(metadataFor(createQwenImageValues())).toMatchObject({ cfg_scale: 4 });+ });});describe('compileUpscaleGraph for MOSS-Image', () => {diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex 7fb402d70d..09edfd28b2 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -6,21 +6,20 @@ import type {MainModelConfig,ResultDestination,} from '@features/generation/contracts';+import type { FamilyPipelineSettings } from '@features/generation/graph';+import type { StepClipping } from '@features/generation/settings';import {- addLoraCollectionLoader,addEdge,addNode,- addTransformerLoraCollectionLoader,- getCompelPromptNodeType,- getActiveCompatibleLoras,+ buildImageToImagePipeline,getLoadedLoras,toGraphContract,toModelIdentifier,} from '@features/generation/graph';-import { isBundledMainForBase } from '@features/generation/settings';+import { getDenoisingStartClipping } from '@features/generation/settings';-import type { UpscaleBase, UpscaleIndexClipping } from './settings';+import type { UpscaleTileControlNet } from './settings';import type { CompiledUpscaleGraph, SpandrelModelConfig, UpscaleWidgetValues } from './types';import {@@ -30,6 +29,8 @@ import {getUpscaleValidationReasons,upscaleArchitectureFor,upscaleDenoiseDimension,+ upscaleDenoiseGrid,+ upscaleNegativePromptUsage,wiresUpscaleNegativePrompt,} from './settings';@@ -44,7 +45,7 @@ export const getUpscaleDenoisingStart = (creativity: number): number => ((creatiexport const getIndexClippedDenoisingStart = (valueStart: number,sigmas: readonly number[],- rounding: UpscaleIndexClipping['rounding']+ rounding: StepClipping['rounding']): number => {const target = 1 - valueStart;let entryIndex = 0;@@ -95,20 +96,30 @@ type UpscaleProjectSettings = Pick<GenerationProjectSettings, 'useCpuNoise'>;const addUpscaleMetadata = (graph: BackendGraphContract,- { frame, output }: UpscalePathResult,+ {+ frame,+ output,+ vaeModel,+ }: {+ /** The image the pass encoded, which the result matches in size, so Recall restores the real one. */+ frame: BackendInvocationContract;+ output: BackendInvocationContract;+ /** The VAE the pipeline loaded; the widget's pick is dropped where it is incompatible or the family ignores it. */+ vaeModel: UpscaleWidgetValues['vae'];+ },settings: UpscaleWidgetValues,- projectSettings: UpscaleProjectSettings,randDevice: string): void => {if (!settings.model || !settings.upscaleModel || !settings.inputImage) {return;}- const architecture = upscaleArchitectureFor(settings.model);const components = activeUpscaleComponents(settings);// FLUX calls this guidance, not CFG, and the encoders have to be recalled with the rest.const guidanceField =- architecture?.negativePrompt === 'never' ? { guidance: settings.cfgScale } : { cfg_scale: settings.cfgScale };+ upscaleNegativePromptUsage(settings.model) === 'never'+ ? { guidance: settings.cfgScale }+ : { cfg_scale: settings.cfgScale };const metadata = addNode(graph, {...guidanceField,...(components.t5EncoderModel ? { t5_encoder: toModelIdentifier(components.t5EncoderModel) } : {}),@@ -123,7 +134,7 @@ const addUpscaleMetadata = (: {}),creativity: settings.creativity,id: 'core_metadata',- // Runs after the path builder, so the graph already holds the LoRAs this architecture loads.+ // Runs after the pipeline, so the graph already holds the LoRAs this architecture loads.loras: getLoadedLoras(graph),model: toModelIdentifier(settings.model),rand_device: randDevice,@@ -140,7 +151,7 @@ const addUpscaleMetadata = (},upscale_model: toModelIdentifier(settings.upscaleModel),upscale_scale: settings.scale,- vae: settings.vae ? toModelIdentifier(settings.vae) : undefined,+ vae: vaeModel ? toModelIdentifier(vaeModel) : undefined,});addEdge(graph, graph.nodes.positive_prompt, 'value', metadata, 'positive_prompt');@@ -153,34 +164,6 @@ const addUpscaleMetadata = (addEdge(graph, metadata, 'metadata', output, 'metadata');};-/** The shared prefix (prompts, seed, Spandrel, unsharp) is built once; builders add loader, conditioning and VAE. */-interface UpscalePathContext {- graph: BackendGraphContract;- settings: UpscaleWidgetValues;- model: MainModelConfig;- /** A field this main model has no slot for is null here, whatever the widget holds. */- components: ReturnType<typeof activeUpscaleComponents>;- destination: ResultDestination;- projectSettings: UpscaleProjectSettings;- positivePrompt: BackendInvocationContract;- negativePrompt: BackendInvocationContract;- seed: BackendInvocationContract;- /** Not always `denoiseSize`: Spandrel ignores the scale for a model that does not enlarge. */- frame: BackendInvocationContract;- denoiseSize: { width: number; height: number };- denoisingStart: number;-}--interface UpscalePathResult {- output: BackendInvocationContract;- /** Spandrel's frame or its resize; metadata records its size, so Recall restores the real one. */- frame: BackendInvocationContract;- /** Names the pass in the queue, so "multi-diffusion" is not claimed where none runs. */- title: string;-}--type UpscalePathBuilder = (context: UpscalePathContext) => UpscalePathResult;-/** Spandrel ignores scale for 1x models and rounds to 8 where nodes need 16; a mismatch fails after upscaling. */const fitFrameToDenoiseSize = (graph: BackendGraphContract,@@ -200,411 +183,63 @@ const fitFrameToDenoiseSize = (return fitted;};-const buildSdUpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- destination,- projectSettings,- positivePrompt,- negativePrompt,- seed,- frame,- denoisingStart,-}) => {- const { tileControlnetModel } = settings;-- if (!tileControlnetModel) {- throw new Error('Upscale needs a Tile or Union ControlNet compatible with the main model.');- }+/** The widget's values in the pipeline's terms. Upscale has no component source, and leaves CFG rescale off. */+const toPipelineSettings = (settings: UpscaleWidgetValues, model: MainModelConfig): FamilyPipelineSettings => {+ const components = activeUpscaleComponents(settings);- const noise = addNode(graph, { id: 'noise', type: 'noise', use_cpu: projectSettings.useCpuNoise });- const imageToLatents = addNode(graph, {- fp32: settings.vaePrecision === 'fp32',- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'i2l',- });- const output = addNode(graph, {- fp32: settings.vaePrecision === 'fp32',- id: 'upscale_output',- is_intermediate: destination === 'canvas',- tile_size: settings.tileSize,- tiled: true,- type: 'l2i',- use_cache: false,- });- const denoise = addNode(graph, {- cfg_scale: settings.cfgScale,- denoising_end: 1,- denoising_start: denoisingStart,- id: 'tiled_multidiffusion_denoise_latents',+ return {+ cfgRescaleMultiplier: 0,+ cfgScale: settings.cfgScale,+ clipEmbedModel: components.clipEmbedModel,+ clipSkip: settings.clipSkip,+ componentSourceModel: null,+ loras: settings.loras,+ mistralEncoderModel: components.mistralEncoderModel,+ qwen35EncoderModel: components.qwen35EncoderModel,+ qwen3EncoderModel: components.qwen3EncoderModel,+ qwen3VLEncoderModel: components.qwen3VlEncoderModel,+ qwenVLEncoderModel: components.qwenVlEncoderModel,scheduler: coerceUpscaleScheduler(model, settings.scheduler),steps: settings.steps,- tile_height: settings.tileSize,- tile_overlap: settings.tileOverlap,- tile_width: settings.tileSize,- type: 'tiled_multi_diffusion_denoise_latents',- });- const modelLoader = addNode(graph, {- id: 'model_loader',- model: toModelIdentifier(model),- type: model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader',- });- const compelType = getCompelPromptNodeType(model.base);- const posCond = addNode(graph, { id: 'pos_cond', type: compelType });- const negCond = addNode(graph, { id: 'neg_cond', type: compelType });- const activeLoras = settings.loras.filter(- (lora) =>- lora.isEnabled && (lora.model.base === model.base || (model.base === 'sdxl' && lora.model.base === 'sdxl'))- );- let unetSource: BackendInvocationContract = modelLoader;- let clipSource: BackendInvocationContract = modelLoader;- let clip2Source: BackendInvocationContract | undefined = model.base === 'sdxl' ? modelLoader : undefined;-- addEdge(graph, seed, 'value', noise, 'seed');- addEdge(graph, frame, 'width', noise, 'width');- addEdge(graph, frame, 'height', noise, 'height');- addEdge(graph, frame, 'image', imageToLatents, 'image');-- if (model.base === 'sdxl') {- addEdge(graph, positivePrompt, 'value', posCond, 'prompt');- addEdge(graph, positivePrompt, 'value', posCond, 'style');- addEdge(graph, negativePrompt, 'value', negCond, 'prompt');- addEdge(graph, negativePrompt, 'value', negCond, 'style');- } else {- const clipSkip = addNode(graph, { id: 'clip_skip', skipped_layers: settings.clipSkip, type: 'clip_skip' });-- addEdge(graph, modelLoader, 'clip', clipSkip, 'clip');- clipSource = clipSkip;- addEdge(graph, positivePrompt, 'value', posCond, 'prompt');- addEdge(graph, negativePrompt, 'value', negCond, 'prompt');- }-- if (activeLoras.length > 0) {- const loraLoader = addLoraCollectionLoader(graph, activeLoras, model, {- clip: clipSource,- clip2: clip2Source,- unet: unetSource,- });-- unetSource = loraLoader;- clipSource = loraLoader;- clip2Source = model.base === 'sdxl' ? loraLoader : undefined;- }-- addEdge(graph, unetSource, 'unet', denoise, 'unet');- addEdge(graph, clipSource, 'clip', posCond, 'clip');- addEdge(graph, clipSource, 'clip', negCond, 'clip');- if (model.base === 'sdxl') {- addEdge(graph, clip2Source ?? modelLoader, 'clip2', posCond, 'clip2');- addEdge(graph, clip2Source ?? modelLoader, 'clip2', negCond, 'clip2');- }-- const vaeLoader =- settings.vae && settings.vae.base === model.base- ? addNode(graph, { id: 'vae_loader', type: 'vae_loader', vae_model: toModelIdentifier(settings.vae) })- : null;- const vaeSource = vaeLoader ?? modelLoader;-- addEdge(graph, vaeSource, 'vae', imageToLatents, 'vae');- addEdge(graph, vaeSource, 'vae', output, 'vae');- addEdge(graph, noise, 'noise', denoise, 'noise');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');- addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');- addEdge(graph, denoise, 'latents', output, 'latents');-- const control = getUpscaleControlNetValues(settings.structure);- const controlNet1 = addNode(graph, {- begin_step_percent: control.first.beginStepPercent,- control_mode: 'balanced',- control_model: toModelIdentifier(tileControlnetModel),- control_weight: control.first.controlWeight,- end_step_percent: control.first.endStepPercent,- id: 'controlnet_1',- resize_mode: 'just_resize',- type: 'controlnet',- });- const controlNet2 = addNode(graph, {- begin_step_percent: control.second.beginStepPercent,- control_mode: 'balanced',- control_model: toModelIdentifier(tileControlnetModel),- control_weight: control.second.controlWeight,- end_step_percent: control.second.endStepPercent,- id: 'controlnet_2',- resize_mode: 'just_resize',- type: 'controlnet',- });- const controlNetCollector = addNode(graph, { id: 'controlnet_collector', type: 'collect' });-- addEdge(graph, frame, 'image', controlNet1, 'image');- addEdge(graph, frame, 'image', controlNet2, 'image');- addEdge(graph, controlNet1, 'control', controlNetCollector, 'item');- addEdge(graph, controlNet2, 'control', controlNetCollector, 'item');- addEdge(graph, controlNetCollector, 'collection', denoise, 'control');-- return { frame, output, title: `${model.name} multi-diffusion upscale` };-};--/** No tile ControlNet: anchored only by its start. Both VAE ends tile; an untiled encode exceeds consumer GPUs. */-const buildFluxUpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- components,- destination,- positivePrompt,- seed,- frame,- denoiseSize,- denoisingStart,-}) => {- const modelLoader = addNode(graph, {- clip_embed_model: components.clipEmbedModel ? toModelIdentifier(components.clipEmbedModel) : undefined,- id: 'model_loader',- model: toModelIdentifier(model),- t5_encoder_model: components.t5EncoderModel ? toModelIdentifier(components.t5EncoderModel) : undefined,- type: 'flux_model_loader',- vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,- });- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);- const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(graph, activeLoras, 'flux_lora_collection_loader', modelLoader, [- 'transformer',- 'clip',- 't5_encoder',- ])- : modelLoader;- const posCond = addNode(graph, { id: 'pos_cond', type: 'flux_text_encoder' });- const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });- const imageToLatents = addNode(graph, {- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'flux_vae_encode',- });- const denoise = addNode(graph, {- denoising_end: 1,- denoising_start: denoisingStart,- guidance: settings.cfgScale,- height: denoiseSize.height,- id: 'denoise_latents',- num_steps: settings.steps,- scheduler: coerceUpscaleScheduler(model, settings.scheduler),- type: 'flux_denoise',- width: denoiseSize.width,- });- const output = addNode(graph, {- id: 'upscale_output',- is_intermediate: destination === 'canvas',- tile_size: settings.tileSize,- tiled: true,- type: 'flux_vae_decode',- use_cache: false,- });-- addEdge(graph, loraSource, 'clip', posCond, 'clip');- addEdge(graph, loraSource, 't5_encoder', posCond, 't5_encoder');- addEdge(graph, modelLoader, 'max_seq_len', posCond, 't5_max_seq_len');- addEdge(graph, positivePrompt, 'value', posCond, 'prompt');- addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');- addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');- addEdge(graph, loraSource, 'transformer', denoise, 'transformer');- addEdge(graph, seed, 'value', denoise, 'seed');-- const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);-- addEdge(graph, fitted, 'image', imageToLatents, 'image');- addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- addEdge(graph, denoise, 'latents', output, 'latents');- addEdge(graph, modelLoader, 'vae', output, 'vae');-- return { frame: fitted, output, title: `${model.name} upscale` };+ t5EncoderModel: components.t5EncoderModel,+ vae: settings.vae,+ vaePrecision: settings.vaePrecision,+ };};-/** As in Generate, CFG stays off and the slider drives [dev]'s distilled guidance; Klein ignores it. */-const buildFlux2UpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- components,- destination,- positivePrompt,- seed,- frame,- denoiseSize,- denoisingStart,-}) => {- const isDev = model.variant === 'dev';- const encoderField = isDev ? 'mistral_encoder' : 'qwen3_encoder';- const vaeModel = settings.vae ? toModelIdentifier(settings.vae) : undefined;- const modelLoader = addNode(- graph,- isDev- ? {- id: 'model_loader',- mistral_encoder_model: components.mistralEncoderModel- ? toModelIdentifier(components.mistralEncoderModel)- : undefined,- model: toModelIdentifier(model),- type: 'flux2_dev_model_loader',- vae_model: vaeModel,- }- : {- id: 'model_loader',- model: toModelIdentifier(model),- qwen3_encoder_model: components.qwen3EncoderModel- ? toModelIdentifier(components.qwen3EncoderModel)- : undefined,- type: 'flux2_klein_model_loader',- vae_model: vaeModel,- }- );- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);- const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(- graph,- activeLoras,- isDev ? 'flux2_dev_lora_collection_loader' : 'flux2_klein_lora_collection_loader',- modelLoader,- ['transformer', encoderField]- )- : modelLoader;- const posCond = addNode(graph, {- id: 'pos_cond',- type: isDev ? 'flux2_dev_text_encoder' : 'flux2_klein_text_encoder',- });- const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });- const imageToLatents = addNode(graph, {- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'flux2_vae_encode',- });- const denoise = addNode(graph, {- denoising_end: 1,- denoising_start: denoisingStart,- guidance: settings.cfgScale,- height: denoiseSize.height,- id: 'denoise_latents',- num_steps: settings.steps,- scheduler: coerceUpscaleScheduler(model, settings.scheduler),- type: 'flux2_denoise',- width: denoiseSize.width,- });- const output = addNode(graph, {- id: 'upscale_output',- is_intermediate: destination === 'canvas',- tile_size: settings.tileSize,- tiled: true,- type: 'flux2_vae_decode',- use_cache: false,- });-- addEdge(graph, loraSource, encoderField, posCond, encoderField);- addEdge(graph, modelLoader, 'max_seq_len', posCond, 'max_seq_len');- addEdge(graph, positivePrompt, 'value', posCond, 'prompt');- addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');- addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');- addEdge(graph, loraSource, 'transformer', denoise, 'transformer');- addEdge(graph, seed, 'value', denoise, 'seed');-- const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);-- addEdge(graph, fitted, 'image', imageToLatents, 'image');- addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- // The denoise normalizes the encoded latents with this VAE's BN statistics.- addEdge(graph, modelLoader, 'vae', denoise, 'vae');- addEdge(graph, denoise, 'latents', output, 'latents');- addEdge(graph, modelLoader, 'vae', output, 'vae');+/** Creativity's start, translated into the node's terms where it clips by step. */+const getUpscaleEntry = (+ model: MainModelConfig,+ denoiseSize: { width: number; height: number },+ { creativity, steps }: Pick<UpscaleWidgetValues, 'creativity' | 'steps'>+): number => {+ const valueStart = getUpscaleDenoisingStart(creativity);+ const clipping = getDenoisingStartClipping(model);- return { frame: fitted, output, title: `${model.name} upscale` };+ return clipping?.kind === 'step'+ ? getIndexClippedDenoisingStart(valueStart, clipping.sigmas(model, denoiseSize, steps), clipping.rounding)+ : valueStart;};-/** The tile ControlNet is optional (no tiles, no seams); it encodes the frame like `i2l`, so tiles the same way. */-const buildZImageUpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- components,- destination,- positivePrompt,- negativePrompt,- seed,- frame,- denoiseSize,- denoisingStart,-}) => {- const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);- const modelLoader = addNode(graph, {- id: 'model_loader',- model: toModelIdentifier(model),- qwen3_encoder_model: components.qwen3EncoderModel ? toModelIdentifier(components.qwen3EncoderModel) : undefined,- // A Diffusers or complete SDNQ install supplies its own VAE and Qwen3 where none is chosen.- qwen3_source_model: isBundledMainForBase('z-image')(model) ? toModelIdentifier(model) : undefined,- type: 'z_image_model_loader',- vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,- });- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);- const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(graph, activeLoras, 'z_image_lora_collection_loader', modelLoader, [- 'transformer',- 'qwen3_encoder',- ])- : modelLoader;- const imageToLatents = addNode(graph, {- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'z_image_i2l',- });- const denoise = addNode(graph, {- denoising_end: 1,- denoising_start: denoisingStart,- guidance_scale: settings.cfgScale,- height: denoiseSize.height,- id: 'denoise_latents',- scheduler: coerceUpscaleScheduler(model, settings.scheduler),- steps: settings.steps,- type: 'z_image_denoise',- width: denoiseSize.width,- });- const output = addNode(graph, {- id: 'upscale_output',- is_intermediate: destination === 'canvas',- tile_size: settings.tileSize,- tiled: true,- type: 'z_image_l2i',- use_cache: false,- });+/** Structure's tile ControlNet: SD's two split across the schedule, or Z-Image's one, tiled like `i2l`. */+const addTileControl = (+ graph: BackendGraphContract,+ settings: UpscaleWidgetValues,+ kind: UpscaleTileControlNet['kind'],+ { denoise, frame }: { denoise: BackendInvocationContract; frame: BackendInvocationContract }+): void => {+ const { tileControlnetModel } = settings;- addPromptConditioning(graph, {- denoise,- encoderFields: [{ field: 'qwen3_encoder', source: loraSource }],- encoderType: 'z_image_text_encoder',- negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,- positivePrompt,- });- addEdge(graph, loraSource, 'transformer', denoise, 'transformer');- addEdge(graph, seed, 'value', denoise, 'seed');- addEdge(graph, fitted, 'image', imageToLatents, 'image');- addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- // The denoise encodes its control image itself, with this VAE.- addEdge(graph, modelLoader, 'vae', denoise, 'vae');- addEdge(graph, denoise, 'latents', output, 'latents');- addEdge(graph, modelLoader, 'vae', output, 'vae');+ if (!tileControlnetModel) {+ return;+ }- if (settings.tileControlnetModel) {+ if (kind === 'z_image_control') {const control = getZImageTileControlValues(settings.structure);const tileControl = addNode(graph, {begin_step_percent: control.beginStepPercent,control_context_scale: control.controlContextScale,- control_model: toModelIdentifier(settings.tileControlnetModel),+ control_model: toModelIdentifier(tileControlnetModel),end_step_percent: control.endStepPercent,id: 'tile_control',tile_size: settings.tileSize,@@ -612,377 +247,36 @@ const buildZImageUpscalePath: UpscalePathBuilder = ({type: 'z_image_control',});- addEdge(graph, fitted, 'image', tileControl, 'image');+ addEdge(graph, frame, 'image', tileControl, 'image');addEdge(graph, tileControl, 'control', denoise, 'control');- }- return { frame: fitted, output, title: `${model.name} upscale` };-};--/** No tile ControlNet (only LLLite). `anima_l2i` tiles on its own once an untiled decode would fill the card. */-const buildAnimaUpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- components,- destination,- positivePrompt,- negativePrompt,- seed,- frame,- denoiseSize,- denoisingStart,-}) => {- const modelLoader = addNode(graph, {- id: 'model_loader',- model: toModelIdentifier(model),- qwen3_5_encoder_model: components.qwen35EncoderModel ? toModelIdentifier(components.qwen35EncoderModel) : undefined,- qwen3_encoder_model: components.qwen3EncoderModel ? toModelIdentifier(components.qwen3EncoderModel) : undefined,- type: 'anima_model_loader',- vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,- });- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);- const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(graph, activeLoras, 'anima_lora_collection_loader', modelLoader, [- 'transformer',- 'qwen3_encoder',- ])- : modelLoader;- const imageToLatents = addNode(graph, {- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'anima_i2l',- });- const denoise = addNode(graph, {- denoising_end: 1,- denoising_start: denoisingStart,- guidance_scale: settings.cfgScale,- height: denoiseSize.height,- id: 'denoise_latents',- scheduler: coerceUpscaleScheduler(model, settings.scheduler),- steps: settings.steps,- type: 'anima_denoise',- width: denoiseSize.width,- });- const output = addNode(graph, {- id: 'upscale_output',- is_intermediate: destination === 'canvas',- type: 'anima_l2i',- use_cache: false,- });-- addPromptConditioning(graph, {- denoise,- encoderFields: [- { field: 'qwen3_encoder', source: loraSource },- // Straight from the loader: the LoRA collection loader passes Qwen3.5 through untouched.- ...(components.qwen35EncoderModel ? [{ field: 'qwen3_5_encoder', source: modelLoader }] : []),- ],- encoderType: 'anima_text_encoder',- negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,- positivePrompt,- });- addEdge(graph, loraSource, 'transformer', denoise, 'transformer');- addEdge(graph, seed, 'value', denoise, 'seed');- const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);-- addEdge(graph, fitted, 'image', imageToLatents, 'image');- addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- addEdge(graph, denoise, 'latents', output, 'latents');- addEdge(graph, modelLoader, 'vae', output, 'vae');-- return { frame: fitted, output, title: `${model.name} upscale` };-};--/** Uses the Qwen-Image VAE nodes, as Generate does. `krea2_denoise` picks its own shift, so none is sent. */-const buildKrea2UpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- components,- destination,- positivePrompt,- negativePrompt,- seed,- frame,- denoiseSize,- denoisingStart,-}) => {- const modelLoader = addNode(graph, {- id: 'model_loader',- model: toModelIdentifier(model),- qwen3_vl_encoder_model: components.qwen3VlEncoderModel- ? toModelIdentifier(components.qwen3VlEncoderModel)- : undefined,- type: 'krea2_model_loader',- vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,- });- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);- const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(graph, activeLoras, 'krea2_lora_collection_loader', modelLoader, [- 'transformer',- 'qwen3_vl_encoder',- ])- : modelLoader;- const imageToLatents = addNode(graph, {- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'qwen_image_i2l',- });- const denoise = addNode(graph, {- cfg_scale: settings.cfgScale,- denoising_end: 1,- denoising_start: denoisingStart,- height: denoiseSize.height,- id: 'denoise_latents',- steps: settings.steps,- type: 'krea2_denoise',- width: denoiseSize.width,- });- const output = addNode(graph, {- id: 'upscale_output',- is_intermediate: destination === 'canvas',- tile_size: settings.tileSize,- tiled: true,- type: 'qwen_image_l2i',- use_cache: false,- });-- addPromptConditioning(graph, {- denoise,- encoderFields: [{ field: 'qwen3_vl_encoder', source: loraSource }],- encoderType: 'krea2_text_encoder',- negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,- positivePrompt,- });- addEdge(graph, loraSource, 'transformer', denoise, 'transformer');- addEdge(graph, seed, 'value', denoise, 'seed');-- const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);-- addEdge(graph, fitted, 'image', imageToLatents, 'image');- addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- addEdge(graph, denoise, 'latents', output, 'latents');- addEdge(graph, modelLoader, 'vae', output, 'vae');-- return { frame: fitted, output, title: `${model.name} upscale` };-};--/** No shift is sent, so `qwen_image_denoise` keeps its dynamic one, which Creativity is translated against. */-const buildQwenImageUpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- components,- destination,- positivePrompt,- negativePrompt,- seed,- frame,- denoiseSize,- denoisingStart,-}) => {- const modelLoader = addNode(graph, {- id: 'model_loader',- model: toModelIdentifier(model),- qwen_vl_encoder_model: components.qwenVlEncoderModel ? toModelIdentifier(components.qwenVlEncoderModel) : undefined,- type: 'qwen_image_model_loader',- vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,- });- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);- const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(graph, activeLoras, 'qwen_image_lora_collection_loader', modelLoader, [- 'transformer',- 'qwen_vl_encoder',- ])- : modelLoader;- const imageToLatents = addNode(graph, {- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'qwen_image_i2l',- });- const denoise = addNode(graph, {- cfg_scale: settings.cfgScale,- denoising_end: 1,- denoising_start: denoisingStart,- height: denoiseSize.height,- id: 'denoise_latents',- steps: settings.steps,- type: 'qwen_image_denoise',- width: denoiseSize.width,- });- const output = addNode(graph, {- id: 'upscale_output',- is_intermediate: destination === 'canvas',- tile_size: settings.tileSize,- tiled: true,- type: 'qwen_image_l2i',- use_cache: false,- });-- addPromptConditioning(graph, {- collect: false,- denoise,- encoderFields: [{ field: 'qwen_vl_encoder', source: loraSource }],- encoderType: 'qwen_image_text_encoder',- negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,- positivePrompt,- });- addEdge(graph, loraSource, 'transformer', denoise, 'transformer');- addEdge(graph, seed, 'value', denoise, 'seed');-- const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);-- addEdge(graph, fitted, 'image', imageToLatents, 'image');- addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- addEdge(graph, denoise, 'latents', output, 'latents');- addEdge(graph, modelLoader, 'vae', output, 'vae');-- return { frame: fitted, output, title: `${model.name} upscale` };-};--/** Qwen Image's and MOSS-Image's denoise take one conditioning; the others a collected list. */-const addPromptConditioning = (- graph: BackendGraphContract,- {- collect = true,- denoise,- encoderFields,- encoderType,- negativePrompt,- positivePrompt,- }: {- collect?: boolean;- denoise: BackendInvocationContract;- encoderFields: readonly { field: string; source: BackendInvocationContract }[];- encoderType: string;- negativePrompt: BackendInvocationContract | null;- positivePrompt: BackendInvocationContract;+ return;}-): void => {- const branches = [- { conditioningField: 'positive_conditioning', prefix: 'pos', prompt: positivePrompt },- ...(negativePrompt ? [{ conditioningField: 'negative_conditioning', prefix: 'neg', prompt: negativePrompt }] : []),- ];- for (const { conditioningField, prefix, prompt } of branches) {- const encoder = addNode(graph, { id: `${prefix}_cond`, type: encoderType });-- for (const { field, source } of encoderFields) {- addEdge(graph, source, field, encoder, field);- }- addEdge(graph, prompt, 'value', encoder, 'prompt');-- if (collect) {- const collector = addNode(graph, { id: `${prefix}_cond_collect`, type: 'collect' });+ const control = getUpscaleControlNetValues(settings.structure);+ const collector = addNode(graph, { id: 'controlnet_collector', type: 'collect' });++ for (const [id, values] of [+ ['controlnet_1', control.first],+ ['controlnet_2', control.second],+ ] as const) {+ const controlNet = addNode(graph, {+ begin_step_percent: values.beginStepPercent,+ control_mode: 'balanced',+ control_model: toModelIdentifier(tileControlnetModel),+ control_weight: values.controlWeight,+ end_step_percent: values.endStepPercent,+ id,+ resize_mode: 'just_resize',+ type: 'controlnet',+ });- addEdge(graph, encoder, 'conditioning', collector, 'item');- addEdge(graph, collector, 'collection', denoise, conditioningField);- } else {- addEdge(graph, encoder, 'conditioning', denoise, conditioningField);- }+ addEdge(graph, frame, 'image', controlNet, 'image');+ addEdge(graph, controlNet, 'control', collector, 'item');}+ addEdge(graph, collector, 'collection', denoise, 'control');};-/**- * `moss_image_denoise` uses the FLUX.2 VAE's raw latent layout, so FLUX.2's tiled encode/decode nodes fit. Its LoRAs- * load on the transformer only.- * Generate's layout prompt is left out: it only compiles layout drafts or canvas regions.- */-const buildMossImageUpscalePath: UpscalePathBuilder = ({- graph,- settings,- model,- components,- destination,- positivePrompt,- negativePrompt,- seed,- frame,- denoiseSize,- denoisingStart,-}) => {- const modelLoader = addNode(graph, {- id: 'model_loader',- model: toModelIdentifier(model),- qwen3_5_encoder_model: components.qwen35EncoderModel ? toModelIdentifier(components.qwen35EncoderModel) : undefined,- type: 'moss_image_model_loader',- vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,- });- // MOSS-Image LoRAs train the transformer only; the VAE and the Qwen3.5 encoder stay on the model loader.- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);- const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(graph, activeLoras, 'moss_image_lora_collection_loader', modelLoader, [- 'transformer',- ])- : modelLoader;- const imageToLatents = addNode(graph, {- id: 'i2l',- tile_size: settings.tileSize,- tiled: true,- type: 'flux2_vae_encode',- });- const denoise = addNode(graph, {- cfg_scale: settings.cfgScale,- denoising_end: 1,- denoising_start: denoisingStart,- height: denoiseSize.height,- id: 'denoise_latents',- steps: settings.steps,- type: 'moss_image_denoise',- width: denoiseSize.width,- });- const output = addNode(graph, {- id: 'upscale_output',- is_intermediate: destination === 'canvas',- tile_size: settings.tileSize,- tiled: true,- type: 'flux2_vae_decode',- use_cache: false,- });-- addPromptConditioning(graph, {- collect: false,- denoise,- encoderFields: [{ field: 'qwen3_5_encoder', source: modelLoader }],- encoderType: 'moss_image_text_encoder',- negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,- positivePrompt,- });- addEdge(graph, loraSource, 'transformer', denoise, 'transformer');- addEdge(graph, seed, 'value', denoise, 'seed');- const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);-- addEdge(graph, fitted, 'image', imageToLatents, 'image');- addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');- addEdge(graph, imageToLatents, 'latents', denoise, 'latents');- // The denoise reads this VAE's BatchNorm statistics, which define the latent space it works in.- addEdge(graph, modelLoader, 'vae', denoise, 'vae');- addEdge(graph, denoise, 'latents', output, 'latents');- addEdge(graph, modelLoader, 'vae', output, 'vae');-- return { frame: fitted, output, title: `${model.name} upscale` };-};--/** `satisfies` makes a supported architecture without a builder a type error. */-const UPSCALE_PATH_BUILDERS = {- anima: buildAnimaUpscalePath,- flux: buildFluxUpscalePath,- flux2: buildFlux2UpscalePath,- 'krea-2': buildKrea2UpscalePath,- 'moss-image': buildMossImageUpscalePath,- 'qwen-image': buildQwenImageUpscalePath,- 'sd-1': buildSdUpscalePath,- sdxl: buildSdUpscalePath,- 'z-image': buildZImageUpscalePath,-} satisfies Record<UpscaleBase, UpscalePathBuilder>;-export interface ModelOnlyUpscaleRequest {image: ImageWithDims;upscaleModel: SpandrelModelConfig;@@ -1077,36 +371,34 @@ export const compileUpscaleGraph = (}const { inputImage, model, upscaleModel } = settings;+ const architecture = upscaleArchitectureFor(model);- if (!inputImage || !model || !upscaleModel) {+ if (!inputImage || !model || !upscaleModel || !architecture) {throw new Error('Upscale settings are incomplete.');}- const buildPath = UPSCALE_PATH_BUILDERS[model.base as UpscaleBase];-- if (!buildPath) {- throw new Error(`Upscale does not support ${model.base} main models.`);- }-- const architecture = upscaleArchitectureFor(model);- const grid = architecture?.denoiseGrid ?? 8;+ const grid = upscaleDenoiseGrid(model);const denoiseSize = {height: upscaleDenoiseDimension(inputImage.height, settings.scale, grid),width: upscaleDenoiseDimension(inputImage.width, settings.scale, grid),};- const valueClippedStart = getUpscaleDenoisingStart(settings.creativity);- const clipping = architecture?.indexClipping;- const denoisingStart = clipping- ? getIndexClippedDenoisingStart(- valueClippedStart,- clipping.sigmas(model, denoiseSize, settings.steps),- clipping.rounding- )- : valueClippedStart;- const graph: BackendGraphContract = { edges: [], id: 'upscale-graph', nodes: {} };- const positivePrompt = addNode(graph, { id: 'positive_prompt', type: 'string' });- const negativePrompt = addNode(graph, { id: 'negative_prompt', type: 'string' });- const seed = addNode(graph, { id: 'seed', type: 'integer' });+ const { denoise, graph, latents, output, vaeModel } = buildImageToImagePipeline({+ denoiseSize,+ denoisingStart: getUpscaleEntry(model, denoiseSize, settings),+ model,+ multiDiffusion: architecture.multiDiffusion+ ? { tileOverlap: settings.tileOverlap, tileSize: settings.tileSize }+ : null,+ output: { id: 'upscale_output', isIntermediate: destination === 'canvas' },+ settings: toPipelineSettings(settings, model),+ useCpuNoise: projectSettings.useCpuNoise,+ vaeTileSize: settings.tileSize,+ });++ if (!latents) {+ throw new Error(`Upscale cannot encode an image for ${model.name}.`);+ }+const spandrelAutoscale = addNode(graph, {fit_to_multiple_of_8: true,id: 'spandrel_autoscale',@@ -1119,26 +411,31 @@ export const compileUpscaleGraph = (addEdge(graph, spandrelAutoscale, 'image', unsharpMask, 'image');- const path = buildPath({- components: activeUpscaleComponents(settings),- denoiseSize,- denoisingStart,- destination,- frame: unsharpMask,- graph,- model,- negativePrompt,- positivePrompt,- projectSettings,- seed,- settings,+ const frame = fitFrameToDenoiseSize(graph, unsharpMask, denoiseSize);+ // An untiled encode of the full frame does not fit consumer VRAM; the pipeline tiles the decode.+ const encode = addNode(graph, {+ ...(latents.fp32 === undefined ? {} : { fp32: latents.fp32 }),+ id: 'i2l',+ tile_size: settings.tileSize,+ tiled: true,+ type: latents.encodeType,});- addUpscaleMetadata(graph, path, settings, projectSettings, randDevice);+ addEdge(graph, frame, 'image', encode, 'image');+ addEdge(graph, latents.vae.node, latents.vae.field, encode, 'vae');+ addEdge(graph, encode, 'latents', denoise, 'latents');+ if (architecture.tileControlNet) {+ addTileControl(graph, settings, architecture.tileControlNet.kind, { denoise, frame });+ }+ addUpscaleMetadata(graph, { frame, output, vaeModel }, settings, randDevice);return {backendGraph: graph,- graph: toGraphContract(graph, path.title),+ // Names the pass in the queue, so "multi-diffusion" is not claimed where none runs.+ graph: toGraphContract(+ graph,+ architecture.multiDiffusion ? `${model.name} multi-diffusion upscale` : `${model.name} upscale`+ ),negativePromptNodeId: 'negative_prompt',outputNodeId: 'upscale_output',positivePromptNodeId: 'positive_prompt',diff --git a/invokeai/frontend/webv2/src/features/upscale/core/indexClippedStarts.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/indexClippedStarts.test.tsindex 79620f2eb0..860c15f3f8 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/indexClippedStarts.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/indexClippedStarts.test.ts@@ -1,7 +1,9 @@/** The starts the widget sends index-clipping denoise nodes, recorded for the backend to replay. */import type { MainModelConfig } from '@features/generation/contracts';+import type { StepClipping } from '@features/generation/settings';+import { getDenoisingStartClipping } from '@features/generation/settings';import { describe, expect, it } from 'vitest';import type { UpscaleBase } from './settings';@@ -24,9 +26,9 @@ const BASES = [...new Set(MODELS.map((model) => model.base))];describe('index-clipped denoising starts', () => {it('covers every architecture whose denoise node clips by index', () => {- const indexClipped = Object.entries(UPSCALE_ARCHITECTURES)- .filter(([, architecture]) => architecture.indexClipping)- .map(([base]) => base);+ const indexClipped = Object.keys(UPSCALE_ARCHITECTURES).filter(+ (base) => getDenoisingStartClipping({ base, type: 'main' })?.kind === 'step'+ );expect([...BASES].sort()).toEqual(indexClipped.sort());});@@ -37,8 +39,8 @@ describe('index-clipped denoising starts', () => {STEP_COUNTS.flatMap((steps) =>CREATIVITIES.map((creativity) => {const valueStart = getUpscaleDenoisingStart(creativity);- const clipping = UPSCALE_ARCHITECTURES[base].indexClipping!;- const model = { base, variant } as MainModelConfig;+ const model = { base, type: 'main', variant } as MainModelConfig;+ const clipping = getDenoisingStartClipping(model) as StepClipping;const sigmas = clipping.sigmas(model, { height: side, width: side }, steps);return {diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.tsindex c5ec714be6..57c16a2e8e 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts@@ -2,7 +2,10 @@ import type { GenerateLora, VaeModelConfig } from '@features/generation/contractimport type { ModelConfig } from '@features/models';import { getSchedulerOptions } from '@features/generation/settings';-import { resetArchitectureCapabilities } from '@features/models/core/architectureCapabilities';+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/models/core/architectureCapabilities';import {architectureCapabilitiesFixture,seedArchitectureCapabilities,@@ -16,6 +19,7 @@ import {isUpscaleBatchCountFixed,resolveUpscaleSubmissionValues,getUpscaleOutputDimensions,+ getUpscaleValidationIssues,getUpscaleValidationReasons,normalizeUpscaleWidgetValues,spandrelAutoscaleDimension,@@ -23,7 +27,6 @@ import {isTileControlNetCandidate,selectUpscaleMainModel,syncUpscaleWidgetValuesWithModels,- UPSCALE_ARCHITECTURES,UPSCALE_PRESETS,upscaleSchedulerOptions,} from './settings';@@ -189,6 +192,40 @@ describe('architecture-driven validation', () => {expect(values.tileControlnetModel).toBeNull();});+ it("refuses an architecture the backend does not describe, rather than guess its node's grid", () => {+ const values = upscaleReady([+ model('main', 'main', 'flux'),+ model('spandrel', 'spandrel_image_to_image', 'any'),+ model('t5', 't5_encoder', 'any'),+ model('clip', 'clip_embed', 'any'),+ model('fluxvae', 'vae', 'flux'),+ ]);++ setArchitectureCapabilities(architectureCapabilitiesFixture.filter((row) => row.base !== 'flux'));++ expect(getUpscaleValidationIssues(values)).toContainEqual({+ message: 'The backend does not describe the FLUX.1 architecture, so Upscale cannot run it.',+ section: 'generation',+ });+ });++ it('exempts a self-contained SDNQ pipeline, which ships its own parts, and asks one that lacks them for its encoders', () => {+ const submodels = Object.fromEntries(+ ['transformer', 'vae', 'text_encoder', 'tokenizer', 'text_encoder_2', 'tokenizer_2'].map((name) => [name, {}])+ );+ const complete = { ...model('main', 'main', 'flux'), format: 'sdnq_quantized', submodels } as ModelConfig;+ const { text_encoder_2: _t5, ...withoutT5 } = submodels;+ const partial = { ...complete, submodels: withoutT5 } as ModelConfig;+ const spandrel = model('spandrel', 'spandrel_image_to_image', 'any');++ expect(getUpscaleValidationReasons(upscaleReady([complete, spandrel]))).toEqual([]);+ expect(getUpscaleValidationReasons(upscaleReady([partial, spandrel]))).toEqual([+ 'Upscale needs a T5 encoder for this main model.',+ 'Upscale needs a CLIP Embed model for this main model.',+ 'Upscale needs a VAE for this main model.',+ ]);+ });+it('blocks the run when a required component has been uninstalled', () => {const installed = [model('main', 'main', 'flux'),@@ -204,17 +241,6 @@ describe('architecture-driven validation', () => {});});-describe('the architecture table', () => {- it.each(Object.entries(UPSCALE_ARCHITECTURES))('agrees with the served %s capabilities', (base, architecture) => {- // The fixture is the response the backend serves, pinned by `test_capabilities_fixture.py`, so a grid or- // negative-prompt change on a denoise node fails here instead of at enqueue.- const served = architectureCapabilitiesFixture.find((row) => row.base === base && row.variant === null);-- expect(served?.features.dimension_grid).toBe(architecture.denoiseGrid);- expect(served?.features.negative_prompt.usage).toBe(architecture.negativePrompt);- });-});-const withVariant = (config: ModelConfig, variant: string): ModelConfig => ({ ...config, variant }) as ModelConfig;const QWEN3_4B = withVariant(model('qwen3-4b', 'qwen3_encoder', 'any'), 'qwen3_4b');diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.tsindex 7d34ec1e50..0639002032 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts@@ -6,6 +6,7 @@ import type {ModelIdentifierConfig,VaePrecision,} from '@features/generation/contracts';+import type { ImageToImagePipelineBase } from '@features/generation/graph';import type { GenerateSubmissionSource, ProjectPromptDraft } from '@features/generation/settings';import type { ModelConfig } from '@features/models';@@ -14,8 +15,12 @@ import {DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,getDefaultGenerateSettings,+ getDenoisingStartClipping,+ getGenerationDimensions,getGenerationUiPolicy,+ getNegativePromptUsage,getSchedulerOptions,+ isArchitectureDescribed,isAnimaQwen35Encoder,isAnimaQwen3Encoder,isBundledFlux2Main,@@ -28,6 +33,7 @@ import {isMossImageQwen35Encoder,isModelIdentifierConfig,isQwen3Vl4bEncoder,+ isSelfContainedSDNQFlux1Pipeline,isVaeCompatibleWithGenerateModel,isVaeModelConfig,isZImageQwen3Encoder,@@ -43,73 +49,7 @@ import { isSeedMode, SEED_MAX } from '@platform/core/seed';import type { SpandrelModelConfig, TileControlNetModelConfig, UpscaleMode, UpscaleWidgetValues } from './types';-// Schedules of nodes that clip `denoising_start` by step index (`indexClipping`); drop once they clip by value.--/** First `steps` sigmas of a flow schedule shifted by `shift`, without the final 0 (diffusers: shift = exp(mu)). */-const shiftedSigmas = (shift: number, steps: number): number[] =>- Array.from({ length: steps }, (_, index) => {- const t = 1 - index / steps;-- return (shift * t) / (1 + (shift - 1) * t);- });--/** `z_image_denoise.Z_IMAGE_SHIFT_FIT`, held at the fit's 4096-token end since the clamp (#378). */-const Z_IMAGE_SHIFT_MIN_SEQ_LEN = 256;-const Z_IMAGE_SHIFT_MAX_SEQ_LEN = 4096;-const Z_IMAGE_BASE_SHIFT = 0.5;-const Z_IMAGE_MAX_SHIFT = 1.15;--/** Z-Image's linear shift for a frame: one token per 16x16 pixels, as `z_image_denoise` patches it. */-const zImageScheduleShift = ({ width, height }: { width: number; height: number }): number => {- const seqLen = Math.min(Math.floor(width / 16) * Math.floor(height / 16), Z_IMAGE_SHIFT_MAX_SEQ_LEN);- const slope = (Z_IMAGE_MAX_SHIFT - Z_IMAGE_BASE_SHIFT) / (Z_IMAGE_SHIFT_MAX_SEQ_LEN - Z_IMAGE_SHIFT_MIN_SEQ_LEN);-- return Math.exp(seqLen * slope + Z_IMAGE_BASE_SHIFT - slope * Z_IMAGE_SHIFT_MIN_SEQ_LEN);-};--/** `ANIMA_SHIFT`: Anima's schedule is shifted by a constant, not by resolution. */-const ANIMA_SCHEDULE_SHIFT = 3;--/** `krea2/sampling_utils.py`: Turbo's fixed mu and Raw's token-count fit; Diffusers installs ship the same config. */-const KREA2_DISTILLED_MU = 1.15;-const KREA2_SHIFT_MIN_SEQ_LEN = 256;-const KREA2_SHIFT_MAX_SEQ_LEN = 6400;-const KREA2_BASE_SHIFT = 0.5;-const KREA2_MAX_SHIFT = 1.15;--/** `exp(mu)`, held at the fit's 6400-token end as `krea2_denoise` does; anything not Raw counts as distilled. */-const krea2ScheduleShift = (model: MainModelConfig, { width, height }: { width: number; height: number }): number => {- if (model.variant !== 'krea2_base') {- return Math.exp(KREA2_DISTILLED_MU);- }-- const seqLen = Math.min(Math.floor(width / 16) * Math.floor(height / 16), KREA2_SHIFT_MAX_SEQ_LEN);- const slope = (KREA2_MAX_SHIFT - KREA2_BASE_SHIFT) / (KREA2_SHIFT_MAX_SEQ_LEN - KREA2_SHIFT_MIN_SEQ_LEN);-- return Math.exp(seqLen * slope + KREA2_BASE_SHIFT - slope * KREA2_SHIFT_MIN_SEQ_LEN);-};--/** `qwen_image_denoise`'s scheduler: mu 0.5 at 256 tokens to 0.9 at 8192, held at the end, stretched to 0.02. */-const QWEN_IMAGE_SHIFT_MIN_SEQ_LEN = 256;-const QWEN_IMAGE_SHIFT_MAX_SEQ_LEN = 8192;-const QWEN_IMAGE_BASE_SHIFT = 0.5;-const QWEN_IMAGE_MAX_SHIFT = 0.9;-const QWEN_IMAGE_SHIFT_TERMINAL = 0.02;--/** As diffusers' FlowMatchEulerDiscreteScheduler builds them, including `stretch_shift_to_terminal`. */-const qwenImageSigmas = ({ width, height }: { width: number; height: number }, steps: number): number[] => {- const seqLen = Math.min(Math.floor(width / 16) * Math.floor(height / 16), QWEN_IMAGE_SHIFT_MAX_SEQ_LEN);- const slope =- (QWEN_IMAGE_MAX_SHIFT - QWEN_IMAGE_BASE_SHIFT) / (QWEN_IMAGE_SHIFT_MAX_SEQ_LEN - QWEN_IMAGE_SHIFT_MIN_SEQ_LEN);- const shifted = shiftedSigmas(- Math.exp(seqLen * slope + (QWEN_IMAGE_BASE_SHIFT - slope * QWEN_IMAGE_SHIFT_MIN_SEQ_LEN)),- steps- );- const scale = (1 - (shifted[steps - 1] ?? 0)) / (1 - QWEN_IMAGE_SHIFT_TERMINAL);-- return shifted.map((sigma) => 1 - (1 - sigma) / scale);-};-+/** A text encoder the widget can be asked for; each is its own persisted field. */export type UpscaleComponentField =| 't5EncoderModel'| 'clipEmbedModel'@@ -215,6 +155,8 @@ export interface UpscaleTileControlNet {readonly required: boolean;/** Checkpoints do not state their mode (Z-Image Tile and Union 2.1 are identical tensors), so the name decides. */readonly matchesName: (name: string) => boolean;+ /** The node it runs as: SD's two `controlnet`s split across the schedule, or Z-Image's one `z_image_control`. */+ readonly kind: 'controlnet' | 'z_image_control';}const nameIncludes =@@ -222,29 +164,14 @@ const nameIncludes =(name: string): boolean =>needles.some((needle) => name.toLowerCase().includes(needle));-export interface UpscaleIndexClipping {- /** Noisiest first, without the final 0. */- readonly sigmas: (- model: MainModelConfig,- size: { width: number; height: number },- steps: number- ) => readonly number[];- /** `int(start * steps)`, or Python's half-to-even `int(round(start * steps))`. */- readonly rounding: 'floor' | 'round';-}--/** Single source of truth: the compiler's `UPSCALE_PATH_BUILDERS` and validation both key off this record. */+/** Upscale's own choices per architecture; the pass itself is Generation's image pipeline for the family. */export interface UpscaleArchitecture {/** Structure drives this ControlNet's weights; without one, Structure is hidden rather than inert. */readonly tileControlNet: UpscaleTileControlNet | null;/** The parts the loader refuses to run without; only bundled pipelines carry their own. */readonly components: (model: MainModelConfig) => UpscaleComponents;- /** Spandrel rounds to 8, which `flux_denoise` (multiple_of=16) rejects after the upscale; coarser grids resize. */- readonly denoiseGrid: number;- /** The served `FeaturesFacet` answer, pinned by test; `cfg-gated` reads it only above CFG 1. */- readonly negativePrompt: 'always' | 'cfg-gated' | 'never';- /** Lets the compiler start an index-clipping node where FLUX would for the same Creativity; null otherwise. */- readonly indexClipping: UpscaleIndexClipping | null;+ /** SD denoises in overlapping tiles, hence its required tile ControlNet; the others run whole. */+ readonly multiDiffusion: boolean;/*** Schedulers that start where Creativity puts the pass; null where all do. LCM on FLUX.1/Z-Image/Anima and* Anima's Heun build their own schedules past the blend. `test_upscale_index_clipped_starts.py` checks these.@@ -260,15 +187,17 @@ export interface UpscaleArchitecture {readonly label: string;}-const SD_TILE_CONTROLNET: UpscaleTileControlNet = { matchesName: nameIncludes('tile', 'union'), required: true };+const SD_TILE_CONTROLNET: UpscaleTileControlNet = {+ kind: 'controlnet',+ matchesName: nameIncludes('tile', 'union'),+ required: true,+};export const UPSCALE_ARCHITECTURES = {'sd-1': {components: () => NO_COMPONENTS,- denoiseGrid: 8,- indexClipping: null,label: 'SD1.5',- negativePrompt: 'always',+ multiDiffusion: true,schedulers: null,takesModelGuidance: false,takesModelSteps: false,@@ -276,23 +205,21 @@ export const UPSCALE_ARCHITECTURES = {},sdxl: {components: () => NO_COMPONENTS,- denoiseGrid: 8,- indexClipping: null,label: 'SDXL',- negativePrompt: 'always',+ multiDiffusion: true,schedulers: null,takesModelGuidance: false,takesModelSteps: false,tileControlNet: SD_TILE_CONTROLNET,},flux: {- // `flux_model_loader` refuses a bare transformer without T5, CLIP Embed and VAE; the backend checks SDNQ submodels.+ // `flux_model_loader` needs T5, CLIP Embed and VAE unless an SDNQ pipeline lists them as submodels.components: (model) =>- model.format === 'sdnq_quantized' ? NO_COMPONENTS : { slots: [T5_ENCODER_SLOT, CLIP_EMBED_SLOT], vae: true },- denoiseGrid: 16,- indexClipping: null,+ isSelfContainedSDNQFlux1Pipeline(model)+ ? NO_COMPONENTS+ : { slots: [T5_ENCODER_SLOT, CLIP_EMBED_SLOT], vae: true },label: 'FLUX.1',- negativePrompt: 'never',+ multiDiffusion: false,// `flux/denoise.py` uses `z_image_denoise`'s schedulers, so this follows the backend contract's Z-Image list.schedulers: ['euler', 'heun'],takesModelGuidance: false,@@ -305,11 +232,8 @@ export const UPSCALE_ARCHITECTURES = {isBundledFlux2Main(model)? NO_COMPONENTS: { slots: [model.variant === 'dev' ? FLUX2_MISTRAL_SLOT : flux2KleinQwen3Slot(model)], vae: true },- denoiseGrid: 16,- // `flux2_denoise` clips by sigma value like FLUX.1, then re-spaces the window to the requested steps.- indexClipping: null,label: 'FLUX.2',- negativePrompt: 'never',+ multiDiffusion: false,// With a start above zero `flux2_denoise` steps with Euler, whatever scheduler it is handed.schedulers: ['euler'],takesModelGuidance: true,@@ -320,17 +244,12 @@ export const UPSCALE_ARCHITECTURES = {// `z_image_model_loader` falls back to a bundled main model's own VAE and Qwen3.components: (model) =>isBundledMainForBase('z-image')(model) ? NO_COMPONENTS : { slots: [Z_IMAGE_QWEN3_SLOT], vae: true },- denoiseGrid: 16,- indexClipping: {- rounding: 'floor',- sigmas: (_model, size, steps) => shiftedSigmas(zImageScheduleShift(size), steps),- },label: 'Z-Image',- negativePrompt: 'cfg-gated',+ multiDiffusion: false,schedulers: ['euler', 'heun'],takesModelGuidance: true,takesModelSteps: false,- tileControlNet: { matchesName: nameIncludes('tile'), required: false },+ tileControlNet: { kind: 'z_image_control', matchesName: nameIncludes('tile'), required: false },},anima: {// Anima-3.8B's semantic connector also reads Qwen3.5; no other Anima model does.@@ -338,10 +257,8 @@ export const UPSCALE_ARCHITECTURES = {slots: model.variant === 'anima_qwen35' ? [ANIMA_QWEN3_SLOT, ANIMA_QWEN35_SLOT] : [ANIMA_QWEN3_SLOT],vae: true,}),- denoiseGrid: 8,- indexClipping: { rounding: 'floor', sigmas: (_model, _size, steps) => shiftedSigmas(ANIMA_SCHEDULE_SHIFT, steps) },label: 'Anima',- negativePrompt: 'cfg-gated',+ multiDiffusion: false,schedulers: ['euler', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde'],takesModelGuidance: true,takesModelSteps: false,@@ -350,13 +267,8 @@ export const UPSCALE_ARCHITECTURES = {'krea-2': {// `krea2_model_loader` refuses a single-file or GGUF transformer without Qwen3-VL and VAE.components: (model) => (model.format === 'diffusers' ? NO_COMPONENTS : { slots: [KREA2_QWEN3_VL_SLOT], vae: true }),- denoiseGrid: 16,- indexClipping: {- rounding: 'round',- sigmas: (model, size, steps) => shiftedSigmas(krea2ScheduleShift(model, size), steps),- },label: 'Krea-2',- negativePrompt: 'cfg-gated',+ multiDiffusion: false,// `krea2_denoise` has no scheduler input: it steps with Euler.schedulers: ['euler'],takesModelGuidance: true,@@ -367,11 +279,8 @@ export const UPSCALE_ARCHITECTURES = {// `moss_image_model_loader` takes a Diffusers install's own Qwen3.5 and VAE; any other format needs both.components: (model) =>model.format === 'diffusers' ? NO_COMPONENTS : { slots: [MOSS_IMAGE_QWEN35_SLOT], vae: true },- denoiseGrid: 16,- // `moss_image_denoise` clips by sigma value like FLUX, then re-spaces the window to the requested steps.- indexClipping: null,label: 'MOSS-Image',- negativePrompt: 'cfg-gated',+ multiDiffusion: false,// `moss_image_denoise` has no scheduler input: it steps its own shifted Euler schedule.schedulers: ['euler'],takesModelGuidance: true,@@ -382,17 +291,16 @@ export const UPSCALE_ARCHITECTURES = {'qwen-image': {// The widget sends no component source, so any non-Diffusers format needs both.components: (model) => (model.format === 'diffusers' ? NO_COMPONENTS : { slots: [QWEN_IMAGE_VL_SLOT], vae: true }),- denoiseGrid: 16,- indexClipping: { rounding: 'round', sigmas: (_model, size, steps) => qwenImageSigmas(size, steps) },label: 'Qwen Image',- negativePrompt: 'cfg-gated',+ multiDiffusion: false,// `qwen_image_denoise` has no scheduler input: it steps with Euler.schedulers: ['euler'],takesModelGuidance: true,takesModelSteps: false,tileControlNet: null,},-} as const satisfies Record<string, UpscaleArchitecture>;+ // A base without Generation's image pipeline fails here: Upscale has no detail pass of its own.+} as const satisfies Partial<Record<ImageToImagePipelineBase, UpscaleArchitecture>>;export type UpscaleBase = keyof typeof UPSCALE_ARCHITECTURES;@@ -418,14 +326,18 @@ export const upscaleComponentsFor = (model: MainModelConfig | null): UpscaleComp/** CFG-gated architectures need a negative branch above CFG 1; a switched-off negative prompt still gets one. */export const wiresUpscaleNegativePrompt = (model: MainModelConfig | null, cfgScale: number): boolean => {- const usage = upscaleArchitectureFor(model)?.negativePrompt;+ const usage = upscaleNegativePromptUsage(model);return usage === 'always' || (usage === 'cfg-gated' && cfgScale > 1);};+/** The served negative-prompt usage; `cfg-gated` reads it only above CFG 1. */+export const upscaleNegativePromptUsage = (model: MainModelConfig | null) =>+ model ? getNegativePromptUsage(model) : 'always';+/** Index clipping starts on a whole step, so one step means pure noise or nothing; the pass needs two. */export const upscaleMinSteps = (model: MainModelConfig | null): number =>- upscaleArchitectureFor(model)?.indexClipping ? 2 : 1;+ model && getDenoisingStartClipping(model)?.kind === 'step' ? 2 : 1;const UPSCALE_CFG_SCALE_MAX = 100;@@ -456,6 +368,10 @@ export const coerceUpscaleScheduler = (model: MainModelConfig | null, scheduler:export const spandrelAutoscaleDimension = (dimension: number, scale: number): number =>Math.floor(Math.trunc(dimension * scale) / 8) * 8;+/** The served grid: Spandrel rounds to 8, which `flux_denoise` (multiple_of=16) rejects after the upscale. */+export const upscaleDenoiseGrid = (model: MainModelConfig | null): number =>+ model ? getGenerationDimensions(model).grid : 8;+export const upscaleDenoiseDimension = (dimension: number, scale: number, grid: number): number =>Math.max(grid, Math.floor(spandrelAutoscaleDimension(dimension, scale) / grid) * grid);@@ -922,6 +838,12 @@ export const getUpscaleValidationIssues = (message: `Upscale supports only ${supportedUpscaleArchitectureLabels()} main models.`,section: 'generation',});+ } else if (!isArchitectureDescribed(values.model)) {+ // Its grid and negative prompt come from the served row, and the fallbacks would build a graph the node refuses.+ issues.push({+ message: `The backend does not describe the ${architecture.label} architecture, so Upscale cannot run it.`,+ section: 'generation',+ });}// `flux_denoise` refuses a Fill model without fill conditioning, which an upscale never supplies.@@ -1118,7 +1040,7 @@ export const getModelOnlyUpscaleFactors = (model: SpandrelModelConfig): number[]return [...presets, nativeScale].sort((a, b) => a - b);};-/** Refine: Spandrel's frame floored to the pass grid. Model only: floored to 8, or the input size for a 1x model. */+/** Refine: input times Scale, floored to the pass grid. Model only: Spandrel's frame, or the input for a 1x model. */export const getUpscaleOutputDimensions = (image: Pick<ImageWithDims, 'width' | 'height'>,values: Pick<UpscaleWidgetValues, 'mode' | 'model' | 'scale' | 'upscaleModel'>@@ -1132,7 +1054,7 @@ export const getUpscaleOutputDimensions = (};}- const grid = upscaleArchitectureFor(values.model)?.denoiseGrid ?? 8;+ const grid = upscaleDenoiseGrid(values.model);return {height: upscaleDenoiseDimension(image.height, values.scale, grid),diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsxindex 4dd5225993..a8afca8ecb 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx@@ -17,7 +17,7 @@ import {getDynamicPromptsConfig,getDynamicPromptsSettingsPatch,} from '@features/generation/settings';-import { upscaleArchitectureFor } from '@features/upscale/core/settings';+import { upscaleNegativePromptUsage } from '@features/upscale/core/settings';import { areJsonValuesStructurallyEqual } from '@platform/core/json';import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';import { memo, useCallback, useMemo } from 'react';@@ -34,9 +34,14 @@ const getChangedKeys = (before: ProjectPromptDraft, written: ProjectPromptDraftP/** Compare prompt/LoRA content across reconstructed values to avoid costly rerenders and reset autocomplete state. */+/** The served answer is read when this runs; the revision is an argument so the React Compiler re-reads it on reload. */+const getNegativePromptUsage = (model: MainModelConfig | null, _capabilitiesRevision: number) =>+ upscaleNegativePromptUsage(model);+export const UpscalePromptFields = memo(function UpscalePromptFields({batchCount,+ capabilitiesRevision,isSeedFixed,loras,model,@@ -49,6 +54,7 @@ export const UpscalePromptFields = memo(showSyntaxHighlighting,}: {batchCount: number;+ capabilitiesRevision: number;isSeedFixed: boolean;loras: GenerateLora[];model: MainModelConfig | null;@@ -62,7 +68,7 @@ export const UpscalePromptFields = memo(}) {const { t } = useTranslation();const { notifications, readPromptDraft } = useUpscaleUiActions();- const negativePromptUsage = upscaleArchitectureFor(model)?.negativePrompt ?? 'always';+ const negativePromptUsage = getNegativePromptUsage(model, capabilitiesRevision);/*** Applies a prompt change that reaches past the prompt text, which Ctrl+Z in the prompt cannot undo, with an Undo@@ -287,6 +293,7 @@ export const UpscalePromptFields = memo(},(previous, next) =>previous.batchCount === next.batchCount &&+ previous.capabilitiesRevision === next.capabilitiesRevision &&previous.isSeedFixed === next.isSeedFixed &&previous.negativePromptHeightPx === next.negativePromptHeightPx &&previous.onPatchPromptDraft === next.onPatchPromptDraft &&diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsxindex d5c8ac1af5..8d03b87a84 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx@@ -245,14 +245,24 @@ const useModelOnlyPlanNote = (nativeScale: number | null, scale: number): string: t('widgets.upscale.nativeScalePasses', { count: plan.passes, native: nativeScale });};+/** The result's size. Refine floors it to the served grid; the revision is an argument for the reason `getFieldErrors` gives. */+const getOutputDimensions = (+ inputImage: NonNullable<UpscaleWidgetValues['inputImage']>,+ values: Pick<UpscaleWidgetValues, 'mode' | 'model' | 'scale' | 'upscaleModel'>,+ _capabilitiesRevision: number+) => getUpscaleOutputDimensions(inputImage, values);+const UpscaleOutputPreflight = memo(function UpscaleOutputPreflight({+ capabilitiesRevision,inputImage,mode,model,scale,upscaleModel,- }: Pick<UpscaleWidgetValues, 'inputImage' | 'mode' | 'model' | 'scale' | 'upscaleModel'>) {+ }: Pick<UpscaleWidgetValues, 'inputImage' | 'mode' | 'model' | 'scale' | 'upscaleModel'> & {+ capabilitiesRevision: number;+ }) {const { t } = useTranslation();// Refine's detail pass resizes to Scale whatever the upscaler does, so only Model only explains the upscaler.const nativeScale = mode === 'model-only' ? getSpandrelNativeScale(upscaleModel) : null;@@ -262,7 +272,7 @@ const UpscaleOutputPreflight = memo(return null;}- const output = getUpscaleOutputDimensions(inputImage, { mode, model, scale, upscaleModel });+ const output = getOutputDimensions(inputImage, { mode, model, scale, upscaleModel }, capabilitiesRevision);const outputMegapixels = (output.width * output.height) / 1_000_000;const isLargeOutput = outputMegapixels >= LARGE_OUTPUT_MEGAPIXELS;@@ -366,10 +376,12 @@ const UpscaleOutputPreflight = memo();},(previous, next) =>+ previous.capabilitiesRevision === next.capabilitiesRevision &&previous.scale === next.scale &&previous.mode === next.mode &&- // The grid comes from the architecture, so another model of the same base changes nothing.+ // The grid is served per base and variant, so another model of both changes nothing.previous.model?.base === next.model?.base &&+ previous.model?.variant === next.model?.variant &&getSpandrelNativeScale(previous.upscaleModel) === getSpandrelNativeScale(next.upscaleModel) &&areInputImagesEquivalent(previous.inputImage, next.inputImage));@@ -730,6 +742,7 @@ export const UpscaleWidgetView = ({ instance }: { instance?: { id: string } }) =<Stack gap="2.5"><UpscaleImageField inputImage={values.inputImage} onChange={set.inputImage} /><UpscaleOutputPreflight+ capabilitiesRevision={capabilitiesRevision}inputImage={values.inputImage}mode={values.mode}model={values.model}@@ -846,6 +859,7 @@ export const UpscaleWidgetView = ({ instance }: { instance?: { id: string } }) =><UpscalePromptFieldsbatchCount={values.batchCount}+ capabilitiesRevision={capabilitiesRevision}isSeedFixed={values.seedMode === 'fixed'}loras={values.loras}model={values.model}diff --git a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.jsonindex 5b8157a0bb..0072ed9c0b 100644--- a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json+++ b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json@@ -62,7 +62,7 @@{"s":"users-guide/models/local-models/flux-3","t":"FLUX.3","d":"Generate and edit images with FLUX.3 Image Klein (step-distilled) and Klein Base, including editing with up to ten reference images, LoRAs, layout boxes from Canvas regional guidance and the GGUF, single-file and quantized builds.","c":2,"h":[["license","License"],["hardware","Hardware"],["speed-and-quality-by-build","Speed and quality by build"],["installing","Installing"],["quantized-single-files","Quantized single files"],["reference-images","Reference images"],["loras","LoRAs"],["canvas","Canvas"],["layout-boxes-from-regional-guidance","Layout boxes from regional guidance"],["layout-and-box-edits-in-the-prompt","Layout and box edits in the prompt"],["prompt-upsampler-model","Prompt upsampler model"],["prompt-upsampler-in-generation","Prompt upsampler in generation"],["what-the-upsampler-sees","What the upsampler sees"],["metadata-and-recall","Metadata and recall"],["repeatability-and-cost","Repeatability and cost"],["fidelity-to-the-reference","Fidelity to the reference"],["pid-super-resolution-decode","PiD super-resolution decode"],["workflow-nodes","Workflow nodes"]]},{"s":"users-guide/models/local-models/ideogram4","t":"Ideogram 4","d":"Generate images with the Ideogram 4 text-to-image models.","c":2,"h":[["ideogram-4","Ideogram 4"],["license","License"],["installing-ideogram-4","Installing Ideogram 4"],["memory-use-during-generation","Memory use during generation"],["prompting-ideogram-4","Prompting Ideogram 4"],["generation-settings","Generation settings"],["lora","LoRA"]]},{"s":"users-guide/models/local-models/krea-2","t":"Krea-2","d":"Generate images with the Krea-2 text-to-image models (Turbo and Raw), including the GGUF / single-file workflow, the conditioning enhancers, training-free style reference, edit LoRAs with reference images and Control LoRAs.","c":2,"h":[["license","License"],["hardware","Hardware"],["installing","Installing"],["qwen3-vl-gguf-encoders","Qwen3-VL GGUF encoders"],["conditioning-enhancers","Conditioning enhancers"],["multiple-conditionings","Multiple conditionings"],["style-reference","Style reference"],["lora","LoRA"],["edit-loras-and-reference-images","Edit LoRAs and reference images"],["in-the-generate-panel-and-on-the-canvas","In the Generate panel and on the Canvas"],["in-the-workflow-editor","In the workflow editor"],["reference-kv-cache","Reference K/V cache"],["control-lora","Control LoRA"],["on-the-canvas","On the Canvas"],["in-the-workflow-editor-1","In the workflow editor"],["attention-backend","Attention backend"]]},-{"s":"users-guide/models/local-models/moss-image","t":"MOSS-Image","d":"Generate and edit images with OpenMOSS's MOSS-Image Base and SFT, from the Diffusers pipelines or a single-file transformer, including JSON layout prompts, layouts from canvas regions and a prompt enhancer.","c":2,"h":[["license","License"],["hardware","Hardware"],["installing","Installing"],["transformer-formats","Transformer formats"],["generation-settings","Generation settings"],["skip-layers","Skip layers"],["prompting","Prompting"],["json-layouts","JSON layouts"],["layout-with-canvas-regions","Layout with canvas regions"],["prompt-enhancer","Prompt enhancer"],["lora","LoRA"],["limitations","Limitations"],["workflow-nodes","Workflow nodes"]]},+{"s":"users-guide/models/local-models/moss-image","t":"MOSS-Image","d":"Generate and edit images with OpenMOSS's MOSS-Image Base and SFT, from the Diffusers pipelines or a single-file transformer, including JSON layout prompts, layouts from canvas regions and a prompt enhancer.","c":2,"h":[["license","License"],["hardware","Hardware"],["installing","Installing"],["transformer-formats","Transformer formats"],["generation-settings","Generation settings"],["skip-layers","Skip layers"],["prompting","Prompting"],["json-layouts","JSON layouts"],["layout-with-canvas-regions","Layout with canvas regions"],["prompt-enhancer","Prompt enhancer"],["lora","LoRA"],["upscaling","Upscaling"],["limitations","Limitations"],["workflow-nodes","Workflow nodes"]]},{"s":"users-guide/models/local-models/qwen-image","t":"Qwen Image","d":"Generate and edit images with the Qwen Image 2512 text-to-image model and the Qwen Image Edit 2511 reference-image editing model, including GGUF and fp8 installs, the Lightning LoRAs and the Fun and InstantX ControlNet Unions.","c":2,"h":[["license","License"],["hardware","Hardware"],["installing","Installing"],["generation-settings","Generation settings"],["lightning-loras-4-and-8-steps","Lightning LoRAs (4 and 8 steps)"],["image-editing-with-reference-images","Image editing with reference images"],["lora","LoRA"],["controlnet","ControlNet"],["pid-super-resolution-decode","PiD super-resolution decode"],["workflow-nodes","Workflow nodes"]]},{"s":"users-guide/models/local-models/qwen-image-2-1","t":"Qwen-Image-2.1","d":"Generate images with Qwen-Image-2.1 and its 8-step Turbo variant, from the Diffusers folders, a GGUF or an int8 transformer, including transparent (RGBA) output.","c":2,"h":[["qwen-image-21","Qwen-Image-2.1"],["license","License"],["installing-qwen-image-21","Installing Qwen-Image-2.1"],["memory-and-speed","Memory and speed"],["reference-images","Reference images"],["transparent-images","Transparent images"],["loras","LoRAs"],["generation-settings","Generation settings"]]},{"s":"users-guide/models/local-models/sd-3","t":"Stable Diffusion 3.5","d":"Generate images with Stability AI's Stable Diffusion 3.5 Medium and Large models, as Diffusers pipelines or GGUF transformers, including LoRAs, text encoder options and PiD super-resolution decoding.","c":2,"h":[["license","License"],["hardware","Hardware"],["installing","Installing"],["optional-component-overrides","Optional component overrides"],["gguf-transformers","GGUF transformers"],["generation-settings","Generation settings"],["canvas","Canvas"],["lora","LoRA"],["pid-super-resolution-decode","PiD super-resolution decode"],["workflow-editor","Workflow editor"]]},diff --git a/tests/app/invocations/test_upscale_index_clipped_starts.py b/tests/app/invocations/test_upscale_index_clipped_starts.pyindex 570626710e..71d8fd759b 100644--- a/tests/app/invocations/test_upscale_index_clipped_starts.py+++ b/tests/app/invocations/test_upscale_index_clipped_starts.py@@ -4,9 +4,9 @@and `qwen_image_denoise` clip it by step index on a shifted schedule, so the same number enters them farnoisier. The widget therefore does not send them FLUX's start: `getIndexClippedDenoisingStart`(`features/upscale/core/graph.ts`) picks the step whose sigma is nearest the one FLUX would enter at,-from its own copy of each node's schedule and clipping rule (`indexClipping` in `settings.ts`). Krea-2's-shift depends on the variant, which each case records; Qwen Image's schedule is also stretched to end at-its scheduler's terminal sigma.+from Generation's copy of each node's schedule and clipping rule (`getDenoisingStartClipping` in+`features/generation/core/baseGenerationPolicies.ts`). Krea-2's shift depends on the variant, which+each case records; Qwen Image's schedule is also stretched to end at its scheduler's terminal sigma.`upscaleIndexClippedStarts.json`, written by `indexClippedStarts.test.ts` (regenerate with `vitest -u`),records what the widget sends. Each case here drives the real `_run_diffusion` -- the real shift, the