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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Merge remote-tracking branch 'origin/main' into feat/loader-conformance-driver
Alexander Eichhornbb738b7277d8
diff --cc invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.pyindex 8c4f86493d,0b25c8146e..d1f8e29d5d--- a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py+++ b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py@@@ -12,8 -12,7 +12,12 @@@ need a second copyimport torch- from invokeai.backend.quantization.fp8_scaled import expand_weight_scale, is_scale_metadata_key-from invokeai.backend.quantization.fp8_scaled import reject_undecoded_mx_scale++from invokeai.backend.quantization.fp8_scaled import (++ expand_weight_scale,++ is_scale_metadata_key,++ reject_undecoded_mx_scale,++)+from invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plain_fold_cannot_decodedef _strip_comfyui_prefix(sd: dict) -> dict:@@@ -68,15 -66,16 +72,16 @@@ def _dequantize_comfyui_fp8(sd: dict, cbreakif weight_key not in sd:continue+ reject_undecoded_mx_scale(weight_key[: -len(".weight")], sd[scale_key])weight = sd[weight_key].to(compute_dtype)scale = sd[scale_key].to(compute_dtype)- if scale.shape != weight.shape and scale.numel() > 1:- for dim in range(len(weight.shape)):- if dim < len(scale.shape) and scale.shape[dim] != weight.shape[dim]:- block_size = weight.shape[dim] // scale.shape[dim]- if block_size > 1:- scale = scale.repeat_interleave(block_size, dim=dim)- sd[weight_key] = weight * scale+ # Through the shared expansion rather than a local copy of it. The copy that used to live+ # here compared `scale.shape[dim] != weight.shape[dim]`, so a per-output-channel scale --+ # whose length already equals the number of rows -- was expanded by nothing and left to+ # broadcasting, which aligns on the *last* axis. That scales columns instead of rows: a+ # shape error on a non-square weight, and on a square one (every attention out-projection)+ # a model that loads and generates noise.+ sd[weight_key] = weight * expand_weight_scale(weight, scale, weight_key)count += 1return countdiff --cc invokeai/backend/quantization/fp8_scaled.pyindex 6542ead5b6,e1c67a35d9..ad52626782--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@@ -451,7 -460,24 +497,24 @@@ def _normalize_weight_scale(scale: torcreturn scale.flatten()+ def reject_undecoded_mx_scale(path: str, scale: Any) -> None:+ """Refuse an MX exponent grid to anything that is about to multiply it as a number.++ Only ``extract_fp8_scaled_layers`` decodes these (see :func:`decode_mx_block_scales`); several+ loaders instead fold ``weight_scale`` into the weight directly, and there the bytes would be+ used as linear multipliers -- values around 120-135 rather than ``2**(v-127)``, and paired with+ the wrong rows besides. That loads cleanly and generates noise, which is the failure this whole+ decode exists to prevent, arriving through the door it does not cover.+ """+ if getattr(scale, "dtype", None) in _MX_SCALE_DTYPES:+ raise NotImplementedError(+ f"'{path}' carries an MXFP8 (OCP Microscaling) exponent grid, and this loader folds weight scales "+ "without decoding them. Its weights would be scaled by the raw exponent bytes and generate noise. "+ "Use the scaled-fp8 or bf16 build of this checkpoint."+ )++-def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:+def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor, path: str | None = None) -> torch.Tensor:"""Broadcast ``scale`` to line up with ``weight`` for an elementwise multiply.Handles the three layouts producers emit:@@@ -465,14 -491,10 +528,15 @@@a checkpoint using that layout fails to load outright. That is the layout ComfyUI's owndequantizer expands, and the FLUX.2 loader used to expand before this module centralized thelogic.++ ``path`` is the layer the scale belongs to, and only appears in the error. On a checkpoint with+ a thousand Linears, "which one" is the whole of the diagnosis."""- reject_undecoded_mx_scale("<weight_scale>", scale)++ reject_undecoded_mx_scale(path or "<weight_scale>", scale)if scale.numel() == 1:- return scale+ # Flattened rather than returned as-is: a `(1, 1, 1)` scale on an `(out, in)` weight would+ # otherwise broadcast back-aligned into a `(1, out, in)` product.+ return scale.reshape(())if scale.dim() <= 1:if scale.numel() != weight.shape[0]:# A 1-D scale is per-output-channel by definition, so any other length means the filediff --cc tests/backend/quantization/test_nvfp4.pyindex 444058f4e9,a11c525f25..7f385b78c6--- a/tests/backend/quantization/test_nvfp4.py+++ b/tests/backend/quantization/test_nvfp4.py@@@ -29,30 -30,26 +29,18 @@@ from invokeai.backend.quantization.nvfppop_nvfp4_layers,predict_nvfp4_install_size,split_nvfp4_rows,- unblock_scale_grid,)+ from tests.backend.quantization.test_block_scale_tiles import stored_layout+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_tensorsFIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"- def _stored_layout(grid: torch.Tensor) -> torch.Tensor:- """Lay a row-major grid out the way the checkpoints store it, by the index formula measured- against real files: element ``[m, k]`` lands at flat position ``position``."""- rows, blocks = grid.shape- flat = torch.full((rows * blocks,), float("nan"), dtype=grid.dtype)- for m in range(rows):- for k in range(blocks):- position = ((((m // 128) * (blocks // 4) + k // 4) * 32 + m % 32) * 4 + (m % 128) // 32) * 4 + k % 4- flat[position] = grid[m, k]- return flat.reshape(rows, blocks)-def _marker_blob(marker: dict) -> torch.Tensor:- return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)----def _nvfp4_tensors(path: str, codes: torch.Tensor, block_scale: float, global_scale: float) -> dict[str, torch.Tensor]:- """One marked layer in checkpoint layout. A uniform block scale keeps the expectation independent of the- tile layout, which the tests above pin on their own."""- rows, in_features = codes.shape- return {- f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],- f"{path}.weight_scale": torch.full((rows, in_features // 16), block_scale).to(torch.float8_e4m3fn),- f"{path}.weight_scale_2": torch.tensor(global_scale),- f"{path}.comfy_quant": _marker_blob({"format": "nvfp4"}),- }+ """One layer in checkpoint layout, carrying the per-tensor marker this module's subject reads."""+ layer = nvfp4_tensors(path, codes, block_scale=block_scale, global_scale=global_scale)+ layer[f"{path}.comfy_quant"] = comfy_quant_marker({"format": "nvfp4"})+ return layerdef _zero_layer(path: str, rows: int = 128) -> dict[str, torch.Tensor]: