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(pid): load NVIDIA PiD 1.5 decoders

Alexander Eichhorn5906244b54d2
diff --git a/docs/src/content/docs/features/pid-decode.mdx b/docs/src/content/docs/features/pid-decode.mdx
index e50c3b2b8e..26c6b003b3 100644
--- a/docs/src/content/docs/features/pid-decode.mdx
+++ b/docs/src/content/docs/features/pid-decode.mdx
@@ -41,10 +41,12 @@ PiD needs two extra models, both available in **Model Manager → Starter Models
2. The **Gemma 2 2B (PiD caption encoder)** — PiD uses it to condition the decode on your prompt. It installs automatically as a dependency of any PiD decoder, and is shared across all of them.
</Steps>
-Each PiD decoder is roughly 5 GB and the shared Gemma-2 encoder is roughly 5 GB.
+A first-generation PiD decoder download is roughly 5 GB, a PiD 1.5 decoder download roughly 2.8 GB, and the shared Gemma-2 encoder is roughly 5 GB. Once loaded, both generations take about the same memory: the decoder runs in full precision.
<Aside type="note">
-The Starter Models install NVIDIA's **legacy** 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 newer **v1.5** decoders use a different network and are not yet supported — installing one is rejected during model identification rather than failing at decode time.
+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.
+
+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 — as are the `int8_convrot` builds, which are not supported yet.
</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.
diff --git a/invokeai/backend/model_manager/configs/pid_decoder.py b/invokeai/backend/model_manager/configs/pid_decoder.py
index bc6bec3e98..078a8ee320 100644
--- a/invokeai/backend/model_manager/configs/pid_decoder.py
+++ b/invokeai/backend/model_manager/configs/pid_decoder.py
@@ -3,7 +3,9 @@
PiD decoders are released by NVIDIA at https://huggingface.co/nvidia/PiD and
ship per supported backbone (FLUX.1, FLUX.2, SD3, SDXL, Qwen-Image). Most
backbones offer two resolution presets (`res2k_sr4x_*` and `res2kto4k_sr4x_*`),
-while SDXL and Qwen-Image ship only the `res2kto4k_sr4x_*` preset. See
+while SDXL and Qwen-Image ship only the `res2kto4k_sr4x_*` preset. The second
+generation, PiD v1.5, exists for FLUX.1, FLUX.2 and Qwen-Image in the 2K-to-4K
+preset; Comfy-Org repackages both generations as single safetensors files. See
`LICENSE-PiD.txt` at the repo root — code is Apache-2.0, weights are NSCLv1
(non-commercial / research).
"""
@@ -29,7 +31,7 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
PiDDecoderVariantType,
)
-from invokeai.backend.pid.state_dict_utils import pid_net_shapes
+from invokeai.backend.pid.state_dict_utils import PID_VERSION_BY_LQ_HIDDEN_DIM, PiDVersion, pid_net_shapes
# Marker substring produced by `PidNet.lq_proj` (see
# invokeai/backend/pid/_src/networks/pid_net.py). The pretrained PixDiT_T2I
@@ -44,25 +46,28 @@ def _looks_like_pid_decoder(state_dict: dict[str | int, Any]) -> bool:
return any(isinstance(k, str) and _PID_MARKER_SUBSTRING in k for k in state_dict)
-# PidNet's latent input projection: a Conv2d of shape (lq_hidden_dim, lq_latent_channels, 3, 3).
+# PidNet's latent input projection: a Conv2d of shape (lq_hidden_dim, latent input channels, 3, 3).
# Identification reads three separate facts off this one weight — the architecture version (dim 0),
# the backbone (dim 1) and, via the contract, its kernel — which is why it is worth naming.
_LATENT_PROJ_KEY = "lq_proj.latent_proj.0.weight"
-# dim 1 of the latent projection is the backbone's latent channel count. It is the only architectural
-# dimension that varies between backbones, and therefore the only name-independent discriminator
-# available. FLUX.1, SD3 and Qwen-Image are architecturally identical and share 16 channels; nothing
-# in the weights can separate them.
-_LATENT_CHANNELS_TO_BASES: dict[int, set[BaseModelType]] = {
- 4: {BaseModelType.StableDiffusionXL},
- 16: {BaseModelType.Flux, BaseModelType.StableDiffusion3, BaseModelType.QwenImage},
- 128: {BaseModelType.Flux2},
+# dim 1 of the latent projection is the backbone's latent channel count as the projection takes it. It is the only
+# architectural dimension that varies between backbones, and therefore the only name-independent discriminator
+# available. FLUX.1, SD3 and Qwen-Image are architecturally identical and share 16 channels; nothing in the weights
+# can separate them. v1.5 unpatchifies FLUX.2's 128 channels to 32 before the projection, and NVIDIA ships it for
+# FLUX.1, FLUX.2 and Qwen-Image only.
+_LATENT_CHANNELS_TO_BASES: dict[PiDVersion, dict[int, set[BaseModelType]]] = {
+ PiDVersion.V1: {
+ 4: {BaseModelType.StableDiffusionXL},
+ 16: {BaseModelType.Flux, BaseModelType.StableDiffusion3, BaseModelType.QwenImage},
+ 128: {BaseModelType.Flux2},
+ },
+ PiDVersion.V1_5: {
+ 16: {BaseModelType.Flux, BaseModelType.QwenImage},
+ 32: {BaseModelType.Flux2},
+ },
}
-# dim 0 is PidNet's `lq_hidden_dim`. `build_pid_net` constructs the legacy 512-dim network; NVIDIA's
-# v1.5 checkpoints use 1024 (plus PiT injection, scalar gates, etc.) and cannot be loaded into it.
-_SUPPORTED_LQ_HIDDEN_DIM = 512
-
# Keyed by `Any`, not `str`: a bare checkpoint reaches identification with its keys untouched, so a
# `.pth` is free to supply keys that are not strings (see `strip_net_prefix`).
_Shapes = Mapping[Any, tuple[int, ...] | None]
@@ -89,22 +94,21 @@ def _raise_if_discriminator_malformed(shapes: _Shapes, contract: Mapping[str, tu
)
-def _raise_if_architecture_unsupported(shapes: _Shapes) -> None:
- """Reject a PiD decoder whose network shape `build_pid_net` cannot construct.
+def _pid_version(shapes: _Shapes) -> PiDVersion:
+ """The decoder generation, read off the latent projection's width; reject a width no generation has.
- Runs before the contract check so the diagnosis is the accurate one: a v1.5 checkpoint is intact,
- and judging it against the legacy contract would report it as a pile of missing and unexpected
- keys rather than as the newer architecture it is.
+ Runs before the contract check, which depends on it, so the diagnosis is the accurate one: judged against
+ either generation's contract, an unknown architecture would be reported as a pile of missing and unexpected
+ keys rather than as the architecture it is.
"""
lq_hidden_dim = shapes[_LATENT_PROJ_KEY][0] # type: ignore[index] # rank checked above
- if lq_hidden_dim != _SUPPORTED_LQ_HIDDEN_DIM:
- raise InvalidMatchError(
- f"PiD decoder has lq_proj hidden dim {lq_hidden_dim}, but InvokeAI only supports the legacy "
- f"{_SUPPORTED_LQ_HIDDEN_DIM}-dim architecture (NVIDIA's v1.5 checkpoints are not yet supported)."
- )
+ if (version := PID_VERSION_BY_LQ_HIDDEN_DIM.get(lq_hidden_dim)) is None:
+ supported = ", ".join(f"{dim} ({v.value})" for dim, v in PID_VERSION_BY_LQ_HIDDEN_DIM.items())
+ raise InvalidMatchError(f"PiD decoder has lq_proj hidden dim {lq_hidden_dim}; InvokeAI supports {supported}.")
+ return version
-def _raise_if_no_backbone_can_accept(shapes: _Shapes) -> None:
+def _raise_if_no_backbone_can_accept(shapes: _Shapes, version: PiDVersion) -> None:
"""Reject a PiD decoder that none of the five backbone configs could ever claim.
The counterpart to `_validate_base`, and the reason the two are separate. `_validate_base` decides
@@ -118,10 +122,15 @@ def _raise_if_no_backbone_can_accept(shapes: _Shapes) -> None:
reported as a shape mismatch on one weight, which is true and useless.
"""
channels = shapes[_LATENT_PROJ_KEY][1] # type: ignore[index] # rank checked above
- if channels not in _LATENT_CHANNELS_TO_BASES:
+ bases_by_channels = _LATENT_CHANNELS_TO_BASES[version]
+ if channels not in bases_by_channels:
+ supported = ", ".join(
+ f"{count} for {'/'.join(sorted(base.value for base in bases))}"
+ for count, bases in bases_by_channels.items()
+ )
raise InvalidMatchError(
- f"PiD checkpoint has {channels} latent channels; no supported backbone uses this "
- "(supported: 4 for SDXL, 16 for FLUX.1/SD3/Qwen-Image, 128 for FLUX.2)"
+ f"PiD {version.value} checkpoint has {channels} latent channels; no supported backbone uses this "
+ f"(supported: {supported})"
)
@@ -246,22 +255,51 @@ _SINGLE_VARIANT_BACKBONES: dict[BaseModelType, PiDDecoderVariantType] = {
}
-def _variant_from_components(components: tuple[str, ...], base: BaseModelType) -> PiDDecoderVariantType:
+def _variant_from_components(
+ components: tuple[str, ...], base: BaseModelType, version: PiDVersion
+) -> PiDDecoderVariantType:
"""Map NVIDIA's `res2k_sr4x` / `res2kto4k_sr4x` name slice to a variant.
Same specificity ordering as the backbone match. If no component names a preset, fall back to the
- backbone's only published one where there is one, and to ``Res2k_Sr4x`` for those shipping both.
+ only published one where there is one — every v1.5 decoder, and SDXL's and Qwen-Image's v1 — and to
+ ``Res2k_Sr4x`` for the v1 backbones shipping both.
"""
for component in components:
n = component.lower()
- # `res2kto4k` contains `res2k`, so the 2K-to-4K spellings are tested first.
- if "res2kto4k" in n or "res2k_to_4k" in n or "res2k_to4k" in n:
+ # `res2kto4k` contains `res2k`, so the 2K-to-4K spellings are tested first. Comfy-Org names the preset by
+ # its input and output sizes instead (`pid_1.5_flux1_1024_to_4096_4step_bf16`).
+ if "res2kto4k" in n or "res2k_to_4k" in n or "res2k_to4k" in n or "1024_to_4096" in n:
return PiDDecoderVariantType.Res2kTo4k_Sr4x
if "res2k" in n:
return PiDDecoderVariantType.Res2k_Sr4x
+ if version is PiDVersion.V1_5:
+ return PiDDecoderVariantType.Res2kTo4k_Sr4x
return _SINGLE_VARIANT_BACKBONES.get(base, PiDDecoderVariantType.Res2k_Sr4x)
+def _raise_if_named_undistilled(components: tuple[str, ...], folder_name: str) -> None:
+ """Reject a v1.5 decoder whose name marks it as NVIDIA's undistilled teacher.
+
+ NVIDIA published each v1.5 decoder twice: the 4-step distilled student the decode nodes sample, and the
+ undistilled teacher (`PiD_v1pt5_*_undistilled`, Comfy-Org's `pid_1.5_*_bf16` without `_4step`), which is
+ sampled with ~25 CFG steps. Both carry the same keys and shapes, so only the name tells them apart — and
+ sampled with the student schedule a teacher decodes to a degraded image without any error. A name that says
+ neither is accepted.
+
+ Comfy-Org's spelling marks the teacher by what its file name lacks, so it is only read off file names — the
+ last segment of the file's own name or of its install source — never off ``folder_name``, the folder a local
+ install is identified in, which a user may well have named `pid_1.5_decoders`.
+ """
+ for component in components:
+ n = component.lower()
+ file_name = "" if component == folder_name else n.replace("\\", "/").rsplit("/", 1)[-1]
+ if "undistilled" in n or (file_name.startswith("pid_1.5_") and "4step" not in file_name):
+ raise InvalidMatchError(
+ f"PiD v1.5 checkpoint {component!r} is named as an undistilled (teacher) decoder. InvokeAI samples "
+ "PiD with the distilled 4-step schedule; install the `_4step` build instead."
+ )
+
+
class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
"""Shared logic for PiD decoder checkpoint configs.
@@ -290,7 +328,6 @@ class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
# no reason to load for the overwhelming majority of files.
from invokeai.backend.pid.decode import required_pid_net_shapes
- contract = required_pid_net_shapes()
shapes = pid_net_shapes(state_dict)
# Everything from here to `_validate_base` is backbone-independent: each of these rejects a file
@@ -301,20 +338,25 @@ class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
# The latent projection carries both the architecture version and the backbone, so the checks
# that read it can only speak when it is there. When it is not, the file is truncated, and the
# contract check diagnoses that far better than a guess about the architecture would.
+ version = PiDVersion.V1
if _LATENT_PROJ_KEY in shapes:
- _raise_if_discriminator_malformed(shapes, contract)
- _raise_if_architecture_unsupported(shapes)
- _raise_if_no_backbone_can_accept(shapes)
- _raise_if_pid_net_contract_unmet(shapes, contract)
+ # Both generations give this conv the same rank and kernel, so either contract judges its form.
+ _raise_if_discriminator_malformed(shapes, required_pid_net_shapes(version=PiDVersion.V1))
+ version = _pid_version(shapes)
+ _raise_if_no_backbone_can_accept(shapes, version)
+ _raise_if_pid_net_contract_unmet(shapes, required_pid_net_shapes(version=version))
# Guaranteed by the checks above: the contract proved the weight is present and the malformed
# check proved it is a conv. The backbone therefore always comes from the weights — the name
# can only break the FLUX.1 / SD3 / Qwen-Image tie, never pick a backbone on its own.
latent_channels = shapes[_LATENT_PROJ_KEY][1] # type: ignore[index]
components = _name_components(mod, override_fields)
+ if version is PiDVersion.V1_5:
+ _raise_if_named_undistilled(components, mod.path.parent.name)
cls._validate_base(
latent_channels=latent_channels,
+ version=version,
named_base=_backbone_from_components(components),
had_base_override=override_fields.get("base") is not None,
)
@@ -323,7 +365,7 @@ class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
# Read, not popped: `override_fields` is built once by the factory and passed to every
# candidate class, so consuming `variant` here would take it away from whichever PiD class
# actually matches (which, without a `base` override, need not be this one).
- variant = override_fields.get("variant") or _variant_from_components(components, base)
+ variant = override_fields.get("variant") or _variant_from_components(components, base, version)
return cls(**{k: v for k, v in override_fields.items() if k != "variant"}, variant=variant)
@classmethod
@@ -331,6 +373,7 @@ class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
cls,
*,
latent_channels: int,
+ version: PiDVersion,
named_base: BaseModelType | None,
had_base_override: bool,
) -> None:
@@ -341,18 +384,19 @@ class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
would rule out all five are raised in ``from_model_on_disk`` before this runs.
The latent channel count is authoritative and is the only thing separating SDXL (4ch) and
- FLUX.2 (128ch) from the 16ch family. FLUX.1, SD3 and Qwen-Image are architecturally
- identical, so within that family, in order of how much the evidence can be trusted:
+ FLUX.2 (128ch; 32ch in v1.5) from the 16ch family. FLUX.1, SD3 and Qwen-Image are
+ architecturally identical, so within that family, in order of how much the evidence can be
+ trusted:
- an explicit ``base`` override wins outright. ``raise_for_override_fields`` has already
validated it against this class's ``Literal``, so it names exactly one of the five, and
whoever set it knows more than a filename anyone can write;
- - failing that, a name component naming exactly one of the three decides;
+ - failing that, a name component naming exactly one of the family decides;
- failing that, the family defaults to FLUX.1.
"""
expected_base = cls.model_fields["base"].default
# Guaranteed present: an unsupported channel count was rejected outright before this ran.
- candidate_bases = _LATENT_CHANNELS_TO_BASES[latent_channels]
+ candidate_bases = _LATENT_CHANNELS_TO_BASES[version][latent_channels]
if expected_base not in candidate_bases:
raise NotAMatchError(f"latent channels={latent_channels} do not match backbone {expected_base}")
@@ -381,7 +425,7 @@ class PiDDecoder_Checkpoint_FLUX_Config(PiDDecoder_Checkpoint_Config_Base, Confi
class PiDDecoder_Checkpoint_Flux2_Config(PiDDecoder_Checkpoint_Config_Base, Config_Base):
- """PiD decoder for the FLUX.2 backbone (128-channel latent)."""
+ """PiD decoder for the FLUX.2 backbone (128-channel latent; PiD v1.5 projects it unpatchified to 32)."""
base: Literal[BaseModelType.Flux2] = Field(default=BaseModelType.Flux2)
variant: PiDDecoderVariantType = Field(description="Resolution preset of the PiD decoder checkpoint.")
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index a6f17efe61..83191a313e 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -139,6 +139,7 @@ from invokeai.backend.model_manager.starter_models.minimax_h3 import (
minimax_h3_turbo_lora,
)
from invokeai.backend.model_manager.starter_models.qwen_image import (
+ pid_1_5_decoder_qwenimage_2kto4k,
pid_decoder_qwenimage_2kto4k,
qwen_image,
qwen_image_edit,
@@ -457,6 +458,7 @@ STARTER_MODELS: list[StarterModel] = [
pid_decoder_sd3_2kto4k,
pid_decoder_sdxl_2kto4k,
pid_decoder_qwenimage_2kto4k,
+ pid_1_5_decoder_qwenimage_2kto4k,
]
sd1_bundle: list[StarterModel] = [
diff --git a/invokeai/backend/model_manager/starter_models/qwen_image.py b/invokeai/backend/model_manager/starter_models/qwen_image.py
index 7516c83f24..ac2f5b7f17 100644
--- a/invokeai/backend/model_manager/starter_models/qwen_image.py
+++ b/invokeai/backend/model_manager/starter_models/qwen_image.py
@@ -18,7 +18,18 @@ pid_decoder_qwenimage_2kto4k = StarterModel(
name="PiD Decoder Qwen-Image (2K to 4K)",
base=BaseModelType.QwenImage,
source="nvidia/PiD::checkpoints_deprecated/PiD_res2kto4k_sr4x_official_qwenimage_distill_4step/model_ema_bf16.pth",
- description="NVIDIA PiD 4x super-resolution decoder for Qwen-Image 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 Qwen-Image 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],
+)
+
+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",
+ 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,
variant=PiDDecoderVariantType.Res2kTo4k_Sr4x,
diff --git a/invokeai/backend/pid/_src/networks/lq_projection_2d.py b/invokeai/backend/pid/_src/networks/lq_projection_2d.py
index b18b5f86c1..3ae70030b7 100644
--- a/invokeai/backend/pid/_src/networks/lq_projection_2d.py
+++ b/invokeai/backend/pid/_src/networks/lq_projection_2d.py
@@ -9,9 +9,11 @@
# to the patch grid without any interpolation.
# Latent branch: Nearest interpolate or fold to align to the patch grid.
#
-# ControlNet-style injection gate (single implementation):
-# "sigma_aware_per_token_per_dim":
-# x + sigmoid(Linear([x, lq]) - exp(log_alpha)*sigma) * lq (per-token per-dim, B,N,D; monotonic in sigma)
+# ControlNet-style injection gates, both monotonic in sigma:
+# "sigma_aware_per_token_per_dim" (PiD v1):
+# x + sigmoid(Linear([x, lq]) - exp(log_alpha)*sigma) * lq (per-token per-dim, B,N,D)
+# "sigma_aware_per_token" (PiD v1.5):
+# x + sigmoid(Linear([x, lq]) - exp(log_alpha)*sigma) * lq (per-token scalar, B,N,1)
import math
from typing import List, Optional
@@ -21,25 +23,24 @@ import torch.nn as nn
import torch.nn.functional as F
# ---------------------------------------------------------------------------
-# Gate module
+# Gate modules
# ---------------------------------------------------------------------------
-class SigmaAwareGatePerTokenPerDim(nn.Module):
- """Per-token per-dim variant of SigmaAwareGatePerTokenPerDim.
+class _SigmaAwareGate(nn.Module):
+ """Sigma-aware gate whose content branch projects to ``gate_dim`` channels.
- Content branch projects to dim instead of 1, so the gate is independent per
- (token, channel) instead of shared across channels. Sigma branch stays scalar
- per sample and broadcasts (B, 1, 1) → (B, N, D).
+ The sigma branch stays scalar per sample and broadcasts (B, 1, 1) over (B, N, gate_dim), so the
+ inputs must be token-shaped: flattened (B*N, D) tokens would broadcast against it to (B*N, B*N, D).
Init: content_proj.bias=2.0, log_alpha=log(5) →
gate ≈ sigmoid(2.0 - 5*sigma): ~0.88 at sigma=0, ~0.5 at sigma=0.4, ~0.05 at sigma=1.
Requires sigma to always be provided (asserts at forward time).
"""
- def __init__(self, dim: int):
+ def __init__(self, dim: int, gate_dim: int):
super().__init__()
- self.content_proj = nn.Linear(dim * 2, dim)
+ self.content_proj = nn.Linear(dim * 2, gate_dim)
nn.init.trunc_normal_(self.content_proj.weight, std=0.01)
nn.init.constant_(self.content_proj.bias, 2.0)
self.log_alpha = nn.Parameter(torch.tensor(math.log(5.0)))
@@ -47,23 +48,26 @@ class SigmaAwareGatePerTokenPerDim(nn.Module):
def compute_gate_scalar(
self, x: torch.Tensor, lq: torch.Tensor, sigma: Optional[torch.Tensor] = None
) -> torch.Tensor:
- assert sigma is not None, "SigmaAwareGatePerTokenPerDim requires sigma input"
- content_logit = self.content_proj(torch.cat([x, lq], dim=-1)) # (B, N, D)
+ assert sigma is not None, f"{type(self).__name__} requires sigma input"
+ content_logit = self.content_proj(torch.cat([x, lq], dim=-1)) # (B, N, gate_dim)
sigma_offset = -self.log_alpha.exp() * sigma.float().view(-1, 1, 1) # (B, 1, 1)
- return torch.sigmoid(content_logit + sigma_offset) # (B, N, D)
+ return torch.sigmoid(content_logit + sigma_offset) # (B, N, gate_dim)
def forward(self, x: torch.Tensor, lq: torch.Tensor, sigma: Optional[torch.Tensor] = None) -> torch.Tensor:
return x + self.compute_gate_scalar(x, lq, sigma) * lq
-_SUPPORTED_GATE_TYPE = "sigma_aware_per_token_per_dim"
+_GATE_DIMS = {
+ "sigma_aware_per_token_per_dim": lambda dim: dim,
+ "sigma_aware_per_token": lambda dim: 1,
+}
def _build_gate(gate_type: str, dim: int, zero_init: bool = True) -> nn.Module:
# zero_init is intentionally not forwarded: redundant with zero-init output_heads.
- if gate_type != _SUPPORTED_GATE_TYPE:
- raise ValueError(f"Unknown gate_type: {gate_type!r}. Only {_SUPPORTED_GATE_TYPE!r} is supported.")
- return SigmaAwareGatePerTokenPerDim(dim)
+ if gate_type not in _GATE_DIMS:
+ raise ValueError(f"Unknown gate_type: {gate_type!r}. Must be one of {sorted(_GATE_DIMS)}.")
+ return _SigmaAwareGate(dim, _GATE_DIMS[gate_type](dim))
# ---------------------------------------------------------------------------
@@ -74,15 +78,15 @@ def _build_gate(gate_type: str, dim: int, zero_init: bool = True) -> nn.Module:
class ResBlock(nn.Module):
"""Pre-activation residual block: GroupNorm → SiLU → Conv → GroupNorm → SiLU → Conv + skip."""
- def __init__(self, channels: int, num_groups: int = 4):
+ def __init__(self, channels: int, num_groups: int = 4, conv_padding_mode: str = "zeros"):
super().__init__()
self.block = nn.Sequential(
nn.GroupNorm(num_groups, channels),
nn.SiLU(),
- nn.Conv2d(channels, channels, kernel_size=3, padding=1),
+ nn.Conv2d(channels, channels, kernel_size=3, padding=1, padding_mode=conv_padding_mode),
nn.GroupNorm(num_groups, channels),
nn.SiLU(),
- nn.Conv2d(channels, channels, kernel_size=3, padding=1),
+ nn.Conv2d(channels, channels, kernel_size=3, padding=1, padding_mode=conv_padding_mode),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
@@ -122,14 +126,18 @@ class LQProjection2D(nn.Module):
patch_size: spatial patch size of the transformer (e.g. 16).
sr_scale: super-resolution scale factor (LQ is sr_scale times smaller).
latent_spatial_down_factor: VAE spatial downscale factor (default 8).
+ latent_unpatchify_factor: spatial unpatchify factor for patchified latents, applied before the
+ alignment below. 1 disables it; PiD v1.5 uses 2 for FLUX.2, turning
+ [B, 128, H/16, W/16] into [B, 32, H/8, W/8].
num_res_blocks: number of ResBlocks after initial conv projection in each branch.
0 = no ResBlocks (original shallow design).
4 = recommended for stronger feature extraction (~4x deeper).
num_outputs: number of output feature sets — one per transformer block
for controlnet injection.
- gate_type: must be "sigma_aware_per_token_per_dim" (sigma-conditioned per-token per-dim gate).
+ gate_type: "sigma_aware_per_token_per_dim" (PiD v1) or "sigma_aware_per_token" (PiD v1.5).
interval: inject every N blocks (only relevant when num_outputs > 1).
zero_init: if True, zero-init all output projections for safe pretrained start.
+ conv_padding_mode: padding mode of every Conv2d in the image / latent / merge branches.
pit_output: if True, add a dedicated output head for PiT block injection.
The PiT head output is appended as the last element of forward() output.
"""
@@ -143,15 +151,22 @@ class LQProjection2D(nn.Module):
patch_size: int = 16,
sr_scale: int = 4,
latent_spatial_down_factor: int = 8,
+ latent_unpatchify_factor: int = 1,
num_res_blocks: int = 4,
num_outputs: int = 1,
- gate_type: str = _SUPPORTED_GATE_TYPE,
+ gate_type: str = "sigma_aware_per_token_per_dim",
interval: int = 1,
zero_init: bool = True,
+ conv_padding_mode: str = "zeros",
pit_output: bool = False,
):
super().__init__()
assert in_channels > 0 or latent_channels > 0, "At least one of in_channels or latent_channels must be > 0"
+ if latent_spatial_down_factor % latent_unpatchify_factor or latent_channels % latent_unpatchify_factor**2:
+ raise ValueError(
+ f"latent_unpatchify_factor {latent_unpatchify_factor} must divide latent_spatial_down_factor "
+ f"({latent_spatial_down_factor}) and its square latent_channels ({latent_channels})."
+ )
self.in_channels = in_channels
self.latent_channels = latent_channels
@@ -160,6 +175,7 @@ class LQProjection2D(nn.Module):
self.patch_size = patch_size
self.sr_scale = sr_scale
self.latent_spatial_down_factor = latent_spatial_down_factor
+ self.latent_unpatchify_factor = latent_unpatchify_factor
self.num_outputs = num_outputs
self.interval = interval
self.zero_init = zero_init
@@ -174,21 +190,23 @@ class LQProjection2D(nn.Module):
self.image_unshuffle_factor = patch_size // sr_scale
unshuffle_ch = in_channels * self.image_unshuffle_factor**2
layers = [
- nn.Conv2d(unshuffle_ch, hidden_dim, kernel_size=3, stride=1, padding=1),
+ nn.Conv2d(unshuffle_ch, hidden_dim, kernel_size=3, stride=1, padding=1, padding_mode=conv_padding_mode),
nn.SiLU(),
- nn.Conv2d(hidden_dim, hidden_dim, kernel_size=3, stride=1, padding=1),
+ nn.Conv2d(hidden_dim, hidden_dim, kernel_size=3, stride=1, padding=1, padding_mode=conv_padding_mode),
]
for _ in range(num_res_blocks):
- layers.append(ResBlock(hidden_dim))
+ layers.append(ResBlock(hidden_dim, conv_padding_mode=conv_padding_mode))
self.image_conv = nn.Sequential(*layers)
else:
self.image_conv = None
self.image_unshuffle_factor = 0
# --- Latent branch ---
- # Spatial alignment (fold / upsample) → Conv proj → ResBlocks
+ # (Unpatchify →) spatial alignment (fold / upsample) → Conv proj → ResBlocks
if latent_channels > 0:
- z_to_patch_ratio = (sr_scale * latent_spatial_down_factor) / patch_size
+ effective_latent_channels = latent_channels // latent_unpatchify_factor**2
+ effective_latent_spatial_down_factor = latent_spatial_down_factor // latent_unpatchify_factor
+ z_to_patch_ratio = (sr_scale * effective_latent_spatial_down_factor) / patch_size
self.z_to_patch_ratio = z_to_patch_ratio
if z_to_patch_ratio > 1:
@@ -196,10 +214,10 @@ class LQProjection2D(nn.Module):
# LearnedLatentUpsampler (PixelShuffle) caused DDP numerical issues on multi-node.
self.latent_upsampler = None
self.latent_upsample_ratio = int(z_to_patch_ratio)
- latent_proj_in_ch = latent_channels
+ latent_proj_in_ch = effective_latent_channels
elif z_to_patch_ratio == 1:
self.latent_upsampler = None
- latent_proj_in_ch = latent_channels
+ latent_proj_in_ch = effective_latent_channels
else:
fold_factor = int(1 / z_to_patch_ratio)
assert fold_factor * z_to_patch_ratio == 1.0, (
@@ -207,15 +225,17 @@ class LQProjection2D(nn.Module):
)
self.latent_upsampler = None
self.latent_fold_factor = fold_factor
- latent_proj_in_ch = latent_channels * fold_factor**2
+ latent_proj_in_ch = effective_latent_channels * fold_factor**2
layers = [
- nn.Conv2d(latent_proj_in_ch, hidden_dim, kernel_size=3, stride=1, padding=1),
+ nn.Conv2d(
+ latent_proj_in_ch, hidden_dim, kernel_size=3, stride=1, padding=1, padding_mode=conv_padding_mode
+ ),
nn.SiLU(),
- nn.Conv2d(hidden_dim, hidden_dim, kernel_size=3, stride=1, padding=1),
+ nn.Conv2d(hidden_dim, hidden_dim, kernel_size=3, stride=1, padding=1, padding_mode=conv_padding_mode),
]
for _ in range(num_res_blocks):
- layers.append(ResBlock(hidden_dim))
+ layers.append(ResBlock(hidden_dim, conv_padding_mode=conv_padding_mode))
self.latent_proj = nn.Sequential(*layers)
else:
self.latent_proj = None
@@ -224,9 +244,10 @@ class LQProjection2D(nn.Module):
# --- Merge + shared ResBlocks (if both branches active) ---
if in_channels > 0 and latent_channels > 0:
+ # A 1x1 conv pads nothing, so the padding mode does not reach it.
layers = [nn.Conv2d(hidden_dim * 2, hidden_dim, kernel_size=1), nn.SiLU()]
for _ in range(num_res_blocks):
- layers.append(ResBlock(hidden_dim))
+ layers.append(ResBlock(hidden_dim, conv_padding_mode=conv_padding_mode))
self.merge = nn.Sequential(*layers)
else:
self.merge = None
@@ -329,10 +350,17 @@ class LQProjection2D(nn.Module):
return self.image_conv(x) # [B, hidden_dim, target_pH, target_pW]
def _align_latent_to_patch_grid(self, lq_latent: torch.Tensor, pH: int, pW: int) -> torch.Tensor:
- """Align LQ latent to patch grid via nearest interpolate or fold.
+ """Align LQ latent to patch grid via (unpatchify and) nearest interpolate or fold.
Returns [B, hidden_dim, pH, pW].
"""
+ if (u := self.latent_unpatchify_factor) > 1:
+ # FLUX.2-style patchified latent: [B, C*u*u, H, W] -> [B, C, H*u, W*u], no BN inverse normalization.
+ B, C, H, W = lq_latent.shape
+ if C != self.latent_channels:
+ raise ValueError(f"Expected {self.latent_channels} LQ latent channels, got {C}.")
+ lq_latent = lq_latent.reshape(B, C // (u * u), u, u, H, W).permute(0, 1, 4, 2, 5, 3)
+ lq_latent = lq_latent.reshape(B, C // (u * u), H * u, W * u)
B, z_dim = lq_latent.shape[:2]
if self.z_to_patch_ratio > 1:
diff --git a/invokeai/backend/pid/_src/networks/pid_net.py b/invokeai/backend/pid/_src/networks/pid_net.py
index c8b24d7760..9f5f3c9df3 100644
--- a/invokeai/backend/pid/_src/networks/pid_net.py
+++ b/invokeai/backend/pid/_src/networks/pid_net.py
@@ -4,7 +4,7 @@
# conditioning for image super-resolution. The base T2I architecture is unchanged;
# LQ information is injected via per-block gated injection between transformer
# blocks ("controlnet" mode — the only mode supported in this inference subset).
-# Gate: sigma_aware_per_token_per_dim (sigma-conditioned LQ injection).
+# Gates: sigma_aware_per_token_per_dim (PiD v1) or sigma_aware_per_token (PiD v1.5).
#
# All LQ modules are zero-initialized by default (zero_init_lq=True) so the network
# starts identical to the pretrained T2I model.
@@ -39,12 +39,17 @@ class PidNet(PixDiT_T2I):
lq_latent_channels: LQ latent channels (e.g. 16 for Wan VAE, 0 to disable).
lq_hidden_dim: internal projection hidden dimension.
lq_num_res_blocks: number of ResBlocks per branch for deeper feature extraction.
- lq_gate_type: "sigma_aware_per_token_per_dim" only.
+ lq_latent_unpatchify_factor: unpatchify factor applied to the LQ latent before the projection
+ (PiD v1.5 uses 2 for FLUX.2's patchified latents; 1 disables it).
+ lq_conv_padding_mode: padding mode of every Conv2d in the LQ projection.
+ lq_gate_type: "sigma_aware_per_token_per_dim" (PiD v1) or "sigma_aware_per_token" (PiD v1.5);
+ the PiT LQ gate uses the same type.
lq_interval: inject every N blocks.
zero_init_lq: zero-init all LQ projections for safe pretrained start.
train_lq_proj_only: freeze base T2I, train only LQ projection modules.
sr_scale: super-resolution scale factor (default 4).
latent_spatial_down_factor: VAE spatial downscale factor (default 8).
+ pit_lq_inject: inject LQ features into the PiT pixel blocks through a dedicated output head.
"""
def __init__(
@@ -81,6 +86,8 @@ class PidNet(PixDiT_T2I):
lq_latent_channels: int = 0,
lq_hidden_dim: int = 512,
lq_num_res_blocks: int = 4,
+ lq_latent_unpatchify_factor: int = 1,
+ lq_conv_padding_mode: str = "zeros",
lq_gate_type: str = "sigma_aware_per_token_per_dim",
lq_interval: int = 1,
zero_init_lq: bool = True,
@@ -91,7 +98,6 @@ class PidNet(PixDiT_T2I):
# Inject LQ features into PiT pixel blocks via a dedicated output head
# from the same LQ projection CNN backbone. Added to s_cond before PiT loop.
pit_lq_inject: bool = False,
- pit_lq_gate_type: str = "sigma_aware_per_token_per_dim",
):
super().__init__(
in_channels=in_channels,
@@ -129,6 +135,7 @@ class PidNet(PixDiT_T2I):
self.train_lq_proj_only = train_lq_proj_only
num_lq_outputs = (patch_depth + lq_interval - 1) // lq_interval
+ self.num_lq_outputs = num_lq_outputs
self.pit_lq_inject = pit_lq_inject
@@ -140,11 +147,13 @@ class PidNet(PixDiT_T2I):
patch_size=patch_size,
sr_scale=sr_scale,
latent_spatial_down_factor=latent_spatial_down_factor,
+ latent_unpatchify_factor=lq_latent_unpatchify_factor,
num_res_blocks=lq_num_res_blocks,
num_outputs=num_lq_outputs,
gate_type=lq_gate_type,
interval=lq_interval,
zero_init=zero_init_lq,
+ conv_padding_mode=lq_conv_padding_mode,
pit_output=pit_lq_inject,
)
@@ -152,7 +161,7 @@ class PidNet(PixDiT_T2I):
if pit_lq_inject:
from invokeai.backend.pid._src.networks.lq_projection_2d import _build_gate
- self.pit_lq_gate = _build_gate(pit_lq_gate_type, hidden_size, zero_init=zero_init_lq)
+ self.pit_lq_gate = _build_gate(lq_gate_type, hidden_size, zero_init=zero_init_lq)
else:
self.pit_lq_gate = None
@@ -295,7 +304,14 @@ class PidNet(PixDiT_T2I):
# Compute LQ features (split along L internally when CP is active).
has_lq = lq_video_or_image is not None or lq_latent is not None
- lq_features = self._compute_lq_features(lq_video_or_image, lq_latent, lq_mask, Hs, Ws) if has_lq else None
+ lq_features = None
+ pit_lq_feature = None
+ if has_lq:
+ lq_outputs = self._compute_lq_features(lq_video_or_image, lq_latent, lq_mask, Hs, Ws)
+ # The PiT head's output rides last; the patch blocks gate on the first `num_lq_outputs` only.
+ lq_features = lq_outputs[: self.num_lq_outputs]
+ if self.pit_lq_inject:
+ pit_lq_feature = lq_outputs[self.num_lq_outputs]
collected_features = None # populated by _run_patch_blocks when feature_indices is set
@@ -432,13 +448,14 @@ class PidNet(PixDiT_T2I):
s = torch.cat([s, s.new_zeros(B, pad_len, s.shape[2])], dim=1)
# Pixel pathway with optional PiT LQ injection — operates on rank-local
- # patches under CP. lq_features[-1] was already split along L in
- # `_compute_lq_features`, so its B*L_local view lines up with s.
- s_cond = s.reshape(B * L_local, self.hidden_size)
- if self.pit_lq_inject and lq_features is not None:
- pit_lq = lq_features[-1].reshape(B * L_local, self.hidden_size)
- sigma_flat = degrade_sigma.repeat_interleave(L_local) if degrade_sigma is not None else None
- s_cond = self.pit_lq_gate(s_cond, pit_lq, sigma=sigma_flat)
+ # patches under CP. The PiT LQ feature was already split along L in
+ # `_compute_lq_features`, so its token axis lines up with s. The gate runs on
+ # [B, L_local, D] tokens: it broadcasts sigma as (B, 1, 1), which flattened
+ # [B*L, D] tokens would turn into [B*L, B*L, D].
+ s_cond_tokens = s
+ if pit_lq_feature is not None:
+ s_cond_tokens = self.pit_lq_gate(s_cond_tokens, pit_lq_feature, sigma=degrade_sigma)
+ s_cond = s_cond_tokens.reshape(B * L_local, self.hidden_size)
# Pixel embedder runs on the full image (cheap; identical across CP
# ranks). Reshape and slice to the rank-local subset of patches so that
diff --git a/invokeai/backend/pid/decode.py b/invokeai/backend/pid/decode.py
index 4a9f4abe56..e493d05e3b 100644
--- a/invokeai/backend/pid/decode.py
+++ b/invokeai/backend/pid/decode.py
@@ -13,7 +13,8 @@ Hyperparameters were extracted from PiD's `pid_sr4x` base net config and
the per-backbone experiment overrides (NVIDIA's upstream `pid/_src/configs/`,
not vendored here — only the values needed at inference). See
`shared_config.py` and `experiment/{flux,flux2,sd3}.py` in the upstream
-repository for the source of truth.
+repository for the source of truth; the PiD v1.5 deltas come from
+`common/defaults/net.py` (`PID_SR4X_V1PT5`) and `experiment_2kto4k_v1pt5/`.
"""
from __future__ import annotations
@@ -30,6 +31,7 @@ from torch import Tensor
from invokeai.backend.model_manager.taxonomy import BaseModelType
from invokeai.backend.pid._src.networks.pid_net import PidNet
+from invokeai.backend.pid.state_dict_utils import PID_VERSION_BY_LQ_HIDDEN_DIM, PiDVersion
from invokeai.backend.util.logging import InvokeAILogger
_PID_ACTIVATION_CHUNK_SIZE = 1024
@@ -69,7 +71,6 @@ _PID_SR4X_BASE: dict = {
"train_lq_proj_only": False,
"sr_scale": 4,
"pit_lq_inject": False,
- "pit_lq_gate_type": "sigma_aware_per_token_per_dim",
}
# Per-backbone net deltas (mirrors upstream experiment/{name}.py).
@@ -96,6 +97,24 @@ _PER_BACKBONE: dict[BaseModelType, dict] = {
},
}
+# PiD v1.5 net deltas over the v1 base (upstream `PID_SR4X_V1PT5` in configs/common/defaults/net.py). Upstream also
+# enables `lq_aux_rgb_head`, a training-only reconstruction head the released checkpoints do not carry.
+_V1_5_NET_DELTAS: dict = {
+ "lq_hidden_dim": 1024,
+ "lq_gate_type": "sigma_aware_per_token",
+ "lq_conv_padding_mode": "replicate",
+ "pit_lq_inject": True,
+ "rope_ref_h": 2048,
+ "rope_ref_w": 2048,
+}
+
+# The backbones NVIDIA released v1.5 decoders for, with their own deltas (upstream `PID_SR4X_V1PT5_FOR_FLUX2`).
+_V1_5_PER_BACKBONE: dict[BaseModelType, dict] = {
+ BaseModelType.Flux: {},
+ BaseModelType.Flux2: {"lq_latent_unpatchify_factor": 2},
+ BaseModelType.QwenImage: {},
+}
+
# Distilled-student schedule (`student_t_list` from shared_config).
_STUDENT_T_LIST: list[float] = [0.999, 0.866, 0.634, 0.342, 0.0]
@@ -195,8 +214,8 @@ def estimate_pid_decode_working_memory(
return min(chunked, unoptimized)
-def build_pid_net(backbone: BaseModelType) -> PidNet:
- """Build an uninitialised PidNet of the right shape for *backbone*.
+def build_pid_net(backbone: BaseModelType, version: PiDVersion = PiDVersion.V1) -> PidNet:
+ """Build an uninitialised PidNet of the right shape for *backbone* and decoder *version*.
The returned network is on CPU and in float32; the caller is responsible
for casting it to the desired dtype/device before loading weights.
@@ -206,13 +225,21 @@ def build_pid_net(backbone: BaseModelType) -> PidNet:
f"PiD decoder backbone {backbone!r} is not supported. Expected one of: {list(_PER_BACKBONE.keys())}."
)
kwargs = {**_PID_SR4X_BASE, **_PER_BACKBONE[backbone]}
+ if version is PiDVersion.V1_5:
+ if backbone not in _V1_5_PER_BACKBONE:
+ raise ValueError(
+ f"PiD v1.5 decoder backbone {backbone!r} is not supported. Expected one of: "
+ f"{list(_V1_5_PER_BACKBONE.keys())}."
+ )
+ kwargs |= {**_V1_5_NET_DELTAS, **_V1_5_PER_BACKBONE[backbone]}
return PidNet(**kwargs)
# The one PidNet parameter whose shape depends on the backbone: a Conv2d whose in-channels are the
-# backbone's latent channel count (4 SDXL / 16 FLUX.1, SD3, Qwen-Image / 128 FLUX.2). Every other
-# parameter is name- and shape-identical across all five, which is what lets model identification
-# hold a checkpoint to one contract before it knows which backbone the checkpoint is for.
+# backbone's latent channel count as the projection takes it (4 SDXL / 16 FLUX.1, SD3, Qwen-Image /
+# 128 FLUX.2, unpatchified to 32 in v1.5). Within a generation every other parameter is name- and
+# shape-identical across its backbones, which is what lets model identification hold a checkpoint to
+# one contract before it knows which backbone the checkpoint is for. Its dim 0 names the generation.
BACKBONE_DISCRIMINATOR_KEY = "lq_proj.latent_proj.0.weight"
# The backbone the contract is probed from. Any of the five would do — see the docstring below.
@@ -220,8 +247,10 @@ _KEY_CONTRACT_BACKBONE = BaseModelType.Flux
@lru_cache(maxsize=None)
-def required_pid_net_shapes(backbone: BaseModelType = _KEY_CONTRACT_BACKBONE) -> Mapping[str, tuple[int, ...]]:
- """Every parameter `PidNet` expects, mapped to its shape.
+def required_pid_net_shapes(
+ backbone: BaseModelType = _KEY_CONTRACT_BACKBONE, version: PiDVersion = PiDVersion.V1
+) -> Mapping[str, tuple[int, ...]]:
+ """Every parameter a *version* `PidNet` expects, mapped to its shape.
This is the contract `load_pid_decoder` enforces — set equality on the keys, plus the shape
agreement `load_state_dict` demands — so model identification can accept precisely the files the
@@ -236,13 +265,14 @@ def required_pid_net_shapes(backbone: BaseModelType = _KEY_CONTRACT_BACKBONE) ->
otherwise shift the seedless stream by an amount that depends on how many candidate files were
probed, making later unseeded randomness depend on install order.
- ``backbone`` exists for `test_pid_decode.py`, which pins that the key set is identical across all
- five and that `BACKBONE_DISCRIMINATOR_KEY` is the only shape that varies. Identification itself
- must use the default: it has to validate a checkpoint *before* it can know the backbone, since
- the backbone is read from one of the weights the contract is there to require.
+ ``backbone`` exists for the tests, which pin that within a generation the key set is identical
+ across its backbones and that `BACKBONE_DISCRIMINATOR_KEY` is the only shape that varies.
+ Identification itself must use the default backbone: it has to validate a checkpoint *before* it
+ can know the backbone, since the backbone is read from one of the weights the contract is there to
+ require. It does pass ``version``, read off that weight's width, which no backbone varies.
"""
with torch.random.fork_rng(devices=[]), torch.device("meta"):
- net = build_pid_net(backbone)
+ net = build_pid_net(backbone, version)
return MappingProxyType({k: tuple(v.shape) for k, v in net.state_dict().items()})
@@ -251,10 +281,18 @@ def load_pid_decoder(state_dict: dict[Any, Tensor], backbone: BaseModelType) ->
The state dict is expected to be the model-manager loader's output, i.e.
already stripped of the `net.` prefix used by NVIDIA's distill model
- serialisation. The caller still owns dtype/device placement of the
- returned net.
+ serialisation. The decoder generation is read off the latent projection's
+ width; a state dict that names none is built as v1, so a truncated or
+ malformed file still reaches the key reports below. The caller still owns
+ dtype/device placement of the returned net.
"""
- net = build_pid_net(backbone)
+ discriminator_shape = getattr(state_dict.get(BACKBONE_DISCRIMINATOR_KEY), "shape", None)
+ version = (
+ PID_VERSION_BY_LQ_HIDDEN_DIM.get(discriminator_shape[0], PiDVersion.V1)
+ if discriminator_shape
+ else PiDVersion.V1
+ )
+ net = build_pid_net(backbone, version)
# A `.pth` unpickles to whatever it contains, and a bare (un-prefixed) checkpoint reaches here
# with its keys untouched — see `strip_net_prefix`. `nn.Module.load_state_dict` calls
diff --git a/invokeai/backend/pid/state_dict_utils.py b/invokeai/backend/pid/state_dict_utils.py
index 503ef8be51..74353d5ef4 100644
--- a/invokeai/backend/pid/state_dict_utils.py
+++ b/invokeai/backend/pid/state_dict_utils.py
@@ -16,12 +16,28 @@ Deliberately dependency-free — the config imports it during model identificati
the vendored PiD network stack would be wasted work.
"""
+from enum import Enum
from typing import Any, TypeVar
# NVIDIA's official PiD `.pth` checkpoints store the student under this prefix (see
# `PidDistillModel.state_dict(prefix="net.")` in the vendored upstream).
NET_PREFIX = "net."
+
+class PiDVersion(str, Enum):
+ """NVIDIA's PiD decoder generations.
+
+ Both share the backbone. v1.5 widens the LQ projection, injects LQ features into the pixel blocks too (PiT)
+ and gates per token rather than per token and channel.
+ """
+
+ V1 = "v1"
+ V1_5 = "v1.5"
+
+
+# dim 0 of `lq_proj.latent_proj.0.weight`, the one shape that tells the generations apart before a network exists.
+PID_VERSION_BY_LQ_HIDDEN_DIM: dict[int, PiDVersion] = {512: PiDVersion.V1, 1024: PiDVersion.V1_5}
+
# Sibling submodules of the distillation setup. They are not part of PidNet, and some of them shadow
# its parameter names (`net_ema.lq_proj.…`), so they must be dropped rather than renamed.
_DISTILL_ONLY_PREFIXES = ("net_ema.", "fake_score.", "discriminator.")
diff --git a/tests/backend/model_manager/configs/test_pid_decoder_config.py b/tests/backend/model_manager/configs/test_pid_decoder_config.py
index b7c6f3283f..e01587c4f4 100644
--- a/tests/backend/model_manager/configs/test_pid_decoder_config.py
+++ b/tests/backend/model_manager/configs/test_pid_decoder_config.py
@@ -6,9 +6,9 @@ Covers what identification has to get right before a checkpoint reaches the deco
enforces. Checking a subset is not a milder version of the same guarantee — loaders run under
`skip_torch_weight_init()`, so a weight the checkpoint does not supply is uninitialised memory
rather than a default, and a file accepted here but refused there decodes nothing.
-- Architecture: InvokeAI's build_pid_net constructs only the legacy 512-dim PidNet. NVIDIA's v1.5
- decoders use lq_hidden_dim=1024 (plus PiT injection, scalar gates, ...), which cannot be loaded
- into it, so such a checkpoint must be rejected here instead of crashing mid-decode.
+- Architecture: the LQ projection's width names the decoder generation (512 for v1, 1024 for v1.5),
+ and the file is held to that generation's contract. A width no generation has is rejected as an
+ architecture rather than reported as a pile of missing and unexpected keys.
- Backbone and variant: read from the weights where the weights can say, and from name evidence only
for the FLUX.1 / SD3 / Qwen-Image tie the weights cannot break.
@@ -38,6 +38,7 @@ from invokeai.backend.model_manager.configs.pid_decoder import (
from invokeai.backend.model_manager.configs.unknown import Unknown_Config
from invokeai.backend.model_manager.taxonomy import BaseModelType, PiDDecoderVariantType
from invokeai.backend.pid.decode import BACKBONE_DISCRIMINATOR_KEY, required_pid_net_shapes
+from invokeai.backend.pid.state_dict_utils import PiDVersion
_OVERRIDE_FIELDS: dict[str, object] = {
"hash": "blake3:fakehash",
@@ -71,13 +72,15 @@ def test_the_config_and_the_network_agree_on_the_discriminator_weight() -> None:
assert _LATENT_PROJ_KEY == BACKBONE_DISCRIMINATOR_KEY
-def _pid_state_dict(lq_hidden_dim: int = 512, latent_channels: int = 16) -> dict[str, object]:
- """A complete PiD-looking state dict: every weight PidNet expects, at the shape it expects, with
- the discriminator conv overridden to the given hidden dim / latent channel count."""
- sd: dict[str, object] = {
- f"{_NET_PREFIX}{k}": _FakeShapeTensor(*shape) for k, shape in required_pid_net_shapes().items()
- }
- sd[f"{_NET_PREFIX}{_LATENT_PROJ_KEY}"] = _FakeShapeTensor(lq_hidden_dim, latent_channels, 3, 3)
+def _pid_state_dict(
+ lq_hidden_dim: int | None = None, latent_channels: int = 16, version: PiDVersion = PiDVersion.V1
+) -> dict[str, object]:
+ """A complete PiD-looking state dict: every weight a *version* PidNet expects, at the shape it expects, with
+ the discriminator conv overridden to the given latent channel count (and hidden dim, if given)."""
+ contract = required_pid_net_shapes(version=version)
+ sd: dict[str, object] = {f"{_NET_PREFIX}{k}": _FakeShapeTensor(*shape) for k, shape in contract.items()}
+ width = contract[_LATENT_PROJ_KEY][0] if lq_hidden_dim is None else lq_hidden_dim
+ sd[f"{_NET_PREFIX}{_LATENT_PROJ_KEY}"] = _FakeShapeTensor(width, latent_channels, 3, 3)
return sd
@@ -109,16 +112,101 @@ def test_legacy_512_checkpoint_is_accepted() -> None:
assert config.base.value == "flux"
-def test_v1_5_checkpoint_is_rejected_at_identification() -> None:
- """A 1024-dim (v1.5) checkpoint must be rejected, not accepted and crashed on later.
+ ("config_class", "latent_channels", "file_name", "base"),
+ [
+ (
+ PiDDecoder_Checkpoint_FLUX_Config,
+ 16,
+ "pid_1.5_flux1_1024_to_4096_4step_bf16.safetensors",
+ BaseModelType.Flux,
+ ),
+ (
+ PiDDecoder_Checkpoint_QwenImage_Config,
+ 16,
+ "pid_1.5_qwenimage_1024_to_4096_4step_bf16.safetensors",
+ BaseModelType.QwenImage,
+ ),
+ (
+ PiDDecoder_Checkpoint_Flux2_Config,
+ 32,
+ "pid_1.5_flux2_1024_to_4096_4step_bf16.safetensors",
+ BaseModelType.Flux2,
+ ),
+ ],
+)
+def test_a_v1_5_checkpoint_identifies_under_comfy_org_s_name(
+ config_class: type, latent_channels: int, file_name: str, base: BaseModelType
+) -> None:
+ """Comfy-Org ships the v1.5 decoders as single files named by input and output size; FLUX.2's is unpatchified
+ to 32 channels before its projection. Only the 2K-to-4K preset exists for v1.5, and the name says so."""
+ fields = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"}
+ state_dict = _pid_state_dict(latent_channels=latent_channels, version=PiDVersion.V1_5)
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), state_dict, file_name=file_name)
+ config = config_class.from_model_on_disk(mod, dict(fields))
+ assert config.base is base
+ assert config.variant is PiDDecoderVariantType.Res2kTo4k_Sr4x
- The architecture check runs before the contract check so the diagnosis is the accurate one: a
- v1.5 file is intact, and judged against the legacy contract it would be reported as a pile of
- missing and unexpected keys rather than as the newer architecture it is.
- """
+
[email protected]("latent_channels", [4, 128])
+def test_v1_5_has_no_sdxl_or_unpatchified_flux2_decoder(latent_channels: int) -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(latent_channels=latent_channels, version=PiDVersion.V1_5))
+ with pytest.raises(InvalidMatchError, match=f"PiD v1.5 checkpoint has {latent_channels} latent channels"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
+def test_a_v1_checkpoint_at_v1_5_width_lacks_the_pit_injection() -> None:
+ """The width selects the v1.5 contract, and a v1 file widened to it is missing what v1.5 adds."""
with TemporaryDirectory() as tmpdir:
mod = _mock_mod(Path(tmpdir), _pid_state_dict(lq_hidden_dim=1024))
- with pytest.raises(InvalidMatchError, match="lq_proj hidden dim 1024"):
+ with pytest.raises(InvalidMatchError, match="missing 5 of the weights required by PidNet"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
+ "file_name",
+ ["pid_1.5_qwenimage_1024_to_4096_bf16.safetensors", "PiD_v1pt5_res2kto4k_sr4x_qwenimage_undistilled.pth"],
+)
+def test_a_v1_5_teacher_is_rejected_by_its_name(file_name: str) -> None:
+ """Teacher and 4-step student share every key and shape, and sampled with the student schedule a teacher
+ decodes to a degraded image without any error. Comfy-Org's teacher files lack `_4step`; NVIDIA's say
+ `undistilled`. The name is the only evidence, so it has to be heeded."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(version=PiDVersion.V1_5), file_name=file_name)
+ with pytest.raises(InvalidMatchError, match="undistilled"):
+ PiDDecoder_Checkpoint_QwenImage_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS, base="qwen-image"))
+
+
+def test_a_v1_5_student_in_a_folder_named_like_a_comfy_file_is_accepted() -> None:
+ """Comfy-Org's teacher spelling is read off file names: a local install is identified before it moves, so its
+ parent is whatever folder the user keeps decoders in."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(
+ Path(tmpdir),
+ _pid_state_dict(version=PiDVersion.V1_5),
+ dir_name="pid_1.5_decoders",
+ file_name="pid_1.5_qwenimage_1024_to_4096_4step_bf16.safetensors",
+ )
+ config = PiDDecoder_Checkpoint_QwenImage_Config.from_model_on_disk(
+ mod, dict(_OVERRIDE_FIELDS, base="qwen-image")
+ )
+ assert config.base is BaseModelType.QwenImage
+
+
+def test_a_v1_5_file_whose_name_names_no_preset_is_2k_to_4k() -> None:
+ """v1.5 exists only as 2K-to-4K, so a renamed FLUX.1 file must not take the v1 FLUX default of 2K."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(version=PiDVersion.V1_5), file_name="decoder.safetensors")
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+ assert config.variant is PiDDecoderVariantType.Res2kTo4k_Sr4x
+
+
+def test_an_lq_width_no_generation_has_is_rejected_as_an_architecture() -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(lq_hidden_dim=768))
+ with pytest.raises(InvalidMatchError, match=r"lq_proj hidden dim 768; InvokeAI supports 512 \(v1\), 1024"):
PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
@@ -255,17 +343,19 @@ def _write_pid_checkpoint(root: Path, state_dict: dict[Any, object]) -> Path:
return path
-def _real_pid_state_dict(lq_hidden_dim: int = 512, latent_channels: int = 16) -> dict[str, object]:
+def _real_pid_state_dict(
+ lq_hidden_dim: int | None = None, latent_channels: int = 16, version: PiDVersion = PiDVersion.V1
+) -> dict[str, object]:
"""`_pid_state_dict` with tensors that can actually be serialised.
PidNet is ~5.5 GB in float32, so every weight is a zero-stride view onto one shared scalar: the
shapes are the real ones, the file is ~50 KB, and `torch.save` deduplicates the storage.
"""
scalar = torch.zeros(())
- sd: dict[str, object] = {
- f"{_NET_PREFIX}{k}": scalar.expand(shape) for k, shape in required_pid_net_shapes().items()
- }
- sd[f"{_NET_PREFIX}{_LATENT_PROJ_KEY}"] = scalar.expand(lq_hidden_dim, latent_channels, 3, 3)
+ contract = required_pid_net_shapes(version=version)
+ sd: dict[str, object] = {f"{_NET_PREFIX}{k}": scalar.expand(shape) for k, shape in contract.items()}
+ width = contract[_LATENT_PROJ_KEY][0] if lq_hidden_dim is None else lq_hidden_dim
+ sd[f"{_NET_PREFIX}{_LATENT_PROJ_KEY}"] = scalar.expand(width, latent_channels, 3, 3)
return sd
@@ -291,14 +381,22 @@ class TestUnusableCheckpointIsNeverRegistered:
return sd
def _truncated_v1_5(self) -> dict[str, object]:
- """Both wrong at once. The architecture check fires first, so this is the case where an
- unsupported-but-not-fatal verdict would let a *truncated* file through to Unknown_Config."""
- sd = _real_pid_state_dict(lq_hidden_dim=1024)
- del sd[f"{_NET_PREFIX}lq_proj.output_heads.3.weight"]
+ """A v1.5 file is held to the v1.5 contract, down to the one weight only its PiT injection has."""
+ sd = _real_pid_state_dict(version=PiDVersion.V1_5)
+ del sd[f"{_NET_PREFIX}pit_lq_gate.log_alpha"]
return sd
- def _intact_v1_5(self) -> dict[str, object]:
- return _real_pid_state_dict(lq_hidden_dim=1024)
+ def _unknown_architecture(self) -> dict[str, object]:
+ """Intact but for an LQ width no generation has: every config class would reject it for that reason."""
+ return _real_pid_state_dict(lq_hidden_dim=768)
+
+ def _int8_convrot_v1_5(self) -> dict[str, object]:
+ """Comfy-Org's `pid_1.5_*_int8_convrot` builds carry a scale and a marker beside each int8 weight. Loading
+ such a weight as the float parameter it replaces decodes garbage, so the file must not register."""
+ sd = _real_pid_state_dict(version=PiDVersion.V1_5)
+ sd[f"{_NET_PREFIX}patch_blocks.0.attn.qkv_x.weight_scale"] = torch.ones(())
+ sd[f"{_NET_PREFIX}patch_blocks.0.attn.qkv_x.comfy_quant"] = torch.zeros(28, dtype=torch.uint8)
+ return sd
def _unsupported_latent_channels(self) -> dict[str, object]:
return _real_pid_state_dict(latent_channels=32)
@@ -328,8 +426,9 @@ class TestUnusableCheckpointIsNeverRegistered:
[
("_partial", "missing 456 of the weights"),
("_missing_backbone_weight", "missing 1 of the weights required by PidNet"),
- ("_truncated_v1_5", "lq_proj hidden dim 1024"),
- ("_intact_v1_5", "lq_proj hidden dim 1024"),
+ ("_truncated_v1_5", "missing 1 of the weights required by PidNet"),
+ ("_unknown_architecture", "lq_proj hidden dim 768"),
+ ("_int8_convrot_v1_5", "2 keys PidNet does not expect"),
("_unsupported_latent_channels", "32 latent channels"),
("_malformed_discriminator", "malformed lq_proj.latent_proj.0.weight"),
("_bare_with_a_non_string_key", "2 keys PidNet does not expect"),
@@ -347,10 +446,11 @@ class TestUnusableCheckpointIsNeverRegistered:
assert result.invalid_matches
assert expected_reason in str(result.invalid_matches[0])
- def test_a_valid_checkpoint_still_identifies(self) -> None:
- """The counterweight: none of the above may make a real decoder harder to install."""
+ @pytest.mark.parametrize("version", list(PiDVersion))
+ def test_a_valid_checkpoint_still_identifies(self, version: PiDVersion) -> None:
+ """The counterweight: none of the above may make a real decoder of either generation harder to install."""
with TemporaryDirectory() as tmpdir:
- path = _write_pid_checkpoint(Path(tmpdir), _real_pid_state_dict())
+ path = _write_pid_checkpoint(Path(tmpdir), _real_pid_state_dict(version=version))
result = ModelConfigFactory.from_model_on_disk(path, allow_unknown=True)
assert result.config is not None
diff --git a/tests/backend/pid/test_pid_decode.py b/tests/backend/pid/test_pid_decode.py
index d051e32d4c..eeba03d237 100644
--- a/tests/backend/pid/test_pid_decode.py
+++ b/tests/backend/pid/test_pid_decode.py
@@ -315,7 +315,7 @@ class TestLoadPidDecoderRejectsPartialCheckpoints:
def tiny_net(self, monkeypatch: pytest.MonkeyPatch) -> "TestLoadPidDecoderRejectsPartialCheckpoints._TinyNet":
"""Stand in for the (multi-GB) real PidNet — only load_state_dict's bookkeeping is under test."""
net = self._TinyNet()
- monkeypatch.setattr("invokeai.backend.pid.decode.build_pid_net", lambda backbone: net)
+ monkeypatch.setattr("invokeai.backend.pid.decode.build_pid_net", lambda backbone, version: net)
return net
def test_complete_state_dict_loads(self, tiny_net: torch.nn.Module) -> None:
diff --git a/tests/backend/pid/test_pid_v1_5.py b/tests/backend/pid/test_pid_v1_5.py
new file mode 100644
index 0000000000..e09441b89c
--- /dev/null
+++ b/tests/backend/pid/test_pid_v1_5.py
@@ -0,0 +1,266 @@
+"""PiD v1.5: the network paths NVIDIA's second decoder generation uses, and how a checkpoint selects them.
+
+v1.5 keeps the v1 backbone and changes the LQ projection around it: a 1024-wide projection, a per-token scalar gate
+instead of a per-token per-channel one, replicate padding, LQ injection into the PiT pixel blocks, and for FLUX.2
+an unpatchify of the 128-channel latent to 32 channels. The expected shapes below were read off the header of
+Comfy-Org's `PixelDiT/diffusion_models/pid_1.5_qwenimage_1024_to_4096_4step_bf16.safetensors` (and its FLUX.2
+sibling), and the settings no weight shape reveals from upstream's `PID_SR4X_V1PT5` net config — not derived from
+the code under test.
+"""
+
+import math
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+from invokeai.backend.model_manager.taxonomy import BaseModelType
+from invokeai.backend.pid import decode as pid_decode_module
+from invokeai.backend.pid._src.networks.lq_projection_2d import LQProjection2D, _build_gate
+from invokeai.backend.pid._src.networks.pid_net import PidNet
+from invokeai.backend.pid.decode import (
+ BACKBONE_DISCRIMINATOR_KEY,
+ build_pid_net,
+ load_pid_decoder,
+ required_pid_net_shapes,
+)
+from invokeai.backend.pid.state_dict_utils import PiDVersion
+
+# Only in the v1.5 header, and 57 keys whose shape differs from the v1 (`pid_qwenimage_…_4step_bf16`) header.
+_V1_5_ONLY_KEYS = {
+ "lq_proj.pit_head.weight",
+ "lq_proj.pit_head.bias",
+ "pit_lq_gate.content_proj.weight",
+ "pit_lq_gate.content_proj.bias",
+ "pit_lq_gate.log_alpha",
+}
+_SHAPES_THAT_DIFFER_FROM_V1 = 57
+
+
+class TestV1_5Contract:
+ def test_matches_the_released_checkpoint(self) -> None:
+ v1 = required_pid_net_shapes()
+ v1_5 = required_pid_net_shapes(version=PiDVersion.V1_5)
+
+ assert v1_5.keys() - v1.keys() == _V1_5_ONLY_KEYS
+ assert v1.keys() <= v1_5.keys()
+ assert v1_5[BACKBONE_DISCRIMINATOR_KEY] == (1024, 16, 3, 3)
+ assert v1_5["lq_proj.latent_proj.2.weight"] == (1024, 1024, 3, 3)
+ assert v1_5["lq_proj.output_heads.0.weight"] == (1536, 1024)
+ assert v1_5["lq_proj.pit_head.weight"] == (1536, 1024)
+ assert v1_5["lq_proj.gate_modules.6.content_proj.weight"] == (1, 3072)
+ assert v1_5["pit_lq_gate.content_proj.weight"] == (1, 3072)
+ assert v1_5["pit_lq_gate.log_alpha"] == ()
+ differing = {k for k in v1 if v1[k] != v1_5[k]}
+ assert len(differing) == _SHAPES_THAT_DIFFER_FROM_V1
+ assert all(k.startswith("lq_proj.") for k in differing), "v1.5 must leave the backbone untouched"
+
+ @pytest.mark.parametrize(
+ ("backbone", "latent_channels"),
+ [(BaseModelType.Flux, 16), (BaseModelType.QwenImage, 16), (BaseModelType.Flux2, 32)],
+ )
+ def test_one_contract_holds_for_every_backbone(self, backbone: BaseModelType, latent_channels: int) -> None:
+ """FLUX.2's 128 channels are unpatchified before the projection, so its discriminator reads 32."""
+ canonical = required_pid_net_shapes(version=PiDVersion.V1_5)
+ per_backbone = required_pid_net_shapes(backbone, PiDVersion.V1_5)
+
+ assert per_backbone.keys() == canonical.keys()
+ assert {k for k in canonical if per_backbone[k] != canonical[k]} <= {BACKBONE_DISCRIMINATOR_KEY}
+ assert per_backbone[BACKBONE_DISCRIMINATOR_KEY] == (1024, latent_channels, 3, 3)
+
+ @pytest.mark.parametrize("backbone", [BaseModelType.StableDiffusion3, BaseModelType.StableDiffusionXL])
+ def test_exists_only_for_the_backbones_nvidia_released(self, backbone: BaseModelType) -> None:
+ with pytest.raises(ValueError, match="v1.5 decoder backbone"):
+ required_pid_net_shapes(backbone, PiDVersion.V1_5)
+
+
+ ("version", "padding_mode", "rope_ref"),
+ [(PiDVersion.V1, "zeros", 1024), (PiDVersion.V1_5, "replicate", 2048)],
+)
+def test_the_released_settings_no_weight_shape_reveals(version: PiDVersion, padding_mode: str, rope_ref: int) -> None:
+ """Padding and the RoPE reference size change no parameter shape, so no contract or load check can see them."""
+ with torch.random.fork_rng(devices=[]), torch.device("meta"):
+ net = build_pid_net(BaseModelType.QwenImage, version)
+
+ padded_convs = [m for m in net.lq_proj.modules() if isinstance(m, torch.nn.Conv2d) and m.kernel_size != (1, 1)]
+ assert padded_convs
+ assert {conv.padding_mode for conv in padded_convs} == {padding_mode}
+ assert (net.rope_ref_grid_h, net.rope_ref_grid_w) == (rope_ref // 16, rope_ref // 16)
+
+
+def test_loading_builds_the_generation_the_latent_projection_names(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An unknown width is built as v1, so the file still gets the loader's key and shape reports."""
+ built: list[PiDVersion] = []
+
+ class _Built(Exception):
+ pass
+
+ def build(backbone: BaseModelType, version: PiDVersion) -> PidNet:
+ built.append(version)
+ raise _Built
+
+ monkeypatch.setattr(pid_decode_module, "build_pid_net", build)
+ for width in (512, 1024, 768):
+ with pytest.raises(_Built):
+ load_pid_decoder(
+ {BACKBONE_DISCRIMINATOR_KEY: torch.empty(width, 16, 3, 3, device="meta")}, BaseModelType.Flux
+ )
+ with pytest.raises(_Built):
+ load_pid_decoder({}, BaseModelType.Flux)
+
+ assert built == [PiDVersion.V1, PiDVersion.V1_5, PiDVersion.V1, PiDVersion.V1]
+
+
+def test_the_per_token_gate_is_one_scalar_per_token_decaying_with_sigma() -> None:
+ """content_proj zeroed and log_alpha 0: the gate is sigmoid(-sigma), 1/2 at sigma 0 and 1/4 at sigma ln 3."""
+ gate = _build_gate("sigma_aware_per_token", dim=4)
+ with torch.no_grad():
+ gate.content_proj.weight.zero_()
+ gate.content_proj.bias.zero_()
+ gate.log_alpha.zero_()
+ x = torch.zeros(2, 3, 4)
+ lq = torch.ones(2, 3, 4)
+
+ out = gate(x, lq, sigma=torch.tensor([0.0, math.log(3.0)]))
+
+ assert gate.content_proj.out_features == 1
+ torch.testing.assert_close(out[0], torch.full((3, 4), 0.5))
+ torch.testing.assert_close(out[1], torch.full((3, 4), 0.25))
+
+
+def test_unpatchify_is_the_pixel_shuffle_of_the_latent() -> None:
+ """FLUX.2 patchifies 2x2 latent pixels into channels exactly as `pixel_unshuffle` does, so undoing it must equal
+ `pixel_shuffle`. Unit patch ratio and an identity projection leave the unpatchified latent observable."""
+ proj = LQProjection2D(
+ in_channels=0,
+ latent_channels=8,
+ hidden_dim=4,
+ patch_size=8,
+ sr_scale=1,
+ latent_spatial_down_factor=16,
+ latent_unpatchify_factor=2,
+ )
+ proj.latent_proj = torch.nn.Identity()
+ latent = torch.arange(8 * 2 * 2, dtype=torch.float32).reshape(1, 8, 2, 2)
+
+ aligned = proj._align_latent_to_patch_grid(latent, 4, 4)
+
+ torch.testing.assert_close(aligned, F.pixel_shuffle(latent, 2))
+
+
[email protected](("padding_mode", "uniform"), [("replicate", True), ("zeros", False)])
+def test_replicate_padding_keeps_a_constant_latent_constant_at_the_border(padding_mode: str, uniform: bool) -> None:
+ """Every layer of the projection maps a spatially constant input to a spatially constant output, except a conv
+ that pads with zeros: its border tokens see the padding. One conv left on zeros breaks the uniformity."""
+ torch.manual_seed(0)
+ proj = LQProjection2D(
+ in_channels=0,
+ latent_channels=2,
+ hidden_dim=4,
+ out_dim=4,
+ patch_size=2,
+ sr_scale=1,
+ latent_spatial_down_factor=2,
+ num_res_blocks=1,
+ conv_padding_mode=padding_mode,
+ )
+ latent = torch.full((1, 2, 4, 4), 0.7)
+
+ with torch.no_grad():
+ tokens = proj(lq_latent=latent, target_pH=4, target_pW=4)[0]
+
+ spread = (tokens - tokens[:, :1]).abs().max().item()
+ assert (spread < 1e-5) is uniform, spread
+
+
+def _tiny_v1_5_net() -> PidNet:
+ net = PidNet(
+ in_channels=3,
+ num_groups=2,
+ hidden_size=8,
+ pixel_hidden_size=4,
+ pixel_attn_hidden_size=8,
+ pixel_num_groups=2,
+ patch_depth=2,
+ pixel_depth=1,
+ num_text_blocks=1,
+ patch_size=2,
+ txt_embed_dim=6,
+ txt_max_length=4,
+ rope_mode="original",
+ rope_ref_h=4,
+ rope_ref_w=4,
+ lq_in_channels=0,
+ lq_latent_channels=2,
+ lq_hidden_dim=4,
+ lq_num_res_blocks=1,
+ lq_conv_padding_mode="replicate",
+ lq_gate_type="sigma_aware_per_token",
+ lq_interval=1,
+ sr_scale=1,
+ latent_spatial_down_factor=2,
+ pit_lq_inject=True,
+ ).eval()
+ with torch.no_grad():
+ # The backbone zero-inits its final layer, which would make every output zero. The patch-block heads are
+ # zeroed instead, so the LQ latent reaches the pixels through the PiT injection alone.
+ torch.nn.init.normal_(net.final_layer.linear.weight)
+ for head in net.lq_proj.output_heads:
+ head.weight.zero_()
+ head.bias.zero_()
+ return net
+
+
+class TestPiTInjection:
+ """The PiT gate broadcasts sigma per sample over [B, L, D] tokens; the PiT head's output rides last."""
+
+ @pytest.fixture
+ def inputs(self) -> dict[str, torch.Tensor]:
+ torch.manual_seed(1)
+ return {
+ "x": torch.randn(2, 3, 4, 4),
+ "t": torch.tensor([500.0, 250.0]),
+ "y": torch.randn(2, 4, 6),
+ # On the 2x2 patch grid itself: a unit patch ratio aligns nothing.
+ "lq_latent": torch.randn(2, 2, 2, 2),
+ "degrade_sigma": torch.tensor([0.0, 0.7]),
+ }
+
+ @staticmethod
+ def _forward(net: PidNet, inputs: dict[str, torch.Tensor], **overrides: torch.Tensor) -> torch.Tensor:
+ args = inputs | overrides
+ with torch.no_grad():
+ return net(
+ args["x"], args["t"], args["y"], lq_latent=args["lq_latent"], degrade_sigma=args["degrade_sigma"]
+ )
+
+ def test_a_sample_decodes_the_same_alone_as_inside_a_batch(self, inputs: dict[str, torch.Tensor]) -> None:
+ """Fed flattened [B*L, D] tokens the gate mixed every token of the batch with every sample's sigma."""
+ torch.manual_seed(0)
+ net = _tiny_v1_5_net()
+
+ batched = self._forward(net, inputs)
+ alone = self._forward(net, {k: v[1:] for k, v in inputs.items()})
+
+ assert batched.abs().max() > 0
+ torch.testing.assert_close(batched[1:], alone)
+
+ def test_the_lq_latent_reaches_the_pixels_through_the_pit_head(self, inputs: dict[str, torch.Tensor]) -> None:
+ torch.manual_seed(0)
+ net = _tiny_v1_5_net()
+ with_pit = self._forward(net, inputs)
+ with torch.no_grad():
+ net.lq_proj.pit_head.weight.zero_()
+ net.lq_proj.pit_head.bias.zero_()
+
+ assert not torch.allclose(self._forward(net, inputs), with_pit)
+
+ def test_each_sample_is_gated_by_its_own_sigma(self, inputs: dict[str, torch.Tensor]) -> None:
+ torch.manual_seed(0)
+ net = _tiny_v1_5_net()
+
+ straight = self._forward(net, inputs)
+ swapped = self._forward(net, inputs, degrade_sigma=inputs["degrade_sigma"].flip(0))
+
+ assert not torch.allclose(straight[1], swapped[1])