Skip to content

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.

refactor(generation): hand Canvas the family graph facts instead of scanning topology (#10135)

Josh Corbett5089ce9a9864
diff --git a/docs/src/content/docs/contributing/new-model-integration.mdx b/docs/src/content/docs/contributing/new-model-integration.mdx
index bbbf9649e8..b4da032615 100644
--- a/docs/src/content/docs/contributing/new-model-integration.mdx
+++ b/docs/src/content/docs/contributing/new-model-integration.mdx
@@ -761,7 +761,7 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
- ): BackendGraphContract => {
+ ): FamilyGraph => {
const vaeModel = getCompatibleVae(settings, model);
const graph: BackendGraphContract = { edges: [], id: createId('new_model_graph'), nodes: {} };
const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);
@@ -774,7 +774,6 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
vae_model: vaeModel ?? undefined,
});
const posCond = addNode(graph, { id: 'pos_cond', type: 'new_model_text_encoder' });
- const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });
const size = getDenoiseSize(settings, model);
const denoise = addNode(graph, {
cfg_scale: settings.cfgScale,
@@ -792,24 +791,40 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');
addEdge(graph, modelLoader, 'qwen3_vl_encoder', posCond, 'qwen3_vl_encoder');
addEdge(graph, positivePrompt, 'value', posCond, 'prompt');
- addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');
- addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');
- // …the same chain for `negative_prompt` → `neg_cond` → `neg_cond_collect` when useCfg…
+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');
+ // …the same chain for `negative_prompt` → `neg_cond` when useCfg…
addEdge(graph, seed, 'value', denoise, 'seed');
addEdge(graph, denoise, 'latents', output, 'latents');
addEdge(graph, modelLoader, 'vae', output, 'vae');
addMetadata(graph, output, settings, model, 'new_model_txt2img', projectSettings, {
vae: vaeModel ?? undefined,
});
- return graph;
+ return {
+ // Mask-based regional guidance needs conditioning collectors, which this record then names.
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ // Null when the architecture has no image-to-latents node; Canvas then refuses the image modes.
+ latents: { encodeType: 'new_model_i2l', vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
```
- The builder produces the **txt2img** graph only; the canvas grafts img2img, inpaint and outpaint onto it. That depends on these conventions:
- - Node ids `positive_prompt`, `negative_prompt`, `seed`, `model_loader`, `pos_cond`, `neg_cond`, `pos_cond_collect`, `neg_cond_collect` and `denoise_latents`.
- - An output node `canvas_output` whose `vae` input has an edge (`requireVaeSource`).
+ The builder produces the **txt2img** graph only; the canvas grafts img2img, inpaint and outpaint onto it. It grafts onto the nodes the returned `FamilyGraph` (`familyGraph.ts`) names, not onto guessed ids:
+ - `denoise` and `denoiseSize`: the base denoise and the size it works at, which PiD native shrinks to a quarter. Read the size from that node; SD reads it from its noise node.
+ - `latents`: the encode node type and the VAE the graph decodes with, the same source the decode reads. SD families also name the UNet and the fp32 switch.
+ - `conditioning`: the global prompt nodes and collectors regional guidance copies and joins, plus any reference-image collectors the builder wired. Mask-based regional guidance requires this record to be non-null.
+ - `layoutPrompt`: the node a layout architecture places regions on.
+
+ It still depends on these conventions:
+ - Node ids `positive_prompt`, `negative_prompt` and `seed`.
+ - An output node `canvas_output`.
- `addDecodeOutput` if the architecture supports PiD decoding, otherwise `addImageOutputNode`.
+ `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.
+
Validation that only one architecture needs belongs in `getModelFamilyValidationReasons` (`baseGenerationPolicies.ts`).
4. **Component pickers** (encoder, VAE, Diffusers component source)
@@ -827,7 +842,7 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
5. **Canvas**
- - Map the encode node in `CANVAS_I2L_NODE_TYPES` (`canvas/compileCanvasGraph.ts`). The map is `Partial`, so a missing entry only fails at runtime.
+ - 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`.
- Add a case to `BASE_CASES` in `canvas/compileCanvasGraph.test.ts`.
@@ -874,7 +889,8 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
- [ ] `contracts.ts`, `supportedBases.ts` and its test
- [ ] Builder in `graph.ts` and registered in `GRAPH_BUILDERS`
- [ ] Component slot policy (per variant where only one needs it), encoder filters, new settings keys everywhere
-- [ ] `CANVAS_I2L_NODE_TYPES` and `BASE_CASES`
+- [ ] `FamilyGraph` facts checked through `generateGraphCases`, with `latents` and Canvas `BASE_CASES`
+- [ ] Non-null `conditioning` naming the global prompt nodes and collectors for mask-based regional guidance
- [ ] Recall
- [ ] Model registry, labels, `en.json`
- [ ] `SHAPE_OVERRIDES` / `CANDIDATE_VARIANTS` for variant-dependent graphs
@@ -901,7 +917,7 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
### Control and regional guidance
- Control: set `FeaturesFacet.control_kinds`. Add the config (`configs/controlnet.py`, base class `ControlNet_Checkpoint_Config_Base`) and the node. In webv2, update `canvas/controlValidation.ts`, `canvas/addControlLayers.ts` and `src/workbench/widgets/layers/controlModelOptions.ts`.
-- Regional guidance: set `FeaturesFacet.supports_regional_guidance` and honor the conditioning `mask` in the denoise node. In webv2, update `canvas/addRegionalGuidance.ts`.
+- Regional guidance: set `FeaturesFacet.supports_regional_guidance` and honor the conditioning `mask` in the denoise node. In webv2, update `canvas/addRegionalGuidance.ts`. For mask-based regions, the builder must also return non-null `FamilyGraph.conditioning` naming the global prompt nodes and the collectors they join. Layout-based regions instead name `FamilyGraph.layoutPrompt`. Cover the new wiring through `generateGraphCases` and the `family graph facts` tests in `graph.test.ts`.
### PiD decoding
@@ -1074,9 +1090,9 @@ For **img2img, inpaint and outpaint**, add:
- invokeai
- app/invocations/vae
- new_model_image_to_latents.py
- - frontend/webv2/src/features/generation/core/canvas
- - compileCanvasGraph.ts `CANVAS_I2L_NODE_TYPES`
- - compileCanvasGraph.test.ts `BASE_CASES`
+ - frontend/webv2/src/features/generation/core
+ - graph.ts the builder's `latents`
+ - canvas/compileCanvasGraph.test.ts `BASE_CASES`
</FileTree>
---
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts
index 2c7870924e..ac97a24d67 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import type { AddControlLayersOptions, ControlLayerGraphInput, ControlModelIdentifier } from './addControlLayers';
-import { addControlLayers, CONTROL_DENOISE_NODE_ID, isControlKindSupportedForBase } from './addControlLayers';
+import { addControlLayers, isControlKindSupportedForBase } from './addControlLayers';
interface TestGraph {
id: string;
@@ -41,11 +41,14 @@ const layer = (overrides: Partial<ControlLayerGraphInput> = {}): ControlLayerGra
...overrides,
});
+// Cast: TestGraph is structurally the BackendGraphContract shape addControlLayers needs.
+const addTo = (graph: TestGraph, options: Omit<AddControlLayersOptions, 'denoise'>) =>
+ addControlLayers(graph as never, { ...options, denoise: graph.nodes.denoise_latents });
+
// Convenience to run addControlLayers against a fresh graph.
-const run = (options: AddControlLayersOptions) => {
+const run = (options: Omit<AddControlLayersOptions, 'denoise'>) => {
const graph = baseGraph();
- // Cast: TestGraph is structurally the BackendGraphContract shape addControlLayers needs.
- addControlLayers(graph as never, options);
+ addTo(graph, options);
return graph;
};
@@ -98,12 +101,6 @@ describe('isControlKindSupportedForBase', () => {
});
});
-describe('CONTROL_DENOISE_NODE_ID', () => {
- it('is the deterministic denoise node id', () => {
- expect(CONTROL_DENOISE_NODE_ID).toBe('denoise_latents');
- });
-});
-
describe('addControlLayers — controlnet on sd-1', () => {
it('creates a controlnet node with exact fields and wires the collector to denoise.control', () => {
const m = model('sd-1');
@@ -454,7 +451,7 @@ describe('addControlLayers — Qwen-Image control', () => {
const combine = { id: 'combine', type: 'mask_combine' };
graph.nodes.resize = resize;
graph.nodes.combine = combine;
- addControlLayers(graph as never, {
+ addTo(graph, {
base: 'qwen-image',
inpaint: { image: { field: 'image', node: resize }, mask: { field: 'image', node: combine } },
layers: [qwenLayer('Q1')],
@@ -786,12 +783,3 @@ describe('addControlLayers — unsupported kind rejected', () => {
expect(() => run({ base: 'sd-1', layers: [layer({ weight: Number.NaN })] })).toThrow(/invalid_adapter_values/);
});
});
-
-describe('addControlLayers — missing denoise node', () => {
- it('throws when the base graph has no denoise node', () => {
- const graph: TestGraph = { id: 'g', nodes: {}, edges: [] };
- expect(() => addControlLayers(graph as never, { base: 'sd-1', layers: [layer()] })).toThrow(
- /missing the denoise node/
- );
- });
-});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts
index 25a7a384ea..0403d3a32f 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.ts
@@ -10,9 +10,6 @@ import type { ControlAdapterKind } from './controlValidation';
import { createControlValidationSequence } from './controlValidation';
-/** The deterministic denoise node id every canvas base graph uses. */
-export const CONTROL_DENOISE_NODE_ID = 'denoise_latents';
-
const LLLITE_COLLECTOR_NODE_ID = 'control_lllite_collector';
/** The control-adapter kinds a control layer can carry. */
@@ -83,6 +80,8 @@ const feedImage = (
export interface AddControlLayersOptions {
/** The main model base — selects the adapter nodes and support. */
base: SupportedGenerateBase;
+ /** The family's base denoise, which every control adapter feeds. */
+ denoise: BackendInvocationContract;
/**
* The main model variant (a FLUX `dev_fill` blocks Control LoRA; a Qwen-Image `edit` blocks its control; FLUX.2's
* control needs `dev`).
@@ -159,11 +158,7 @@ const controlNetNodeType = (base: string): string => (base === 'flux' ? 'flux_co
/** Validate defensively through the shared policy before graph wiring. */
export const addControlLayers = (graph: BackendGraphContract, options: AddControlLayersOptions): void => {
- const { base, inpaint, layers, modelVariant } = options;
- const denoise = graph.nodes[CONTROL_DENOISE_NODE_ID];
- if (!denoise) {
- throw new Error('addControlLayers: base graph is missing the denoise node.');
- }
+ const { base, denoise, inpaint, layers, modelVariant } = options;
let controlNetCollector: BackendInvocationContract | null = null;
let t2iAdapterCollector: BackendInvocationContract | null = null;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts
index 6af63798b0..9fa6f9d272 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts
@@ -171,8 +171,27 @@ const region = (overrides: Partial<RegionalGuidanceInput> = {}): RegionalGuidanc
...overrides,
});
-const run = (graph: TestGraph, options: AddRegionalGuidanceOptions): TestGraph => {
- addRegionalGuidance(graph as never, options);
+type RunOptions = Omit<AddRegionalGuidanceOptions, 'conditioning' | 'denoise'> &
+ Partial<Pick<AddRegionalGuidanceOptions, 'conditioning'>>;
+
+/** The facts a family builder hands out for these graphs: the global conditioning nodes the fixture created. */
+const conditioningOf = (graph: TestGraph): AddRegionalGuidanceOptions['conditioning'] => ({
+ fluxReduxCollector: null,
+ ipAdapterCollector: null,
+ negative:
+ graph.nodes.neg_cond && graph.nodes.neg_cond_collect
+ ? { collector: graph.nodes.neg_cond_collect, node: graph.nodes.neg_cond }
+ : null,
+ positive: graph.nodes.pos_cond,
+ positiveCollector: graph.nodes.pos_cond_collect,
+});
+
+const run = (graph: TestGraph, options: RunOptions): TestGraph => {
+ addRegionalGuidance(graph as never, {
+ conditioning: conditioningOf(graph),
+ denoise: graph.nodes.denoise_latents,
+ ...options,
+ });
return graph;
};
@@ -417,6 +436,35 @@ describe('addRegionalGuidance — SD1', () => {
expect(collectorEdge).toBeDefined();
expect(hasEdge(g, 'ip_adapter_ref1', 'ip_adapter', collectorEdge!.source.node_id, 'item')).toBe(true);
});
+ it('joins the ip_adapter collector the builder already feeds the denoise from', () => {
+ const graph = sdBaseGraph();
+ const builderCollector = { id: 'ip_adapter_collector', type: 'collect' };
+ graph.nodes[builderCollector.id] = builderCollector;
+ const g = run(graph, {
+ base: 'sd-1',
+ conditioning: { ...conditioningOf(graph), ipAdapterCollector: builderCollector },
+ regions: [
+ region({
+ referenceImages: [
+ {
+ beginEndStepPct: [0, 1],
+ clipVisionModel: 'ViT-H',
+ id: 'ref1',
+ imageName: 'ref.png',
+ method: 'full',
+ model: ipModel('sd-1'),
+ type: 'ip_adapter',
+ weight: 0.8,
+ },
+ ],
+ }),
+ ],
+ });
+
+ expect(hasEdge(g, 'ip_adapter_ref1', 'ip_adapter', 'ip_adapter_collector', 'item')).toBe(true);
+ expect(g.nodes.regional_ip_adapter_collector).toBeUndefined();
+ expect(g.edges.filter((e) => e.destination.field === 'ip_adapter')).toEqual([]);
+ });
});
describe('addRegionalGuidance — SD2', () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
index 3d105efd8f..c1419b5832 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
@@ -1,4 +1,5 @@
import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';
+import type { FamilyConditioning } from '@features/generation/core/familyGraph';
import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
import { getArchitectureFeatures } from '@features/generation/core/architectureCapabilities';
@@ -8,14 +9,6 @@ import { getEffectivePositivePrompt, unwrapPromptFence } from '@features/generat
import type { Rect } from './types';
-/** The deterministic denoise node id every canvas base graph uses. */
-const DENOISE_NODE_ID = 'denoise_latents';
-/** The deterministic global positive/negative conditioning + collector node ids. */
-const POS_COND_ID = 'pos_cond';
-const NEG_COND_ID = 'neg_cond';
-const POS_COND_COLLECT_ID = 'pos_cond_collect';
-const NEG_COND_COLLECT_ID = 'neg_cond_collect';
-
/** The bases whose text encoder accepts a region mask and whose denoiser accepts a conditioning list. */
export type MaskRegionalGuidanceBase = 'sd-1' | 'sd-2' | 'sdxl' | 'flux' | 'flux2' | 'krea-2' | 'z-image' | 'anima';
/** The bases that read regions as boxes of a structured layout prompt; a mask contributes only its bounds. */
@@ -271,6 +264,10 @@ export interface RegionalGuidanceInput {
/** Options for {@link addRegionalGuidance}. */
export interface AddRegionalGuidanceOptions {
base: MaskRegionalGuidanceBase;
+ /** The family's global conditioning the regions copy encoders from and join. */
+ conditioning: FamilyConditioning;
+ /** The family's base denoise, which regional reference images feed. */
+ denoise: BackendInvocationContract;
modelVariant?: string | null;
regions: readonly RegionalGuidanceInput[];
/** Applies model-specific transforms before a regional positive conditioning is collected. */
@@ -344,23 +341,14 @@ const copyEncoderEdges = (
}
};
-/** Resolves (or lazily creates) the collector feeding `denoise.<field>`, with a stable fallback id. */
-const resolveDenoiseCollector = (
+/** Creates a collector feeding `denoise.<field>`, for when the builder wired none. */
+const addDenoiseCollector = (
graph: BackendGraphContract,
denoise: BackendInvocationContract,
denoiseField: string,
- fallbackId: string
+ id: string
): BackendInvocationContract => {
- const existing = graph.edges.find(
- (edge) => edge.destination.node_id === denoise.id && edge.destination.field === denoiseField
- );
- if (existing) {
- const node = graph.nodes[existing.source.node_id];
- if (node) {
- return node;
- }
- }
- const collector = addNode(graph, { id: fallbackId, type: 'collect' });
+ const collector = addNode(graph, { id, type: 'collect' });
addEdge(graph, collector, 'collection', denoise, denoiseField);
return collector;
};
@@ -384,23 +372,14 @@ const addRegionalConditioning = (
/** Masked conditioning for mask bases. Inputs must be prevalidated and gated by regional support. */
export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegionalGuidanceOptions): void => {
- const { base, modelVariant, regions, transformRegionalPositiveConditioning } = options;
- const denoise = graph.nodes[DENOISE_NODE_ID];
- if (!denoise) {
- throw new Error('addRegionalGuidance: base graph is missing the denoise node.');
- }
- const posCondCollect = graph.nodes[POS_COND_COLLECT_ID];
- if (!posCondCollect) {
- throw new Error('addRegionalGuidance: base graph is missing the positive conditioning collector.');
- }
- const negCondCollect = graph.nodes[NEG_COND_COLLECT_ID] ?? null;
+ const { base, conditioning, denoise, modelVariant, regions, transformRegionalPositiveConditioning } = options;
+ const { negative, positive, positiveCollector } = conditioning;
const support = getRegionalGuidanceSupport(base);
if (!support) {
throw new Error(`addRegionalGuidance: ${base} has no regional guidance path.`);
}
- let ipAdapterCollector: BackendInvocationContract | null = null;
- let fluxReduxCollector: BackendInvocationContract | null = null;
+ let { fluxReduxCollector, ipAdapterCollector } = conditioning;
for (const region of regions) {
const maskToTensor = addNode(graph, {
@@ -417,29 +396,29 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg
modelVariant,
`rg_pos_cond_${region.id}`,
region.positivePrompt,
- POS_COND_ID
+ positive.id
);
addEdge(graph, maskToTensor, 'mask', posCond, 'mask');
const conditioningSource = transformRegionalPositiveConditioning?.(posCond, region.id) ?? posCond;
- addEdge(graph, conditioningSource, 'conditioning', posCondCollect, 'item');
+ addEdge(graph, conditioningSource, 'conditioning', positiveCollector, 'item');
}
// Negative prompt → negative collector.
- if (region.negativePrompt && support.negativePrompt && negCondCollect) {
+ if (region.negativePrompt && support.negativePrompt && negative) {
const negCond = addRegionalConditioning(
graph,
base,
modelVariant,
`rg_neg_cond_${region.id}`,
region.negativePrompt,
- NEG_COND_ID
+ negative.node.id
);
addEdge(graph, maskToTensor, 'mask', negCond, 'mask');
- addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');
+ addEdge(graph, negCond, 'conditioning', negative.collector, 'item');
}
// Auto-negative encodes positive text over the inverted region mask.
- if (region.autoNegative && region.positivePrompt && support.autoNegative && negCondCollect) {
+ if (region.autoNegative && region.positivePrompt && support.autoNegative && negative) {
const invert = addNode(graph, { id: `rg_invert_mask_${region.id}`, type: 'invert_tensor_mask' });
addEdge(graph, maskToTensor, 'mask', invert, 'mask');
const inverted = addRegionalConditioning(
@@ -448,18 +427,16 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg
modelVariant,
`rg_pos_cond_inverted_${region.id}`,
region.positivePrompt,
- POS_COND_ID
+ positive.id
);
addEdge(graph, invert, 'mask', inverted, 'mask');
- addEdge(graph, inverted, 'conditioning', negCondCollect, 'item');
+ addEdge(graph, inverted, 'conditioning', negative.collector, 'item');
}
// Reference images (mask-scoped): ip_adapter on SD, flux_redux on FLUX.
for (const ref of region.referenceImages) {
if (ref.type === 'ip_adapter' && support.referenceImages === 'ip_adapter') {
- if (!ipAdapterCollector) {
- ipAdapterCollector = resolveDenoiseCollector(graph, denoise, 'ip_adapter', 'regional_ip_adapter_collector');
- }
+ ipAdapterCollector ??= addDenoiseCollector(graph, denoise, 'ip_adapter', 'regional_ip_adapter_collector');
const node = addNode(graph, {
begin_step_percent: ref.beginEndStepPct[0],
clip_vision_model: ref.clipVisionModel,
@@ -474,14 +451,12 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg
addEdge(graph, maskToTensor, 'mask', node, 'mask');
addEdge(graph, node, 'ip_adapter', ipAdapterCollector, 'item');
} else if (ref.type === 'flux_redux' && support.referenceImages === 'flux_redux') {
- if (!fluxReduxCollector) {
- fluxReduxCollector = resolveDenoiseCollector(
- graph,
- denoise,
- 'redux_conditioning',
- 'regional_flux_redux_collector'
- );
- }
+ fluxReduxCollector ??= addDenoiseCollector(
+ graph,
+ denoise,
+ 'redux_conditioning',
+ 'regional_flux_redux_collector'
+ );
const node = addNode(graph, {
downsampling_factor: ref.settings.downsampling_factor,
id: `flux_redux_${ref.id}`,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
index ae0167371a..cb9158299c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
@@ -2219,6 +2219,56 @@ describe('compileCanvasGraph — regional guidance', () => {
expect(getEdge(backendGraph, 'pos_cond_collect', 'item')?.source.node_id).toBe('pos_cond');
});
+ it('joins regional FLUX Redux references to the collector the builder feeds from the global ones', () => {
+ const reduxModel = { base: 'flux', key: 'redux', name: 'FLUX Redux', type: 'flux_redux' } as const;
+ const { backendGraph } = compile(fluxModel, 'txt2img', {
+ regionalGuidance: [
+ region('r1', {
+ referenceImages: [
+ {
+ id: 'regional',
+ imageName: 'regional-redux.png',
+ model: reduxModel,
+ settings: { downsampling_factor: 1, weight: 1 },
+ type: 'flux_redux',
+ },
+ ],
+ }),
+ ],
+ settings: {
+ referenceImages: [
+ {
+ config: {
+ image: { original: { image: { height: 512, image_name: 'global-redux.png', width: 512 } } },
+ imageInfluence: 'medium',
+ model: reduxModel,
+ type: 'flux_redux',
+ },
+ id: 'global',
+ isEnabled: true,
+ },
+ ],
+ },
+ });
+ const reduxInputs = backendGraph.edges.filter(
+ (edge) => edge.destination.node_id === 'denoise_latents' && edge.destination.field === 'redux_conditioning'
+ );
+
+ expect(reduxInputs).toHaveLength(1);
+ const builderCollector = reduxInputs[0]!.source.node_id;
+ expect(builderCollector).toMatch(/^flux_redux_collector_/);
+ expect(backendGraph.nodes.regional_flux_redux_collector).toBeUndefined();
+ expect(getEdge(backendGraph, builderCollector, 'item')).toBeDefined();
+ expect(
+ backendGraph.edges.some(
+ (edge) =>
+ edge.source.node_id === 'flux_redux_regional' &&
+ edge.source.field === 'redux_cond' &&
+ edge.destination.node_id === builderCollector
+ )
+ ).toBe(true);
+ });
+
it('grafts FLUX.2 [dev] regions through Mistral conditioning', () => {
const { backendGraph } = compile(flux2DevModel, 'txt2img', { regionalGuidance: [region('r1')] });
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
index 2782d12212..d2df20c10f 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 { SupportedGenerateBase } from '@features/generation/core/baseGenerationPolicies';
import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';
+import type { FamilyGraph, FamilyLatentSpace } from '@features/generation/core/familyGraph';
import type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';
import {
@@ -17,7 +18,7 @@ import {
isExternalGenerationMode,
isExternalTextOnlyCanvasModel,
} from '@features/generation/core/externalProvider';
-import { buildExternalGraph, findVaeSource, GRAPH_BUILDERS } from '@features/generation/core/graph';
+import { buildExternalGraph, getFamilyGraphBuilder } from '@features/generation/core/graph';
import {
addEdge,
addNode,
@@ -58,29 +59,6 @@ import {
import { type CanvasSize, resolveCanvasProcessingSize } from './canvasProcessingSize';
import { isAnimaInpaintAdapterModel } from './controlValidation';
-/** Map bases to encode nodes; SD families share i2l. */
-const CANVAS_I2L_NODE_TYPES: Partial<Record<SupportedGenerateBase, string>> = {
- 'sd-1': 'i2l',
- 'sd-2': 'i2l',
- sdxl: 'i2l',
- 'sd-3': 'sd3_i2l',
- flux: 'flux_vae_encode',
- flux2: 'flux2_vae_encode',
- // FLUX.3 encodes with the FLUX.2 VAE.
- flux3: 'flux2_vae_encode',
- cogview4: 'cogview4_i2l',
- 'qwen-image': 'qwen_image_i2l',
- 'z-image': 'z_image_i2l',
- // Krea-2 shares the Qwen-Image VAE, so it encodes with that family's node too.
- 'krea-2': 'qwen_image_i2l',
- 'qwen-image-2-1': 'qwen_image_2_1_i2l',
- anima: 'anima_i2l',
- // MOSS-Image denoises in the FLUX.2 VAE's raw latent layout, so it encodes with that family's node.
- 'moss-image': 'flux2_vae_encode',
- wan: 'wan_i2l',
- // Ideogram lacks an encode node; reject these modes with an actionable error.
-};
-
/**
* SD-3, FLUX, FLUX.2, FLUX.3 and MOSS-Image use start = 1 - strength^0.2; MOSS-Image clips its shifted schedule in
* sigma space like FLUX.2. FLUX Fill always starts at 0; other bases use 1 - strength.
@@ -241,37 +219,6 @@ const withProcessingDimensions = (settings: GenerateSettings, processingSize: Ca
width: processingSize.width,
});
-/** Locates the node + field feeding a decode/denoise input edge (e.g. `canvas_output.vae`). */
-const findEdgeSource = (
- graph: BackendGraphContract,
- destNodeId: string,
- destField: string
-): { node: BackendInvocationContract; field: string } | null => {
- const edge = graph.edges.find(
- (candidate) => candidate.destination.node_id === destNodeId && candidate.destination.field === destField
- );
- const node = edge ? graph.nodes[edge.source.node_id] : undefined;
- return edge && node ? { field: edge.source.field, node } : null;
-};
-
-/** Resolves the VAE source the base graph decodes with, for the encode side (throws if absent). */
-const requireVaeSource = (graph: BackendGraphContract): { node: BackendInvocationContract; field: string } => {
- const source = findVaeSource(graph);
- if (!source) {
- throw new Error('Canvas generation could not resolve a VAE source in the base graph.');
- }
- return source;
-};
-
-/** The size the base graph denoises at: the `noise` node carries it for SD families, the denoise node elsewhere. */
-const getDenoiseSize = (graph: BackendGraphContract, denoise: BackendInvocationContract): CanvasSize => {
- const { height, width } = graph.nodes.noise ?? denoise;
- if (typeof width !== 'number' || typeof height !== 'number') {
- throw new TypeError('Canvas generation could not read the denoise size from the base graph.');
- }
- return { height, width };
-};
-
const findMetadataNode = (graph: BackendGraphContract): BackendInvocationContract | undefined =>
Object.values(graph.nodes).find((node) => node.type === 'core_metadata');
@@ -445,28 +392,27 @@ const setMetadataMode = (graph: BackendGraphContract, mode: string, strength: nu
}
};
-/** Only the SD `i2l` node supports precision and color compensation settings. */
-const isSdI2l = (i2lType: string): boolean => i2lType === 'i2l';
-
-/** Adds the base-appropriate image-to-latents encode node fed by `imageName`. */
+/** Adds the family's image-to-latents encode node fed by `imageName`. */
const addEncodeNode = (
graph: BackendGraphContract,
- i2lType: string,
+ latents: FamilyLatentSpace,
settings: GenerateSettings,
imageName: string | null
): BackendInvocationContract =>
addNode(graph, {
id: 'canvas_i2l',
...(imageName ? { image: { image_name: imageName } } : {}),
- type: i2lType,
- ...(isSdI2l(i2lType)
- ? {
- color_compensation: settings.colorCompensation ? 'SDXL' : 'None',
- fp32: settings.vaePrecision === 'fp32',
- }
- : {}),
+ type: latents.encodeType,
+ ...(latents.fp32 === undefined ? {} : { fp32: latents.fp32 }),
+ ...(latents.encodeType === 'i2l' ? { color_compensation: settings.colorCompensation ? 'SDXL' : 'None' } : {}),
});
+/** Encodes with the VAE the family decodes with and feeds the latents to its denoise. */
+const connectEncode = (family: FamilyGraph, latents: FamilyLatentSpace, encode: BackendInvocationContract): void => {
+ addEdge(family.graph, latents.vae.node, latents.vae.field, encode, 'vae');
+ addEdge(family.graph, encode, 'latents', family.denoise, 'latents');
+};
+
const addInputResizeNode = (
graph: BackendGraphContract,
id: string,
@@ -482,50 +428,38 @@ const addInputResizeNode = (
width: processingSize.width,
});
-/** Resolves the encode node type for a supported base (throws otherwise). */
-const requireI2lType = (model: GenerateModelConfig): string => {
- const i2lType = CANVAS_I2L_NODE_TYPES[model.base as SupportedGenerateBase];
- if (!i2lType) {
+/** The family's latent space, for the image modes that encode into it (throws when the family has none). */
+const requireLatents = (family: FamilyGraph, model: GenerateModelConfig): FamilyLatentSpace => {
+ if (!family.latents) {
throw new Error(`Canvas generation is not supported for ${model.name}.`);
}
- return i2lType;
-};
-
-/** Resolves the base graph's denoise node (throws if absent). */
-const requireDenoise = (graph: BackendGraphContract): BackendInvocationContract => {
- const denoise = graph.nodes.denoise_latents;
- if (!denoise) {
- throw new Error('Canvas generation could not find the denoise node in the base graph.');
- }
- return denoise;
+ return family.latents;
};
/** Grafts the image-to-latents encode path onto a freshly built base graph (img2img). */
const graftImageToImage = (
- graph: BackendGraphContract,
+ family: FamilyGraph,
model: GenerateModelConfig,
settings: GenerateSettings,
compositeImageName: string,
strength: number,
bbox: CompileCanvasGraphInput['bbox']
): void => {
- const i2lType = requireI2lType(model);
- const denoise = requireDenoise(graph);
- const vaeSource = requireVaeSource(graph);
+ const { graph } = family;
+ const latents = requireLatents(family, model);
// The source image is encoded at the size the graph denoises at. That is the processing size, except under
// native PiD, which denoises at a quarter of it and decodes straight back up (legacy `addPidImageToImageNative`).
- const encodeSize = getDenoiseSize(graph, denoise);
+ const encodeSize = family.denoiseSize;
const needsResize = !sizesMatch(bbox, encodeSize);
- const encode = addEncodeNode(graph, i2lType, settings, needsResize ? null : compositeImageName);
+ const encode = addEncodeNode(graph, latents, settings, needsResize ? null : compositeImageName);
if (needsResize) {
const resize = addInputResizeNode(graph, 'canvas_resize_initial_to_processing', compositeImageName, encodeSize);
addEdge(graph, resize, 'image', encode, 'image');
}
- addEdge(graph, vaeSource.node, vaeSource.field, encode, 'vae');
- addEdge(graph, encode, 'latents', denoise, 'latents');
- setCanvasDenoisingRange(denoise, model, settings, strength);
+ connectEncode(family, latents, encode);
+ setCanvasDenoisingRange(family.denoise, model, settings, strength);
setMetadataMode(graph, 'img2img', strength);
};
@@ -614,13 +548,11 @@ const addAnimaInpaintAdapter = (
* inpaint-conditioned adapters read.
*/
const graftMaskTail = (
- graph: BackendGraphContract,
+ family: FamilyGraph,
args: {
model: GenerateModelConfig;
settings: GenerateSettings;
- i2lType: string;
- denoise: BackendInvocationContract;
- vaeSource: { node: BackendInvocationContract; field: string };
+ latents: FamilyLatentSpace;
initialImageName: string;
compositing: CanvasCompositingSettings;
destination: CompileCanvasGraphInput['destination'];
@@ -634,7 +566,8 @@ const graftMaskTail = (
adapterImageEdge?: { node: BackendInvocationContract; field: string };
}
): CanvasInpaintSources => {
- const { compositing, denoise, destination, i2lType, initialImageName, model, settings, vaeSource } = args;
+ const { compositing, destination, initialImageName, latents, model, settings } = args;
+ const { denoise, graph } = family;
const needsResize = !sizesMatch(args.bbox, args.processingSize);
// The base decoder, until the composited output below takes over canvas_output from it.
@@ -646,7 +579,7 @@ const graftMaskTail = (
const gradientMask = addNode(graph, {
coherence_mode: compositing.coherenceMode,
edge_radius: compositing.coherenceEdgeSize,
- fp32: isSdI2l(i2lType) ? settings.vaePrecision === 'fp32' : false,
+ fp32: latents.fp32 ?? false,
id: 'create_gradient_mask',
...(args.gradientImageEdge ? {} : { image: { image_name: initialImageName } }),
minimum_denoise: compositing.coherenceMinDenoise,
@@ -660,11 +593,10 @@ const graftMaskTail = (
if (args.gradientImageEdge) {
addEdge(graph, args.gradientImageEdge.node, args.gradientImageEdge.field, gradientMask, 'image');
}
- addEdge(graph, vaeSource.node, vaeSource.field, gradientMask, 'vae');
+ addEdge(graph, latents.vae.node, latents.vae.field, gradientMask, 'vae');
// The optional UNet edge only applies to SD-family models (legacy `isMainModelWithoutUnet`).
- const unetSource = findEdgeSource(graph, 'denoise_latents', 'unet');
- if (unetSource) {
- addEdge(graph, unetSource.node, unetSource.field, gradientMask, 'unet');
+ if (latents.unet) {
+ addEdge(graph, latents.unet.node, latents.unet.field, gradientMask, 'unet');
}
addEdge(graph, gradientMask, 'denoise_mask', denoise, 'denoise_mask');
@@ -766,15 +698,14 @@ const addNoiseBeforeEncode = (
/** Grafts the inpaint pipeline (content covers the bbox, an inpaint mask restricts it). */
const graftInpaint = (
- graph: BackendGraphContract,
+ family: FamilyGraph,
input: CompileCanvasGraphInput,
compositing: CanvasCompositingSettings,
processingSize: CanvasSize
): CanvasInpaintSources => {
const { model } = input;
- const i2lType = requireI2lType(model);
- const denoise = requireDenoise(graph);
- const vaeSource = requireVaeSource(graph);
+ const { denoise, graph } = family;
+ const latents = requireLatents(family, model);
const initialImageName = input.compositeImageName as string;
const maskImageName = input.maskImageName as string;
const strength = input.strength;
@@ -793,7 +724,7 @@ const graftInpaint = (
? addInputResizeNode(graph, 'canvas_resize_noise_mask_to_processing', input.noiseMaskImageName, processingSize)
: null;
- const encode = addEncodeNode(graph, i2lType, input.settings, null);
+ const encode = addEncodeNode(graph, latents, input.settings, null);
const noiseResult = addNoiseBeforeEncode(
graph,
initialImageName,
@@ -806,25 +737,22 @@ const graftInpaint = (
} else if (noiseResult.imageField) {
encode.image = noiseResult.imageField;
}
- addEdge(graph, vaeSource.node, vaeSource.field, encode, 'vae');
- addEdge(graph, encode, 'latents', denoise, 'latents');
+ connectEncode(family, latents, encode);
- const inpaint = graftMaskTail(graph, {
+ const inpaint = graftMaskTail(family, {
...(initialResize ? { adapterImageEdge: { field: 'image', node: initialResize } } : {}),
bbox: input.bbox,
compositing,
- denoise,
destination: input.destination,
...(initialResize ? { gradientImageEdge: { field: 'image', node: initialResize } } : {}),
...(maskResize
? { gradientMaskEdge: { field: 'image', node: maskResize } }
: { gradientMaskImage: { image_name: maskImageName } }),
- i2lType,
initialImageName,
+ latents,
model,
processingSize,
settings: input.settings,
- vaeSource,
});
setMetadataMode(graph, 'inpaint', strength);
@@ -833,15 +761,14 @@ const graftInpaint = (
/** Grafts the outpaint pipeline (bbox extends past content / has transparent holes). */
const graftOutpaint = (
- graph: BackendGraphContract,
+ family: FamilyGraph,
input: CompileCanvasGraphInput,
compositing: CanvasCompositingSettings,
processingSize: CanvasSize
): CanvasInpaintSources => {
const { model } = input;
- const i2lType = requireI2lType(model);
- const denoise = requireDenoise(graph);
- const vaeSource = requireVaeSource(graph);
+ const { denoise, graph } = family;
+ const latents = requireLatents(family, model);
const initialImageName = input.compositeImageName as string;
const strength = input.strength;
const needsResize = !sizesMatch(input.bbox, processingSize);
@@ -897,28 +824,25 @@ const graftOutpaint = (
? addInputResizeNode(graph, 'canvas_resize_noise_mask_to_processing', input.noiseMaskImageName, processingSize)
: null;
- const encode = addEncodeNode(graph, i2lType, input.settings, null);
+ const encode = addEncodeNode(graph, latents, input.settings, null);
const noiseResult = addNoiseBeforeEncode(graph, initialImageName, input.noiseMaskImageName, infill, noiseMaskResize);
if (noiseResult.edgeFrom) {
addEdge(graph, noiseResult.edgeFrom, 'image', encode, 'image');
}
- addEdge(graph, vaeSource.node, vaeSource.field, encode, 'vae');
- addEdge(graph, encode, 'latents', denoise, 'latents');
+ connectEncode(family, latents, encode);
- const inpaint = graftMaskTail(graph, {
+ const inpaint = graftMaskTail(family, {
adapterImageEdge: { field: 'image', node: infill },
bbox: input.bbox,
compositing,
- denoise,
destination: input.destination,
...(needsResize ? { gradientImageEdge: { field: 'image', node: infill } } : {}),
gradientMaskEdge,
- i2lType,
initialImageName,
+ latents,
model,
processingSize,
settings: input.settings,
- vaeSource,
});
setMetadataMode(graph, 'outpaint', strength);
@@ -978,12 +902,12 @@ const toLayoutElement = (
* (which PiD can shrink below the processing size) and clamped to it. The base graph's `layout_prompt` node assembles
* them with the global prompt at run time; regions the layout cannot place are left out.
*/
-const addMossImageLayoutRegions = (graph: BackendGraphContract, options: AddLayoutRegionsOptions): void => {
- const layoutPrompt = graph.nodes.layout_prompt;
+const addMossImageLayoutRegions = (family: FamilyGraph, options: AddLayoutRegionsOptions): void => {
+ const { layoutPrompt } = family;
if (!layoutPrompt) {
throw new Error('addMossImageLayoutRegions: base graph is missing the layout prompt node.');
}
- const size = getDenoiseSize(graph, requireDenoise(graph));
+ const size = family.denoiseSize;
const scale = { x: size.width / options.bbox.width, y: size.height / options.bbox.height };
// The frame and the boxes come from one size, so they cannot drift apart.
layoutPrompt.width = size.width;
@@ -1036,8 +960,8 @@ const toIdeogram4Region = (
* through `positive_prompt`, and core metadata already records its output. Regions the caption cannot place are left
* out, and without any the graph stays untouched.
*/
-const addIdeogram4Regions = (graph: BackendGraphContract, options: AddLayoutRegionsOptions): void => {
- const captionBuilder = graph.nodes.caption_builder;
+const addIdeogram4Regions = (family: FamilyGraph, options: AddLayoutRegionsOptions): void => {
+ const captionBuilder = family.layoutPrompt;
if (!captionBuilder) {
throw new Error('addIdeogram4Regions: base graph is missing the caption builder node.');
}
@@ -1069,8 +993,8 @@ const toFlux3Region = (region: RegionalGuidanceInput, options: AddLayoutRegionsO
* builder wired reference images, as edit rows for the output; core metadata then records the caption encoded. Regions
* the table cannot place are left out, and without any the graph stays untouched.
*/
-const addFlux3LayoutRegions = (graph: BackendGraphContract, options: AddLayoutRegionsOptions): void => {
- const layoutPrompt = graph.nodes.layout_prompt;
+const addFlux3LayoutRegions = (family: FamilyGraph, options: AddLayoutRegionsOptions): void => {
+ const { graph, layoutPrompt } = family;
if (!layoutPrompt) {
throw new Error('addFlux3LayoutRegions: base graph is missing the layout prompt node.');
}
@@ -1088,7 +1012,7 @@ const addFlux3LayoutRegions = (graph: BackendGraphContract, options: AddLayoutRe
/** Each layout base places its regions through its own prompt node. */
const LAYOUT_REGION_GRAFTS: Record<
LayoutRegionalGuidanceBase,
- (graph: BackendGraphContract, options: AddLayoutRegionsOptions) => void
+ (family: FamilyGraph, options: AddLayoutRegionsOptions) => void
> = {
flux3: addFlux3LayoutRegions,
'ideogram-4': addIdeogram4Regions,
@@ -1149,23 +1073,24 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv
};
}
- const builder = GRAPH_BUILDERS[model.base as SupportedGenerateBase];
+ const builder = getFamilyGraphBuilder(model.base);
if (!builder) {
throw new Error(`Canvas generation is not supported for ${model.name}.`);
}
- const backendGraph = builder(settings, model, outputIsIntermediate, runtimeProjectSettings);
+ const family = builder(settings, model, outputIsIntermediate, runtimeProjectSettings);
+ const backendGraph = family.graph;
const { compositing } = input;
// Validation above guarantees the composite/mask images required per mode.
let inpaint: CanvasInpaintSources | undefined;
if (mode === 'img2img') {
- graftImageToImage(backendGraph, model, settings, compositeImageName as string, strength, bbox);
+ graftImageToImage(family, model, settings, compositeImageName as string, strength, bbox);
} else if (mode === 'inpaint') {
- inpaint = graftInpaint(backendGraph, input, compositing, processingSize);
+ inpaint = graftInpaint(family, input, compositing, processingSize);
} else if (mode === 'outpaint') {
- inpaint = graftOutpaint(backendGraph, input, compositing, processingSize);
+ inpaint = graftOutpaint(family, input, compositing, processingSize);
}
// Every mode accepts already-resolved, separately uploaded control inputs; inpaint and outpaint also hand the
@@ -1173,6 +1098,7 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv
if (input.controlLayers && input.controlLayers.length > 0) {
addControlLayers(backendGraph, {
base: model.base as SupportedGenerateBase,
+ denoise: family.denoise,
inpaint,
layers: input.controlLayers,
modelVariant: model.variant ?? undefined,
@@ -1186,10 +1112,15 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv
const regionalSupport = getRegionalGuidanceSupport(regionalBase);
if (regions.length > 0 && regionalSupport && isRegionalGuidanceSupportedForBase(regionalBase)) {
if (isLayoutRegionalGuidanceBase(regionalBase)) {
- LAYOUT_REGION_GRAFTS[regionalBase](backendGraph, { bbox, layoutKinds: regionalSupport.layoutKinds, regions });
+ LAYOUT_REGION_GRAFTS[regionalBase](family, { bbox, layoutKinds: regionalSupport.layoutKinds, regions });
} else {
+ if (!family.conditioning) {
+ throw new Error(`Regional guidance has no global conditioning to join in the ${model.name} graph.`);
+ }
addRegionalGuidance(backendGraph, {
base: regionalBase,
+ conditioning: family.conditioning,
+ denoise: family.denoise,
modelVariant: model.variant,
regions,
...(regionalBase === 'krea-2'
diff --git a/invokeai/frontend/webv2/src/features/generation/core/familyGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/familyGraph.ts
new file mode 100644
index 0000000000..041f57b989
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/familyGraph.ts
@@ -0,0 +1,56 @@
+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';
+
+/** A node output that feeds an input: the node and its output field. */
+export interface GraphOutput {
+ node: BackendInvocationContract;
+ field: string;
+}
+
+/**
+ * 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.
+ */
+export interface FamilyGraph {
+ graph: BackendGraphContract;
+ /** The base denoise every attachment feeds: latents, denoise mask, control, regional conditioning. */
+ denoise: BackendInvocationContract;
+ /** The size the denoise works at: the requested size, except PiD native denoises at a quarter of it. */
+ denoiseSize: { width: number; height: number };
+ /** The latent space Canvas encodes images into; null when the family has no encode node (Ideogram 4, ERNIE-Image). */
+ latents: FamilyLatentSpace | null;
+ /** The global conditioning regional guidance copies and joins; null where the family has no collectors. */
+ conditioning: FamilyConditioning | null;
+ /** The node a layout base places regions on: MOSS-Image's and FLUX.3's layout prompt, Ideogram 4's caption builder. */
+ layoutPrompt: BackendInvocationContract | null;
+}
+
+export interface FamilyLatentSpace {
+ /** The image-to-latents node type. */
+ encodeType: string;
+ /** The VAE the graph decodes with, override and seamless wrapping included; encodes and masks use the same one. */
+ vae: GraphOutput;
+ /** The UNet the gradient mask reads; SD families only. */
+ unet?: GraphOutput;
+ /** SD encode and gradient-mask nodes carry an fp32 switch; other families' nodes have none. */
+ fp32?: boolean;
+}
+
+export interface FamilyConditioning {
+ /** The global positive conditioning node regional conditioning copies encoder edges from. */
+ positive: BackendInvocationContract;
+ /** The collector feeding the denoise's positive conditioning, which regional positives join. */
+ positiveCollector: BackendInvocationContract;
+ /** The global negative conditioning and its collector; null where the denoise takes no negative collection. */
+ negative: { node: BackendInvocationContract; collector: BackendInvocationContract } | null;
+ /**
+ * The collector the builder already feeds `denoise.ip_adapter` from, when it wired reference images. Only read where
+ * regional references are IP-Adapters (SD families).
+ */
+ ipAdapterCollector: BackendInvocationContract | null;
+ /**
+ * The collector the builder already feeds `denoise.redux_conditioning` from, when it wired FLUX Redux. Only read where
+ * regional references are FLUX Redux (FLUX).
+ */
+ fluxReduxCollector: BackendInvocationContract | null;
+}
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
index fe93501fae..8da4a97049 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@ -16,10 +16,18 @@ import {
getDefaultGenerateSettings,
getGenerationValidationIssues,
isSupportedGenerateModel,
+ type SupportedGenerateBase,
} from './baseGenerationPolicies';
-import { compileGenerateGraph, resolveGenerateSeed } from './graph';
-import { generateGraphCases, satisfiedSettingsFor } from './graphCoverage.testing';
+import { compileGenerateGraph, getFamilyGraphBuilder, GRAPH_BUILDERS, resolveGenerateSeed } from './graph';
+import {
+ fullyFilledSettingsFor,
+ generateGraphCases,
+ satisfiedSettingsFor,
+ tunedSettingsFor,
+} from './graphCoverage.testing';
+import { isPidDecodeNodeType } from './pidGraph';
import { getReferenceImagePromptTags } from './referenceImage';
+import { REFINER_DENOISE_NODE_ID } from './sdxlRefinerGraph';
const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };
const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };
@@ -1223,6 +1231,158 @@ describe('compileGenerateGraph', () => {
});
});
+describe('getFamilyGraphBuilder', () => {
+ it('returns builders for supported bases only, never Object.prototype members', () => {
+ expect(getFamilyGraphBuilder('sdxl')).toBeTypeOf('function');
+ expect(getFamilyGraphBuilder('constructor')).toBeNull();
+ expect(getFamilyGraphBuilder('toString')).toBeNull();
+ expect(getFamilyGraphBuilder('__proto__')).toBeNull();
+ });
+});
+
+describe('family graph facts', () => {
+ const projectSettings = { useCpuNoise: true, useNsfwChecker: false, useWatermark: false };
+ const build = (model: MainModelConfig, settings: GenerateSettings) =>
+ GRAPH_BUILDERS[model.base as SupportedGenerateBase](settings, model, false, projectSettings);
+ const buildWith = (model: MainModelConfig, overrides: Partial<GenerateSettings> = {}) =>
+ build(model, createSettings(model, overrides));
+
+ it('names the SD decode VAE, override and seamless wrapping included, and the UNet after LoRAs', () => {
+ expect(buildWith(sd1Model).latents?.vae).toMatchObject({ field: 'vae', node: { id: 'model_loader' } });
+ expect(buildWith(sd1Model, { vae }).latents?.vae.node.id).toBe('vae_loader');
+ expect(buildWith(sd1Model, { seamlessXAxis: true, vae }).latents).toMatchObject({
+ encodeType: 'i2l',
+ unet: { field: 'unet', node: { id: 'seamless' } },
+ vae: { field: 'vae', node: { id: 'seamless' } },
+ });
+
+ const withLora = buildWith(sd1Model, { loras: [{ isEnabled: true, model: sd1Lora, weight: 0.5 }] });
+ expect(withLora.latents?.unet).toMatchObject({ field: 'unet', node: { type: 'lora_collection_loader' } });
+ expect(buildWith(sd1Model, { vaePrecision: 'fp32' }).latents?.fp32).toBe(true);
+ expect(buildWith(sd1Model, { vaePrecision: 'fp16' }).latents?.fp32).toBe(false);
+ });
+
+ it('reports a quarter of the requested size as the native PiD denoise size', () => {
+ const family = buildWith(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ gemma2EncoderModel: { base: 'any', key: 'gemma2', name: 'Gemma 2 2B', type: 'gemma2_encoder' },
+ height: 2048,
+ pidDecoderModel: { base: 'flux', key: 'pid-flux', name: 'PiD flux', type: 'pid_decoder' },
+ pidMode: 'native',
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ width: 2048,
+ });
+
+ expect(family.denoiseSize).toEqual({ height: 512, width: 512 });
+ // The FLUX PiD decode takes no VAE, so the record names the loader the graph decodes with.
+ expect(family.latents?.vae).toMatchObject({ field: 'vae', node: { id: 'model_loader' } });
+ });
+
+ const recipes = { filled: fullyFilledSettingsFor, required: satisfiedSettingsFor, tuned: tunedSettingsFor };
+ const familyCases = generateGraphCases.flatMap((testCase) =>
+ (Object.keys(recipes) as (keyof typeof recipes)[]).map((recipe) => ({
+ ...testCase,
+ label: `${testCase.label} / ${recipe}`,
+ recipe,
+ }))
+ );
+
+ it.each(familyCases)('$label hands out the facts its emitted graph carries', ({ base, recipe, shape }) => {
+ const { model, settings } = recipes[recipe](base, shape);
+ const { conditioning, denoise, denoiseSize, graph, latents, layoutPrompt } = build(model, settings);
+ const sourceOf = (nodeId: string, field: string) => {
+ const edge = getEdge(graph, nodeId, field);
+ return edge ? { field: edge.source.field, nodeId: edge.source.node_id } : undefined;
+ };
+ const named = (output: { node: { id: string }; field: string } | undefined) =>
+ output ? { field: output.field, nodeId: output.node.id } : undefined;
+ const reaches = (fromId: string, toId: string): boolean => {
+ const seen = new Set([fromId]);
+ const queue = [fromId];
+ for (let id = queue.shift(); id !== undefined; id = queue.shift()) {
+ if (id === toId) {
+ return true;
+ }
+ for (const edge of graph.edges) {
+ if (edge.source.node_id === id && !seen.has(edge.destination.node_id)) {
+ seen.add(edge.destination.node_id);
+ queue.push(edge.destination.node_id);
+ }
+ }
+ }
+ return false;
+ };
+ const decode =
+ Object.values(graph.nodes).find((node) => isPidDecodeNodeType(node.type)) ?? graph.nodes.canvas_output!;
+
+ // The decode reads the base denoise, or the refiner stage that finishes it.
+ const decodeLatents = sourceOf(decode.id, 'latents');
+ expect(
+ decodeLatents?.nodeId === REFINER_DENOISE_NODE_ID
+ ? sourceOf(REFINER_DENOISE_NODE_ID, 'latents')?.nodeId
+ : decodeLatents?.nodeId
+ ).toBe(denoise.id);
+ expect(denoise).toBe(graph.nodes[denoise.id]);
+
+ const { height, width } = graph.nodes.noise ?? denoise;
+ expect(denoiseSize).toEqual({ height, width });
+
+ expect(latents === null).toBe(['ernie-image', 'ideogram-4'].includes(base));
+ if (latents) {
+ // The FLUX and SD-3 PiD decodes take no VAE; those graphs decode with the loader's.
+ expect(named(latents.vae)).toEqual(sourceOf(decode.id, 'vae') ?? { field: 'vae', nodeId: 'model_loader' });
+ expect(named(latents.unet)).toEqual(sourceOf(denoise.id, 'unet'));
+ }
+
+ expect(conditioning === null).toBe(
+ !['sd-1', 'sd-2', 'sdxl', 'flux', 'flux2', 'krea-2', 'z-image', 'anima'].includes(base)
+ );
+ if (conditioning) {
+ expect(reaches(conditioning.positive.id, conditioning.positiveCollector.id)).toBe(true);
+ expect(
+ graph.edges.some(
+ (edge) => edge.source.node_id === conditioning.positiveCollector.id && edge.destination.node_id === denoise.id
+ )
+ ).toBe(true);
+ if (conditioning.negative) {
+ expect(reaches(conditioning.negative.node.id, conditioning.negative.collector.id)).toBe(true);
+ expect(sourceOf(denoise.id, 'negative_conditioning')?.nodeId).toBe(conditioning.negative.collector.id);
+ }
+ }
+
+ expect(layoutPrompt === null).toBe(!['flux3', 'ideogram-4', 'moss-image'].includes(base));
+ if (layoutPrompt) {
+ expect(sourceOf(layoutPrompt.id, 'prompt')?.nodeId).toBe('positive_prompt');
+ }
+ });
+
+ it('hands out the reference-image collectors the builder feeds the denoise from', () => {
+ const sd = buildWith(sd1Model, {
+ referenceImages: [
+ {
+ config: {
+ beginEndStepPct: [0, 1] as [number, number],
+ clipVisionModel: 'ViT-H' as const,
+ image: refImage,
+ method: 'full' as const,
+ model: sd1IpAdapter,
+ type: 'ip_adapter' as const,
+ weight: 1,
+ },
+ id: 'ip',
+ isEnabled: true,
+ },
+ ],
+ });
+ const collector = sd.conditioning?.ipAdapterCollector;
+
+ expect(collector?.type).toBe('collect');
+ expect(getEdge(sd.graph, 'denoise_latents', 'ip_adapter')?.source.node_id).toBe(collector?.id);
+ expect(buildWith(sd1Model).conditioning?.ipAdapterCollector).toBeNull();
+ });
+});
+
describe('generate seeds', () => {
it('keeps the entered seed in every mode but random', () => {
expect(resolveGenerateSeed(createSettings(sdxlModel, { seed: 123, seedMode: 'fixed' }))).toBe(123);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index 901ae7d279..fb12657538 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -7,6 +7,7 @@ import type {
import { SEED_MAX } from '@platform/core/seed';
+import type { FamilyGraph } from './familyGraph';
import type {
CompiledGenerateGraph,
ComponentModelConfig,
@@ -61,7 +62,7 @@ import {
toGraphContract,
} from './graphBuilder';
import { addKrea2ConditioningEnhancers } from './krea2Conditioning';
-import { addPidDecode, getPidDenoiseSize, getPidMetadata, isPidDecodeNodeType, shouldUsePidDecode } from './pidGraph';
+import { addPidDecode, getPidDenoiseSize, getPidMetadata, shouldUsePidDecode } from './pidGraph';
import { getCompelPromptNodeType } from './prompt/compel';
import { getEffectiveReferenceImage, getEnabledReferenceImages } from './referenceImage';
import { getActiveRefiner, getBaseDenoisingRange } from './sdxlRefiner';
@@ -82,6 +83,14 @@ const getCompatibleComponent = (
filter: GenerateComponentFilter
): ComponentModelConfig | null => (component && filter(component) ? component : null);
+// Encode node types shared across families: a family that denoises in another's VAE latent space encodes with its node.
+/** FLUX.2's VAE encode; FLUX.3 and MOSS-Image denoise in the FLUX.2 VAE's raw latent layout. */
+const FLUX2_ENCODE_TYPE = 'flux2_vae_encode';
+/** Qwen-Image's VAE encode; Krea-2 shares the Qwen-Image VAE. Canvas and reference-image encodes use it alike. */
+const QWEN_IMAGE_ENCODE_TYPE = 'qwen_image_i2l';
+/** Qwen-Image-2.1's VAE encode, for Canvas and reference-image encodes alike. */
+const QWEN_IMAGE_2_1_ENCODE_TYPE = 'qwen_image_2_1_i2l';
+
const toImageField = (image: GenerateReferenceImageAsset) => ({
image_name: getEffectiveReferenceImage(image).image_name,
});
@@ -114,7 +123,7 @@ const addIPAdapterReferenceImages = (
settings: GenerateSettings,
model: MainModelConfig,
denoise: BackendInvocationContract
-) => {
+): BackendInvocationContract | null => {
const strengthOnly = isStrengthOnlyIPAdapterBase(model.base);
// Anima drops a strength-0 adapter anyway; sending one would still encode the image, or install the encoder.
const refs = getEnabledReferenceImages(settings.referenceImages, 'ip_adapter').filter(
@@ -122,7 +131,7 @@ const addIPAdapterReferenceImages = (
);
if (refs.length === 0) {
- return;
+ return null;
}
const collector = addNode(graph, { id: createId('ip_adapter_collector'), type: 'collect' });
@@ -156,6 +165,7 @@ const addIPAdapterReferenceImages = (
}
addEdge(graph, collector, 'collection', denoise, 'ip_adapter');
+ return collector;
};
const FLUX_REDUX_INFLUENCE = {
@@ -171,13 +181,13 @@ const addFluxReduxReferenceImages = (
settings: GenerateSettings,
model: MainModelConfig,
denoise: BackendInvocationContract
-) => {
+): BackendInvocationContract | null => {
const refs = getEnabledReferenceImages(settings.referenceImages, 'flux_redux').filter(
(ref) => ref.config.model?.base === model.base
);
if (refs.length === 0) {
- return;
+ return null;
}
const collector = addNode(graph, { id: createId('flux_redux_collector'), type: 'collect' });
@@ -201,6 +211,7 @@ const addFluxReduxReferenceImages = (
}
addEdge(graph, collector, 'collection', denoise, 'redux_conditioning');
+ return collector;
};
const addFluxKontextReferenceImages = (
@@ -325,7 +336,7 @@ const buildSDGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
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);
@@ -441,13 +452,14 @@ const buildSDGraph = (
addEdge(graph, unetSource, 'unet', denoise, 'unet');
addEdge(graph, noise, 'noise', denoise, 'noise');
- addIPAdapterReferenceImages(graph, settings, model, denoise);
+ 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;
// Create decode only after resolving the final VAE source.
+ const vaeSource = seamless ?? vaeLoader ?? modelLoader;
const output = addDecodeOutput({
denoise: refinerDenoise ?? denoise,
graph,
@@ -458,7 +470,7 @@ const buildSDGraph = (
positivePrompt,
seed,
settings,
- vaeSource: seamless ?? vaeLoader ?? modelLoader,
+ vaeSource,
});
addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings, {
@@ -478,7 +490,25 @@ const buildSDGraph = (
});
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ 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,
+ };
};
const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({
@@ -548,32 +578,6 @@ const addDecodeOutput = ({
return output;
};
-/**
- * The node and field a built graph decodes with, for grafting an encode onto it. An ordinary decode carries it on
- * `canvas_output.vae`. A PiD decode carries it on its `vae` edge when its node type takes that input: only the FLUX.2
- * decode reads it, the others keep the edge as the record of the decode VAE. The FLUX and SD-3 PiD decodes take none,
- * and those builders decode with the model loader, which the fallback names. Null when no builder convention applies.
- */
-export const findVaeSource = (
- graph: BackendGraphContract
-): { node: BackendInvocationContract; field: string } | null => {
- const edge = graph.edges.find(
- (candidate) =>
- candidate.destination.field === 'vae' &&
- (candidate.destination.node_id === 'canvas_output' ||
- isPidDecodeNodeType(graph.nodes[candidate.destination.node_id]?.type))
- );
- if (edge) {
- const node = graph.nodes[edge.source.node_id];
- return node ? { field: edge.source.field, node } : null;
- }
- // A PiD decode without a `vae` edge is the FLUX or SD-3 one. Their builders decode with `model_loader`, which takes
- // any VAE override as a loader input, so its `vae` output is the decode VAE.
- const modelLoader = graph.nodes.model_loader;
- const decodesWithPid = Object.values(graph.nodes).some((node) => isPidDecodeNodeType(node.type));
- return modelLoader && decodesWithPid ? { field: 'vae', node: modelLoader } : null;
-};
-
/** 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.
@@ -584,7 +588,7 @@ const buildSD3Graph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
const graph: BackendGraphContract = { edges: [], id: createId('sd3_graph'), nodes: {} };
const vaeModel = getCompatibleVae(settings, model);
const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);
@@ -649,7 +653,14 @@ const buildSD3Graph = (
...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: 'sd3_i2l', vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
/**
@@ -676,7 +687,7 @@ const buildFluxGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
if (model.variant === 'dev_fill') {
throw new Error('FLUX Fill models do not support text-to-image generation.');
}
@@ -744,8 +755,8 @@ const buildFluxGraph = (
if (model.name.toLowerCase().includes('kontext')) {
addFluxKontextReferenceImages(graph, settings, denoise, 'flux_kontext_reference_image');
}
- addIPAdapterReferenceImages(graph, settings, model, denoise);
- addFluxReduxReferenceImages(graph, settings, model, denoise);
+ 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,
guidance: settings.cfgScale,
@@ -759,7 +770,20 @@ const buildFluxGraph = (
});
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ 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,
+ };
};
const buildFlux2Graph = (
@@ -767,7 +791,7 @@ const buildFlux2Graph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
const isDev = model.variant === 'dev';
const sourceModel = getFlux2ComponentSource(model, settings);
const hasBundledComponents = isBundledFlux2Main(model) || sourceModel;
@@ -876,7 +900,20 @@ const buildFlux2Graph = (
});
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ return {
+ conditioning: {
+ fluxReduxCollector: null,
+ ipAdapterCollector: null,
+ negative: null,
+ positive: posCond,
+ positiveCollector: posCondCollect,
+ },
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: FLUX2_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
const buildCogView4Graph = (
@@ -884,7 +921,7 @@ const buildCogView4Graph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
const graph: BackendGraphContract = { edges: [], id: createId('cogview4_graph'), nodes: {} };
const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);
const modelLoader = addNode(graph, { id: 'model_loader', model, type: 'cogview4_model_loader' });
@@ -912,7 +949,14 @@ const buildCogView4Graph = (
addEdge(graph, denoise, 'latents', output, 'latents');
addMetadata(graph, output, settings, model, 'cogview4_txt2img', projectSettings, { scheduler: undefined });
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: 'cogview4_i2l', vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
const buildErnieImageGraph = (
@@ -920,7 +964,7 @@ const buildErnieImageGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
// Bundles supply submodels; single-file models need explicit encoder/VAE selections.
const isDiffusers = model.format === 'diffusers';
const vaeModel = getCompatibleVae(settings, model);
@@ -977,7 +1021,14 @@ const buildErnieImageGraph = (
mistral_encoder: mistralEncoderModel ?? undefined,
});
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: null,
+ layoutPrompt: null,
+ };
};
const buildQwenImageGraph = (
@@ -985,7 +1036,7 @@ const buildQwenImageGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
const sourceModel = getCompatibleComponentSource(settings, model);
const hasBundledComponents = model.format === 'diffusers' || sourceModel;
const vaeModel = getCompatibleVae(settings, model);
@@ -1088,7 +1139,7 @@ const buildQwenImageGraph = (
const firstImage = qwenReferenceImages[0]?.config.image;
if (firstImage) {
- const refI2l = addNode(graph, { id: createId('qwen_ref_i2l'), type: 'qwen_image_i2l' });
+ const refI2l = addNode(graph, { id: createId('qwen_ref_i2l'), type: QWEN_IMAGE_ENCODE_TYPE });
const refImageNode = addNode(graph, {
id: createId('qwen_ref_img_for_vae'),
image: toImageField(firstImage),
@@ -1111,7 +1162,14 @@ const buildQwenImageGraph = (
});
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ 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,
+ };
};
const buildZImageGraph = (
@@ -1119,7 +1177,7 @@ const buildZImageGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
const sourceModel = getDiffusersSource(settings, model);
const qwen3EncoderModel =
settings.qwen3EncoderModel && isZImageQwen3Encoder(settings.qwen3EncoderModel) ? settings.qwen3EncoderModel : null;
@@ -1219,7 +1277,20 @@ const buildZImageGraph = (
...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
- return graph;
+ 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: 'z_image_i2l', vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
const buildAnimaGraph = (
@@ -1227,7 +1298,7 @@ const buildAnimaGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
const vaeModel = requireComponent(getCompatibleVae(settings, model), 'Anima VAE');
const qwen3EncoderModel = requireComponent(
settings.qwen3EncoderModel && isAnimaQwen3Encoder(settings.qwen3EncoderModel) ? settings.qwen3EncoderModel : null,
@@ -1297,7 +1368,7 @@ const buildAnimaGraph = (
addEdge(graph, seed, 'value', denoise, 'seed');
addEdge(graph, denoise, 'latents', output, 'latents');
- addIPAdapterReferenceImages(graph, settings, model, denoise);
+ const ipAdapterCollector = addIPAdapterReferenceImages(graph, settings, model, denoise);
addMetadata(graph, output, settings, model, 'anima_txt2img', projectSettings, {
qwen3_encoder: qwen3EncoderModel,
...(qwen35EncoderModel ? { qwen3_5_encoder: qwen35EncoderModel } : {}),
@@ -1306,7 +1377,20 @@ const buildAnimaGraph = (
});
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ return {
+ conditioning: {
+ fluxReduxCollector: null,
+ ipAdapterCollector,
+ negative: negCond && negCondCollect ? { collector: negCondCollect, node: negCond } : null,
+ positive: posCond,
+ positiveCollector: posCondCollect,
+ },
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: 'anima_i2l', vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
/**
@@ -1339,7 +1423,12 @@ const addKrea2EditReferences = (
for (const image of referenceImages) {
// `reference` sizes the image as ai-toolkit trains edit LoRAs, so width and height stay unset.
- const encode = addNode(graph, { id: createId('krea2_ref_i2l'), image, reference: true, type: 'qwen_image_i2l' });
+ const encode = addNode(graph, {
+ id: createId('krea2_ref_i2l'),
+ image,
+ reference: true,
+ type: QWEN_IMAGE_ENCODE_TYPE,
+ });
const collect = addNode(graph, { id: createId('krea2_ref_latents_collect'), type: 'collect' });
addEdge(graph, vaeSource, 'vae', encode, 'vae');
@@ -1363,7 +1452,7 @@ const buildKrea2Graph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
// Standalone Krea needs a separate VAE/encoder without a component source.
const isDiffusers = model.format === 'diffusers';
const vaeModel = getCompatibleVae(settings, model);
@@ -1483,7 +1572,21 @@ const buildKrea2Graph = (
});
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ return {
+ conditioning: {
+ fluxReduxCollector: null,
+ ipAdapterCollector: null,
+ // Krea-2's negative conditioning feeds the denoise directly, so regional negatives have nothing to join.
+ negative: 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,
+ };
};
const buildQwenImage21Graph = (
@@ -1491,7 +1594,7 @@ const buildQwenImage21Graph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
// A Diffusers pipeline brings its VAE and encoder; for single-file and GGUF transformers the generation policy
// requires both before this runs.
const vaeModel = getCompatibleVae(settings, model);
@@ -1552,7 +1655,14 @@ const buildQwenImage21Graph = (
addEdge(graph, denoise, 'metadata', output, 'metadata');
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: QWEN_IMAGE_2_1_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
/**
@@ -1587,7 +1697,7 @@ const addQwenImage21ReferenceImages = (
image: toImageField(config.image),
type: 'image',
});
- const i2l = addNode(graph, { id: createId('qwen21_ref_i2l'), reference: true, type: 'qwen_image_2_1_i2l' });
+ const i2l = addNode(graph, { id: createId('qwen21_ref_i2l'), reference: true, type: QWEN_IMAGE_2_1_ENCODE_TYPE });
addEdge(graph, imageNode, 'image', i2l, 'image');
addEdge(graph, nodes.modelLoader, 'vae', i2l, 'vae');
@@ -1620,7 +1730,7 @@ const buildMossImageGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
// A Diffusers pipeline brings its encoder and VAE; a single-file transformer needs both. The filter drops a stale
// Qwen3.5 4B selection left over from Anima-3.8B, which shares the setting.
const isDiffusers = model.format === 'diffusers';
@@ -1706,7 +1816,14 @@ const buildMossImageGraph = (
addEdge(graph, layoutPrompt, 'value', metadata, 'moss_image_layout_prompt');
}
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: FLUX2_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt,
+ };
};
const buildFlux3Graph = (
@@ -1714,7 +1831,7 @@ const buildFlux3Graph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
// A single-file or GGUF FLUX.3 model is the transformer alone; a Diffusers one bundles the VAE and encoder.
const isDiffusers = model.format === 'diffusers';
const vaeModel = getCompatibleVae(settings, model);
@@ -1804,7 +1921,14 @@ const buildFlux3Graph = (
});
addReferenceImageMetadata(graph, output, settings);
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: FLUX2_ENCODE_TYPE, vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt,
+ };
};
const buildIdeogram4Graph = (
@@ -1812,7 +1936,7 @@ const buildIdeogram4Graph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
// Standalone Ideogram needs its other branch, encoder, and VAE; bundles supply them.
const isDiffusers = model.format === 'diffusers';
const unconditionalModel = settings.ideogram4UnconditionalModel;
@@ -1881,7 +2005,14 @@ const buildIdeogram4Graph = (
// Record the caption the encoder saw; the positive prompt alone does not show regions or palette.
addEdge(graph, captionBuilder, 'value', metadata, 'ideogram4_caption');
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: null,
+ layoutPrompt: captionBuilder,
+ };
};
const buildWanGraph = (
@@ -1889,7 +2020,7 @@ const buildWanGraph = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-): BackendGraphContract => {
+): FamilyGraph => {
// GGUF Wan sources encoder/VAE from standalone selections or a bundle.
const sourceModel = getDiffusersSource(settings, model);
const vaeModel = getCompatibleVae(settings, model);
@@ -1951,7 +2082,14 @@ const buildWanGraph = (
wan_transformer_low_noise: settings.wanLowNoiseModel ?? undefined,
});
- return graph;
+ return {
+ conditioning: null,
+ denoise,
+ denoiseSize: { height: denoise.height, width: denoise.width },
+ graph,
+ latents: { encodeType: 'wan_i2l', vae: { field: 'vae', node: modelLoader } },
+ layoutPrompt: null,
+ };
};
/** Canvas inputs per external mode: the composited bbox is the init image for img2img. */
@@ -2030,7 +2168,7 @@ type GenerateGraphBuilder = (
model: MainModelConfig,
outputIsIntermediate: boolean,
projectSettings: GenerationProjectSettings
-) => BackendGraphContract;
+) => FamilyGraph;
export const GRAPH_BUILDERS = {
'sd-1': buildSDGraph,
@@ -2052,6 +2190,10 @@ export const GRAPH_BUILDERS = {
wan: buildWanGraph,
} satisfies Record<SupportedGenerateBase, GenerateGraphBuilder>;
+/** 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;
+
export const compileGenerateGraph = (
settings: GenerateSettings,
model: GenerateModelConfig,
@@ -2072,7 +2214,7 @@ export const compileGenerateGraph = (
return buildExternalGraph(settings, model, outputIsIntermediate, runtimeProjectSettings);
}
- const builder = GRAPH_BUILDERS[model.base as SupportedGenerateBase];
+ const builder = getFamilyGraphBuilder(model.base);
if (!builder) {
const dimensionGrid = getGenerationDimensions(model).grid;
@@ -2080,7 +2222,7 @@ export const compileGenerateGraph = (
throw new Error(`${model.name} dimensions must be multiples of ${dimensionGrid}.`);
}
- const graph = builder(settings, model, outputIsIntermediate, runtimeProjectSettings);
+ const { graph } = builder(settings, model, outputIsIntermediate, runtimeProjectSettings);
// External providers return finished images; the filters apply to every locally decoded family.
addOutputPostprocessors(graph, runtimeProjectSettings, outputIsIntermediate);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts
index ccb1b6605b..740a4afbd5 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts
@@ -31,8 +31,7 @@ export const isPidDecodeNodeType = (type: string | undefined): type is PidDecode
/**
* The decode node types that take a `vae` input. PiD takes the latent in the VAE's normalized space, and only
* FLUX.2 stores it denormalized, so only its decode reads the VAE (BatchNorm statistics to normalize its latent).
- * The others take the stored latent as is, but the edge still records which VAE the graph decodes with:
- * `findVaeSource` reads it to give a Canvas img2img encode that same VAE, override and seamless wrapping included.
+ * The others take the stored latent as is, but the edge still records in the emitted graph which VAE it decodes with.
*/
const PID_DECODE_NODES_WITH_VAE_INPUT: ReadonlySet<string> = new Set([
'flux2_pid_decode',