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 followup (#9474)

Alexander Eichhorn8af4faedb81e
diff --git a/docs/src/content/docs/features/pid-decode.mdx b/docs/src/content/docs/features/pid-decode.mdx
index 7f6745d6d0..0192e96097 100644
--- a/docs/src/content/docs/features/pid-decode.mdx
+++ b/docs/src/content/docs/features/pid-decode.mdx
@@ -1,6 +1,6 @@
---
title: PiD Super-Resolution Decode
-lastUpdated: 2026-08-04
+lastUpdated: 2026-08-06
sidebar:
order: 5
---
@@ -12,7 +12,7 @@ import { Steps, Aside, Tabs, TabItem } from '@astrojs/starlight/components'
Because it decodes in pixel space and is conditioned on your prompt, PiD often recovers finer texture and edge detail than a plain VAE decode followed by an upscaler.
<Aside type="note">
-PiD replaces the VAE decode step of a single generation. It is not a separate "upscale" pass you run on an existing image — you enable it before generating.
+In the **Generate** tab and on the **Canvas**, PiD replaces the VAE decode step of a generation — you enable it *before* generating, it is not applied to a finished image. To run PiD over an image you already have, use the separate **PiD Upscale (4x)** node in the Workflow editor ([see below](#running-pid-on-an-existing-image)).
</Aside>
## Supported models
@@ -44,9 +44,11 @@ PiD needs two extra models, both available in **Model Manager → Starter Models
Each PiD decoder is roughly 5 GB and the shared Gemma-2 encoder is roughly 5 GB.
<Aside type="note">
-The Starter Models install NVIDIA's **legacy** PiD checkpoints (the ones now under `checkpoints_deprecated/` on Hugging Face). 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.
+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.
</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:
@@ -67,6 +69,16 @@ When PiD mode is not *Off*, pick your **PiD Decoder** and **Gemma-2 Encoder** be
PiD is available in both the **Generate** tab (text-to-image) and on the **Canvas** (image-to-image), in both Fit and Native modes.
+## Running PiD on an existing image
+
+Everything above describes PiD as a *decode* step: it needs the latent the model just produced, so it only exists inside a generation. If you want to push an image you already have through PiD, the Workflow editor has a separate **PiD Upscale (4x)** node.
+
+It encodes your image with the FLUX VAE and hands the resulting latent to the PiD decoder, giving a 4× result in one pass — the PiD analogue of an ESRGAN / SUPIR upscale. Connect a FLUX VAE, a **FLUX** PiD decoder and the Gemma-2 encoder, and optionally give it a caption describing the image (the decoder is caption-conditioned; an empty caption is the cheapest option but usually the weaker result).
+
+<Aside type="caution">
+This node is a **prototype** and FLUX-only in both directions: it requires InvokeAI's FLUX `AutoEncoder` VAE (a diffusers `AutoencoderKL`, e.g. Z-Image's, is rejected) and a FLUX PiD decoder. Since the input is a plain image rather than the generating model's own latent, results are less faithful than PiD used as a decode.
+</Aside>
+
## Tips & limitations
On GPUs with limited VRAM, enable the experimental PiD memory optimizations in `invokeai.yaml`, then restart InvokeAI:
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index bf12040a76..5b7337d587 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -1133,6 +1133,14 @@ class ModelInstallService(ModelInstallServiceBase):
except DuplicateModelException:
# In case a duplicate models sneaks by, we will ignore this error - we "found" the model
pass
+ except InvalidModelConfigException as e:
+ # A file we cannot register at all - unidentifiable with allow_unknown_models off, or
+ # recognised and rejected as unusable (e.g. a truncated checkpoint). ModelSearch already
+ # contains anything this callback raises, so startup survives either way; handling it
+ # here makes that a property of the scan rather than of the caller, and says which file
+ # was skipped and why.
+ self._logger.warning(f"Skipping {model_path.name}: {e}")
+ return False
return True
self._logger.info(f"Scanning {self._app_config.models_path} for orphaned models")
@@ -1153,8 +1161,15 @@ class ModelInstallService(ModelInstallServiceBase):
)
if result.config is None:
- self._logger.error(f"Could not identify model for {model_path}, detailed results: {result.details}")
- raise InvalidModelConfigException(f"Could not identify model for {model_path}")
+ # A model that was recognised and then rejected as unusable (e.g. a truncated checkpoint)
+ # comes with a specific reason. Report that instead of "could not identify", which would be
+ # both wrong and useless to whoever has to work out why the install failed.
+ if invalid := result.invalid_matches:
+ reason = f"Model at {model_path} cannot be used: {invalid[0]}"
+ else:
+ reason = f"Could not identify model for {model_path}"
+ self._logger.error(f"{reason}, detailed results: {result.details}")
+ raise InvalidModelConfigException(reason)
elif isinstance(result.config, Unknown_Config):
self._logger.error(f"Could not identify model for {model_path}, detailed results: {result.details}")
diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.py
index 09857eb433..aef2be7df0 100644
--- a/invokeai/backend/model_manager/configs/factory.py
+++ b/invokeai/backend/model_manager/configs/factory.py
@@ -34,7 +34,7 @@ from invokeai.backend.model_manager.configs.gemma2_encoder import (
Gemma2Encoder_Gemma2Encoder_Config,
Gemma2Encoder_GGUF_Config,
)
-from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError
+from invokeai.backend.model_manager.configs.identification_utils import InvalidMatchError, NotAMatchError
from invokeai.backend.model_manager.configs.ip_adapter import (
IPAdapter_Checkpoint_FLUX_Config,
IPAdapter_Checkpoint_SD1_Config,
@@ -474,6 +474,15 @@ class ModelClassificationResult:
"""Returns the number of matching model configs found."""
return len(self.all_matches)
+ @property
+ def invalid_matches(self) -> list[InvalidMatchError]:
+ """Rejections from config classes that recognised the model but found it unusable.
+
+ Non-empty means `config` is None because the file is broken, not because it is unidentifiable
+ — callers can report the specific reason instead of a generic "could not identify".
+ """
+ return [r for r in self.details.values() if isinstance(r, InvalidMatchError)]
+
class ModelConfigFactory:
@staticmethod
@@ -687,6 +696,11 @@ class ModelConfigFactory:
except NotAMatchError as e:
# This means the model didn't match this config class. It's not an error, just no match.
details[candidate_name] = e
+ except InvalidMatchError as e:
+ # This means the model *is* this config class' kind of model, but is unusable (e.g. a
+ # truncated checkpoint). Recorded like any other result here; the fallback below is
+ # what treats it differently from a plain no-match.
+ details[candidate_name] = e
except ValidationError as e:
# This means the model matched, but we couldn't create the pydantic model instance for the config.
# Maybe invalid overrides were provided?
@@ -699,6 +713,11 @@ class ModelConfigFactory:
matches = [r for r in details.values() if isinstance(r, Config_Base)]
if not matches:
+ if any(isinstance(r, InvalidMatchError) for r in details.values()):
+ # A config class recognised the model and rejected it as unusable. That is not the same
+ # as "unidentifiable": falling back to Unknown_Config here would register a file we know
+ # to be broken as a normal model record, so the rejection wins over allow_unknown.
+ return ModelClassificationResult(config=None, details=details)
if not allow_unknown:
# No matches and we are not allowed to fall back to Unknown_Config
return ModelClassificationResult(config=None, details=details)
diff --git a/invokeai/backend/model_manager/configs/gemma2_encoder.py b/invokeai/backend/model_manager/configs/gemma2_encoder.py
index 3b062eaa5f..619a4a1e6e 100644
--- a/invokeai/backend/model_manager/configs/gemma2_encoder.py
+++ b/invokeai/backend/model_manager/configs/gemma2_encoder.py
@@ -112,10 +112,12 @@ def _read_gguf_arch_and_hidden_size(path: Path) -> tuple[str, int | None]:
class Gemma2Encoder_GGUF_Config(Config_Base):
"""Single-file GGUF-quantized Gemma-2-2b encoder for PiD (llama.cpp GGUF, e.g. gemma-2-2b-it-Q4_K_M.gguf).
- Unlike the diffusers-directory config, this is a single ``.gguf`` file. transformers dequantizes it
- (``gemma2`` is in its GGUF config mapping) and reads the tokenizer from the GGUF metadata, so no
- companion config.json / tokenizer files are required. Only Gemma-2-2b (2304-dim) is accepted, matching
- PiD's fixed caption projection; 9B/27B GGUFs are rejected here as for the directory config.
+ Unlike the diffusers-directory config, this is a single ``.gguf`` file: the model config and the
+ tokenizer are read from the GGUF metadata, so no companion config.json / tokenizer files are required.
+ The weights are loaded natively by ``Gemma2EncoderGGUFLoader`` — the large 2D projections stay
+ quantized as ``GGMLTensor`` and are dequantized on demand by the model cache, rather than being fully
+ dequantized into memory at load time. Only Gemma-2-2b (2304-dim) is accepted, matching PiD's fixed
+ caption projection; 9B/27B GGUFs are rejected here as for the directory config.
"""
base: Literal[BaseModelType.Any] = Field(default=BaseModelType.Any)
diff --git a/invokeai/backend/model_manager/configs/identification_utils.py b/invokeai/backend/model_manager/configs/identification_utils.py
index ce7d2c792d..5231b73901 100644
--- a/invokeai/backend/model_manager/configs/identification_utils.py
+++ b/invokeai/backend/model_manager/configs/identification_utils.py
@@ -20,6 +20,29 @@ class NotAMatchError(Exception):
super().__init__(reason)
+class InvalidMatchError(Exception):
+ """Exception for when a config class recognises a model and then rejects it as unusable.
+
+ `NotAMatchError` means "this is not my kind of model": classification moves on to the remaining
+ config classes and, if none of them match either, falls back to `Unknown_Config` so the file is
+ still registered. That fallback is right for a file nobody recognises and wrong for one that was
+ recognised and found broken — a truncated checkpoint would be stored as a normal (if unknown)
+ model record and only fail once something tried to load it.
+
+ Raising this instead makes the rejection final: `ModelConfigFactory.from_model_on_disk` returns
+ no config regardless of `allow_unknown`, so nothing is written to the database.
+
+ Deliberately *not* a subclass of `NotAMatchError` — the factory catches that one per candidate
+ class and would swallow this along with it.
+
+ Args:
+ reason: Why the recognised model is unusable.
+ """
+
+ def __init__(self, reason: str):
+ super().__init__(reason)
+
+
def get_config_dict_or_raise(config_path: Path | set[Path]) -> dict[str, Any]:
"""Load the diffusers/transformers model config file and return it as a dictionary. The config file is expected
to be in JSON format.
diff --git a/invokeai/backend/model_manager/configs/pid_decoder.py b/invokeai/backend/model_manager/configs/pid_decoder.py
index 1552515861..dcc783953a 100644
--- a/invokeai/backend/model_manager/configs/pid_decoder.py
+++ b/invokeai/backend/model_manager/configs/pid_decoder.py
@@ -9,12 +9,14 @@ while SDXL and Qwen-Image ship only the `res2kto4k_sr4x_*` preset. See
"""
import re
+from collections.abc import Mapping
from typing import Any, Literal, Self
from pydantic import Field
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Config_Base
from invokeai.backend.model_manager.configs.identification_utils import (
+ InvalidMatchError,
NotAMatchError,
raise_for_override_fields,
raise_if_not_file,
@@ -23,9 +25,11 @@ from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
ModelFormat,
+ ModelSourceType,
ModelType,
PiDDecoderVariantType,
)
+from invokeai.backend.pid.state_dict_utils import pid_net_shapes
# Marker substring produced by `PidNet.lq_proj` (see
# invokeai/backend/pid/_src/networks/pid_net.py). The pretrained PixDiT_T2I
@@ -40,104 +44,232 @@ 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)
-# The latent input projection (`lq_proj.latent_proj.0`) is a Conv2d whose
-# in-channel count equals the backbone's latent channel count — the released
-# sr4x checkpoints apply no spatial fold here, so the Conv's dim-1 is exactly
-# `lq_latent_channels` (see `_PER_BACKBONE` in invokeai/backend/pid/decode.py):
-# FLUX.1 / SD3 = 16, FLUX.2 = 128. This is the only architectural dimension
-# that varies between backbones and is therefore a filename-independent
-# discriminator between FLUX.2 and the 16-channel family. (FLUX.1 and SD3 are
-# architecturally identical and cannot be told apart from the weights alone.)
-# We match the key by suffix because the official `.pth` keep the `net.` prefix.
-_LATENT_PROJ_KEY_SUFFIX = "lq_proj.latent_proj.0.weight"
+# PidNet's latent input projection: a Conv2d of shape (lq_hidden_dim, lq_latent_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 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]
+
-def _latent_channels_from_state_dict(state_dict: dict[str | int, Any]) -> int | None:
- """Read the backbone's latent channel count from the `lq_proj` input Conv.
+def _raise_if_discriminator_malformed(shapes: _Shapes, contract: Mapping[str, tuple[int, ...]]) -> None:
+ """Reject a checkpoint whose latent projection is present but is not a conv weight.
- Returns None if the diagnostic weight is absent or not a 4D conv tensor.
+ Every read identification makes off this weight requires it to be a 4D conv, and each used to
+ answer None when it was not — so a malformed tensor made the architecture check, the backbone
+ check and the channel check all abstain at once, and the file fell through to name-only matching,
+ which happily accepted it. Loading then failed on a size mismatch.
+
+ Only reached when the weight is present: its *absence* is a truncation, which
+ `_raise_if_pid_net_contract_unmet` diagnoses far better than a guess about the architecture.
"""
- for k, v in state_dict.items():
- if isinstance(k, str) and k.endswith(_LATENT_PROJ_KEY_SUFFIX):
- shape = getattr(v, "shape", None)
- if shape is not None and len(shape) == 4:
- return int(shape[1])
- return None
+ shape = shapes[_LATENT_PROJ_KEY]
+ expected = contract[_LATENT_PROJ_KEY]
+ if shape is None or len(shape) != len(expected) or shape[2:] != expected[2:]:
+ raise InvalidMatchError(
+ f"PiD checkpoint has a malformed {_LATENT_PROJ_KEY}: expected a "
+ f"{len(expected)}D conv weight with a {'x'.join(str(d) for d in expected[2:])} kernel, got "
+ f"{shape if shape is not None else 'a value with no shape'}"
+ )
+
+
+def _raise_if_architecture_unsupported(shapes: _Shapes) -> None:
+ """Reject a PiD decoder whose network shape `build_pid_net` cannot construct.
+
+ 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.
+ """
+ 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)."
+ )
+
+
+def _raise_if_no_backbone_can_accept(shapes: _Shapes) -> 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
+ *which* backbone a checkpoint belongs to and says "not this one" with `NotAMatchError` — four of
+ the five classes are meant to say exactly that about every valid checkpoint. A rejection here is
+ backbone-independent, so all five would raise it for the same reason, leaving the file with no
+ match at all and letting the factory register it through the `Unknown_Config` fallback: a PiD
+ decoder on record as a model nothing can load. Hence `InvalidMatchError`.
+
+ Runs before the contract check because a decoder for an unsupported backbone would otherwise be
+ 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:
+ 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)"
+ )
-# The `lq_proj.latent_proj.0` Conv's out-channel count 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. We read dim-0 to reject an incompatible checkpoint at
-# identification time instead of failing with a size-mismatch deep inside the decode.
-_SUPPORTED_LQ_HIDDEN_DIM = 512
+def _and_more(items: list[Any]) -> str:
+ return f" (+ {len(items) - 5} more)" if len(items) > 5 else ""
-def _lq_hidden_dim_from_state_dict(state_dict: dict[str | int, Any]) -> int | None:
- """Read PidNet's `lq_hidden_dim` (the `lq_proj.latent_proj.0` Conv out-channels), or None if absent."""
- for k, v in state_dict.items():
- if isinstance(k, str) and k.endswith(_LATENT_PROJ_KEY_SUFFIX):
- shape = getattr(v, "shape", None)
- if shape is not None and len(shape) == 4:
- return int(shape[0])
- return None
+def _raise_if_pid_net_contract_unmet(shapes: _Shapes, contract: Mapping[str, tuple[int, ...]]) -> None:
+ """Hold the checkpoint to exactly the contract `load_pid_decoder` enforces.
+ Checking only the LQ projection accepted a file that carried every LQ weight and none of the 385
+ backbone weights; the loader then refused it. A subset check 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.
-def _name_for_matching(mod: ModelOnDisk) -> str:
- """Searchable name for backbone/variant heuristics.
+ Missing *and* unexpected keys are fatal here because both are fatal there, which is what makes
+ installation and loading accept the same set of files. A stricter installer cannot reject a file
+ that would have loaded: the loader already refuses everything rejected here.
+
+ `_LATENT_PROJ_KEY` is excluded from the shape comparison, and only from that: it is the one
+ parameter whose shape legitimately varies by backbone, and its variable dimensions each have a
+ dedicated check above with a dedicated message.
+ """
+ # No "this is a base PixDiT_T2I checkpoint" special case, unlike `load_pid_decoder`: those weights
+ # carry no `lq_proj` key at all, so such a file never reaches here — `_looks_like_pid_decoder`
+ # has already turned it away, and with a better message.
+ # Both sorts take `key=str`: a bare checkpoint's keys need not all be strings (see
+ # `strip_net_prefix`), and sorting a mixed set raises TypeError — which the factory answers with
+ # the `Unknown_Config` registration these checks exist to prevent, so the crash fails as a silent
+ # accept rather than loudly. Only `unexpected` can hold one today; sorting both the same way keeps
+ # that from depending on which set is on which side of the subtraction.
+ if missing := sorted(contract.keys() - shapes.keys(), key=str):
+ raise InvalidMatchError(
+ f"PiD checkpoint is missing {len(missing)} of the weights required by PidNet; the file is "
+ f"incomplete and cannot be used as a PiD decoder: {missing[:5]}{_and_more(missing)}"
+ )
+
+ if unexpected := sorted(shapes.keys() - contract.keys(), key=str):
+ raise InvalidMatchError(
+ f"PiD checkpoint has {len(unexpected)} keys PidNet does not expect, which `load_pid_decoder` "
+ f"rejects too: {unexpected[:5]}{_and_more(unexpected)}"
+ )
+
+ mismatched = [(k, shapes[k], want) for k, want in contract.items() if k != _LATENT_PROJ_KEY and shapes[k] != want]
+ if mismatched:
+ k, got, want = mismatched[0]
+ raise InvalidMatchError(
+ f"PiD checkpoint has {len(mismatched)} weights whose shape PidNet cannot accept "
+ f"(e.g. {k}: {got}, expected {want}); loading it would fail with a size mismatch"
+ )
+
+
+def _name_components(mod: ModelOnDisk, override_fields: dict[str, Any]) -> tuple[str, ...]:
+ """The name evidence for backbone and variant, most specific first.
NVIDIA distributes PiD checkpoints as
- ``PiD_res2k_sr4x_official_<backbone>_distill_4step/model_ema_bf16.pth`` — the
- backbone + variant live in the *directory* name, not the weights filename.
- We therefore match against both the filename and its parent directory.
+ ``PiD_res2k_sr4x_official_<backbone>_distill_4step/model_ema_bf16.pth``, so the backbone and the
+ preset usually live in the *directory* name rather than the weights filename. A direct
+ single-file install stores the checkpoint as ``<uuid>/model_ema_bf16.pth`` and drops that
+ directory, which is why the install source is consulted at all: for an HF or URL install it still
+ carries NVIDIA's name.
+
+ These used to be concatenated into one string and substring-matched, which let a fixed backbone
+ precedence decide cases the name had already answered — `/flux/model_sd3.pth` matched `flux`
+ first and was registered as FLUX although the file itself says sd3. Matching component by
+ component and taking the first that names exactly one backbone lets the more specific name win.
+
+ A local install contributes no source: the model manager sets `source` to the file's own path
+ when there is no remote one (`ModelConfigFactory.build_common_fields`), so trusting it would mean
+ matching against arbitrary ancestor directories of wherever the user keeps their models. Nothing
+ is lost by dropping it — `install_path` identifies a local file *before* it moves it, so the
+ filename and parent directory are still the originals.
"""
- return f"{mod.path.parent.name} {mod.path.name}"
+ components = [mod.path.name, mod.path.parent.name]
+ if override_fields.get("source_type") != ModelSourceType.Path:
+ components.append(str(override_fields.get("source") or ""))
+ return tuple(c for c in components if c)
+
+
+# Ordered so that a more specific spelling is consumed before a more general one that it contains:
+# `flux2` before `flux`. That is precedence between two spellings of one answer, not between two
+# answers — see `_backbone_named_in`.
+_BACKBONE_NAME_PATTERNS: tuple[tuple[BaseModelType, re.Pattern[str]], ...] = (
+ (BaseModelType.Flux2, re.compile(r"flux[_\-.]?2")),
+ (BaseModelType.StableDiffusionXL, re.compile(r"sdxl")),
+ (BaseModelType.QwenImage, re.compile(r"qwen[_\-.]?image")),
+ (BaseModelType.StableDiffusion3, re.compile(r"sd[_\-.]?3")),
+ (BaseModelType.Flux, re.compile(r"flux")),
+)
-def _backbone_from_filename(name: str) -> BaseModelType | None:
- """Heuristic backbone match against NVIDIA's checkpoint filename conventions.
+def _backbone_named_in(text: str) -> BaseModelType | None:
+ """The single backbone *text* names, or None if it names none — or more than one.
- Returns None if no backbone can be inferred.
+ Two different backbones in one string is not a precedence question, it is a text that decides
+ nothing; resolving it by a fixed order is how a directory named `flux` came to outrank a file
+ named `model_sd3`. Abstaining leaves the decision to the explicit `base` override, or to the
+ FLUX.1 default for the 16-channel family.
"""
- n = name.lower()
- # Order matters: 'flux2' must match before 'flux'.
- if re.search(r"\bflux[_-]?2\b|flux2", n):
- return BaseModelType.Flux2
- if "flux" in n:
- return BaseModelType.Flux
- if re.search(r"\bsdxl\b|sdxl", n):
- return BaseModelType.StableDiffusionXL
- if re.search(r"qwen[_-]?image|qwenimage", n):
- return BaseModelType.QwenImage
- if re.search(r"\bsd[_-]?3\b|sd3", n):
- return BaseModelType.StableDiffusion3
+ remaining, found = text.lower(), set()
+ for base, pattern in _BACKBONE_NAME_PATTERNS:
+ if pattern.search(remaining):
+ found.add(base)
+ # Consumed so the general spelling cannot match the specific one's leftovers.
+ remaining = pattern.sub(" ", remaining)
+ return next(iter(found)) if len(found) == 1 else None
+
+
+def _backbone_from_components(components: tuple[str, ...]) -> BaseModelType | None:
+ """The backbone named by the most specific component that names exactly one."""
+ for component in components:
+ if (named := _backbone_named_in(component)) is not None:
+ return named
return None
-def _variant_from_filename(name: str) -> PiDDecoderVariantType:
- """Map NVIDIA's `res2k_sr4x` / `res2kto4k_sr4x` filename slice to a variant.
+# Backbones for which NVIDIA ships exactly one preset — for these the variant is known even when the
+# name gives nothing away. FLUX.1 / FLUX.2 / SD3 ship both presets and fall back to `Res2k_Sr4x`.
+_SINGLE_VARIANT_BACKBONES: dict[BaseModelType, PiDDecoderVariantType] = {
+ BaseModelType.StableDiffusionXL: PiDDecoderVariantType.Res2kTo4k_Sr4x,
+ BaseModelType.QwenImage: PiDDecoderVariantType.Res2kTo4k_Sr4x,
+}
+
- Defaults to ``Res2k_Sr4x`` when no clear marker is present.
+def _variant_from_components(components: tuple[str, ...], base: BaseModelType) -> 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.
"""
- n = name.lower()
- if "res2kto4k" in n or "res2k_to_4k" in n or "res2k_to4k" in n:
- return PiDDecoderVariantType.Res2kTo4k_Sr4x
- return PiDDecoderVariantType.Res2k_Sr4x
+ 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:
+ return PiDDecoderVariantType.Res2kTo4k_Sr4x
+ if "res2k" in n:
+ return PiDDecoderVariantType.Res2k_Sr4x
+ return _SINGLE_VARIANT_BACKBONES.get(base, PiDDecoderVariantType.Res2k_Sr4x)
class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
"""Shared logic for PiD decoder checkpoint configs.
- Concrete subclasses pin `base` to a specific backbone. Backbone matching is
- driven primarily by the latent channel count read from the weights, with the
- filename / directory name as a tie-breaker for the architecturally identical
- FLUX.1 / SD3 pair. `variant` is carried as data without participating in the
- discriminator tag (one config class per backbone).
+ Concrete subclasses pin `base` to a specific backbone. A checkpoint is first held to the full
+ `PidNet` contract — the same keys and shapes `load_pid_decoder` demands — and the backbone then
+ comes from the latent channel count in the weights, with an explicit override or the name as the
+ tie-breaker for the architecturally identical FLUX.1 / SD3 / Qwen-Image family. `variant` is
+ carried as data without participating in the discriminator tag (one config class per backbone).
"""
type: Literal[ModelType.PiDDecoder] = Field(default=ModelType.PiDDecoder)
@@ -146,82 +278,99 @@ class PiDDecoder_Checkpoint_Config_Base(Checkpoint_Config_Base):
@classmethod
def from_model_on_disk(cls, mod: ModelOnDisk, override_fields: dict[str, Any]) -> Self:
raise_if_not_file(mod)
+ # An explicit `base` is validated against this class's Literal here, so it already narrows
+ # identification to exactly one of the five PiD config classes.
raise_for_override_fields(cls, override_fields)
state_dict = mod.load_state_dict()
if not _looks_like_pid_decoder(state_dict):
raise NotAMatchError("state dict does not look like a PiD decoder (no 'lq_proj.*' keys)")
- # Reject checkpoints whose network shape InvokeAI's build_pid_net cannot construct (e.g. NVIDIA's
- # v1.5 decoders use lq_hidden_dim=1024) at identification time, instead of accepting them and
- # failing with a size-mismatch deep inside the decode.
- lq_hidden_dim = _lq_hidden_dim_from_state_dict(state_dict)
- if lq_hidden_dim is not None and lq_hidden_dim != _SUPPORTED_LQ_HIDDEN_DIM:
- raise NotAMatchError(
- 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)."
- )
-
- # Whether the caller explicitly pinned a base (e.g. a starter-model install passes base=sd-3).
- # In the ambiguous 16-channel FLUX.1/SD3 case this override is trusted when the filename is silent.
- had_base_override = override_fields.get("base") is not None
- cls._validate_base(mod, state_dict, had_base_override=had_base_override)
-
- variant = override_fields.pop("variant", None) or _variant_from_filename(_name_for_matching(mod))
- return cls(**override_fields, variant=variant)
+ # Imported lazily: it pulls in the vendored PiD network stack, which model identification has
+ # 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
+ # *every* PiD config class would reject for the same reason, which is exactly the case the plain
+ # no-match signal cannot carry — no class matches, and the factory registers the file through its
+ # `Unknown_Config` fallback. See `_raise_if_no_backbone_can_accept`.
+ #
+ # 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.
+ 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)
+
+ # 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)
+
+ cls._validate_base(
+ latent_channels=latent_channels,
+ named_base=_backbone_from_components(components),
+ had_base_override=override_fields.get("base") is not None,
+ )
+
+ base: BaseModelType = cls.model_fields["base"].default
+ # 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)
+ return cls(**{k: v for k, v in override_fields.items() if k != "variant"}, variant=variant)
@classmethod
def _validate_base(
- cls, mod: ModelOnDisk, state_dict: dict[str | int, Any], *, had_base_override: bool = False
+ cls,
+ *,
+ latent_channels: int,
+ named_base: BaseModelType | None,
+ had_base_override: bool,
) -> None:
"""Confirm this checkpoint belongs to the config's pinned backbone.
- The latent channel count (read from the weights) is authoritative and
- separates FLUX.2 (128ch) from the 16ch family. FLUX.1 and SD3 share an
- identical architecture, so within the 16ch family we fall back to the
- filename / directory name, defaulting to FLUX.1 when it is silent.
+ Every rejection here is a `NotAMatchError` and only ever means "not *this* backbone", which
+ four of the five classes are supposed to say about every valid checkpoint. The reasons that
+ 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:
- ``had_base_override`` is True when the caller explicitly pinned ``base``
- (e.g. a starter-model install). In the ambiguous 16ch case, a trusted
- override wins over the FLUX.1 default — necessary because the HF
- single-file download renames the parent directory, dropping the
- ``…official_sd3_distill…`` hint that would otherwise identify SD3.
+ - 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, the family defaults to FLUX.1.
"""
expected_base = cls.model_fields["base"].default
- channels = _latent_channels_from_state_dict(state_dict)
-
- if channels is not None:
- candidate_bases = _LATENT_CHANNELS_TO_BASES.get(channels)
- if candidate_bases is None:
- raise NotAMatchError(
- 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)"
- )
- if expected_base not in candidate_bases:
- raise NotAMatchError(f"latent channels={channels} do not match backbone {expected_base}")
- if len(candidate_bases) > 1:
- # Ambiguous 16ch family — disambiguate FLUX.1 vs SD3 by name.
- named_base = _backbone_from_filename(_name_for_matching(mod))
- if named_base in candidate_bases:
- if named_base is not expected_base:
- raise NotAMatchError(f"name indicates {named_base}, not {expected_base}")
- elif had_base_override:
- # Name is silent, but the caller explicitly pinned this base → trust it.
- return
- elif expected_base is not BaseModelType.Flux:
- # Name gives no usable hint and no override → default the family to FLUX.1.
- raise NotAMatchError("ambiguous 16-channel PiD checkpoint; defaulting to FLUX.1")
+ # Guaranteed present: an unsupported channel count was rejected outright before this ran.
+ candidate_bases = _LATENT_CHANNELS_TO_BASES[latent_channels]
+
+ if expected_base not in candidate_bases:
+ raise NotAMatchError(f"latent channels={latent_channels} do not match backbone {expected_base}")
+ if len(candidate_bases) == 1 or had_base_override:
return
- # No diagnostic weight (unexpected) → fall back to filename-only matching.
- inferred_base = _backbone_from_filename(_name_for_matching(mod))
- if inferred_base is None:
- raise NotAMatchError(
- "cannot determine PiD decoder backbone from weights or filename "
- "(expected one of: flux, flux2, sd3, sdxl, qwen-image)"
- )
- if inferred_base is not expected_base:
- raise NotAMatchError(f"backbone is {inferred_base}, not {expected_base}")
+ # A name pointing outside the family — a 16-channel file called "sdxl" — contradicts the
+ # weights and is discarded rather than obeyed. Obeying it would have all three 16ch classes
+ # reject the file, leaving a perfectly good decoder to the `Unknown_Config` fallback.
+ if named_base not in candidate_bases:
+ named_base = None
+
+ if named_base is None:
+ if expected_base is not BaseModelType.Flux:
+ raise NotAMatchError("ambiguous 16-channel PiD checkpoint; defaulting to FLUX.1")
+ return
+ if named_base is not expected_base:
+ raise NotAMatchError(f"name indicates {named_base}, not {expected_base}")
class PiDDecoder_Checkpoint_FLUX_Config(PiDDecoder_Checkpoint_Config_Base, Config_Base):
diff --git a/invokeai/backend/model_manager/load/model_loaders/pid_decoder.py b/invokeai/backend/model_manager/load/model_loaders/pid_decoder.py
index 0a91c27ee4..ffffcf7858 100644
--- a/invokeai/backend/model_manager/load/model_loaders/pid_decoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/pid_decoder.py
@@ -19,12 +19,7 @@ from invokeai.backend.model_manager.load.load_default import ModelLoader
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.pid.decode import load_pid_decoder
-
-# NVIDIA's official PiD `.pth` checkpoints store the student under the `net.`
-# prefix (see `PidDistillModel.state_dict(prefix="net.")` in the vendored
-# upstream). We strip it on load so PidNet.load_state_dict() can consume the
-# dict directly.
-_NET_PREFIX = "net."
+from invokeai.backend.pid.state_dict_utils import strip_net_prefix
def _load_raw_checkpoint(path: Path) -> dict[str, torch.Tensor]:
@@ -41,22 +36,6 @@ def _load_raw_checkpoint(path: Path) -> dict[str, torch.Tensor]:
raise ValueError(f"Unrecognised PiD decoder checkpoint extension: {suffix!r}")
-def _strip_net_prefix(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
- if not any(k.startswith(_NET_PREFIX) for k in state_dict if isinstance(k, str)):
- return state_dict
- out: dict[str, torch.Tensor] = {}
- for k, v in state_dict.items():
- if isinstance(k, str) and k.startswith(_NET_PREFIX):
- out[k[len(_NET_PREFIX) :]] = v
- elif isinstance(k, str) and (
- k.startswith("net_ema.") or k.startswith("fake_score.") or k.startswith("discriminator.")
- ):
- continue
- else:
- out[k] = v
- return out
-
-
@ModelLoaderRegistry.register(base=BaseModelType.Flux, type=ModelType.PiDDecoder, format=ModelFormat.Checkpoint)
@ModelLoaderRegistry.register(base=BaseModelType.Flux2, type=ModelType.PiDDecoder, format=ModelFormat.Checkpoint)
@ModelLoaderRegistry.register(
@@ -81,7 +60,7 @@ class PiDDecoderLoader(ModelLoader):
# PiDDecoder_Checkpoint_*_Config when the user added the model.
backbone: BaseModelType = config.base
- raw_sd = _strip_net_prefix(_load_raw_checkpoint(Path(config.path)))
+ raw_sd = strip_net_prefix(_load_raw_checkpoint(Path(config.path)))
# Build the live PidNet on CPU and pour the checkpoint in — then drop
# the dict so we don't hold two copies in RAM at once.
diff --git a/invokeai/backend/pid/decode.py b/invokeai/backend/pid/decode.py
index 172445bbd0..4a9f4abe56 100644
--- a/invokeai/backend/pid/decode.py
+++ b/invokeai/backend/pid/decode.py
@@ -18,9 +18,12 @@ repository for the source of truth.
from __future__ import annotations
+from collections.abc import Mapping
from contextlib import nullcontext
from dataclasses import dataclass, field
-from typing import Optional
+from functools import lru_cache
+from types import MappingProxyType
+from typing import Any, Optional
import torch
from torch import Tensor
@@ -206,7 +209,44 @@ def build_pid_net(backbone: BaseModelType) -> PidNet:
return PidNet(**kwargs)
-def load_pid_decoder(state_dict: dict[str, Tensor], backbone: BaseModelType) -> PidNet:
+# 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_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.
+_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.
+
+ 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
+ loader accepts rather than a superset it will later refuse. Checking a subset is not a milder
+ version of the same thing: loaders run under `skip_torch_weight_init()`, so a weight the
+ checkpoint does not supply is uninitialised memory rather than a default.
+
+ Derived from the vendored network itself instead of a hand-written list, and built on the meta
+ device inside a forked RNG state. Meta construction allocates nothing (~0.3 MB, ~250 ms once per
+ process, cached); the fork is the belt to those braces, since it holds regardless of what the
+ vendored constructors do. Identification must not advance the global RNG — an install would
+ 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.
+ """
+ with torch.random.fork_rng(devices=[]), torch.device("meta"):
+ net = build_pid_net(backbone)
+ return MappingProxyType({k: tuple(v.shape) for k, v in net.state_dict().items()})
+
+
+def load_pid_decoder(state_dict: dict[Any, Tensor], backbone: BaseModelType) -> PidNet:
"""Instantiate a PidNet for *backbone* and populate it with *state_dict*.
The state dict is expected to be the model-manager loader's output, i.e.
@@ -215,9 +255,23 @@ def load_pid_decoder(state_dict: dict[str, Tensor], backbone: BaseModelType) ->
returned net.
"""
net = build_pid_net(backbone)
- # strict=False keeps parity with the upstream loader: missing LQ-projection
- # keys are tolerated when reloading PixDiT_T2I weights into PidNet, and
- # extra keys (e.g. legacy EMA artefacts) are dropped.
+
+ # 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
+ # `.startswith()` on every key, so a non-string one raises AttributeError from inside torch
+ # before any of the reporting below runs. Reject it here instead, so a malformed checkpoint gets
+ # the same kind of message as every other unusable one.
+ if not_strings := sorted((k for k in state_dict if not isinstance(k, str)), key=str):
+ raise RuntimeError(
+ f"PiD checkpoint has {len(not_strings)} keys that are not strings and so cannot name a "
+ f"PidNet parameter: {not_strings[:5]}"
+ + (f" (+ {len(not_strings) - 5} more)" if len(not_strings) > 5 else "")
+ )
+
+ # strict=False so we can report missing and unexpected keys separately; both are fatal. The model
+ # cache builds loaders under `skip_torch_weight_init()`, which no-ops every `reset_parameters()`,
+ # so a key the checkpoint does not supply is left as uninitialised memory rather than a sane
+ # default — a partial checkpoint would decode to garbage / NaNs instead of failing.
missing, unexpected = net.load_state_dict(state_dict, strict=False)
if unexpected:
raise RuntimeError(
@@ -225,15 +279,17 @@ def load_pid_decoder(state_dict: dict[str, Tensor], backbone: BaseModelType) ->
+ (f" (+ {len(unexpected) - 5} more)" if len(unexpected) > 5 else "")
)
if missing:
- # We tolerate missing `lq_proj.*` (e.g. if the user accidentally
- # passed a vanilla PixDiT_T2I checkpoint), but anything else points
- # to a real architecture mismatch.
- non_lq = [k for k in missing if "lq_proj" not in k]
- if non_lq:
- raise RuntimeError(
- f"PiD checkpoint is missing non-LQ keys required by PidNet: {non_lq[:5]}"
- + (f" (+ {len(non_lq) - 5} more)" if len(non_lq) > 5 else "")
- )
+ lq = [k for k in missing if k.startswith("lq_proj.")]
+ detail = (
+ " (the LQ projection is incomplete — this looks like a base PixDiT_T2I checkpoint rather than a "
+ "PiD super-resolution decoder)"
+ if lq and len(lq) == len(missing)
+ else ""
+ )
+ raise RuntimeError(
+ f"PiD checkpoint is missing {len(missing)} keys required by PidNet{detail}: {missing[:5]}"
+ + (f" (+ {len(missing) - 5} more)" if len(missing) > 5 else "")
+ )
return net
@@ -593,6 +649,7 @@ def assert_pid_decoder_matches_base(decoder_base: BaseModelType, node_base: Base
__all__ = [
+ "BACKBONE_DISCRIMINATOR_KEY",
"PID_CHI_PROMPT",
"PID_MODEL_MAX_LENGTH",
"PID_NEGATIVE_PROMPT",
@@ -602,4 +659,5 @@ __all__ = [
"build_pid_net",
"encode_caption_for_pid",
"load_pid_decoder",
+ "required_pid_net_shapes",
]
diff --git a/invokeai/backend/pid/state_dict_utils.py b/invokeai/backend/pid/state_dict_utils.py
new file mode 100644
index 0000000000..503ef8be51
--- /dev/null
+++ b/invokeai/backend/pid/state_dict_utils.py
@@ -0,0 +1,86 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The key-space normalisation shared by PiD identification and PiD loading.
+
+NVIDIA's official `.pth` checkpoints serialise `PidDistillModel`, which keeps the student network
+under a `net.` prefix and carries the other distill submodules (the EMA copy, the fake-score net,
+the discriminator) alongside it. Two consumers have to reduce a checkpoint to the same key space:
+
+- `model_manager/configs/pid_decoder.py`, to decide whether a file is a usable PiD decoder;
+- `model_manager/load/model_loaders/pid_decoder.py`, which feeds `PidNet.load_state_dict`.
+
+They used to carry a copy each, and the copies had already diverged (only the loader dropped the
+distill-only submodules). The failure mode of that drift is silent in the direction that matters:
+identification accepting a file the loader then refuses. Hence one implementation, here.
+
+Deliberately dependency-free — the config imports it during model identification, where pulling in
+the vendored PiD network stack would be wasted work.
+"""
+
+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."
+
+# 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.")
+
+T = TypeVar("T")
+
+
+def _normalized_key(key: Any) -> str | None:
+ """The key as `PidNet` sees it, or None if it belongs to a distill-only submodule."""
+ if not isinstance(key, str):
+ return None
+ if key.startswith(NET_PREFIX):
+ return key[len(NET_PREFIX) :]
+ if key.startswith(_DISTILL_ONLY_PREFIXES):
+ return None
+ return key
+
+
+def has_net_prefix(state_dict: dict[Any, Any]) -> bool:
+ """Whether this checkpoint is a `PidDistillModel` serialisation rather than a bare `PidNet`."""
+ return any(isinstance(k, str) and k.startswith(NET_PREFIX) for k in state_dict)
+
+
+def strip_net_prefix(state_dict: dict[Any, T]) -> dict[Any, T]:
+ """Reduce a checkpoint to `PidNet`'s own key space.
+
+ A checkpoint with no `net.` prefix is already in that space and is returned untouched — the
+ distill-only filter is not applied there, because without the prefix there is no evidence this
+ is a distill serialisation, and a stray `discriminator.*` key should reach the unexpected-key
+ checks (identification's and the loader's) rather than be silently dropped.
+
+ That pass-through is why the result is not `dict[str, T]`. A `.pth` unpickles to whatever it
+ contains, so a bare checkpoint can hand back keys that are not strings, and they are kept on
+ purpose: dropping them would hide a malformed file from the checks that exist to catch it.
+
+ Both consumers therefore have to cope with a key type they cannot assume. `nn.Module.load_state_dict`
+ calls `.startswith()` on every key and raises `AttributeError` on a non-string one, so
+ `load_pid_decoder` rejects those before it hands anything to torch; and sorting a mixed key set
+ raises `TypeError`, so identification sorts its key reports with ``key=str``.
+ """
+ if not has_net_prefix(state_dict):
+ return state_dict
+ return {nk: v for k, v in state_dict.items() if (nk := _normalized_key(k)) is not None}
+
+
+def pid_net_shapes(state_dict: dict[Any, Any]) -> dict[Any, tuple[int, ...] | None]:
+ """The checkpoint's keys as `PidNet` will see them, each mapped to its tensor's shape.
+
+ Mirrors :func:`strip_net_prefix` exactly, including its key type: a bare checkpoint's keys are
+ passed through as they are and need not all be strings. The value is None for anything carrying
+ no ``.shape``: a checkpoint is free to hold arbitrary objects, and one sitting under a PidNet
+ parameter name is malformed rather than grounds for an AttributeError mid-identification.
+
+ Identification works from this rather than from the raw dict so that a weight is found by *name*
+ and not by suffix. Suffix-matching the raw dict reads `net_ema.lq_proj.latent_proj.0.weight` as
+ the backbone discriminator when a checkpoint carries only the EMA copy — the very submodule
+ :func:`strip_net_prefix` exists to drop.
+ """
+ return {
+ k: (tuple(shape) if (shape := getattr(v, "shape", None)) is not None else None)
+ for k, v in strip_net_prefix(state_dict).items()
+ }
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 8e546f2131..48cfb63489 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -34018,7 +34018,7 @@
"cpu_only"
],
"title": "Gemma2Encoder_GGUF_Config",
- "description": "Single-file GGUF-quantized Gemma-2-2b encoder for PiD (llama.cpp GGUF, e.g. gemma-2-2b-it-Q4_K_M.gguf).\n\nUnlike the diffusers-directory config, this is a single ``.gguf`` file. transformers dequantizes it\n(``gemma2`` is in its GGUF config mapping) and reads the tokenizer from the GGUF metadata, so no\ncompanion config.json / tokenizer files are required. Only Gemma-2-2b (2304-dim) is accepted, matching\nPiD's fixed caption projection; 9B/27B GGUFs are rejected here as for the directory config."
+ "description": "Single-file GGUF-quantized Gemma-2-2b encoder for PiD (llama.cpp GGUF, e.g. gemma-2-2b-it-Q4_K_M.gguf).\n\nUnlike the diffusers-directory config, this is a single ``.gguf`` file: the model config and the\ntokenizer are read from the GGUF metadata, so no companion config.json / tokenizer files are required.\nThe weights are loaded natively by ``Gemma2EncoderGGUFLoader`` \u2014 the large 2D projections stay\nquantized as ``GGMLTensor`` and are dequantized on demand by the model cache, rather than being fully\ndequantized into memory at load time. Only Gemma-2-2b (2304-dim) is accepted, matching PiD's fixed\ncaption projection; 9B/27B GGUFs are rejected here as for the directory config."
},
"Gemma2Encoder_Gemma2Encoder_Config": {
"properties": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 00e43d3b5e..44e470dc49 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -14115,10 +14115,12 @@ export type components = {
* Gemma2Encoder_GGUF_Config
* @description Single-file GGUF-quantized Gemma-2-2b encoder for PiD (llama.cpp GGUF, e.g. gemma-2-2b-it-Q4_K_M.gguf).
*
- * Unlike the diffusers-directory config, this is a single ``.gguf`` file. transformers dequantizes it
- * (``gemma2`` is in its GGUF config mapping) and reads the tokenizer from the GGUF metadata, so no
- * companion config.json / tokenizer files are required. Only Gemma-2-2b (2304-dim) is accepted, matching
- * PiD's fixed caption projection; 9B/27B GGUFs are rejected here as for the directory config.
+ * Unlike the diffusers-directory config, this is a single ``.gguf`` file: the model config and the
+ * tokenizer are read from the GGUF metadata, so no companion config.json / tokenizer files are required.
+ * The weights are loaded natively by ``Gemma2EncoderGGUFLoader`` — the large 2D projections stay
+ * quantized as ``GGMLTensor`` and are dequantized on demand by the model cache, rather than being fully
+ * dequantized into memory at load time. Only Gemma-2-2b (2304-dim) is accepted, matching PiD's fixed
+ * caption projection; 9B/27B GGUFs are rejected here as for the directory config.
*/
Gemma2Encoder_GGUF_Config: {
/**
diff --git a/tests/app/services/model_install/test_orphan_scan.py b/tests/app/services/model_install/test_orphan_scan.py
new file mode 100644
index 0000000000..6525a741dc
--- /dev/null
+++ b/tests/app/services/model_install/test_orphan_scan.py
@@ -0,0 +1,57 @@
+"""The startup orphan scan must survive a model file it cannot register.
+
+`_register_orphaned_models` runs inside `ModelInstallService.start()`, which stores and re-raises
+anything that escapes it. Identification can now reject a file outright — a checkpoint recognised as
+a PiD decoder and found unusable, or anything at all when `allow_unknown_models` is off — where it
+previously always produced at worst an `Unknown_Config` record.
+
+Two layers keep that from ending the boot: `ModelSearch._walk_directory` wraps every
+`on_model_found` call, and the callback itself catches `InvalidModelConfigException`. This pins the
+outcome rather than either mechanism, so removing one without the other is caught here: startup
+completes, and the unusable file is not registered.
+"""
+
+from pathlib import Path
+
+import torch
+from requests.sessions import Session
+
+from invokeai.app.services.config import InvokeAIAppConfig
+from invokeai.app.services.download import DownloadQueueServiceBase
+from invokeai.app.services.model_install import ModelInstallService
+from invokeai.app.services.model_records import ModelRecordServiceSQL
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.backend.model_manager.model_manager_fixtures import * # noqa F403
+from tests.fixtures.sqlite_database import create_mock_sqlite_database
+from tests.test_nodes import TestEventService
+
+# A single `lq_proj.*` weight: enough for identification to recognise a PiD decoder, far too little
+# for one to be built from. `.pth` is the format NVIDIA ships.
+_ORPHAN_RELATIVE_PATH = "pid/model_ema_bf16.pth"
+
+
+def test_startup_scan_skips_a_checkpoint_it_cannot_register(
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue: DownloadQueueServiceBase,
+ mm2_session: Session,
+) -> None:
+ orphan = mm2_app_config.models_path / _ORPHAN_RELATIVE_PATH
+ orphan.parent.mkdir(parents=True, exist_ok=True)
+ torch.save({"net.lq_proj.latent_proj.1.weight": torch.zeros(1)}, orphan)
+ mm2_app_config.scan_models_on_startup = True
+
+ logger = InvokeAILogger.get_logger()
+ installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=ModelRecordServiceSQL(create_mock_sqlite_database(mm2_app_config, logger), logger),
+ download_queue=mm2_download_queue,
+ event_bus=TestEventService(),
+ session=mm2_session,
+ )
+
+ try:
+ installer.start()
+ assert installer._startup_error is None
+ assert _ORPHAN_RELATIVE_PATH not in {Path(m.path).as_posix() for m in installer.record_store.all_models()}
+ finally:
+ installer.stop()
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 43b2a7830c..62d1045aab 100644
--- a/tests/backend/model_manager/configs/test_pid_decoder_config.py
+++ b/tests/backend/model_manager/configs/test_pid_decoder_config.py
@@ -1,22 +1,43 @@
"""Regression tests for PiD decoder checkpoint identification.
-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. The config
-must reject such a checkpoint at identification time instead of accepting it and crashing with a size
-mismatch deep inside the decode.
+Covers what identification has to get right before a checkpoint reaches the decode:
+
+- The contract: identification holds a file to exactly the key set and shapes `load_pid_decoder`
+ 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.
+- 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.
+
+Anything rejected for a backbone-independent reason must be rejected *outright* (`InvalidMatchError`)
+rather than fall through to the factory's `Unknown_Config` fallback — see
+`TestUnusableCheckpointIsNeverRegistered`.
"""
from pathlib import Path
from tempfile import TemporaryDirectory
+from typing import Any
from unittest.mock import MagicMock
import pytest
+import torch
-from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError
+from invokeai.backend.model_manager.configs.factory import ModelConfigFactory
+from invokeai.backend.model_manager.configs.identification_utils import InvalidMatchError, NotAMatchError
from invokeai.backend.model_manager.configs.pid_decoder import (
+ _LATENT_PROJ_KEY,
+ PiDDecoder_Checkpoint_Flux2_Config,
PiDDecoder_Checkpoint_FLUX_Config,
- _lq_hidden_dim_from_state_dict,
+ PiDDecoder_Checkpoint_QwenImage_Config,
+ PiDDecoder_Checkpoint_SD3_Config,
+ PiDDecoder_Checkpoint_SDXL_Config,
)
+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
_OVERRIDE_FIELDS: dict[str, object] = {
"hash": "blake3:fakehash",
@@ -30,26 +51,47 @@ _OVERRIDE_FIELDS: dict[str, object] = {
"base": "flux",
}
+# What the model manager records for a single-file install from Hugging Face: the source still
+# carries NVIDIA's directory name, and is trusted evidence because it is not a local filesystem path.
+_HF_SOURCE_TYPE: dict[str, object] = {"source_type": "hf_repo_id"}
+
class _FakeShapeTensor:
def __init__(self, *shape: int) -> None:
self.shape = shape
-def _pid_state_dict(lq_hidden_dim: int, latent_channels: int = 16) -> dict[str, object]:
- # A minimal PiD-looking state dict: the lq_proj marker + the diagnostic input Conv whose dim-0 is the
- # lq_hidden_dim and dim-1 is the latent channel count.
- return {"net.lq_proj.latent_proj.0.weight": _FakeShapeTensor(lq_hidden_dim, latent_channels, 3, 3)}
+# NVIDIA's `.pth` files keep PidDistillModel's `net.` prefix; identification has to see through it.
+_NET_PREFIX = "net."
-def test_lq_hidden_dim_read_from_state_dict() -> None:
- assert _lq_hidden_dim_from_state_dict(_pid_state_dict(512)) == 512
- assert _lq_hidden_dim_from_state_dict(_pid_state_dict(1024)) == 1024
- assert _lq_hidden_dim_from_state_dict({}) is None
+def test_the_config_and_the_network_agree_on_the_discriminator_weight() -> None:
+ """`pid_decoder` names the weight it reads the architecture and backbone from; `decode` names the
+ one whose shape varies per backbone. A drift between the two silently unhooks identification."""
+ assert _LATENT_PROJ_KEY == BACKBONE_DISCRIMINATOR_KEY
-def _mock_mod(root: Path, state_dict: dict[str, object]) -> MagicMock:
- path = root / "model_ema_bf16.pth"
+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)
+ return sd
+
+
+def _mock_mod(
+ root: Path,
+ state_dict: dict[str, object],
+ dir_name: str | None = None,
+ file_name: str = "model_ema_bf16.pth",
+) -> MagicMock:
+ """A ModelOnDisk stand-in. `dir_name` mimics NVIDIA's checkpoint directory; omit it for a direct
+ single-file install, where the file lands in a UUID directory that says nothing about the model."""
+ parent = root / dir_name if dir_name else root
+ parent.mkdir(parents=True, exist_ok=True)
+ path = parent / file_name
path.write_bytes(b"x")
mod = MagicMock()
mod.path = path
@@ -57,18 +99,444 @@ def _mock_mod(root: Path, state_dict: dict[str, object]) -> MagicMock:
return mod
+def test_legacy_512_checkpoint_is_accepted() -> None:
+ """A legacy 512-dim FLUX checkpoint (16 latent channels) identifies successfully. The counterweight
+ to everything below: none of the strictness may make a real decoder harder to install."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict())
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+ assert config.type.value == "pid_decoder"
+ 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."""
+ """A 1024-dim (v1.5) checkpoint must be rejected, not accepted and crashed on later.
+
+ 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.
+ """
with TemporaryDirectory() as tmpdir:
- mod = _mock_mod(Path(tmpdir), _pid_state_dict(1024))
- with pytest.raises(NotAMatchError, match="lq_proj hidden dim 1024"):
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(lq_hidden_dim=1024))
+ with pytest.raises(InvalidMatchError, match="lq_proj hidden dim 1024"):
PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
-def test_legacy_512_checkpoint_is_accepted() -> None:
- """A legacy 512-dim FLUX checkpoint (16 latent channels) still identifies successfully."""
+def test_unsupported_latent_channel_count_is_rejected() -> None:
+ """No backbone uses 32 latent channels, so all five configs reject it for the same reason — which
+ is exactly the case a plain no-match cannot carry, since it leaves the file to `Unknown_Config`."""
with TemporaryDirectory() as tmpdir:
- mod = _mock_mod(Path(tmpdir), _pid_state_dict(512, latent_channels=16))
- config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
- assert config.type.value == "pid_decoder"
- assert config.base.value == "flux"
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(latent_channels=32))
+ with pytest.raises(InvalidMatchError, match="32 latent channels"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
+class TestPidNetContract:
+ """Identification accepts exactly what `load_pid_decoder` accepts: the same 456 keys, the same
+ shapes, and no extras.
+
+ Checking only the LQ projection let a file with all 71 LQ weights and none of the 385 backbone
+ weights be registered, to be refused at load time. That 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.
+
+ Every rejection here is `InvalidMatchError`, not `NotAMatchError`: the file has already
+ identified itself as a PiD checkpoint, so it must not fall through to the factory's
+ `Unknown_Config` fallback (see `TestUnusableCheckpointIsNeverRegistered`).
+ """
+
+ @pytest.mark.parametrize(
+ "dropped",
+ [
+ "lq_proj.output_heads.3.weight",
+ "lq_proj.gate_modules.0.log_alpha",
+ "lq_proj.latent_proj.3.block.2.bias",
+ ],
+ )
+ def test_a_missing_lq_weight_is_rejected(self, dropped: str) -> None:
+ sd = _pid_state_dict()
+ del sd[f"{_NET_PREFIX}{dropped}"]
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="missing 1 of the weights required by PidNet"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+ @pytest.mark.parametrize("dropped", ["y_pos_embedding", "s_embedder.proj.weight", "final_layer.linear.weight"])
+ def test_a_missing_backbone_weight_is_rejected(self, dropped: str) -> None:
+ """The gap the LQ-only check left: 385 of the 456 weights were never looked at, so a
+ checkpoint truncated anywhere outside the LQ projection installed cleanly and then failed."""
+ sd = _pid_state_dict()
+ assert f"{_NET_PREFIX}{dropped}" in sd, "fixture drifted from the real contract"
+ del sd[f"{_NET_PREFIX}{dropped}"]
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="missing 1 of the weights required by PidNet"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+ def test_an_unexpected_key_is_rejected(self) -> None:
+ """`load_pid_decoder` refuses these too, so accepting them here would install a file that
+ cannot load."""
+ sd = _pid_state_dict()
+ sd[f"{_NET_PREFIX}not_a_pid_key"] = _FakeShapeTensor(1)
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="1 keys PidNet does not expect"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+ def test_a_wrong_shaped_weight_is_rejected(self) -> None:
+ """Right names, wrong tensors. Loading would fail on a size mismatch deep in the decode."""
+ sd = _pid_state_dict()
+ sd[f"{_NET_PREFIX}final_layer.linear.weight"] = _FakeShapeTensor(3, 3)
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="shape PidNet cannot accept"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+ def test_a_base_pixdit_checkpoint_is_turned_away_before_any_of_this(self) -> None:
+ """The base text-to-image weights the decoder is distilled from carry no `lq_proj` key at
+ all, so they never reach the contract check — and get a better message than a key count."""
+ sd = {k: v for k, v in _pid_state_dict().items() if "lq_proj" not in k}
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(NotAMatchError, match="does not look like a PiD decoder"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+ def test_marker_key_alone_is_not_enough(self) -> None:
+ """The old behaviour: one `lq_proj.*` key identified a decoder, and the rest were tolerated."""
+ sd = {f"{_NET_PREFIX}{_LATENT_PROJ_KEY}": _FakeShapeTensor(512, 16, 3, 3)}
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="missing 455 of the weights"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+ def test_truncation_is_reported_as_truncation_even_without_the_diagnostic_weight(self) -> None:
+ """The architecture and the backbone are both read from `lq_proj.latent_proj.0.weight`, so a
+ file truncated past *that* weight used to fail with "cannot determine backbone" — accurate,
+ but not the reason, and not the message the install flow promises for a truncated checkpoint.
+ Those reads are skipped when the weight is absent rather than made to guess at it."""
+ sd = {f"{_NET_PREFIX}lq_proj.latent_proj.1.weight": _FakeShapeTensor(1)}
+ fields = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"}
+ with TemporaryDirectory() as tmpdir:
+ # No directory name and no base override: nothing but the weights identifies this file.
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="missing 456 of the weights"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(fields))
+
+ def test_a_rank_1_latent_projection_is_rejected(self) -> None:
+ """Identification reads the architecture, the backbone and the kernel off this one weight.
+ A tensor of the wrong rank made all three reads abstain at once, and the file fell through to
+ name-only matching — which, given a name that supplied a backbone, accepted it."""
+ sd = _pid_state_dict()
+ sd[f"{_NET_PREFIX}{_LATENT_PROJ_KEY}"] = _FakeShapeTensor(512)
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd, dir_name="PiD_res2k_sr4x_official_flux_distill_4step")
+ with pytest.raises(InvalidMatchError, match="malformed lq_proj.latent_proj.0.weight"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+ def test_distill_only_submodules_do_not_count(self) -> None:
+ """`net_ema.*` shadows PidNet's own parameter names. The loader drops those submodules, so
+ identification has to as well — otherwise a checkpoint carrying only the EMA copy would look
+ complete here and then fail in `load_pid_decoder`."""
+ sd: dict[str, object] = {
+ f"net_ema.{k}": _FakeShapeTensor(*shape) for k, shape in required_pid_net_shapes().items()
+ }
+ sd[f"{_NET_PREFIX}{_LATENT_PROJ_KEY}"] = _FakeShapeTensor(512, 16, 3, 3)
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), sd)
+ with pytest.raises(InvalidMatchError, match="missing 455 of the weights"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+
+
+def _write_pid_checkpoint(root: Path, state_dict: dict[Any, object]) -> Path:
+ """Write a state dict as a real `.pth`, the format NVIDIA ships, so the factory reaches it through
+ the same pickle-scan-and-`torch.load` path a real download would."""
+ path = root / "model_ema_bf16.pth"
+ torch.save(state_dict, path)
+ return path
+
+
+def _real_pid_state_dict(lq_hidden_dim: int = 512, latent_channels: int = 16) -> 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)
+ return sd
+
+
+class TestUnusableCheckpointIsNeverRegistered:
+ """Rejecting an unusable checkpoint in the config class is only half the job.
+
+ Every config class signals "not mine" with `NotAMatchError`, which the factory collects and then,
+ with `allow_unknown_models` (default: true), papers over by returning `Unknown_Config`. A file that
+ identified itself as a PiD decoder and was then found unusable would therefore still be installed —
+ as an unknown model, with a database record, failing only when something tried to load it.
+ `InvalidMatchError` is what makes the rejection stick, and every reason that would rule out *all
+ five* backbone configs has to raise it, not just the truncation case.
+ """
+
+ def _partial(self) -> dict[str, object]:
+ """A single `lq_proj.*` weight: enough to be recognised, far from loadable."""
+ return {f"{_NET_PREFIX}lq_proj.latent_proj.1.weight": torch.zeros(1)}
+
+ def _missing_backbone_weight(self) -> dict[str, object]:
+ """Every LQ weight present, one backbone weight gone — what the LQ-only check let through."""
+ sd = _real_pid_state_dict()
+ del sd[f"{_NET_PREFIX}final_layer.linear.weight"]
+ 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"]
+ return sd
+
+ def _intact_v1_5(self) -> dict[str, object]:
+ return _real_pid_state_dict(lq_hidden_dim=1024)
+
+ def _unsupported_latent_channels(self) -> dict[str, object]:
+ return _real_pid_state_dict(latent_channels=32)
+
+ def _malformed_discriminator(self) -> dict[str, object]:
+ sd = _real_pid_state_dict()
+ sd[f"{_NET_PREFIX}{_LATENT_PROJ_KEY}"] = torch.zeros(512)
+ return sd
+
+ def _bare_with_a_non_string_key(self) -> dict[Any, object]:
+ """A complete *bare* contract plus two keys PidNet does not expect, one of them not a string.
+
+ A bare checkpoint is passed through `strip_net_prefix` untouched, so a `.pth` can hand
+ identification whatever it was pickled with. Reporting the unexpected keys sorts them, and
+ sorting `{1, "not_a_pid_key"}` raises TypeError — which the factory catches as a generic
+ candidate failure and answers with the Unknown_Config registration this class is about. A
+ crash in an unusability check therefore does not fail loudly; it fails as a silent accept.
+ """
+ scalar = torch.zeros(())
+ sd: dict[Any, object] = {k: scalar.expand(shape) for k, shape in required_pid_net_shapes().items()}
+ sd[1] = torch.zeros(1)
+ sd["not_a_pid_key"] = torch.zeros(1)
+ return sd
+
+ @pytest.mark.parametrize(
+ ("case", "expected_reason"),
+ [
+ ("_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"),
+ ("_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"),
+ ],
+ )
+ def test_factory_returns_no_config_even_with_allow_unknown(self, case: str, expected_reason: str) -> None:
+ with TemporaryDirectory() as tmpdir:
+ path = _write_pid_checkpoint(Path(tmpdir), getattr(self, case)())
+ result = ModelConfigFactory.from_model_on_disk(path, allow_unknown=True)
+
+ assert result.config is None, "a recognised-but-unusable checkpoint must not be registered"
+ assert not any(isinstance(r, Unknown_Config) for r in result.details.values())
+ # The reason survives for `_probe` to report, so the user is told what is actually wrong
+ # instead of the misleading "could not identify model".
+ 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."""
+ with TemporaryDirectory() as tmpdir:
+ path = _write_pid_checkpoint(Path(tmpdir), _real_pid_state_dict())
+ result = ModelConfigFactory.from_model_on_disk(path, allow_unknown=True)
+
+ assert result.config is not None
+ assert not result.invalid_matches
+ assert result.config.base is BaseModelType.Flux
+
+
+class TestBackboneFromInstallSource:
+ """FLUX.1, SD3 and Qwen-Image PiD decoders are architecturally identical (16 latent channels), so the
+ backbone can only come from the name. A direct single-file install has none — but its source does."""
+
+ _SD3_SOURCE = "nvidia/PiD::checkpoints/PiD_res2k_sr4x_official_sd3_distill_4step/model_ema_bf16.pth"
+ # A neutral stand-in for the UUID directory a direct install lands in, so a fluke match in the
+ # TemporaryDirectory name cannot shadow the source.
+ _UUID_DIR = "checkpoints"
+
+ def test_source_identifies_sd3_without_a_base_override(self) -> None:
+ """Without this, a directly installed SD3 decoder is recorded as FLUX and then rejected by the
+ SD3 decode node."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name=self._UUID_DIR)
+ overrides = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"} | {
+ "source": self._SD3_SOURCE,
+ **_HF_SOURCE_TYPE,
+ }
+ config = PiDDecoder_Checkpoint_SD3_Config.from_model_on_disk(mod, dict(overrides))
+ assert config.base is BaseModelType.StableDiffusion3
+
+ def test_flux_config_rejects_a_checkpoint_the_source_names_as_sd3(self) -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name=self._UUID_DIR)
+ overrides = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"} | {
+ "source": self._SD3_SOURCE,
+ **_HF_SOURCE_TYPE,
+ }
+ with pytest.raises(NotAMatchError, match="name indicates"):
+ PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(overrides))
+
+ def test_qwen_image_source_is_recognised(self) -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name=self._UUID_DIR)
+ overrides = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"} | {
+ "source": "nvidia/PiD::checkpoints_deprecated/PiD_res2kto4k_sr4x_official_qwenimage_distill_4step/model_ema_bf16.pth",
+ **_HF_SOURCE_TYPE,
+ }
+ config = PiDDecoder_Checkpoint_QwenImage_Config.from_model_on_disk(mod, dict(overrides))
+ assert config.base is BaseModelType.QwenImage
+
+ def test_base_override_still_wins_when_nothing_names_the_backbone(self) -> None:
+ """The starter installer's explicit base remains the fallback for a fully anonymous file."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict())
+ config = PiDDecoder_Checkpoint_SD3_Config.from_model_on_disk(
+ mod, dict(_OVERRIDE_FIELDS, base="sd-3", source="local file")
+ )
+ assert config.base is BaseModelType.StableDiffusion3
+
+ def test_base_override_beats_a_name_that_says_otherwise(self) -> None:
+ """A filename is something anyone can write; an explicit base has already been validated
+ against this class's Literal, so it names exactly one of the five and is trusted first."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name="PiD_res2k_sr4x_official_flux_distill_4step")
+ config = PiDDecoder_Checkpoint_SD3_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS, base="sd-3"))
+ assert config.base is BaseModelType.StableDiffusion3
+
+
+class TestNameEvidence:
+ """The name only ever breaks the 16-channel FLUX.1 / SD3 / Qwen-Image tie — the weights decide
+ everything else. These pin how the name is read when it is consulted."""
+
+ def test_the_filename_beats_the_parent_directory(self) -> None:
+ """The reported case. Concatenating every name component into one string and substring-matching
+ it let a fixed backbone precedence decide what the name had already answered: `/flux/model_sd3.pth`
+ matched `flux` first and was registered as FLUX although the file itself says sd3."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name="flux", file_name="model_sd3.pth")
+ fields = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"}
+ config = PiDDecoder_Checkpoint_SD3_Config.from_model_on_disk(mod, dict(fields))
+ assert config.base is BaseModelType.StableDiffusion3
+
+ def test_one_component_naming_two_backbones_decides_nothing(self) -> None:
+ """Two different backbones in one name is not a precedence question — it is a name that
+ decides nothing, and the 16ch family falls back to its FLUX.1 default."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), file_name="pid_sd3_and_flux.pth")
+ fields = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"}
+ with pytest.raises(NotAMatchError, match="ambiguous 16-channel"):
+ PiDDecoder_Checkpoint_SD3_Config.from_model_on_disk(mod, dict(fields))
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(fields))
+ assert config.base is BaseModelType.Flux
+
+ def test_flux2_is_a_spelling_of_flux2_not_an_ambiguity(self) -> None:
+ """`flux2` contains `flux`; consuming the specific spelling first keeps that a precedence
+ question between two spellings of one answer rather than a two-backbone tie."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), file_name="pid_flux2_sr4x.pth")
+ fields = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"}
+ with pytest.raises(NotAMatchError, match="latent channels=16 do not match"):
+ PiDDecoder_Checkpoint_Flux2_Config.from_model_on_disk(mod, dict(fields))
+ # 16 channels rule FLUX.2 out on the weights; the name still must not make this FLUX.1.
+ with pytest.raises(NotAMatchError, match="ambiguous 16-channel"):
+ PiDDecoder_Checkpoint_SD3_Config.from_model_on_disk(mod, dict(fields))
+
+ def test_a_local_path_source_is_not_name_evidence(self) -> None:
+ """The model manager sets `source` to the file's own path when there is no remote one, so
+ trusting it would mean matching against arbitrary ancestor directories of the user's model
+ library. Nothing is lost: a local install is identified before it is moved."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict())
+ fields = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"} | {
+ "source": "D:/sd3-models/pid/model_ema_bf16.pth",
+ "source_type": "path",
+ }
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(fields))
+ assert config.base is BaseModelType.Flux
+
+ def test_a_name_pointing_outside_the_family_is_discarded_not_obeyed(self) -> None:
+ """A 16-channel file called `sdxl` contradicts its own weights. Obeying the name would have
+ all three 16ch classes reject it, leaving a perfectly good decoder to `Unknown_Config`."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), file_name="pid_sdxl_sr4x.pth")
+ fields = {k: v for k, v in _OVERRIDE_FIELDS.items() if k != "base"}
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(fields))
+ assert config.base is BaseModelType.Flux
+
+
+class TestVariantIdentification:
+ """The variant is read from NVIDIA's directory name where there is one, and falls back to the
+ backbone's only published preset otherwise (SDXL and Qwen-Image ship 2K-to-4K only)."""
+
+ def test_directory_name_wins(self) -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name="PiD_res2kto4k_sr4x_official_flux_distill_4step")
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+ assert config.variant is PiDDecoderVariantType.Res2kTo4k_Sr4x
+
+ def test_install_source_is_used_when_the_stored_name_is_silent(self) -> None:
+ """A direct single-file install lands in a UUID directory, but the HF source still names the preset."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name="checkpoints")
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(
+ mod,
+ dict(
+ _OVERRIDE_FIELDS,
+ source="nvidia/PiD::checkpoints_deprecated/PiD_res2kto4k_sr4x_official_flux_distill_4step/model_ema_bf16.pth",
+ **_HF_SOURCE_TYPE,
+ ),
+ )
+ assert config.variant is PiDDecoderVariantType.Res2kTo4k_Sr4x
+
+ def test_a_local_path_source_does_not_name_the_preset(self) -> None:
+ """Same reasoning as for the backbone: `source` is the file's own path for a local install,
+ so an ancestor directory must not decide the record's resolution preset."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict())
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(
+ mod, dict(_OVERRIDE_FIELDS, source="E:/res2kto4k-models/pid/model_ema_bf16.pth", source_type="path")
+ )
+ assert config.variant is PiDDecoderVariantType.Res2k_Sr4x
+
+ def test_flux_defaults_to_2k_when_the_name_is_silent(self) -> None:
+ """FLUX.1 ships both presets, so a nameless single-file install keeps the 2K default."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict())
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))
+ assert config.variant is PiDDecoderVariantType.Res2k_Sr4x
+
+ def test_sdxl_single_file_install_gets_the_only_published_preset(self) -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(latent_channels=4))
+ config = PiDDecoder_Checkpoint_SDXL_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS, base="sdxl"))
+ assert config.variant is PiDDecoderVariantType.Res2kTo4k_Sr4x
+
+ def test_qwen_image_single_file_install_gets_the_only_published_preset(self) -> None:
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict())
+ config = PiDDecoder_Checkpoint_QwenImage_Config.from_model_on_disk(
+ mod, dict(_OVERRIDE_FIELDS, base="qwen-image")
+ )
+ assert config.variant is PiDDecoderVariantType.Res2kTo4k_Sr4x
+
+ def test_explicit_variant_override_wins(self) -> None:
+ """A starter-model install passes the variant it knows it is downloading."""
+ with TemporaryDirectory() as tmpdir:
+ mod = _mock_mod(Path(tmpdir), _pid_state_dict(), dir_name="PiD_res2kto4k_sr4x_official_flux_distill_4step")
+ config = PiDDecoder_Checkpoint_FLUX_Config.from_model_on_disk(
+ mod, dict(_OVERRIDE_FIELDS, variant=PiDDecoderVariantType.Res2k_Sr4x)
+ )
+ assert config.variant is PiDDecoderVariantType.Res2k_Sr4x
diff --git a/tests/backend/model_manager/load/test_gemma2_encoder_gguf_loader.py b/tests/backend/model_manager/load/test_gemma2_encoder_gguf_loader.py
index aa514d4bf0..21b5ace139 100644
--- a/tests/backend/model_manager/load/test_gemma2_encoder_gguf_loader.py
+++ b/tests/backend/model_manager/load/test_gemma2_encoder_gguf_loader.py
@@ -3,19 +3,34 @@
The loader keeps the large 2D projection weights quantized (as GGMLTensor, dequantized on demand by the
model cache) and materializes only the embedding and RMSNorm weights, so a GGUF Gemma-2 encoder no longer
costs the same VRAM as the unquantized model.
+
+The load tests run against a synthetic 2-layer Gemma-2 built from mocked GGUF tensors — small enough to
+quantize, load and run a forward pass on in CI, while exercising the real code path: quantized retention,
+the llama.cpp norm (+1) convention, meta-buffer repair and a forward with quantized weights in place.
+Set ``INVOKEAI_TEST_GEMMA2_GGUF`` to a real Gemma-2-2b GGUF to additionally run the end-to-end comparison
+against transformers' own (fully dequantizing) GGUF loader.
"""
+import importlib
+import os
from pathlib import Path
+from typing import Any
+import accelerate
+import gguf
+import numpy as np
import pytest
+import torch
+import invokeai.backend.quantization.gguf.loaders
from invokeai.backend.model_manager.load.model_loaders.gemma2_encoder import (
_convert_gemma_llamacpp_to_pytorch,
load_gemma2_model_from_gguf,
)
+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
-# A local Gemma-2-2b Q4_K_M GGUF for the (skipped-in-CI) end-to-end load/compare test.
-_LOCAL_GGUF = Path("E:/ModelStuffSSD/gemma-2-2b-it-q4_k_m.gguf")
+# A real Gemma-2-2b GGUF for the opt-in end-to-end load/compare test.
+_LOCAL_GGUF_ENV_VAR = "INVOKEAI_TEST_GEMMA2_GGUF"
def test_convert_maps_every_gemma_component() -> None:
@@ -57,14 +72,193 @@ def test_convert_rejects_unmapped_keys(bad_key: str) -> None:
_convert_gemma_llamacpp_to_pytorch({bad_key: 1})
[email protected](not _LOCAL_GGUF.exists(), reason="requires a local Gemma-2-2b GGUF file")
+# --------------------------------------------------------------------------------------------------
+# Synthetic GGUF fixture
+# --------------------------------------------------------------------------------------------------
+
+# A Gemma-2 shaped small enough to quantize and run in CI. Every dimension that ends up as a tensor's
+# last axis is a multiple of Q8_0's 32-element block size.
+_VOCAB = 96
+_HIDDEN = 64
+_INTERMEDIATE = 128
+_HEADS = 4
+_KV_HEADS = 2
+_HEAD_DIM = 16
+_LAYERS = 2
+
+_TINY_GEMMA_CONFIG: dict[str, Any] = {
+ "model_type": "gemma2",
+ "vocab_size": _VOCAB,
+ "hidden_size": _HIDDEN,
+ "intermediate_size": _INTERMEDIATE,
+ "num_hidden_layers": _LAYERS,
+ "num_attention_heads": _HEADS,
+ "num_key_value_heads": _KV_HEADS,
+ "head_dim": _HEAD_DIM,
+ "max_position_embeddings": 128,
+ "query_pre_attn_scalar": _HEAD_DIM,
+ "sliding_window": 32,
+ "rope_theta": 10000.0,
+}
+
+
+def _q8(*shape: int) -> GGMLTensor:
+ """A Q8_0-quantized GGMLTensor, like the 2D projection weights in a real Gemma-2 GGUF."""
+ rng = np.random.default_rng(seed=sum(shape))
+ data = rng.normal(scale=0.05, size=shape).astype(np.float32)
+ quantized = gguf.quants.quantize(data, gguf.GGMLQuantizationType.Q8_0)
+ return GGMLTensor(torch.from_numpy(quantized), gguf.GGMLQuantizationType.Q8_0, torch.Size(shape), torch.float32)
+
+
+def _f32(*shape: int) -> GGMLTensor:
+ """An unquantized (F32) GGMLTensor — how llama.cpp stores the RMSNorm weights."""
+ rng = np.random.default_rng(seed=sum(shape) + 1)
+ data = torch.from_numpy(rng.normal(loc=1.0, scale=0.05, size=shape).astype(np.float32))
+ return GGMLTensor(data, gguf.GGMLQuantizationType.F32, torch.Size(shape), torch.float32)
+
+
+def _tiny_gguf_state_dict() -> dict[str, GGMLTensor]:
+ """llama.cpp-named tensors for the tiny Gemma-2 above, as `gguf_sd_loader` would return them."""
+ sd: dict[str, GGMLTensor] = {
+ "token_embd.weight": _q8(_VOCAB, _HIDDEN),
+ "output_norm.weight": _f32(_HIDDEN),
+ }
+ for i in range(_LAYERS):
+ sd |= {
+ f"blk.{i}.attn_q.weight": _q8(_HEADS * _HEAD_DIM, _HIDDEN),
+ f"blk.{i}.attn_k.weight": _q8(_KV_HEADS * _HEAD_DIM, _HIDDEN),
+ f"blk.{i}.attn_v.weight": _q8(_KV_HEADS * _HEAD_DIM, _HIDDEN),
+ f"blk.{i}.attn_output.weight": _q8(_HIDDEN, _HEADS * _HEAD_DIM),
+ f"blk.{i}.ffn_gate.weight": _q8(_INTERMEDIATE, _HIDDEN),
+ f"blk.{i}.ffn_up.weight": _q8(_INTERMEDIATE, _HIDDEN),
+ f"blk.{i}.ffn_down.weight": _q8(_HIDDEN, _INTERMEDIATE),
+ f"blk.{i}.attn_norm.weight": _f32(_HIDDEN),
+ f"blk.{i}.post_attention_norm.weight": _f32(_HIDDEN),
+ f"blk.{i}.ffn_norm.weight": _f32(_HIDDEN),
+ f"blk.{i}.post_ffw_norm.weight": _f32(_HIDDEN),
+ }
+ return sd
+
+
+def tiny_gguf(monkeypatch: pytest.MonkeyPatch) -> dict[str, GGMLTensor]:
+ """Mock out the two GGUF file readers so the loader runs against in-memory tensors."""
+ sd = _tiny_gguf_state_dict()
+ # transformers exposes its submodules lazily, so reach for the module object explicitly.
+ monkeypatch.setattr(
+ importlib.import_module("transformers.modeling_gguf_pytorch_utils"),
+ "load_gguf_checkpoint",
+ lambda path, return_tensors=True: {"config": dict(_TINY_GEMMA_CONFIG)},
+ )
+ monkeypatch.setattr(
+ invokeai.backend.quantization.gguf.loaders, "gguf_sd_loader", lambda path, compute_dtype: dict(sd)
+ )
+ return sd
+
+
+# --------------------------------------------------------------------------------------------------
+# Loader behaviour
+# --------------------------------------------------------------------------------------------------
+
+
+class TestNativeGgufLoad:
+ def test_projections_stay_quantized(self, tiny_gguf: dict[str, GGMLTensor]) -> None:
+ """The point of the native loader: the large 2D weights are never dequantized at load time."""
+ model = load_gemma2_model_from_gguf(Path("unused.gguf"), torch.float32)
+
+ for layer in model.layers:
+ for proj in (
+ layer.self_attn.q_proj,
+ layer.self_attn.k_proj,
+ layer.self_attn.v_proj,
+ layer.self_attn.o_proj,
+ layer.mlp.gate_proj,
+ layer.mlp.up_proj,
+ layer.mlp.down_proj,
+ ):
+ assert isinstance(proj.weight, GGMLTensor)
+ # The dequantized shape is what the module's math sees, not the packed byte count.
+ assert proj.weight.shape == (proj.out_features, proj.in_features)
+
+ def test_embedding_and_norms_are_materialized(self, tiny_gguf: dict[str, GGMLTensor]) -> None:
+ model = load_gemma2_model_from_gguf(Path("unused.gguf"), torch.float32)
+
+ # nn.Embedding needs indexed access, so the embedding cannot stay quantized.
+ assert not isinstance(model.embed_tokens.weight, GGMLTensor)
+ assert model.embed_tokens.weight.shape == (_VOCAB, _HIDDEN)
+ torch.testing.assert_close(model.embed_tokens.weight, tiny_gguf["token_embd.weight"].get_dequantized_tensor())
+
+ # llama.cpp folds the +1 into the stored norm weight; Gemma2RMSNorm re-adds it at runtime, so
+ # the loader must subtract it back out (matching transformers' Gemma2TensorProcessor).
+ for name, gguf_key in (
+ ("norm", "output_norm.weight"),
+ ("layers.0.input_layernorm", "blk.0.attn_norm.weight"),
+ ("layers.1.post_feedforward_layernorm", "blk.1.post_ffw_norm.weight"),
+ ):
+ weight = model.get_submodule(name).weight
+ assert not isinstance(weight, GGMLTensor)
+ torch.testing.assert_close(weight, tiny_gguf[gguf_key].get_dequantized_tensor() - 1.0)
+
+ def test_nothing_is_left_on_the_meta_device(self, tiny_gguf: dict[str, GGMLTensor]) -> None:
+ """The model is built with `init_empty_weights`, so a weight the GGUF does not supply would
+ silently remain a meta tensor and only fail at the first forward."""
+ model = load_gemma2_model_from_gguf(Path("unused.gguf"), torch.float32)
+
+ assert not any(p.is_meta for p in model.parameters())
+ assert not any(b.is_meta for b in model.buffers())
+
+ def test_meta_buffers_are_repaired(self, monkeypatch: pytest.MonkeyPatch, tiny_gguf: dict[str, GGMLTensor]) -> None:
+ """The rotary embedding's `inv_freq` is not in the GGUF. Depending on the accelerate version
+ `init_empty_weights` also puts buffers on meta, and the loader has to rebuild them."""
+ real_init_empty_weights = accelerate.init_empty_weights
+ monkeypatch.setattr(
+ accelerate, "init_empty_weights", lambda include_buffers=True: real_init_empty_weights(include_buffers=True)
+ )
+
+ model = load_gemma2_model_from_gguf(Path("unused.gguf"), torch.float32)
+
+ inv_freq = model.rotary_emb.inv_freq
+ assert not inv_freq.is_meta
+ assert inv_freq.shape == (_HEAD_DIM // 2,)
+ assert torch.isfinite(inv_freq).all()
+ expected = 1.0 / (
+ _TINY_GEMMA_CONFIG["rope_theta"] ** (torch.arange(0, _HEAD_DIM, 2, dtype=torch.float32) / _HEAD_DIM)
+ )
+ torch.testing.assert_close(inv_freq.float(), expected)
+
+ def test_forward_runs_with_quantized_weights(self, tiny_gguf: dict[str, GGMLTensor]) -> None:
+ """End of the line: the quantized projections have to survive an actual forward pass."""
+ model = load_gemma2_model_from_gguf(Path("unused.gguf"), torch.float32)
+
+ input_ids = torch.tensor([[3, 17, 42, 8]])
+ with torch.no_grad():
+ hidden_states = model(input_ids, torch.ones_like(input_ids))[0]
+
+ assert hidden_states.shape == (1, 4, _HIDDEN)
+ assert torch.isfinite(hidden_states).all()
+ # The projections were not dequantized in place by running the model.
+ assert isinstance(model.layers[0].self_attn.q_proj.weight, GGMLTensor)
+
+ def test_unexpected_tensor_is_rejected(
+ self, monkeypatch: pytest.MonkeyPatch, tiny_gguf: dict[str, GGMLTensor]
+ ) -> None:
+ """A tensor that maps cleanly but has no home in the configured model (here: a block beyond
+ `num_hidden_layers`) must fail loudly instead of being dropped."""
+ sd = dict(tiny_gguf) | {f"blk.{_LAYERS}.attn_q.weight": _q8(_HEADS * _HEAD_DIM, _HIDDEN)}
+ monkeypatch.setattr(
+ invokeai.backend.quantization.gguf.loaders, "gguf_sd_loader", lambda path, compute_dtype: sd
+ )
+
+ with pytest.raises(RuntimeError, match="Unexpected keys"):
+ load_gemma2_model_from_gguf(Path("unused.gguf"), torch.float32)
+
+
[email protected](not os.environ.get(_LOCAL_GGUF_ENV_VAR), reason=f"set {_LOCAL_GGUF_ENV_VAR} to a Gemma-2-2b GGUF")
def test_native_gguf_load_keeps_projections_quantized_and_matches_reference() -> None:
- import torch
from transformers import AutoTokenizer, Gemma2ForCausalLM
- from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
-
- model = load_gemma2_model_from_gguf(_LOCAL_GGUF, torch.float32)
+ gguf_path = Path(os.environ[_LOCAL_GGUF_ENV_VAR])
+ model = load_gemma2_model_from_gguf(gguf_path, torch.float32)
# Projections stay quantized; embedding and norms are materialized; nothing left on meta.
assert isinstance(model.layers[1].self_attn.q_proj.weight, GGMLTensor)
@@ -73,7 +267,7 @@ def test_native_gguf_load_keeps_projections_quantized_and_matches_reference() ->
assert not isinstance(model.layers[0].input_layernorm.weight, GGMLTensor)
assert not any(p.is_meta for p in model.parameters())
- tok = AutoTokenizer.from_pretrained(str(_LOCAL_GGUF.parent), gguf_file=_LOCAL_GGUF.name, local_files_only=True)
+ tok = AutoTokenizer.from_pretrained(str(gguf_path.parent), gguf_file=gguf_path.name, local_files_only=True)
inputs = tok(["a golden retriever puppy in a sunlit meadow"], return_tensors="pt")
with torch.no_grad():
@@ -81,12 +275,12 @@ def test_native_gguf_load_keeps_projections_quantized_and_matches_reference() ->
# Reference: transformers' own GGUF loader, which fully dequantizes every weight.
reference = Gemma2ForCausalLM.from_pretrained(
- str(_LOCAL_GGUF.parent), gguf_file=_LOCAL_GGUF.name, torch_dtype=torch.float32
+ str(gguf_path.parent), gguf_file=gguf_path.name, torch_dtype=torch.float32
).model
reference.eval()
with torch.no_grad():
hs_ref = reference(inputs.input_ids, inputs.attention_mask)[0]
- # Both decode the same q4_k_m weights; the small residual is quantization-path noise.
+ # Both decode the same weights; the small residual is quantization-path noise.
assert hs_native.shape == hs_ref.shape
assert (hs_native.float() - hs_ref.float()).abs().mean().item() < 0.05
diff --git a/tests/backend/pid/test_pid_decode.py b/tests/backend/pid/test_pid_decode.py
index 91f6c014af..d051e32d4c 100644
--- a/tests/backend/pid/test_pid_decode.py
+++ b/tests/backend/pid/test_pid_decode.py
@@ -1,5 +1,7 @@
-"""Regression tests for the PiD distill schedule and decoder/base validation."""
+"""Regression tests for the PiD distill schedule, decoder/base validation and checkpoint completeness."""
+import math
+from typing import Any
from unittest.mock import patch
import pytest
@@ -10,6 +12,8 @@ from invokeai.backend.pid import decode as pid_decode_module
from invokeai.backend.pid._src.networks.pid_net import PidNet
from invokeai.backend.pid._src.networks.pixeldit_official import PiTBlock
from invokeai.backend.pid.decode import (
+ _PER_BACKBONE,
+ BACKBONE_DISCRIMINATOR_KEY,
PiDDecodeConfig,
PiDDecoder,
_get_t_list,
@@ -17,6 +21,8 @@ from invokeai.backend.pid.decode import (
_velocity_to_x0,
assert_pid_decoder_matches_base,
estimate_pid_decode_working_memory,
+ load_pid_decoder,
+ required_pid_net_shapes,
)
_CPU = torch.device("cpu")
@@ -235,3 +241,106 @@ def test_mismatched_decoder_base_is_rejected() -> None:
def test_z_image_node_accepts_flux_decoder() -> None:
"""Z-Image reuses the FLUX decoder, so its node passes node_base=FLUX and accepts a FLUX decoder."""
assert_pid_decoder_matches_base(BaseModelType.Flux, BaseModelType.Flux, node_title="Z-Image PiD Decode")
+
+
+class TestRequiredPidNetShapes:
+ """The contract model identification holds a checkpoint to, probed from a meta `PidNet`."""
+
+ def test_covers_the_whole_network(self) -> None:
+ shapes = required_pid_net_shapes()
+ lq = {k for k in shapes if k.startswith("lq_proj.")}
+ # The LQ projection is a small fraction of the net: checking only it (as identification once
+ # did) leaves the 385 backbone weights to be discovered missing at load time.
+ assert len(lq) == 71
+ assert len(shapes) - len(lq) == 385
+ # Latent projection conv, one output head + one gate per injection point (patch_depth 14 /
+ # lq_interval 2 = 7). The image branch is disabled (lq_in_channels=0), so it must not appear.
+ assert shapes[BACKBONE_DISCRIMINATOR_KEY] == (512, 16, 3, 3)
+ assert sum(k.endswith(".weight") and ".output_heads." in k for k in lq) == 7
+ assert sum(k.endswith(".log_alpha") for k in lq) == 7
+ assert not any(".image_conv." in k for k in lq)
+
+ def test_one_contract_holds_for_every_backbone(self) -> None:
+ """Identification validates a checkpoint *before* it can know the backbone, so it probes one
+ canonical backbone and applies that contract to all five. This pins what makes that sound:
+ the key names never vary, and `BACKBONE_DISCRIMINATOR_KEY` is the only shape that does. A
+ backbone that ever varies anything else has to fail here, while it is being added, rather
+ than silently weakening the install-time check."""
+ canonical = required_pid_net_shapes()
+ for backbone in _PER_BACKBONE:
+ per_backbone = required_pid_net_shapes(backbone)
+ assert per_backbone.keys() == canonical.keys(), backbone
+ differing = {k for k in canonical if per_backbone[k] != canonical[k]}
+ assert differing <= {BACKBONE_DISCRIMINATOR_KEY}, (backbone, differing)
+ # And it varies in exactly the dimension identification reads the backbone from.
+ assert per_backbone[BACKBONE_DISCRIMINATOR_KEY][1] == _PER_BACKBONE[backbone]["lq_latent_channels"]
+
+ def test_unsupported_backbone_raises(self) -> None:
+ with pytest.raises(ValueError, match="not supported"):
+ required_pid_net_shapes(BaseModelType.StableDiffusion1)
+
+ def test_probing_does_not_consume_the_global_rng(self) -> None:
+ """The probe builds a real PidNet only to read parameter names and shapes. Constructing one
+ normally runs every `reset_parameters()`, which draws from the global CPU RNG — during
+ *model identification*. Later unseeded randomness would then depend on how many candidate
+ files were probed, i.e. on install order."""
+ torch.manual_seed(0)
+ control = torch.rand(4)
+
+ torch.manual_seed(0)
+ required_pid_net_shapes.cache_clear()
+ required_pid_net_shapes()
+ after = torch.rand(4)
+
+ assert torch.equal(control, after), "identification must not advance the global RNG"
+
+ def test_the_contract_is_too_large_to_build_for_real(self) -> None:
+ """Why the probe must stay on the meta device: the network it describes is ~5.5 GB in
+ float32. Model identification builds one for every PiD-looking file it is handed."""
+ elements = sum(math.prod(shape) for shape in required_pid_net_shapes().values())
+ assert elements * 4 > 5 * 1024**3
+
+
+class TestLoadPidDecoderRejectsPartialCheckpoints:
+ """Loaders run under `skip_torch_weight_init()`, so any key the checkpoint omits stays uninitialised
+ memory. `load_pid_decoder` must therefore refuse a partial state dict instead of decoding garbage."""
+
+ class _TinyNet(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.lq_proj = torch.nn.Linear(2, 2)
+ self.blocks = torch.nn.Linear(2, 2)
+
+ @pytest.fixture
+ 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)
+ return net
+
+ def test_complete_state_dict_loads(self, tiny_net: torch.nn.Module) -> None:
+ assert load_pid_decoder(dict(tiny_net.state_dict()), BaseModelType.Flux) is tiny_net
+
+ def test_missing_lq_keys_are_rejected(self, tiny_net: torch.nn.Module) -> None:
+ sd = {k: v for k, v in tiny_net.state_dict().items() if not k.startswith("lq_proj.")}
+ with pytest.raises(RuntimeError, match="LQ projection is incomplete"):
+ load_pid_decoder(sd, BaseModelType.Flux)
+
+ def test_missing_backbone_keys_are_rejected(self, tiny_net: torch.nn.Module) -> None:
+ sd = {k: v for k, v in tiny_net.state_dict().items() if k != "blocks.weight"}
+ with pytest.raises(RuntimeError, match="missing 1 keys"):
+ load_pid_decoder(sd, BaseModelType.Flux)
+
+ def test_unexpected_keys_are_rejected(self, tiny_net: torch.nn.Module) -> None:
+ sd = dict(tiny_net.state_dict()) | {"not_a_pid_key": torch.zeros(1)}
+ with pytest.raises(RuntimeError, match="unexpected keys"):
+ load_pid_decoder(sd, BaseModelType.Flux)
+
+ def test_non_string_keys_are_rejected_before_torch_sees_them(self, tiny_net: torch.nn.Module) -> None:
+ """A bare checkpoint keeps whatever keys the `.pth` was pickled with (see `strip_net_prefix`),
+ so one need not be a string. `nn.Module.load_state_dict` calls `.startswith()` on every key and
+ raises `AttributeError` on a non-string one — from inside torch, before it reports anything —
+ so `load_pid_decoder` has to catch it first and say what is actually wrong with the file."""
+ sd: dict[Any, torch.Tensor] = dict(tiny_net.state_dict()) | {1: torch.zeros(1)}
+ with pytest.raises(RuntimeError, match="1 keys that are not strings"):
+ load_pid_decoder(sd, BaseModelType.Flux)
diff --git a/tests/backend/pid/test_pid_state_dict_utils.py b/tests/backend/pid/test_pid_state_dict_utils.py
new file mode 100644
index 0000000000..df161edd53
--- /dev/null
+++ b/tests/backend/pid/test_pid_state_dict_utils.py
@@ -0,0 +1,97 @@
+"""Regression tests for the PiD key-space normalisation shared by identification and loading.
+
+Identification and the loader used to carry a copy each, and the copies had diverged: only the
+loader dropped the distill-only submodules. That drift is silent in the dangerous direction —
+identification accepting a checkpoint the loader then refuses — so these tests pin that both
+consumers see exactly the same keys.
+"""
+
+import torch
+
+from invokeai.backend.pid.state_dict_utils import has_net_prefix, pid_net_shapes, strip_net_prefix
+
+
+class TestStripNetPrefix:
+ def test_student_prefix_is_removed(self) -> None:
+ sd = {"net.lq_proj.latent_proj.0.weight": torch.zeros(1), "net.blocks.0.weight": torch.zeros(1)}
+ assert set(strip_net_prefix(sd)) == {"lq_proj.latent_proj.0.weight", "blocks.0.weight"}
+
+ def test_distill_only_submodules_are_dropped(self) -> None:
+ """`net_ema.*` shadows PidNet's own parameter names, so it must be dropped, not renamed."""
+ sd = {
+ "net.lq_proj.a": torch.zeros(1),
+ "net_ema.lq_proj.a": torch.zeros(1),
+ "fake_score.x": torch.zeros(1),
+ "discriminator.y": torch.zeros(1),
+ }
+ assert set(strip_net_prefix(sd)) == {"lq_proj.a"}
+
+ def test_a_bare_pid_net_checkpoint_is_untouched(self) -> None:
+ """Without the prefix there is no evidence this is a distill serialisation, so nothing is
+ filtered — a stray key should reach the loader's "unexpected keys" check, not vanish."""
+ sd = {"lq_proj.a": torch.zeros(1), "discriminator.y": torch.zeros(1)}
+ assert strip_net_prefix(sd) is sd
+
+ def test_values_survive_the_rename(self) -> None:
+ tensor = torch.arange(3.0)
+ assert torch.equal(strip_net_prefix({"net.lq_proj.a": tensor})["lq_proj.a"], tensor)
+
+ def test_non_string_keys_are_dropped_rather_than_crashing(self) -> None:
+ # `mod.load_state_dict()` is typed `dict[str | int, Any]`; a torch checkpoint can carry
+ # non-string keys, and neither consumer should raise on one.
+ assert set(strip_net_prefix({"net.lq_proj.a": torch.zeros(1), 0: torch.zeros(1)})) == {"lq_proj.a"}
+
+ def test_a_bare_checkpoints_non_string_keys_survive(self) -> None:
+ """The other half of the pass-through, and the reason the result is not `dict[str, T]`.
+
+ A prefixed checkpoint has its non-string keys filtered out by the rename above; a bare one is
+ returned as-is, so callers get whatever the `.pth` was pickled with. Dropping them would hide
+ a malformed file from the checks meant to catch it — but it does put the burden on both
+ consumers, neither of which may assume the key type: identification sorts its key reports with
+ `key=str`, and `load_pid_decoder` rejects non-strings before torch can trip over them.
+ """
+ sd = {"lq_proj.a": torch.zeros(1), 0: torch.zeros(1)}
+ assert set(strip_net_prefix(sd)) == {"lq_proj.a", 0}
+ assert set(pid_net_shapes(sd)) == {"lq_proj.a", 0}
+
+
+class TestPidNetShapes:
+ def test_matches_strip_net_prefix_exactly(self) -> None:
+ """The whole point of the shared module: identification's view and the loader's view of a
+ checkpoint's key space cannot differ."""
+ sd = {
+ "net.lq_proj.a": torch.zeros(1),
+ "net_ema.lq_proj.a": torch.zeros(1),
+ "discriminator.y": torch.zeros(1),
+ "blocks.0.weight": torch.zeros(1),
+ }
+ assert pid_net_shapes(sd).keys() == strip_net_prefix(sd).keys()
+
+ def test_carries_shapes(self) -> None:
+ assert pid_net_shapes({"net.lq_proj.latent_proj.0.weight": torch.zeros(512, 16, 3, 3)}) == {
+ "lq_proj.latent_proj.0.weight": (512, 16, 3, 3)
+ }
+ # 0-dim parameters are real: PidNet's gate modules carry scalar `log_alpha`s.
+ assert pid_net_shapes({"net.lq_proj.gate_modules.0.log_alpha": torch.zeros(())}) == {
+ "lq_proj.gate_modules.0.log_alpha": ()
+ }
+
+ def test_a_value_with_no_shape_is_reported_as_none(self) -> None:
+ """A checkpoint can hold arbitrary objects. One sitting under a PidNet parameter name is
+ malformed, which identification reports — not an AttributeError mid-probe."""
+ assert pid_net_shapes({"net.lq_proj.a": "not a tensor"}) == {"lq_proj.a": None}
+
+ def test_the_ema_copy_cannot_be_read_as_the_students_weight(self) -> None:
+ """Identification used to find the discriminator weight by *suffix* over the raw dict, so a
+ checkpoint carrying only the EMA copy had `net_ema.lq_proj.latent_proj.0.weight` read as the
+ student's. Looking it up by name in the normalised map cannot do that."""
+ sd = {"net.blocks.0.weight": torch.zeros(1), "net_ema.lq_proj.latent_proj.0.weight": torch.zeros(512, 16, 3, 3)}
+ assert "lq_proj.latent_proj.0.weight" not in pid_net_shapes(sd)
+
+
+class TestHasNetPrefix:
+ def test_detects_the_distill_serialisation(self) -> None:
+ assert has_net_prefix({"net.lq_proj.a": torch.zeros(1)})
+ assert not has_net_prefix({"lq_proj.a": torch.zeros(1)})
+ # `net_ema.` is not the student prefix — the dot matters.
+ assert not has_net_prefix({"net_ema.lq_proj.a": torch.zeros(1)})