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.

fix(pid): make PiD 1.5 usable for FLUX.1 and FLUX.2

Alexander Eichhorna6903aa30e8b
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
index 746621ae2f..14eea2ba68 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
@@ -142,7 +142,8 @@ CLIP and T5 encoders.
## PiD super-resolution decode
FLUX.1 latents can be decoded with a PiD decoder, which produces a 4× super-resolved image. Install *PiD
-Decoder FLUX (2K)* or *PiD Decoder FLUX (2K to 4K)*; see [PiD Super-Resolution
+Decoder FLUX (2K)*, *PiD Decoder FLUX (2K to 4K)* or the newer *PiD 1.5 Decoder FLUX (2K to 4K)* (also as an
+int8 build); see [PiD Super-Resolution
Decode](/users-guide/image-generation/advanced-topics/pid-decode/).
## Workflow nodes
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
index e44f067adc..4c7471c6ed 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
@@ -154,7 +154,8 @@ FLUX.2 [dev]** (and their *Collection* versions).
## PiD super-resolution decode
FLUX.2 Klein latents can be decoded with a PiD decoder for a 4× super-resolved image. Install *PiD Decoder
-FLUX.2 (2K)* or *PiD Decoder FLUX.2 (2K to 4K)*; see [PiD Super-Resolution
+FLUX.2 (2K)*, *PiD Decoder FLUX.2 (2K to 4K)* or the newer *PiD 1.5 Decoder FLUX.2 (2K to 4K)* (also as
+an int8 build); see [PiD Super-Resolution
Decode](/users-guide/image-generation/advanced-topics/pid-decode/).
## Workflow nodes
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/pid-decode.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/pid-decode.mdx
index 82fd9acea1..1fe55efa95 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/pid-decode.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/pid-decode.mdx
@@ -44,16 +44,16 @@ PiD needs two extra models, both available in **Model Manager → Starter Models
A first-generation PiD decoder download is roughly 5 GB, a PiD 1.5 decoder download roughly 2.8 GB (1.6 GB for its int8 build), and the shared Gemma-2 encoder is roughly 5 GB. Once loaded, a decoder runs in full precision and takes about 5.6 GB in either generation; the PiD 1.5 int8 build keeps its transformer layers in int8 and takes about 2 GB.
<Aside type="note">
-Most Starter Models install NVIDIA's first-generation PiD checkpoints, which are spread over both the `checkpoints/` and the `checkpoints_deprecated/` folder of the `nvidia/PiD` repository depending on the backbone and preset. NVIDIA's second generation, **PiD 1.5**, exists for FLUX.1, FLUX.2 and Qwen-Image in the *2K-to-4K* preset. *PiD 1.5 Decoder Qwen-Image* is a Starter Model; the FLUX.1 and FLUX.2 decoders install from Comfy-Org's single files by URL, e.g. `https://huggingface.co/Comfy-Org/PixelDiT/resolve/main/diffusion_models/pid_1.5_flux2_1024_to_4096_4step_bf16.safetensors`. Both generations decode through the same nodes.
+Most Starter Models install NVIDIA's first-generation PiD checkpoints, which are spread over both the `checkpoints/` and the `checkpoints_deprecated/` folder of the `nvidia/PiD` repository depending on the backbone and preset. NVIDIA's second generation, **PiD 1.5**, exists for FLUX.1, FLUX.2 and Qwen-Image in the *2K-to-4K* preset. All three are Starter Models (*PiD 1.5 Decoder FLUX*, *PiD 1.5 Decoder FLUX.2*, *PiD 1.5 Decoder Qwen-Image*), installed from Comfy-Org's single-file builds. Both generations decode through the same nodes.
-Only the `_4step` builds work: the files without it are NVIDIA's undistilled teacher decoders, which need a different sampler, and are rejected during model identification. The `_4step_int8_convrot` builds (*PiD 1.5 Decoder Qwen-Image (2K to 4K, int8)* is a Starter Model) keep the decoder's transformer layers in int8: about 2 GB once loaded instead of 5.6 GB, with output practically identical to the full-precision build.
+Only the `_4step` builds work: the files without it are NVIDIA's undistilled teacher decoders, which need a different sampler, and are rejected during model identification. The `_4step_int8_convrot` builds (each PiD 1.5 decoder has an *int8* Starter Model) keep the decoder's transformer layers in int8: about 2 GB once loaded instead of 5.6 GB, with output practically identical to the full-precision build.
</Aside>
The Gemma-2 caption encoder can also be a single-file **GGUF** (e.g. `gemma-2-2b-it-Q4_K_M.gguf`) that you install manually: InvokeAI loads it natively, keeping the large projection weights quantized instead of expanding them in memory, which cuts the encoder's footprint noticeably. Only Gemma-2-**2b** GGUFs are accepted — PiD's caption projection is fixed to their 2304-dim hidden state.
## Enabling PiD
-Open the **Generation** settings for a supported model and expand the advanced options. You'll find a **PiD** control with three modes:
+Open the **Generation** settings for a supported model and expand the advanced options. You'll find a **PiD Decode** control with three modes:
<Tabs>
<TabItem label="Off">
@@ -89,7 +89,7 @@ On GPUs with limited VRAM, enable the experimental PiD memory optimizations in `
pid_memory_optimization: true
```
-This setting applies to every supported PiD decoder. It reduces peak activation and sampler memory by processing parts of the pixel pathway in chunks and by running the sampler's intermediates in float32 instead of float64 — measured on an RTX 4090, a 2048px decode peaks at ~1.5 GB of activations instead of ~3.7 GB. Decoding speed is roughly unchanged.
+This setting applies to every supported PiD decoder. It reduces peak activation and sampler memory by processing parts of the pixel pathway in chunks and by running the sampler's intermediates in float32 instead of float64 — measured on an RTX 4090, a 2048px decode takes about 2.7–3.4 GB of VRAM on top of the decoder instead of 5.5–6.1 GB, and a 4096px decode about 11–14 GB, which fits on a 24 GB card only with this setting enabled. Decoding speed is roughly unchanged.
It is disabled by default because it **changes the decoded image**. The combined optimized path is not guaranteed to be bit-exact with the default path: chunking can change GPU kernel and reduction choices, while the float32 sampler math differs from the default float64 path. The few-step sampler amplifies that into a small but real difference (~43 dB PSNR — visually indistinguishable, numerically not identical). A seed that reproduced an image with the setting off will not reproduce it exactly with the setting on, and because this is a server-wide `invokeai.yaml` option it is not recorded in image metadata — each decode logs that it ran optimized instead.
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index ddb1c58a6c..91a7ace104 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -117,6 +117,8 @@ from invokeai.backend.model_manager.starter_models.flux import (
flux_schnell_sdnq,
flux_vae,
ip_adapter_flux,
+ pid_1_5_decoder_flux_2kto4k,
+ pid_1_5_decoder_flux_2kto4k_int8,
pid_decoder_flux_2k,
pid_decoder_flux_2kto4k,
union_cnet_flux,
@@ -142,6 +144,8 @@ from invokeai.backend.model_manager.starter_models.flux2 import (
flux2_klein_9b_int8,
flux2_klein_9b_sdnq,
flux2_vae,
+ pid_1_5_decoder_flux2_2kto4k,
+ pid_1_5_decoder_flux2_2kto4k_int8,
pid_decoder_flux2_2k,
pid_decoder_flux2_2kto4k,
)
@@ -553,8 +557,12 @@ STARTER_MODELS: list[StarterModel] = [
gemma2_2b_encoder,
pid_decoder_flux_2k,
pid_decoder_flux_2kto4k,
+ pid_1_5_decoder_flux_2kto4k,
+ pid_1_5_decoder_flux_2kto4k_int8,
pid_decoder_flux2_2k,
pid_decoder_flux2_2kto4k,
+ pid_1_5_decoder_flux2_2kto4k,
+ pid_1_5_decoder_flux2_2kto4k_int8,
pid_decoder_sd3_2k,
pid_decoder_sd3_2kto4k,
pid_decoder_sdxl_2kto4k,
diff --git a/invokeai/backend/model_manager/starter_models/flux.py b/invokeai/backend/model_manager/starter_models/flux.py
index 4506f0a93a..53f1892637 100644
--- a/invokeai/backend/model_manager/starter_models/flux.py
+++ b/invokeai/backend/model_manager/starter_models/flux.py
@@ -41,7 +41,31 @@ pid_decoder_flux_2kto4k = StarterModel(
name="PiD Decoder FLUX (2K to 4K)",
base=BaseModelType.Flux,
source="nvidia/PiD::checkpoints_deprecated/PiD_res2kto4k_sr4x_official_flux_distill_4step/model_ema_bf16.pth",
- description="NVIDIA PiD 4x super-resolution decoder for FLUX latents, 2K-to-4K preset (legacy architecture; NVIDIA's newer v1.5 checkpoint uses a different network that is not yet supported). ~5GB",
+ description="NVIDIA PiD 4x super-resolution decoder for FLUX latents, 2K-to-4K preset (first-generation architecture; see PiD 1.5 for the newer one). ~5GB",
+ type=ModelType.PiDDecoder,
+ format=ModelFormat.Checkpoint,
+ variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
+ dependencies=[gemma2_2b_encoder],
+)
+
+# Comfy-Org's single-file builds of PiD 1.5, pinned to a commit. Only the 4-step (distilled) files: the repo's
+# names without `_4step` are the undistilled teachers, which the config refuses.
+pid_1_5_decoder_flux_2kto4k = StarterModel(
+ name="PiD 1.5 Decoder FLUX (2K to 4K)",
+ base=BaseModelType.Flux,
+ source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/f1aa9118da0a0b53a4433e5de9a4de2e9aae2193/diffusion_models/pid_1.5_flux1_1024_to_4096_4step_bf16.safetensors",
+ description="NVIDIA PiD 1.5 4x super-resolution decoder for FLUX latents, 2K-to-4K preset, in Comfy-Org's single-file build. ~2.8GB",
+ type=ModelType.PiDDecoder,
+ format=ModelFormat.Checkpoint,
+ variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
+ dependencies=[gemma2_2b_encoder],
+)
+
+pid_1_5_decoder_flux_2kto4k_int8 = StarterModel(
+ name="PiD 1.5 Decoder FLUX (2K to 4K, int8)",
+ base=BaseModelType.Flux,
+ source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/f1aa9118da0a0b53a4433e5de9a4de2e9aae2193/diffusion_models/pid_1.5_flux1_1024_to_4096_4step_int8_convrot.safetensors",
+ description="PiD 1.5 FLUX decoder in Comfy-Org's int8_convrot build: its transformer layers stay int8, about 2GB once loaded instead of 5.6GB. ~1.6GB",
type=ModelType.PiDDecoder,
format=ModelFormat.Checkpoint,
variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
diff --git a/invokeai/backend/model_manager/starter_models/flux2.py b/invokeai/backend/model_manager/starter_models/flux2.py
index ca1a874265..b4c12584c4 100644
--- a/invokeai/backend/model_manager/starter_models/flux2.py
+++ b/invokeai/backend/model_manager/starter_models/flux2.py
@@ -33,7 +33,31 @@ pid_decoder_flux2_2kto4k = StarterModel(
name="PiD Decoder FLUX.2 (2K to 4K)",
base=BaseModelType.Flux2,
source="nvidia/PiD::checkpoints_deprecated/PiD_res2kto4k_sr4x_official_flux2_distill_4step/model_ema_bf16.pth",
- description="NVIDIA PiD 4x super-resolution decoder for FLUX.2 Klein latents, 2K-to-4K preset (legacy architecture; NVIDIA's newer v1.5 checkpoint uses a different network that is not yet supported). ~5GB",
+ description="NVIDIA PiD 4x super-resolution decoder for FLUX.2 Klein latents, 2K-to-4K preset (first-generation architecture; see PiD 1.5 for the newer one). ~5GB",
+ type=ModelType.PiDDecoder,
+ format=ModelFormat.Checkpoint,
+ variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
+ dependencies=[gemma2_2b_encoder],
+)
+
+# Comfy-Org's single-file builds of PiD 1.5, pinned to a commit. Only the 4-step (distilled) files: the repo's
+# names without `_4step` are the undistilled teachers, which the config refuses.
+pid_1_5_decoder_flux2_2kto4k = StarterModel(
+ name="PiD 1.5 Decoder FLUX.2 (2K to 4K)",
+ base=BaseModelType.Flux2,
+ source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/f1aa9118da0a0b53a4433e5de9a4de2e9aae2193/diffusion_models/pid_1.5_flux2_1024_to_4096_4step_bf16.safetensors",
+ description="NVIDIA PiD 1.5 4x super-resolution decoder for FLUX.2 Klein latents, 2K-to-4K preset, in Comfy-Org's single-file build. ~2.8GB",
+ type=ModelType.PiDDecoder,
+ format=ModelFormat.Checkpoint,
+ variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
+ dependencies=[gemma2_2b_encoder],
+)
+
+pid_1_5_decoder_flux2_2kto4k_int8 = StarterModel(
+ name="PiD 1.5 Decoder FLUX.2 (2K to 4K, int8)",
+ base=BaseModelType.Flux2,
+ source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/f1aa9118da0a0b53a4433e5de9a4de2e9aae2193/diffusion_models/pid_1.5_flux2_1024_to_4096_4step_int8_convrot.safetensors",
+ description="PiD 1.5 FLUX.2 decoder in Comfy-Org's int8_convrot build: its transformer layers stay int8, about 2GB once loaded instead of 5.6GB. ~1.6GB",
type=ModelType.PiDDecoder,
format=ModelFormat.Checkpoint,
variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
diff --git a/invokeai/backend/model_manager/starter_models/qwen_image.py b/invokeai/backend/model_manager/starter_models/qwen_image.py
index 5b980d1b97..fcdbab05ac 100644
--- a/invokeai/backend/model_manager/starter_models/qwen_image.py
+++ b/invokeai/backend/model_manager/starter_models/qwen_image.py
@@ -28,7 +28,7 @@ pid_decoder_qwenimage_2kto4k = StarterModel(
pid_1_5_decoder_qwenimage_2kto4k = StarterModel(
name="PiD 1.5 Decoder Qwen-Image (2K to 4K)",
base=BaseModelType.QwenImage,
- source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/main/diffusion_models/pid_1.5_qwenimage_1024_to_4096_4step_bf16.safetensors",
+ source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/f1aa9118da0a0b53a4433e5de9a4de2e9aae2193/diffusion_models/pid_1.5_qwenimage_1024_to_4096_4step_bf16.safetensors",
description="NVIDIA PiD 1.5 4x super-resolution decoder for Qwen-Image latents, 2K-to-4K preset, in Comfy-Org's single-file build. ~2.8GB",
type=ModelType.PiDDecoder,
format=ModelFormat.Checkpoint,
@@ -39,7 +39,7 @@ pid_1_5_decoder_qwenimage_2kto4k = StarterModel(
pid_1_5_decoder_qwenimage_2kto4k_int8 = StarterModel(
name="PiD 1.5 Decoder Qwen-Image (2K to 4K, int8)",
base=BaseModelType.QwenImage,
- source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/main/diffusion_models/pid_1.5_qwenimage_1024_to_4096_4step_int8_convrot.safetensors",
+ source="https://huggingface.co/Comfy-Org/PixelDiT/resolve/f1aa9118da0a0b53a4433e5de9a4de2e9aae2193/diffusion_models/pid_1.5_qwenimage_1024_to_4096_4step_int8_convrot.safetensors",
description="PiD 1.5 Qwen-Image decoder in Comfy-Org's int8_convrot build: its transformer layers stay int8, about 2GB once loaded instead of 5.6GB, with output practically identical to the full-precision build. ~1.6GB",
type=ModelType.PiDDecoder,
format=ModelFormat.Checkpoint,
diff --git a/invokeai/backend/pid/decode.py b/invokeai/backend/pid/decode.py
index 826d31d3d8..8e4b74bb04 100644
--- a/invokeai/backend/pid/decode.py
+++ b/invokeai/backend/pid/decode.py
@@ -40,6 +40,7 @@ from invokeai.backend.quantization.int8_convrot import (
split_int8_convrot_layers,
swap_in_int8_linears,
)
+from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
from invokeai.backend.util.state_dict_loading import log_unexpected_keys
@@ -158,30 +159,52 @@ PID_MODEL_MAX_LENGTH: int = 300
# PiD runs a multi-step pixel-diffusion in float32 at the full super-resolved output resolution, so its peak
# activation memory scales with the total OUTPUT pixel count across the batch.
#
-# This is working-memory headroom reserved for the decode itself - it does NOT do the heavy lifting of evicting
-# the main transformer/encoders (the nodes call context.models.offload_all_from_vram() for that before loading
-# PidNet).
-# The cache uses max(this_estimate, device_working_mem_gb=3GB), and an over-large value pushes the working set
-# negative and forces PidNet to partial-load onto the CPU (slow). Experimentally-tunable; calibrate to peak.
-_PID_DECODE_WORKING_MEMORY_SCALING_CONSTANT = 260
-
-# The same estimate for `pid_memory_optimization=True`. Chunking bounds the per-block activations to a fixed
-# working set, so the peak stops being a pure multiple of the output size: it is a smaller per-pixel term plus a
-# constant for the chunk working set (constant because `_PID_ACTIVATION_CHUNK_SIZE` is fixed).
+# The estimate is the headroom the cache keeps free for the decode, and so also what evicts the main transformer:
+# the decode nodes offload only the Gemma encoder, and the cache offloads exactly as much of every other model as
+# this reservation leaves no room for. Too low, and the main transformer stays resident into the decode's peak —
+# on Windows the driver then spills to shared memory instead of raising OOM, so the allocator never frees its pool
+# and the decode crawls. Too high, and PidNet partial-loads onto the CPU on small cards.
#
-# Measured peaks on an RTX 4090 (fp32 PidNet, bf16 autocast, 4 steps, B=1), against U = out_h * out_w * 4 bytes:
-# 1024px 509 MiB (127.2 * U) 1536px 934 MiB (103.8 * U) 2048px 1533 MiB (95.8 * U)
-# Least-squares fit: 85.3 * U + 167 MiB. The earlier 95 * U + 224 MiB calibration carried ~15% headroom
-# over that fit at the measured sizes.
-# The fit underestimates the larger-output path; 120 * U + 224 MiB keeps a small safety margin over the
-# measured 2048px-4096px peaks.
+# Calibrated to what the decode takes off the device — peak (total - free) from cudaMemGetInfo, polled every 5 ms,
+# over a baseline taken after empty_cache() with PidNet resident — not to torch.cuda.max_memory_allocated: the
+# allocator's pool and fragmentation sit 25-30% (cudaMallocAsync) to 60-75% (native) above the tensors themselves,
+# and that memory is just as unavailable to the cache's models. Measured on an RTX 4090 under Windows, FLUX latent,
+# 4 steps, B=1; the max of a v1 and a v1.5 decoder (neither generation is consistently larger once the allocator is
+# counted), in GiB:
#
-# Keeping the unoptimized constant here would be the bug the flag is supposed to avoid: the cache takes
-# max(this_estimate, device_working_mem_gb) and subtracts it from the weight budget, so reserving 4GB for a decode
-# that peaks at 1.5GB withholds VRAM that PidNet could have stayed resident in - exactly the partial-load-to-CPU
-# outcome the comment above warns about, on the low-VRAM systems this feature exists for.
-_PID_DECODE_CHUNKED_SCALING_CONSTANT = 120
-_PID_DECODE_CHUNKED_FIXED_BYTES = 224 * 2**20
+# chunked (pid_memory_optimization) unchunked
+# output px 1024 2048 3072 4096 1024 2048 3072
+# cudaMallocAsync 0.77 2.49 5.89 10.24 1.33 5.17 12.18
+# native 0.81 3.20 7.11 13.19 1.43 5.70 13.36
+#
+# With U = out_h * out_w * 4 bytes, each formula below keeps about 0.4-0.9 GiB over those peaks from 2048px up. The
+# fixed term is the chunk working set (constant because `_PID_ACTIVATION_CHUNK_SIZE` is fixed). Unchunked 4096px
+# (only reachable on 32 GB cards) is extrapolated. The cudaMallocAsync calibration applies to CUDA builds only, where
+# it was measured; `native` stands for everything else — expandable segments (unsupported on Windows, so unmeasured),
+# ROCm, XPU, MPS — since it is the worst case measured, and an unmeasured allocator must err towards reserving too
+# much.
+@dataclass(frozen=True)
+class _PiDWorkingMemoryCalibration:
+ unchunked_per_output_byte: int
+ chunked_per_output_byte: int
+ chunked_fixed_bytes: int = 224 * 2**20
+
+
+_PID_WORKING_MEMORY_CUDA_MALLOC_ASYNC = _PiDWorkingMemoryCalibration(
+ unchunked_per_output_byte=360, chunked_per_output_byte=175
+)
+_PID_WORKING_MEMORY_NATIVE = _PiDWorkingMemoryCalibration(unchunked_per_output_byte=395, chunked_per_output_byte=215)
+
+
+def _pid_working_memory_calibration() -> _PiDWorkingMemoryCalibration:
+ """The calibration for the allocator the decode will run under."""
+ if (
+ TorchDevice.choose_torch_device().type == "cuda"
+ and torch.version.hip is None
+ and torch.cuda.get_allocator_backend() == "cudaMallocAsync"
+ ):
+ return _PID_WORKING_MEMORY_CUDA_MALLOC_ASYNC
+ return _PID_WORKING_MEMORY_NATIVE
def estimate_pid_decode_working_memory(
@@ -226,7 +249,8 @@ def _estimate_pid_activation_memory(
element_size = 4 # PidNet runs in float32 (see model_loaders/pid_decoder.py)
batch_size = int(latent.shape[0])
output_bytes = batch_size * out_h * out_w * element_size
- unoptimized = int(output_bytes * _PID_DECODE_WORKING_MEMORY_SCALING_CONSTANT)
+ calibration = _pid_working_memory_calibration()
+ unoptimized = output_bytes * calibration.unchunked_per_output_byte
if not pid_memory_optimization:
return unoptimized
patch_size = int(_PID_SR4X_BASE["patch_size"])
@@ -234,7 +258,7 @@ def _estimate_pid_activation_memory(
if patch_tokens <= _PID_ACTIVATION_CHUNK_SIZE:
# The pixel blocks take the unchunked path at and below the threshold.
return unoptimized
- chunked = int(output_bytes * _PID_DECODE_CHUNKED_SCALING_CONSTANT + _PID_DECODE_CHUNKED_FIXED_BYTES)
+ chunked = output_bytes * calibration.chunked_per_output_byte + calibration.chunked_fixed_bytes
# The fixed term makes the calibrated chunked formula temporarily greater than the unoptimized
# formula just after chunking engages. Keep the unoptimized estimate until the formulas cross;
# after that point the chunked estimate is the lower (optimized) reservation.
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx
index c936a513f0..459ee6c1ce 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx
@@ -38,6 +38,11 @@ void i18n.use(initReactI18next).init({
hiDiffusionT1Ratio: 'HiDiffusion: T1 Ratio',
hiDiffusionT2Ratio: 'HiDiffusion: T2 Ratio',
hiDiffusionWindowAttn: 'HiDiffusion: Window Attention',
+ pid: 'PiD Decode',
+ pidHelp: 'Replaces the VAE decode with a 4x super-resolution decode.',
+ pidFit: 'Fit to size',
+ pidNative: 'Native 4x',
+ pidOff: 'Off',
seamlessTiling: 'Seamless tiling',
tileX: 'Tile X',
tileY: 'Tile Y',
@@ -55,6 +60,7 @@ void i18n.use(initReactI18next).init({
const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1', name: 'SD 1.5', type: 'main' };
const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2', name: 'SD 2', type: 'main' };
+const fluxModel: MainModelConfig = { base: 'flux', key: 'flux', name: 'FLUX.1 dev', type: 'main' };
let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -97,14 +103,19 @@ const switchByLabel = (label: string): HTMLElement | null =>
(element) => element.textContent === label
) ?? null;
-/** The scrubber's slider is named by `aria-labelledby`, so resolve it through the label element. */
-const sliderByLabel = (label: string): Element | null =>
- [...(host?.querySelectorAll<HTMLElement>('[role="slider"]') ?? [])].find((slider) => {
- const labelId = slider.getAttribute('aria-labelledby');
+/** Sliders and select triggers are named by `aria-labelledby`, so resolve them through the label element. */
+const labelledBy = (selector: string, label: string): Element | null =>
+ [...(host?.querySelectorAll<HTMLElement>(selector) ?? [])].find((control) => {
+ const labelId = control.getAttribute('aria-labelledby');
return labelId !== null && host?.querySelector(`#${CSS.escape(labelId)}`)?.textContent === label;
}) ?? null;
+const sliderByLabel = (label: string): Element | null => labelledBy('[role="slider"]', label);
+
+const selectByLabel = (label: string): Element | null =>
+ labelledBy('[data-scope="select"][data-part="trigger"]', label);
+
afterEach(async () => {
await settle(() => root?.unmount());
host?.remove();
@@ -133,3 +144,18 @@ describe('GenerateAdvancedFields HiDiffusion controls', () => {
expect(host?.textContent).not.toContain('HiDiffusion: T1 Ratio');
});
});
+
+describe('GenerateAdvancedFields PiD control', () => {
+ // FLUX has no other advanced field, so the section must not hide itself while PiD is supported.
+ it('shows the PiD mode for a base whose only advanced field is PiD', async () => {
+ await render(fluxModel, false);
+
+ expect(selectByLabel('PiD Decode')).not.toBeNull();
+ });
+
+ it('omits the PiD mode for a base without PiD decoders', async () => {
+ await render(sd1Model, false);
+
+ expect(selectByLabel('PiD Decode')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx
index d4ce6e09a9..023de62930 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx
@@ -108,7 +108,8 @@ export const GenerateAdvancedFields = ({
!policy.seamlessVisible &&
!policy.hiDiffusionVisible &&
!policy.clipSkipMax &&
- !policy.cfgRescaleVisible
+ !policy.cfgRescaleVisible &&
+ !policy.pidVisible
) {
return null;
}
diff --git a/tests/backend/pid/test_pid_decode.py b/tests/backend/pid/test_pid_decode.py
index ed6ce7dc87..d95485e047 100644
--- a/tests/backend/pid/test_pid_decode.py
+++ b/tests/backend/pid/test_pid_decode.py
@@ -166,25 +166,81 @@ def test_pid_memory_optimization_defaults_to_disabled() -> None:
assert PiDDecodeConfig().pid_memory_optimization is False
-def test_working_memory_estimate_shrinks_when_the_optimization_is_enabled() -> None:
- """The estimates contain only calibrated activation/workspace terms."""
- latent = torch.zeros(1, 16, 64, 64) # FLUX: 64 * 4 * 8 = 2048px output
+# Device-level peak of a FLUX decode in GiB — max of a v1 and a v1.5 decoder, PidNet weights excluded — measured on
+# an RTX 4090 under Windows, keyed by (output px, pid_memory_optimization). See the calibration in `pid/decode.py`.
+_MEASURED_PEAKS_GIB = {
+ "cudaMallocAsync": {
+ (1024, True): 0.77,
+ (2048, True): 2.49,
+ (3072, True): 5.89,
+ (4096, True): 10.24,
+ (1024, False): 1.33,
+ (2048, False): 5.17,
+ (3072, False): 12.18,
+ },
+ "native": {
+ (1024, True): 0.81,
+ (2048, True): 3.20,
+ (3072, True): 7.11,
+ (4096, True): 13.19,
+ (1024, False): 1.43,
+ (2048, False): 5.70,
+ (3072, False): 13.36,
+ },
+}
+_CALIBRATIONS = {
+ "cudaMallocAsync": pid_decode_module._PID_WORKING_MEMORY_CUDA_MALLOC_ASYNC,
+ "native": pid_decode_module._PID_WORKING_MEMORY_NATIVE,
+}
- unoptimized = estimate_pid_decode_working_memory(latent, BaseModelType.Flux)
- optimized = estimate_pid_decode_working_memory(latent, BaseModelType.Flux, True)
- output_bytes = 2048 * 2048 * 4
- # Exact activation-only formulas reject reintroducing a fixed model/cache term.
- assert unoptimized == 260 * output_bytes
- assert optimized == 120 * output_bytes + 224 * 2**20
+ ("allocator", "output_px", "optimized"),
+ [(allocator, px, opt) for allocator, peaks in _MEASURED_PEAKS_GIB.items() for px, opt in peaks],
+)
+def test_working_memory_estimate_covers_the_measured_peak_without_hoarding(
+ monkeypatch: pytest.MonkeyPatch, allocator: str, output_px: int, optimized: bool
+) -> None:
+ """Below the peak the main transformer stays resident into the decode and Windows spills to shared memory; far
+ above it, PidNet partial-loads onto the CPU on small cards. Both bounds come from the measurements."""
+ monkeypatch.setattr(pid_decode_module, "_pid_working_memory_calibration", lambda: _CALIBRATIONS[allocator])
+ side = output_px // 32 # FLUX: 4x super-resolution of an 8x-downsampled latent
+ peak = _MEASURED_PEAKS_GIB[allocator][(output_px, optimized)] * 2**30
+
+ estimate = estimate_pid_decode_working_memory(torch.zeros(1, 16, side, side), BaseModelType.Flux, optimized)
+
+ assert peak <= estimate <= peak + 2**30
+
+
+def test_cuda_malloc_async_gets_its_own_calibration_and_every_other_allocator_the_native_one(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def run_on(device: str, backend: str, hip: str | None = None) -> object:
+ monkeypatch.setattr(pid_decode_module.TorchDevice, "choose_torch_device", lambda: torch.device(device))
+ monkeypatch.setattr(torch.cuda, "get_allocator_backend", lambda: backend)
+ monkeypatch.setattr(torch.version, "hip", hip)
+ return pid_decode_module._pid_working_memory_calibration()
+
+ assert run_on("cuda", "cudaMallocAsync") is pid_decode_module._PID_WORKING_MEMORY_CUDA_MALLOC_ASYNC
+ assert run_on("cuda", "native") is pid_decode_module._PID_WORKING_MEMORY_NATIVE
+ assert run_on("cpu", "cudaMallocAsync") is pid_decode_module._PID_WORKING_MEMORY_NATIVE
+ # Measured on CUDA only: a ROCm build reporting hipMallocAsync as cudaMallocAsync gets the safe side.
+ assert run_on("cuda", "cudaMallocAsync", hip="7.1") is pid_decode_module._PID_WORKING_MEMORY_NATIVE
+
+
[email protected](params=list(_CALIBRATIONS), ids=list(_CALIBRATIONS))
+def each_calibration(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Run a structural estimate test under every allocator's calibration, not only the host's."""
+ monkeypatch.setattr(pid_decode_module, "_pid_working_memory_calibration", lambda: _CALIBRATIONS[request.param])
[email protected]("each_calibration")
def test_working_memory_estimate_keeps_a_fixed_term_for_the_chunk_working_set() -> None:
"""The optimized peak is not a pure multiple of the output size.
- Chunking bounds the per-block activations to a fixed working set, so halving the output area does
- not halve the peak (measured: 509 MiB at 1024px vs 1533 MiB at 2048px — a factor of 3.0, not 4).
- A pure scaling constant would therefore under-reserve at small sizes or over-reserve at large ones.
+ Chunking bounds the per-block activations to a fixed working set, so quartering the output area does
+ not quarter the peak under cudaMallocAsync (measured: 0.77 GiB at 1024px vs 2.49 GiB at 2048px — 3.2x, not
+ 4). Under the native allocator the peak scales almost purely with area, and the fixed term is headroom.
"""
small = estimate_pid_decode_working_memory(torch.zeros(1, 16, 32, 32), BaseModelType.Flux, True)
large = estimate_pid_decode_working_memory(torch.zeros(1, 16, 64, 64), BaseModelType.Flux, True)
@@ -193,6 +249,7 @@ def test_working_memory_estimate_keeps_a_fixed_term_for_the_chunk_working_set()
assert large > 2 * small, "the per-pixel term has been lost"
[email protected]("each_calibration")
def test_working_memory_estimate_accounts_for_every_image_in_the_batch() -> None:
"""The decoder accepts batched latents, so reserving only one image's activations can OOM.
@@ -208,6 +265,7 @@ def test_working_memory_estimate_accounts_for_every_image_in_the_batch() -> None
assert batched_unoptimized == 2 * single_unoptimized
[email protected]("each_calibration")
def test_working_memory_estimate_never_exceeds_the_unoptimized_one() -> None:
"""Below the chunk size the pixel blocks run unchunked, so the fixed chunk-working-set term must
not be charged: a small output would otherwise reserve *more* with the optimization enabled than