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.

feat(webv2): add PiD super-resolution decode support

joshistoast87ec89208c07
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 821311a3f7..02f6ba161d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1085,7 +1085,15 @@
"weight": "Weight",
"width": "Width",
"xAxis": "X axis",
- "yAxis": "Y axis"
+ "yAxis": "Y axis",
+ "pid": "PiD Decode",
+ "pidOff": "Off",
+ "pidFit": "Fit to size",
+ "pidNative": "Native 4x",
+ "pidSteps": "PiD steps",
+ "pidHelp": "Replaces the VAE decode with a 4x super-resolution decode.",
+ "pidFitHelp": "Generates at the requested size, then decodes 4x and scales back down.",
+ "pidNativeHelp": "The requested size is the 4x target; generation runs at a quarter of it."
},
"upscale": {
"addLora": "LoRAs",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
index fc2d257723..54796acc04 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
@@ -317,9 +317,12 @@ describe('component policies', () => {
});
const settings = createSettings(model);
+ // FLUX.2 supports PiD, so its two slots follow the base's own components.
expect(getComponentSectionPolicy(model, settings).slots.map((slot) => slot.key)).toEqual([
'qwen3EncoderModel',
'vae',
+ 'pidDecoderModel',
+ 'gemma2EncoderModel',
]);
expect(getAutoFlux2ComponentSourceModel(model, settings, [incompatibleSource, source])?.key).toBe(source.key);
expect(
@@ -401,12 +404,28 @@ describe('component policies', () => {
});
it('renders no component slots for bases without extra requirements', () => {
- expect(getComponentSectionPolicy(createModel('sdxl'), createSettings(createModel('sdxl'))).slots).toEqual([]);
expect(getComponentSectionPolicy(createModel('cogview4'), createSettings(createModel('cogview4'))).slots).toEqual(
[]
);
});
+ it('offers only the PiD slots for a PiD-capable base with no other components', () => {
+ // SDXL needs no encoders or VAE of its own, but it can decode through PiD, so the two
+ // PiD slots are offered (and are only *required* once PiD is switched on).
+ const model = createModel('sdxl');
+
+ expect(getComponentSectionPolicy(model, createSettings(model)).slots.map((slot) => slot.key)).toEqual([
+ 'pidDecoderModel',
+ 'gemma2EncoderModel',
+ ]);
+ });
+
+ it('does not offer PiD slots for a base with no PiD decode node', () => {
+ const model = createModel('cogview4');
+
+ expect(getComponentSectionPolicy(model, createSettings(model)).slots).toEqual([]);
+ });
+
it('clears incompatible selections when the selected model changes', () => {
const model = createModel('sdxl');
const settings = createSettings(createModel('sd-1'), {
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index 30e2b2f4d2..d31f8c4c5f 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -12,6 +12,7 @@ import type {
GenerateReferenceImageConfig,
GenerateSettings,
MainModelConfig,
+ PidMode,
VaePrecision,
} from './types';
@@ -29,6 +30,13 @@ import {
type GenerateComponentFilter,
} from './componentCompatibility';
import { DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS } from './dynamicPrompts';
+import {
+ DEFAULT_PID_STEPS,
+ getIsPidActive,
+ getIsPidSupportedBase,
+ getPidDecoderBaseForMainBase,
+ getPidDimensionOverrides,
+} from './pid';
import {
clampDimension,
DEFAULT_IDEOGRAM4_SAMPLER_PRESET,
@@ -375,14 +383,31 @@ const getBaseGenerationConfig = (
const getNumber = (value: number | null | undefined, fallback: number): number =>
Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;
-export const getGenerationDimensions = (model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined) => {
+/**
+ * The dimension rules for a model, optionally adjusted for PiD.
+ *
+ * `pidMode` is optional so the many callers that only care about the model keep
+ * working unchanged. In PiD native mode the requested size is the 4x decode target, so
+ * the grid is multiplied by 4 (keeping requested / 4 on the model's own grid) and the
+ * optimal side becomes PiD's 2048 rather than the model's 1024.
+ */
+export const getGenerationDimensions = (
+ model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined,
+ pidMode: PidMode = 'off'
+) => {
const config = getBaseGenerationConfig(model);
+ const { grid, optimalSide } = getPidDimensionOverrides(
+ pidMode,
+ model?.base,
+ config.dimensions.grid,
+ config.dimensions.optimalSide
+ );
return {
- grid: config.dimensions.grid,
+ grid,
min: MIN_DIMENSION,
max: MAX_DIMENSION,
- optimal: config.dimensions.optimalSide,
+ optimal: optimalSide,
};
};
@@ -504,6 +529,9 @@ export const getGenerationUiPolicy = (
sdVaeVisible: config.ui.sdVaeOverride,
vaePrecisionVisible: config.ui.vaePrecision,
seedVisible,
+ // Shown for any base with a PiD decode node, whether or not PiD is currently on, so
+ // it can be turned on without hunting for the control.
+ pidVisible: getIsPidSupportedBase(model?.base),
};
};
@@ -627,6 +655,10 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): Generat
krea2SeedVarianceEnabled: false,
krea2SeedVarianceStrength: DEFAULT_KREA2_SEED_VARIANCE_STRENGTH,
krea2SeedVarianceRandomizePercent: DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT,
+ pidMode: 'off',
+ pidDecoderModel: null,
+ gemma2EncoderModel: null,
+ pidSteps: DEFAULT_PID_STEPS,
referenceImages: [],
scheduler: defaults.scheduler,
seamlessXAxis: false,
@@ -678,6 +710,8 @@ export type GenerateComponentValueKey =
| 'wanT5EncoderModel'
| 'wanLowNoiseModel'
| 'componentSourceModel'
+ | 'pidDecoderModel'
+ | 'gemma2EncoderModel'
| 'vae';
export interface ComponentPolicyContext {
@@ -716,6 +750,8 @@ const TYPE_QWEN3: ModelTaxonomyType[] = ['qwen3_encoder'];
const TYPE_QWEN_VL: ModelTaxonomyType[] = ['qwen_vl_encoder'];
const TYPE_QWEN3_VL: ModelTaxonomyType[] = ['qwen3_vl_encoder'];
const TYPE_WAN_T5: ModelTaxonomyType[] = ['wan_t5_encoder'];
+const TYPE_PID_DECODER: ModelTaxonomyType[] = ['pid_decoder'];
+const TYPE_GEMMA2: ModelTaxonomyType[] = ['gemma2_encoder'];
const TYPE_T5: ModelTaxonomyType[] = ['t5_encoder'];
const TYPE_VAE: ModelTaxonomyType[] = ['vae'];
@@ -776,6 +812,42 @@ const qwen3VlEncoderSlot = (helpText: string): ComponentSlotPolicy =>
filter: (candidate) => candidate.type === 'qwen3_vl_encoder',
});
+/**
+ * PiD's decoder and caption encoder.
+ *
+ * Both are only *required* while PiD is on, but the slots are always offered for a
+ * PiD-capable base so the models can be chosen before switching PiD on. The decoder is
+ * filtered to the base whose checkpoints are valid for the selected model — Z-Image
+ * shows FLUX decoders, since it shares FLUX's VAE and ships none of its own.
+ */
+const pidDecoderSlot = (): ComponentSlotPolicy =>
+ slot({
+ key: 'pidDecoderModel',
+ label: 'PiD Decoder',
+ modelTypes: TYPE_PID_DECODER,
+ valueKind: 'component',
+ helpText: 'Required while PiD is on. Must match the main model’s base.',
+ filter: (candidate, ctx) =>
+ candidate.type === 'pid_decoder' && candidate.base === getPidDecoderBaseForMainBase(ctx.model.base),
+ required: (ctx) => getIsPidActive(ctx.settings.pidMode, ctx.model.base),
+ missingMessage: 'Generate needs a PiD decoder while PiD is on.',
+ });
+
+const gemma2EncoderSlot = (): ComponentSlotPolicy =>
+ slot({
+ key: 'gemma2EncoderModel',
+ label: 'Gemma-2 Encoder',
+ modelTypes: TYPE_GEMMA2,
+ valueKind: 'component',
+ helpText: 'Required while PiD is on. Shared by every PiD decoder.',
+ filter: (candidate) => candidate.type === 'gemma2_encoder',
+ required: (ctx) => getIsPidActive(ctx.settings.pidMode, ctx.model.base),
+ missingMessage: 'Generate needs a Gemma-2 encoder while PiD is on.',
+ });
+
+/** The PiD slots, for splicing into a PiD-capable base's component list. */
+const pidSlots = (): ComponentSlotPolicy[] => [pidDecoderSlot(), gemma2EncoderSlot()];
+
const wanT5EncoderSlot = (helpText: string): ComponentSlotPolicy =>
slot({
key: 'wanT5EncoderModel',
@@ -923,7 +995,7 @@ const createPolicy = (defaultOpen: boolean, slots: readonly ComponentSlotPolicy[
const EMPTY_COMPONENT_POLICY: ComponentSectionPolicy = createPolicy(false, []);
-export const getComponentSectionPolicy = (
+const getBaseComponentSectionPolicy = (
model: GenerateModelConfig | undefined,
_settings: GenerateSettings
): ComponentSectionPolicy => {
@@ -955,7 +1027,7 @@ export const getComponentSectionPolicy = (
...(ctx.model.type !== 'external_image_generator' && ctx.model.variant === 'dev_fill'
? ['FLUX Fill models do not support text-to-image generation.']
: []),
- ...validateSlots(getComponentSectionPolicy(ctx.model, ctx.settings), ctx),
+ ...validateSlots(getBaseComponentSectionPolicy(ctx.model, ctx.settings), ctx),
],
};
case 'flux2':
@@ -1073,6 +1145,33 @@ export const getComponentSectionPolicy = (
}
};
+/**
+ * The component slots for a model, plus PiD's two slots on any PiD-capable base.
+ *
+ * Appended in a wrapper rather than written into each base's case: PiD supports six
+ * bases, one of which (SDXL) has no component case at all, and each existing case keeps
+ * its own bespoke validation untouched this way. Only the PiD slots are validated here
+ * — the inner policy validates its own.
+ */
+export const getComponentSectionPolicy = (
+ model: GenerateModelConfig | undefined,
+ settings: GenerateSettings
+): ComponentSectionPolicy => {
+ const policy = getBaseComponentSectionPolicy(model, settings);
+
+ if (!model || model.type === 'external_image_generator' || !getIsPidSupportedBase(model.base)) {
+ return policy;
+ }
+
+ const slots = [...policy.slots, ...pidSlots()];
+
+ return {
+ defaultOpen: policy.defaultOpen,
+ slots,
+ validate: (ctx) => [...policy.validate(ctx), ...validateSlots({ slots: pidSlots() }, ctx)],
+ };
+};
+
const getComponentPolicyContext = (model: GenerateModelConfig, settings: GenerateSettings): ComponentPolicyContext => ({
model,
settings,
@@ -1087,6 +1186,8 @@ const getComponentPolicyContext = (model: GenerateModelConfig, settings: Generat
wanT5EncoderModel: settings.wanT5EncoderModel,
wanLowNoiseModel: settings.wanLowNoiseModel,
t5EncoderModel: settings.t5EncoderModel,
+ pidDecoderModel: settings.pidDecoderModel,
+ gemma2EncoderModel: settings.gemma2EncoderModel,
vae: settings.vae,
},
});
@@ -1101,6 +1202,8 @@ const COMPONENT_SETTING_LABELS: Record<GenerateComponentValueKey, string> = {
wanT5EncoderModel: 'Wan T5 Encoder',
wanLowNoiseModel: 'Low-noise expert',
t5EncoderModel: 'T5 Encoder',
+ pidDecoderModel: 'PiD Decoder',
+ gemma2EncoderModel: 'Gemma-2 Encoder',
vae: 'VAE',
componentSourceModel: 'Component source',
};
@@ -1452,7 +1555,9 @@ export const getGenerationModelAvailabilityReasons = (
const getDimensionValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {
const reasons: string[] = [];
- const dimensions = getGenerationDimensions(model);
+ // The PiD-adjusted grid: in native mode the requested size is the 4x target, so it must
+ // be a multiple of grid * 4 for requested / 4 to land on the model's own grid.
+ const dimensions = getGenerationDimensions(model, settings.pidMode);
if (!Number.isFinite(settings.width) || settings.width < dimensions.min || settings.width > dimensions.max) {
reasons.push(`Generate width must be between ${dimensions.min} and ${dimensions.max}.`);
@@ -1469,6 +1574,31 @@ const getDimensionValidationReasons = (model: GenerateModelConfig, settings: Gen
return reasons;
};
+/**
+ * PiD guards beyond "are the models selected", which the component slots already cover.
+ *
+ * PiD is only wired for text-to-image here, so a mode left on for an unsupported base is
+ * reported rather than silently ignored — otherwise the user would get an ordinary decode
+ * and wonder why the image is not 4x.
+ */
+const getPidValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {
+ if (settings.pidMode === 'off') {
+ return [];
+ }
+
+ if (!getIsPidSupportedBase(model.base)) {
+ return [`PiD is not supported for ${model.name}. Turn PiD off to generate with this model.`];
+ }
+
+ const reasons: string[] = [];
+
+ if (settings.pidSteps < 1) {
+ reasons.push('PiD steps must be at least 1.');
+ }
+
+ return reasons;
+};
+
const getReferenceImageValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {
const reasons: string[] = [];
const enabled = settings.referenceImages.filter((referenceImage) => referenceImage.isEnabled);
@@ -1553,6 +1683,7 @@ export const getGenerationValidationReasons = (model: GenerateModelConfig, setti
const reasons = [
...getDimensionValidationReasons(model, settings),
...getReferenceImageValidationReasons(model, settings),
+ ...getPidValidationReasons(model, settings),
];
if (model.type === 'external_image_generator') {
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 df2362e63c..1ad0d1a07e 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@ -722,3 +722,194 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {
expect(getEdge(graph, 'pos_cond', 'wan_t5_encoder')?.source.node_id).toBe('model_loader');
});
});
+
+describe('PiD decode', () => {
+ const pidDecoder = (base: string): ComponentModelConfig => ({
+ base,
+ key: `pid-${base}`,
+ name: `PiD ${base}`,
+ type: 'pid_decoder',
+ });
+ const gemma2: ComponentModelConfig = { base: 'any', key: 'gemma2', name: 'Gemma 2 2B', type: 'gemma2_encoder' };
+
+ const pidSettings = (base: string, overrides: Partial<GenerateSettings> = {}): Partial<GenerateSettings> => ({
+ gemma2EncoderModel: gemma2,
+ pidDecoderModel: pidDecoder(base),
+ pidMode: 'fit',
+ ...overrides,
+ });
+
+ it('keeps the ordinary VAE decode when PiD is off', () => {
+ const graph = compile(fluxModel, { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae });
+
+ expect(getNodeByType(graph, 'flux_vae_decode')).toBeDefined();
+ expect(getNodeByType(graph, 'flux_pid_decode')).toBeUndefined();
+ });
+
+ it('replaces the VAE decode with a PiD decode and downscales in fit mode', () => {
+ const graph = compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ ...pidSettings('flux'),
+ height: 1024,
+ width: 1024,
+ });
+
+ expect(getNodeByType(graph, 'flux_vae_decode')).toBeUndefined();
+ const decode = getNodeByType(graph, 'flux_pid_decode');
+ expect(decode).toBeDefined();
+ // The resize is the output, because the 4x decode must come back to the asked-for size.
+ const output = graph.nodes.canvas_output;
+ expect(output?.type).toBe('img_resize');
+ expect(output).toMatchObject({ height: 1024, width: 1024 });
+ expect(getEdge(graph, 'canvas_output', 'image')?.source.node_id).toBe(decode?.id);
+ });
+
+ it('generates at the full size in fit mode', () => {
+ const graph = compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ ...pidSettings('flux'),
+ height: 1024,
+ width: 1024,
+ });
+
+ expect(graph.nodes.denoise_latents).toMatchObject({ height: 1024, width: 1024 });
+ });
+
+ it('generates at a quarter size in native mode and makes the decode the output', () => {
+ const graph = compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ ...pidSettings('flux', { pidMode: 'native' }),
+ height: 2048,
+ width: 2048,
+ });
+
+ expect(graph.nodes.denoise_latents).toMatchObject({ height: 512, width: 512 });
+ // No downscale: PiD's 4x output IS the result.
+ expect(graph.nodes.canvas_output?.type).toBe('flux_pid_decode');
+ expect(getNodeByType(graph, 'img_resize')).toBeUndefined();
+ });
+
+ it('wires the prompt, seed and both loaders into the decode', () => {
+ const graph = compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ ...pidSettings('flux'),
+ });
+ const decode = getNodeByType(graph, 'flux_pid_decode');
+
+ expect(getEdge(graph, decode!.id, 'prompt')?.source.node_id).toBe('positive_prompt');
+ expect(getEdge(graph, decode!.id, 'seed')?.source.node_id).toBe('seed');
+ expect(getEdge(graph, decode!.id, 'latents')?.source.node_id).toBe('denoise_latents');
+ expect(getNodeByType(graph, 'pid_decoder_loader')).toMatchObject({ pid_decoder_model: pidDecoder('flux') });
+ expect(getNodeByType(graph, 'gemma2_encoder_loader')).toMatchObject({ gemma2_model: gemma2 });
+ });
+
+ it('does not wire a VAE into decoders that use fixed constants', () => {
+ const graph = compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ ...pidSettings('flux'),
+ });
+ const decode = getNodeByType(graph, 'flux_pid_decode');
+
+ // FLUX.1 and SD3 use fixed VAE constants and expose no `vae` input.
+ expect(getEdge(graph, decode!.id, 'vae')).toBeUndefined();
+ });
+
+ it('wires a VAE into decoders that read its constants at runtime', () => {
+ const graph = compile(qwenImageModel, { ...pidSettings('qwen-image') });
+ const decode = getNodeByType(graph, 'qwen_image_pid_decode');
+
+ expect(getEdge(graph, decode!.id, 'vae')?.source.node_id).toBe('model_loader');
+ });
+
+ it('uses a FLUX decoder for Z-Image, which shares its VAE', () => {
+ const graph = compile(zImageModel, { ...pidSettings('flux') });
+
+ expect(getNodeByType(graph, 'z_image_pid_decode')).toBeDefined();
+ expect(getNodeByType(graph, 'pid_decoder_loader')).toMatchObject({ pid_decoder_model: pidDecoder('flux') });
+ });
+
+ it('decodes through PiD for SDXL, sizing the noise node instead of the denoise node', () => {
+ const graph = compile(sdxlModel, { ...pidSettings('sdxl', { pidMode: 'native' }), height: 2048, width: 2048 });
+
+ // SDXL is sized via its noise node; its grid is 8, so 2048 / 4 = 512.
+ expect(graph.nodes.noise).toMatchObject({ height: 512, width: 512 });
+ expect(graph.nodes.canvas_output?.type).toBe('sdxl_pid_decode');
+ });
+
+ it('decodes through PiD for SD3', () => {
+ const graph = compile(sd3Model, { ...pidSettings('sd-3') });
+
+ expect(getNodeByType(graph, 'sd3_pid_decode')).toBeDefined();
+ expect(getNodeByType(graph, 'sd3_l2i')).toBeUndefined();
+ });
+
+ it('decodes through PiD for FLUX.2', () => {
+ const graph = compile(flux2Model, { ...pidSettings('flux2') });
+
+ expect(getNodeByType(graph, 'flux2_pid_decode')).toBeDefined();
+ expect(getNodeByType(graph, 'flux2_vae_decode')).toBeUndefined();
+ });
+
+ it('records the PiD settings in metadata', () => {
+ const graph = compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ ...pidSettings('flux'),
+ });
+ const metadata = getNodeByType(graph, 'core_metadata');
+
+ expect(metadata).toMatchObject({ pid_mode: 'fit', pid_steps: 4 });
+ });
+
+ it('refuses to compile PiD on an unsupported base rather than silently ignoring it', () => {
+ // CogView4 has no PiD decode node. Falling back to an ordinary decode would leave the
+ // user wondering why the output is not 4x.
+ expect(() => compile(cogView4Model, { pidMode: 'fit' })).toThrow(/PiD is not supported/);
+ });
+
+ it('requires both PiD models before compiling', () => {
+ expect(() =>
+ compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ pidMode: 'fit',
+ pidDecoderModel: pidDecoder('flux'),
+ })
+ ).toThrow(/Gemma-2 encoder/);
+ expect(() =>
+ compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ pidMode: 'fit',
+ gemma2EncoderModel: gemma2,
+ })
+ ).toThrow(/PiD decoder/);
+ });
+
+ it('enforces the 4x grid on the requested size in native mode', () => {
+ // FLUX's grid is 16, so native requires multiples of 64.
+ expect(() =>
+ compile(fluxModel, {
+ clipEmbedModel: clipEmbed,
+ t5EncoderModel: t5Encoder,
+ vae: fluxVae,
+ ...pidSettings('flux', { pidMode: 'native' }),
+ height: 2048,
+ width: 2032,
+ })
+ ).toThrow(/multiple of 64/);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index b9b637ad01..95a7d28aba 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -43,6 +43,7 @@ import {
toModelIdentifier,
toGraphContract,
} from './graphBuilder';
+import { addPidDecode, getPidDenoiseSize, getPidMetadata, shouldUsePidDecode } from './pidGraph';
import { getEffectiveReferenceImage } from './referenceImage';
import { SEED_MAX } from './settings';
@@ -312,12 +313,13 @@ const buildSDGraph = (
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);
const noise = addNode(graph, {
- height: settings.height,
+ height: sdDenoiseSize.height,
id: 'noise',
type: 'noise',
use_cpu: projectSettings.useCpuNoise,
- width: settings.width,
+ width: sdDenoiseSize.width,
});
const denoise = addNode(graph, {
cfg_rescale_multiplier: settings.cfgRescaleMultiplier,
@@ -329,14 +331,6 @@ const buildSDGraph = (
steps: settings.steps,
type: 'denoise_latents',
});
- const output = addNode(graph, {
- color_compensation: colorCompensation,
- fp32: settings.vaePrecision === 'fp32',
- id: 'canvas_output',
- is_intermediate: outputIsIntermediate,
- type: 'l2i',
- use_cache: false,
- });
// A VAE override only applies when it matches the main model's architecture.
const vaeLoader =
settings.vae && settings.vae.base === model.base
@@ -408,8 +402,21 @@ const buildSDGraph = (
addEdge(graph, unetSource, 'unet', denoise, 'unet');
addEdge(graph, noise, 'noise', denoise, 'noise');
addIPAdapterReferenceImages(graph, settings, model, denoise);
- addEdge(graph, denoise, 'latents', output, 'latents');
- addEdge(graph, seamless ?? vaeLoader ?? modelLoader, 'vae', output, 'vae');
+ // Created here rather than with the other nodes because the decode's VAE source is
+ // only settled once the seamless / VAE-override nodes above are known.
+ const output = addDecodeOutput({
+ denoise,
+ graph,
+ l2iProps: { color_compensation: colorCompensation, fp32: settings.vaePrecision === 'fp32' },
+ l2iType: 'l2i',
+ model,
+ outputIsIntermediate,
+ positivePrompt,
+ seed,
+ settings,
+ vaeSource: seamless ?? vaeLoader ?? modelLoader,
+ });
+
addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings, {
scheduler,
});
@@ -427,6 +434,80 @@ const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({
const addImageOutputNode = (graph: BackendGraphContract, type: string, outputIsIntermediate: boolean) =>
addNode(graph, { id: 'canvas_output', is_intermediate: outputIsIntermediate, type, use_cache: false });
+/**
+ * The decode that turns the denoised latents into the output image: either the base's
+ * ordinary VAE decode, or PiD's 4x super-resolution decode when PiD is on.
+ *
+ * Both branches wire `latents` (and the VAE where the node needs it) and return the
+ * terminal `canvas_output` node, so callers attach metadata to the result either way.
+ */
+const addDecodeOutput = ({
+ graph,
+ settings,
+ model,
+ l2iType,
+ l2iProps,
+ denoise,
+ positivePrompt,
+ seed,
+ vaeSource,
+ vaeField = 'vae',
+ outputIsIntermediate,
+}: {
+ graph: BackendGraphContract;
+ settings: GenerateSettings;
+ model: MainModelConfig;
+ /** The base's ordinary VAE-decode node type, used when PiD is off. */
+ 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;
+};
+
+/**
+ * The width/height to denoise at. Identical to the requested size unless PiD is in
+ * native mode, where the requested size is the 4x decode target and generation runs at
+ * a quarter of it.
+ */
+const getDenoiseSize = (settings: GenerateSettings, model: MainModelConfig): { width: number; height: number } =>
+ // Deliberately the model's OWN grid (the default `off` mode), not the PiD-scaled grid
+ // the dimension fields present: requested / 4 must land on the model's grid.
+ getPidDenoiseSize(settings, model.base, getGenerationDimensions(model).grid);
+
const buildSD3Graph = (
settings: GenerateSettings,
model: MainModelConfig,
@@ -446,17 +527,28 @@ const buildSD3Graph = (
});
const posCond = addNode(graph, { id: 'pos_cond', type: 'sd3_text_encoder' });
const negCond = addNode(graph, { id: 'neg_cond', type: 'sd3_text_encoder' });
+ const sd3DenoiseSize = getDenoiseSize(settings, model);
const denoise = addNode(graph, {
cfg_scale: settings.cfgScale,
denoising_end: 1,
denoising_start: 0,
- height: settings.height,
+ height: sd3DenoiseSize.height,
id: 'denoise_latents',
steps: settings.steps,
type: 'sd3_denoise',
- width: settings.width,
+ width: sd3DenoiseSize.width,
+ });
+ const output = addDecodeOutput({
+ denoise,
+ graph,
+ l2iType: 'sd3_l2i',
+ model,
+ outputIsIntermediate,
+ positivePrompt,
+ seed,
+ settings,
+ vaeSource: modelLoader,
});
- const output = addImageOutputNode(graph, 'sd3_l2i', outputIsIntermediate);
addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');
addEdge(graph, modelLoader, 'clip_l', posCond, 'clip_l');
@@ -465,16 +557,15 @@ const buildSD3Graph = (
addEdge(graph, modelLoader, 'clip_g', negCond, 'clip_g');
addEdge(graph, modelLoader, 't5_encoder', posCond, 't5_encoder');
addEdge(graph, modelLoader, 't5_encoder', negCond, 't5_encoder');
- addEdge(graph, modelLoader, 'vae', output, 'vae');
addEdge(graph, positivePrompt, 'value', posCond, 'prompt');
addEdge(graph, negativePrompt, 'value', negCond, 'prompt');
addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');
addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');
addEdge(graph, seed, 'value', denoise, 'seed');
- addEdge(graph, denoise, 'latents', output, 'latents');
addMetadata(graph, output, settings, model, 'sd3_txt2img', projectSettings, {
scheduler: undefined,
vae: settings.vae ?? undefined,
+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
return graph;
@@ -491,7 +582,7 @@ const buildFluxGraph = (
}
const graph: BackendGraphContract = { edges: [], id: createId('flux_graph'), nodes: {} };
- const { positivePrompt } = addPromptAndSeedNodes(graph);
+ const { positivePrompt, seed } = addPromptAndSeedNodes(graph);
const t5EncoderModel = requireComponent(settings.t5EncoderModel, 'T5 Encoder');
const clipEmbedModel = requireComponent(settings.clipEmbedModel, 'CLIP Embed');
const vaeModel = requireComponent(getCompatibleVae(settings, ['flux']), 'FLUX VAE');
@@ -514,25 +605,35 @@ 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 denoise = addNode(graph, {
denoising_end: 1,
denoising_start: 0,
guidance: settings.cfgScale,
- height: settings.height,
+ height: denoiseSize.height,
id: 'denoise_latents',
num_steps: settings.steps,
scheduler,
type: 'flux_denoise',
- width: settings.width,
+ width: denoiseSize.width,
+ });
+ const output = addDecodeOutput({
+ denoise,
+ graph,
+ l2iType: 'flux_vae_decode',
+ model,
+ outputIsIntermediate,
+ positivePrompt,
+ seed,
+ settings,
+ vaeSource: modelLoader,
});
- const output = addImageOutputNode(graph, 'flux_vae_decode', outputIsIntermediate);
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, loraSource, 'transformer', denoise, 'transformer');
addEdge(graph, modelLoader, 'vae', denoise, 'controlnet_vae');
- addEdge(graph, modelLoader, 'vae', output, 'vae');
addEdge(graph, positivePrompt, 'value', posCond, 'prompt');
addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');
addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');
@@ -542,13 +643,13 @@ const buildFluxGraph = (
}
addIPAdapterReferenceImages(graph, settings, model, denoise);
addFluxReduxReferenceImages(graph, settings, model, denoise);
- addEdge(graph, denoise, 'latents', output, 'latents');
addMetadata(graph, output, settings, model, 'flux_txt2img', projectSettings, {
clip_embed_model: clipEmbedModel,
guidance: settings.cfgScale,
scheduler,
t5_encoder: t5EncoderModel,
vae: vaeModel,
+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
addReferenceImageMetadata(graph, output, settings);
@@ -593,36 +694,46 @@ const buildFlux2Graph = (
: modelLoader;
const posCond = addNode(graph, { id: 'pos_cond', type: 'flux2_klein_text_encoder' });
const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });
+ const flux2DenoiseSize = getDenoiseSize(settings, model);
const denoise = addNode(graph, {
cfg_scale: 1,
denoising_end: 1,
denoising_start: 0,
guidance: settings.cfgScale,
- height: settings.height,
+ height: flux2DenoiseSize.height,
id: 'denoise_latents',
num_steps: settings.steps,
scheduler,
type: 'flux2_denoise',
- width: settings.width,
+ width: flux2DenoiseSize.width,
+ });
+ const output = addDecodeOutput({
+ denoise,
+ graph,
+ l2iType: 'flux2_vae_decode',
+ model,
+ outputIsIntermediate,
+ positivePrompt,
+ seed: graph.nodes.seed,
+ settings,
+ vaeSource: modelLoader,
});
- const output = addImageOutputNode(graph, 'flux2_vae_decode', outputIsIntermediate);
addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');
addEdge(graph, modelLoader, 'max_seq_len', posCond, 'max_seq_len');
addEdge(graph, loraSource, 'transformer', denoise, 'transformer');
addEdge(graph, modelLoader, 'vae', denoise, 'vae');
- addEdge(graph, modelLoader, 'vae', output, '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');
- addEdge(graph, denoise, 'latents', output, 'latents');
addMetadata(graph, output, settings, model, 'flux2_txt2img', projectSettings, {
qwen3_encoder: qwen3EncoderModel ?? undefined,
qwen3_source: sourceModel,
scheduler,
vae: vaeModel ?? undefined,
+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
addReferenceImageMetadata(graph, output, settings);
@@ -700,19 +811,29 @@ const buildQwenImageGraph = (
: modelLoader;
const posCond = addNode(graph, { id: 'pos_cond', type: 'qwen_image_text_encoder' });
const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'qwen_image_text_encoder' }) : null;
+ const qwenDenoiseSize = getDenoiseSize(settings, model);
const denoise = addNode(graph, {
cfg_scale: settings.cfgScale,
- height: settings.height,
+ height: qwenDenoiseSize.height,
id: 'denoise_latents',
steps: settings.steps,
type: 'qwen_image_denoise',
- width: settings.width,
+ width: qwenDenoiseSize.width,
+ });
+ const output = addDecodeOutput({
+ denoise,
+ graph,
+ l2iType: 'qwen_image_l2i',
+ model,
+ outputIsIntermediate,
+ positivePrompt,
+ seed,
+ settings,
+ vaeSource: modelLoader,
});
- const output = addImageOutputNode(graph, 'qwen_image_l2i', outputIsIntermediate);
addEdge(graph, loraSource, 'transformer', denoise, 'transformer');
addEdge(graph, modelLoader, 'qwen_vl_encoder', posCond, 'qwen_vl_encoder');
- addEdge(graph, modelLoader, 'vae', output, 'vae');
addEdge(graph, positivePrompt, 'value', posCond, 'prompt');
addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');
@@ -766,12 +887,12 @@ const buildQwenImageGraph = (
addEdge(graph, refI2l, 'latents', denoise, 'reference_latents');
}
}
- addEdge(graph, denoise, 'latents', output, 'latents');
addMetadata(graph, output, settings, model, 'qwen_image_txt2img', projectSettings, {
qwen_image_component_source: sourceModel,
qwen_image_qwen_vl_encoder: settings.qwenVLEncoderModel ?? undefined,
qwen_image_vae: vaeModel ?? undefined,
scheduler: undefined,
+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
addReferenceImageMetadata(graph, output, settings);
@@ -818,23 +939,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,
guidance_scale: settings.cfgScale,
- height: settings.height,
+ height: zImageDenoiseSize.height,
id: 'denoise_latents',
scheduler,
steps: settings.steps,
type: 'z_image_denoise',
- width: settings.width,
+ width: zImageDenoiseSize.width,
+ });
+ const output = addDecodeOutput({
+ denoise,
+ graph,
+ l2iType: 'z_image_l2i',
+ model,
+ outputIsIntermediate,
+ positivePrompt,
+ seed,
+ settings,
+ vaeSource: modelLoader,
});
- const output = addImageOutputNode(graph, 'z_image_l2i', outputIsIntermediate);
addEdge(graph, loraSource, 'transformer', denoise, 'transformer');
addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');
addEdge(graph, modelLoader, 'vae', denoise, 'vae');
- addEdge(graph, modelLoader, 'vae', output, 'vae');
addEdge(graph, positivePrompt, 'value', posCond, 'prompt');
addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');
addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');
@@ -847,12 +978,12 @@ const buildZImageGraph = (
}
addEdge(graph, seed, 'value', denoise, 'seed');
- addEdge(graph, denoise, 'latents', output, 'latents');
addMetadata(graph, output, settings, model, 'z_image_txt2img', projectSettings, {
qwen3_encoder: qwen3EncoderModel ?? undefined,
qwen3_source: sourceModel,
scheduler,
vae: vaeModel ?? undefined,
+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
return graph;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/pid.test.ts b/invokeai/frontend/webv2/src/features/generation/core/pid.test.ts
new file mode 100644
index 0000000000..5647b8812e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/pid.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ clampPidSteps,
+ getIsPidActive,
+ getIsPidSupportedBase,
+ getPidDecoderBaseForMainBase,
+ getPidDimensionOverrides,
+ getPidGenerationSize,
+ getPidScale,
+ isPidMode,
+ PID_SCALE,
+} from './pid';
+
+describe('getPidDecoderBaseForMainBase', () => {
+ it('maps each supported base to its own decoder base', () => {
+ expect(getPidDecoderBaseForMainBase('flux')).toBe('flux');
+ expect(getPidDecoderBaseForMainBase('flux2')).toBe('flux2');
+ expect(getPidDecoderBaseForMainBase('sd-3')).toBe('sd-3');
+ expect(getPidDecoderBaseForMainBase('sdxl')).toBe('sdxl');
+ expect(getPidDecoderBaseForMainBase('qwen-image')).toBe('qwen-image');
+ });
+
+ it('maps Z-Image to the FLUX decoder, which it shares a VAE with', () => {
+ // Z-Image ships no PiD checkpoints of its own; it reuses FLUX's 16-channel decoder.
+ expect(getPidDecoderBaseForMainBase('z-image')).toBe('flux');
+ });
+
+ it('returns null for bases with no PiD support', () => {
+ expect(getPidDecoderBaseForMainBase('krea-2')).toBeNull();
+ expect(getPidDecoderBaseForMainBase('wan')).toBeNull();
+ expect(getPidDecoderBaseForMainBase('sd-1')).toBeNull();
+ expect(getPidDecoderBaseForMainBase('anima')).toBeNull();
+ expect(getPidDecoderBaseForMainBase(null)).toBeNull();
+ expect(getPidDecoderBaseForMainBase(undefined)).toBeNull();
+ });
+});
+
+describe('getIsPidSupportedBase / getIsPidActive', () => {
+ it('reports support independently of the mode', () => {
+ expect(getIsPidSupportedBase('flux')).toBe(true);
+ expect(getIsPidSupportedBase('krea-2')).toBe(false);
+ });
+
+ it('is inactive while off, and on an unsupported base whatever the mode', () => {
+ expect(getIsPidActive('off', 'flux')).toBe(false);
+ expect(getIsPidActive('fit', 'krea-2')).toBe(false);
+ expect(getIsPidActive('native', 'krea-2')).toBe(false);
+ });
+
+ it('is active for a supported base in fit and native', () => {
+ expect(getIsPidActive('fit', 'flux')).toBe(true);
+ expect(getIsPidActive('native', 'z-image')).toBe(true);
+ });
+});
+
+describe('getPidScale', () => {
+ it('only scales in native mode', () => {
+ expect(getPidScale('off')).toBe(1);
+ expect(getPidScale('fit')).toBe(1);
+ expect(getPidScale('native')).toBe(PID_SCALE);
+ });
+});
+
+describe('getPidGenerationSize', () => {
+ it('leaves the size alone when off or fitting', () => {
+ expect(getPidGenerationSize({ height: 1024, width: 1024 }, 'off', 16)).toEqual({ height: 1024, width: 1024 });
+ expect(getPidGenerationSize({ height: 1024, width: 1024 }, 'fit', 16)).toEqual({ height: 1024, width: 1024 });
+ });
+
+ it('generates at a quarter of the requested size in native mode', () => {
+ // 2048 is the native optimum; a quarter of it is FLUX's own 512 optimum.
+ expect(getPidGenerationSize({ height: 2048, width: 2048 }, 'native', 16)).toEqual({ height: 512, width: 512 });
+ });
+
+ it('keeps a non-square native target proportional', () => {
+ expect(getPidGenerationSize({ height: 1024, width: 2048 }, 'native', 16)).toEqual({ height: 256, width: 512 });
+ });
+
+ it('floors a hand-entered size onto the model grid', () => {
+ // 2044 / 4 = 511, which is not a multiple of 16, so it floors to 496.
+ expect(getPidGenerationSize({ height: 2044, width: 2044 }, 'native', 16)).toEqual({ height: 496, width: 496 });
+ });
+
+ it('never floors below one grid step', () => {
+ expect(getPidGenerationSize({ height: 16, width: 16 }, 'native', 16)).toEqual({ height: 16, width: 16 });
+ });
+});
+
+describe('getPidDimensionOverrides', () => {
+ it('leaves the model rules alone when PiD is off or fitting', () => {
+ expect(getPidDimensionOverrides('off', 'flux', 16, 1024)).toEqual({ grid: 16, optimalSide: 1024 });
+ // Fit generates at the requested size, so the model's own grid still applies.
+ expect(getPidDimensionOverrides('fit', 'flux', 16, 1024)).toEqual({ grid: 16, optimalSide: 1024 });
+ });
+
+ it('scales the grid and reports PiD’s own optimum in native mode', () => {
+ // grid * 4 keeps requested / 4 on the model's grid; 2048 is 512 -> 4x.
+ expect(getPidDimensionOverrides('native', 'flux', 16, 1024)).toEqual({ grid: 64, optimalSide: 2048 });
+ expect(getPidDimensionOverrides('native', 'sdxl', 8, 1024)).toEqual({ grid: 32, optimalSide: 2048 });
+ });
+
+ it('leaves an unsupported base alone even in native mode', () => {
+ expect(getPidDimensionOverrides('native', 'krea-2', 16, 1024)).toEqual({ grid: 16, optimalSide: 1024 });
+ });
+
+ it('produces a grid that divides the native optimum exactly', () => {
+ for (const [base, grid] of [
+ ['flux', 16],
+ ['sdxl', 8],
+ ] as const) {
+ const overrides = getPidDimensionOverrides('native', base, grid, 1024);
+
+ expect(overrides.optimalSide % overrides.grid).toBe(0);
+ // And the resulting generation size lands on the model's own grid.
+ expect(
+ getPidGenerationSize({ height: overrides.optimalSide, width: overrides.optimalSide }, 'native', grid)
+ ).toEqual({ height: overrides.optimalSide / 4, width: overrides.optimalSide / 4 });
+ }
+ });
+});
+
+describe('isPidMode / clampPidSteps', () => {
+ it('accepts only the three modes', () => {
+ expect(isPidMode('off')).toBe(true);
+ expect(isPidMode('fit')).toBe(true);
+ expect(isPidMode('native')).toBe(true);
+ expect(isPidMode('4x')).toBe(false);
+ expect(isPidMode(null)).toBe(false);
+ expect(isPidMode(4)).toBe(false);
+ });
+
+ it('clamps and rounds steps into range', () => {
+ expect(clampPidSteps(4)).toBe(4);
+ expect(clampPidSteps(0)).toBe(1);
+ expect(clampPidSteps(-3)).toBe(1);
+ expect(clampPidSteps(99)).toBe(16);
+ expect(clampPidSteps(4.6)).toBe(5);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/pid.ts b/invokeai/frontend/webv2/src/features/generation/core/pid.ts
new file mode 100644
index 0000000000..741eb35db6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/pid.ts
@@ -0,0 +1,113 @@
+import type { KnownGenerationModelBase as KnownModelBase } from '@features/generation/core/contracts';
+
+import type { PidMode } from './types';
+
+/**
+ * PiD (Pixel Diffusion Decoder) — NVIDIA's few-step pixel-diffusion decoder that
+ * replaces the VAE decode with a caption-conditioned 4x super-resolution decode.
+ *
+ * Pure geometry and base-compatibility rules; the graph wiring lives in `graph.ts`.
+ */
+
+/** PiD's fixed super-resolution factor. Every released checkpoint is 4x. */
+export const PID_SCALE = 4;
+
+/** Default decode steps. The released checkpoints are 4-step distillations. */
+export const DEFAULT_PID_STEPS = 4;
+export const MIN_PID_STEPS = 1;
+export const MAX_PID_STEPS = 16;
+
+/**
+ * PiD res2k decoders are trained 512 -> 2048. In native mode the user-facing
+ * dimensions are the 4x target, so the optimal *target* side is 2048 regardless of the
+ * main model's own optimum.
+ */
+const PID_NATIVE_OPTIMAL_SIDE = 512 * PID_SCALE;
+
+export const PID_MODES: readonly PidMode[] = ['off', 'fit', 'native'];
+
+export const isPidMode = (value: unknown): value is PidMode =>
+ typeof value === 'string' && (PID_MODES as readonly string[]).includes(value);
+
+/**
+ * The generation scale the dimension helpers must account for: 4 in native mode (the
+ * requested size is the 4x target), 1 otherwise.
+ */
+export const getPidScale = (mode: PidMode): number => (mode === 'native' ? PID_SCALE : 1);
+
+/**
+ * The base whose PiD decoder checkpoints are valid for a given main-model base.
+ *
+ * Decoders are trained per backbone, so only a base-matching decoder may be used.
+ * Z-Image is the exception: it shares FLUX.1's 16-channel VAE and ships no decoder of
+ * its own, so it reuses the FLUX decoder. Returns null for bases with no PiD support.
+ */
+export const getPidDecoderBaseForMainBase = (base: string | null | undefined): KnownModelBase | null => {
+ switch (base) {
+ case 'z-image':
+ return 'flux';
+ case 'flux':
+ case 'flux2':
+ case 'sd-3':
+ case 'sdxl':
+ case 'qwen-image':
+ return base;
+ default:
+ return null;
+ }
+};
+
+/** Whether a main-model base can decode through PiD. */
+export const getIsPidSupportedBase = (base: string | null | undefined): boolean =>
+ getPidDecoderBaseForMainBase(base) !== null;
+
+/** Whether PiD is actually engaged: on, and supported by this base. */
+export const getIsPidActive = (mode: PidMode, base: string | null | undefined): boolean =>
+ mode !== 'off' && getIsPidSupportedBase(base);
+
+const roundDownToMultiple = (value: number, multiple: number): number => Math.floor(value / multiple) * multiple;
+
+/**
+ * The resolution to actually denoise at.
+ *
+ * In native mode the requested size is the 4x target, so generation runs at size / 4,
+ * floored onto the model's own grid. Callers snap the requested size to grid * 4 (see
+ * `getGenerationDimensions`), so the division lands exactly on the grid; the floor and
+ * the `max` only guard hand-entered values.
+ */
+export const getPidGenerationSize = (
+ requested: { width: number; height: number },
+ mode: PidMode,
+ modelGrid: number
+): { width: number; height: number } => {
+ if (mode !== 'native') {
+ return { height: requested.height, width: requested.width };
+ }
+
+ return {
+ height: Math.max(roundDownToMultiple(requested.height / PID_SCALE, modelGrid), modelGrid),
+ width: Math.max(roundDownToMultiple(requested.width / PID_SCALE, modelGrid), modelGrid),
+ };
+};
+
+/**
+ * The dimension grid and optimal side to present for a PiD mode.
+ *
+ * Native multiplies the grid by 4 so that requested / 4 stays on the model grid, and
+ * reports PiD's own 2048 target as optimal rather than the model's 1024.
+ */
+export const getPidDimensionOverrides = (
+ mode: PidMode,
+ base: string | null | undefined,
+ modelGrid: number,
+ modelOptimalSide: number
+): { grid: number; optimalSide: number } => {
+ if (!getIsPidActive(mode, base) || mode !== 'native') {
+ return { grid: modelGrid, optimalSide: modelOptimalSide };
+ }
+
+ return { grid: modelGrid * PID_SCALE, optimalSide: PID_NATIVE_OPTIMAL_SIDE };
+};
+
+export const clampPidSteps = (steps: number): number =>
+ Math.min(MAX_PID_STEPS, Math.max(MIN_PID_STEPS, Math.round(steps)));
diff --git a/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts
new file mode 100644
index 0000000000..04b06a69b2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/pidGraph.ts
@@ -0,0 +1,168 @@
+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';
+
+import type { GenerateSettings, PidMode } from './types';
+
+import { addEdge, addNode, createId } from './graphBuilder';
+import { getIsPidActive, getPidGenerationSize } from './pid';
+
+/**
+ * PiD decode wiring: replaces a base's VAE decode with the caption-conditioned 4x
+ * super-resolution decode.
+ *
+ * The geometry rules live in `pid.ts`; this module only builds nodes and edges.
+ */
+
+/** The per-base PiD decode node types. One per base whose builder wires PiD. */
+export const PID_DECODE_NODE_TYPES = {
+ flux: 'flux_pid_decode',
+ flux2: 'flux2_pid_decode',
+ 'qwen-image': 'qwen_image_pid_decode',
+ 'sd-3': 'sd3_pid_decode',
+ sdxl: 'sdxl_pid_decode',
+ 'z-image': 'z_image_pid_decode',
+} as const;
+
+export type PidDecodeNodeType = (typeof PID_DECODE_NODE_TYPES)[keyof typeof PID_DECODE_NODE_TYPES];
+
+/**
+ * Decode nodes that read scaling constants off the VAE at runtime, so the VAE must be
+ * wired even though PiD replaces the decode. FLUX.1 and SD3 use fixed constants and
+ * take no `vae` input.
+ */
+const PID_DECODE_NODES_WITH_VAE_INPUT: ReadonlySet<string> = new Set([
+ 'flux2_pid_decode',
+ 'qwen_image_pid_decode',
+ 'sdxl_pid_decode',
+ 'z_image_pid_decode',
+]);
+
+export const getPidDecodeNodeType = (base: string | null | undefined): PidDecodeNodeType | null =>
+ base && base in PID_DECODE_NODE_TYPES ? PID_DECODE_NODE_TYPES[base as keyof typeof PID_DECODE_NODE_TYPES] : null;
+
+/**
+ * Whether this build should decode through PiD: the mode is on, the base supports it,
+ * and both required models are selected.
+ *
+ * Readiness rejects a half-configured PiD before compilation, so a false here after
+ * readiness has passed means PiD is genuinely off rather than broken.
+ */
+export const shouldUsePidDecode = (
+ settings: Pick<GenerateSettings, 'pidMode' | 'pidDecoderModel' | 'gemma2EncoderModel'>,
+ base: string | null | undefined
+): boolean =>
+ getIsPidActive(settings.pidMode, base) &&
+ settings.pidDecoderModel !== null &&
+ settings.gemma2EncoderModel !== null &&
+ getPidDecodeNodeType(base) !== null;
+
+/** The resolution to denoise at, which in native mode is the requested size / 4. */
+export const getPidDenoiseSize = (
+ settings: Pick<GenerateSettings, 'pidMode' | 'width' | 'height'>,
+ base: string | null | undefined,
+ modelGrid: number
+): { width: number; height: number } =>
+ getPidGenerationSize(
+ { height: settings.height, width: settings.width },
+ getIsPidActive(settings.pidMode, base) ? settings.pidMode : 'off',
+ modelGrid
+ );
+
+interface AddPidDecodeArg {
+ graph: BackendGraphContract;
+ settings: GenerateSettings;
+ base: string;
+ /** The denoise node producing the latents to decode. */
+ denoise: BackendInvocationContract;
+ /** The positive prompt node — PiD conditions its decode on the same caption. */
+ positivePrompt: BackendInvocationContract;
+ /** The seed node, reused for PiD's internal decode noise so results reproduce. */
+ seed: BackendInvocationContract;
+ /** VAE source, wired only for decode nodes that read its constants. */
+ vaeSource?: BackendInvocationContract;
+ /** The VAE output field on `vaeSource` (model loaders expose `vae`). */
+ vaeField?: string;
+ outputIsIntermediate: boolean;
+}
+
+/**
+ * Builds the PiD decode chain and returns the terminal image node.
+ *
+ * The terminal node is always `canvas_output`: result hydration looks the output up by
+ * that exact id (`resultNodeIds: ['canvas_output']`). In fit mode that is the
+ * downscaling `img_resize`; in native mode PiD's 4x output is the result, so the decode
+ * node itself takes the id.
+ */
+export const addPidDecode = ({
+ graph,
+ settings,
+ base,
+ denoise,
+ positivePrompt,
+ seed,
+ vaeSource,
+ vaeField = 'vae',
+ outputIsIntermediate,
+}: AddPidDecodeArg): BackendInvocationContract => {
+ const decodeNodeType = getPidDecodeNodeType(base);
+
+ if (!decodeNodeType || !settings.pidDecoderModel || !settings.gemma2EncoderModel) {
+ throw new Error('PiD decoding needs a PiD decoder and a Gemma-2 encoder.');
+ }
+
+ const isNative = settings.pidMode === 'native';
+ const gemma2Loader = addNode(graph, {
+ gemma2_model: settings.gemma2EncoderModel,
+ id: createId('gemma2_encoder_loader'),
+ type: 'gemma2_encoder_loader',
+ });
+ const pidLoader = addNode(graph, {
+ id: createId('pid_decoder_loader'),
+ pid_decoder_model: settings.pidDecoderModel,
+ type: 'pid_decoder_loader',
+ });
+ const pidDecode = addNode(graph, {
+ // In native mode this node IS the output, so it claims the id and the caller's
+ // intermediate flag; in fit mode the resize downstream is the output.
+ id: isNative ? 'canvas_output' : createId('pid_decode'),
+ is_intermediate: isNative ? outputIsIntermediate : true,
+ num_inference_steps: settings.pidSteps,
+ type: decodeNodeType,
+ use_cache: false,
+ });
+
+ addEdge(graph, denoise, 'latents', pidDecode, 'latents');
+ addEdge(graph, positivePrompt, 'value', pidDecode, 'prompt');
+ addEdge(graph, gemma2Loader, 'gemma2_encoder', pidDecode, 'gemma2_encoder');
+ addEdge(graph, pidLoader, 'pid_decoder', pidDecode, 'pid_decoder');
+ addEdge(graph, seed, 'value', pidDecode, 'seed');
+
+ if (vaeSource && PID_DECODE_NODES_WITH_VAE_INPUT.has(decodeNodeType)) {
+ addEdge(graph, vaeSource, vaeField, pidDecode, 'vae');
+ }
+
+ if (isNative) {
+ return pidDecode;
+ }
+
+ // Fit mode: PiD decoded 4x, so downscale back to the requested size. Keeps the result
+ // exactly the size the user asked for, which is what makes it compositing-safe.
+ const resize = addNode(graph, {
+ height: settings.height,
+ id: 'canvas_output',
+ is_intermediate: outputIsIntermediate,
+ type: 'img_resize',
+ use_cache: false,
+ width: settings.width,
+ });
+ addEdge(graph, pidDecode, 'image', resize, 'image');
+
+ return resize;
+};
+
+/** The PiD fields to record in image metadata. */
+export const getPidMetadata = (settings: GenerateSettings): Record<string, unknown> & { pid_mode: PidMode } => ({
+ gemma2_encoder: settings.gemma2EncoderModel,
+ pid_decoder: settings.pidDecoderModel,
+ pid_mode: settings.pidMode,
+ pid_steps: settings.pidSteps,
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index a0a9a790b4..0d75bbc9a5 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -18,6 +18,7 @@ import type {
import { sanitizeBatchCount } from './batch';
import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';
import { isDynamicPromptsSeedBehaviour, sanitizeMaxPrompts, sanitizeSampleSeed } from './dynamicPrompts';
+import { clampPidSteps, DEFAULT_PID_STEPS, isPidMode } from './pid';
import { isCanonicalPromptTemplateSnapshot, sanitizePromptTemplateSnapshot } from './promptTemplates';
import { cloneCroppableImage, isCanonicalCroppableImage, normalizeCroppableImage } from './referenceImage';
@@ -741,6 +742,10 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n
100,
DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT
),
+ pidMode: isPidMode(values.pidMode) ? values.pidMode : 'off',
+ pidDecoderModel: getModelIdentifierOrNull(values.pidDecoderModel),
+ gemma2EncoderModel: getModelIdentifierOrNull(values.gemma2EncoderModel),
+ pidSteps: clampPidSteps(hasFiniteNumber(values, 'pidSteps') ? (values.pidSteps as number) : DEFAULT_PID_STEPS),
width,
};
};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.ts
index 1b59581f0d..8a88ffe8a6 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts
@@ -235,8 +235,27 @@ export interface GenerateSettings {
krea2SeedVarianceEnabled: boolean;
krea2SeedVarianceStrength: number;
krea2SeedVarianceRandomizePercent: number;
+ /**
+ * PiD (Pixel Diffusion Decoder) replaces the VAE decode with a caption-conditioned
+ * 4x super-resolution decode. Off by default; requires a PiD decoder and a Gemma-2
+ * caption encoder.
+ */
+ pidMode: PidMode;
+ /** PiD decoder checkpoint. Trained per backbone, so it must match the main model's base. */
+ pidDecoderModel: ComponentModelConfig | null;
+ /** The shared Gemma-2 caption encoder PiD conditions its decode on. */
+ gemma2EncoderModel: ComponentModelConfig | null;
+ pidSteps: number;
}
+/**
+ * - `off`: ordinary VAE decode.
+ * - `fit`: generate at the requested size, decode 4x, downscale back to it.
+ * - `native`: the requested size IS the 4x target; generate at size / 4 and keep the
+ * full 4x output.
+ */
+export type PidMode = 'off' | 'fit' | 'native';
+
/**
* Ideogram 4 sampler presets. Each fixes a step count and guidance schedule; the explicit
* step / guidance / mu overrides are applied on top when set.
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx
index a3610ddb75..63dad0e808 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx
@@ -3,9 +3,10 @@ import type { GenerateModelConfig, GenerateSettings } from '@features/generation
import { Badge, createListCollection, HStack, Stack, Switch } from '@chakra-ui/react';
import { getDefaultGenerateSettings, getGenerationUiPolicy } from '@features/generation/core/baseGenerationPolicies';
+import { isPidMode, MAX_PID_STEPS, MIN_PID_STEPS } from '@features/generation/core/pid';
import { isVaeModelConfig } from '@features/generation/core/settings';
import { Field, Select } from '@platform/ui';
-import { useId } from 'react';
+import { useId, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { GenerationModelSelect as ModelSelect } from './GenerationUiContext';
@@ -67,6 +68,23 @@ export const GenerateAdvancedFields = ({
const modelBase = selectedModel?.base;
const modelDefaults = selectedModel ? getDefaultGenerateSettings(selectedModel) : null;
const policy = getGenerationUiPolicy(selectedModel, settings);
+ const pidHelpText =
+ settings.pidMode === 'fit'
+ ? t('widgets.generate.pidFitHelp')
+ : settings.pidMode === 'native'
+ ? t('widgets.generate.pidNativeHelp')
+ : t('widgets.generate.pidHelp');
+ const pidModeCollection = useMemo(
+ () =>
+ createListCollection({
+ items: [
+ { label: t('widgets.generate.pidOff'), value: 'off' },
+ { label: t('widgets.generate.pidFit'), value: 'fit' },
+ { label: t('widgets.generate.pidNative'), value: 'native' },
+ ],
+ }),
+ [t]
+ );
const clipSkipMax = policy.clipSkipMax ?? 0;
const updateNumber = (key: 'cfgRescaleMultiplier' | 'clipSkip', max: number) => (value: number) => {
@@ -213,6 +231,40 @@ export const GenerateAdvancedFields = ({
</Field>
) : null}
+ {policy.pidVisible ? (
+ <HStack alignItems="flex-start" gap="2" p="2">
+ <Field flex="2" label={t('widgets.generate.pid')} helpText={pidHelpText}>
+ <Select
+ aria-label={t('widgets.generate.pid')}
+ collection={pidModeCollection}
+ size="xs"
+ value={[settings.pidMode]}
+ onValueChange={({ value }) => {
+ const mode = value[0];
+
+ if (isPidMode(mode)) {
+ // Committed immediately: switching to or from native changes the dimension
+ // grid, and a debounced write would let a now-invalid size linger.
+ onCommitImmediate({ pidMode: mode });
+ }
+ }}
+ />
+ </Field>
+ {settings.pidMode === 'off' ? null : (
+ <Field flex="1" label={t('widgets.generate.pidSteps')}>
+ <SliderNumberField
+ ariaLabel={t('widgets.generate.pidSteps')}
+ min={MIN_PID_STEPS}
+ max={MAX_PID_STEPS}
+ step={1}
+ value={settings.pidSteps}
+ onChange={(value) => onCommit({ pidSteps: value })}
+ />
+ </Field>
+ )}
+ </HStack>
+ ) : null}
+
{policy.seamlessVisible ? (
<Field label={t('widgets.generate.seamlessTiling')} p="2">
<HStack gap="4">
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx
index 71e91f3946..c2373d904b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx
@@ -38,6 +38,8 @@ const getComponentPolicyContext = (model: GenerateModelConfig, settings: Generat
wanT5EncoderModel: settings.wanT5EncoderModel,
wanLowNoiseModel: settings.wanLowNoiseModel,
t5EncoderModel: settings.t5EncoderModel,
+ pidDecoderModel: settings.pidDecoderModel,
+ gemma2EncoderModel: settings.gemma2EncoderModel,
vae: settings.vae,
},
});
diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.ts
index 2fc291a2e8..8e53af1402 100644
--- a/invokeai/frontend/webv2/src/features/models/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts
@@ -45,6 +45,8 @@ export type ModelTaxonomyType =
| 'qwen_vl_encoder'
| 'qwen3_vl_encoder'
| 'wan_t5_encoder'
+ | 'gemma2_encoder'
+ | 'pid_decoder'
| 'siglip'
| 'spandrel_image_to_image'
| 'flux_redux'
@@ -70,6 +72,7 @@ export type ModelFileFormat =
| 'qwen_vl_encoder'
| 'qwen3_vl_encoder'
| 'wan_t5_encoder'
+ | 'gemma2_encoder'
| 'bnb_quantized_int8b'
| 'bnb_quantized_nf4b'
| 'gguf_quantized'
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
index 41de40ee31..fc1995f45b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -104,6 +104,10 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])
krea2SeedVarianceEnabled: false,
krea2SeedVarianceStrength: 0.1,
krea2SeedVarianceRandomizePercent: 50,
+ pidMode: 'off',
+ pidDecoderModel: null,
+ gemma2EncoderModel: null,
+ pidSteps: 4,
referenceImages: [],
scheduler: 'euler_a',
seamlessXAxis: false,
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index 8f507b37eb..ee9e67163d 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -34,6 +34,10 @@ const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWi
aspectRatioIsLocked: false,
aspectRatioValue: 1,
batchCount: 1,
+ pidMode: 'off',
+ pidDecoderModel: null,
+ gemma2EncoderModel: null,
+ pidSteps: 4,
cfgRescaleMultiplier: 0,
cfgScale: 7,
clipEmbedModel: null,
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index c4b511a3a3..79e6c124f5 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -134,6 +134,10 @@ const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): Ge
aspectRatioIsLocked: false,
aspectRatioValue: 1,
batchCount: 1,
+ pidMode: 'off',
+ pidDecoderModel: null,
+ gemma2EncoderModel: null,
+ pidSteps: 4,
cfgRescaleMultiplier: 0,
cfgScale: 7,
clipEmbedModel: null,