Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(wan): unpack BF16 and embedder tensors when loading GGUF transformers (#10256)

Alexander Eichhorn48b83d98daa5
diff --git a/invokeai/backend/model_manager/load/model_loaders/wan.py b/invokeai/backend/model_manager/load/model_loaders/wan.py
index a2cff77b73..668e7cdb6b 100644
--- a/invokeai/backend/model_manager/load/model_loaders/wan.py
+++ b/invokeai/backend/model_manager/load/model_loaders/wan.py
@@ -61,7 +61,6 @@ from invokeai.backend.quantization.fp8_scaled import (
)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader, unpack_ggml_at_load
-from invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES
from invokeai.backend.quantization.int8_convrot import (
drop_unconsumed_quantization_sidecars,
extract_int8_convrot_markers,
@@ -227,31 +226,6 @@ def _convert_wan_native_to_diffusers(state_dict: dict) -> dict:
return converted
-def _unwrap_unquantized_to_compute_dtype(state_dict: dict) -> dict:
- """Replace non-quantized GGMLTensor entries with plain tensors at compute_dtype.
-
- Why: QuantStack-style GGUFs store biases (and other small tensors) as F16,
- while Wan's ``patch_embedding`` is an ``nn.Conv3d``. ``conv3d`` isn't in
- GGMLTensor's dispatch table, so PyTorch reads the wrapper's underlying F16
- storage directly and crashes against bf16 latents
- (``Input type (c10::BFloat16) and bias type (c10::Half) should be the same``).
-
- For compatible qtypes (F16/F32/BF16) we just pre-cast to compute_dtype here —
- they're not quantized, there's no benefit to keeping them wrapped, and
- unwrapping them sidesteps the missing-op problem entirely. Genuinely
- quantized tensors (Q4_K, Q6_K, etc.) stay wrapped — their on-demand
- dequantization through the linear/addmm dispatch path still works.
- """
- unwrapped: dict = {}
- for key, value in state_dict.items():
- if isinstance(value, GGMLTensor) and value._ggml_quantization_type in TORCH_COMPATIBLE_QTYPES:
- # GGMLTensor.get_dequantized_tensor() already casts to compute_dtype.
- unwrapped[key] = value.get_dequantized_tensor()
- else:
- unwrapped[key] = value
- return unwrapped
-
-
def _drop_benign_extra_keys(sd: dict, source: str, logger: Any) -> None:
"""Remove packaging weights the transformer has no use for, in place.
@@ -396,7 +370,8 @@ class WanGGUFCheckpointModel(ModelLoader):
Mirrors the QwenImage GGUF loader pattern: ``gguf_sd_loader`` -> strip the
ComfyUI ``model.diffusion_model.`` / ``diffusion_model.`` prefix if present
- -> auto-detect arch from state-dict shapes -> ``init_empty_weights`` +
+ -> auto-detect arch from state-dict shapes -> ``init_empty_weights`` ->
+ ``unpack_ggml_at_load`` (non-Linear, unquantized and skip-pattern tensors) ->
``load_state_dict(strict=False, assign=True)``.
"""
@@ -440,18 +415,19 @@ class WanGGUFCheckpointModel(ModelLoader):
if _is_native_wan_layout(sd):
sd = _convert_wan_native_to_diffusers(sd)
- # Pre-cast non-quantized tensors (F16/F32/BF16 biases, scale_shift_table,
- # patch_embedding.weight, etc.) to compute_dtype. This avoids dtype
- # mismatches in conv3d at the input (patch_embedding is the only Conv3d
- # in WanTransformer3DModel; conv3d isn't in GGMLTensor's dispatch table
- # so the wrapper's underlying storage dtype reaches PyTorch directly).
- sd = _unwrap_unquantized_to_compute_dtype(sd)
-
+ # The config is read from the still-packed dict: `_tensor_shape` reports a GGMLTensor's logical shape.
model_config = _build_wan_transformer_config(sd, source="GGUF state dict")
with accelerate.init_empty_weights():
model = WanTransformer3DModel(**model_config)
+ # Unpack what must not stay a GGMLTensor: the Conv3d patch embedding (conv3d is not in its dispatch table),
+ # every unquantized tensor, and the model's declared skip modules, among them `condition_embedder`. A packed
+ # BF16 or quantized tensor reports its uint8 storage dtype, and diffusers casts the timestep to the dtype of
+ # the time embedder's first weight, so a packed weight there fails with "mat1 and mat2 must have the same
+ # dtype". Quantized block Linears stay packed and dequantize on demand.
+ unpack_ggml_at_load(sd, model, _model_declared_skip_patterns(model), self._ram_cache.make_room)
+
incompatible_keys = model.load_state_dict(sd, strict=False, assign=True)
_raise_for_incompatible_keys(incompatible_keys, source="GGUF state dict")
return model
diff --git a/tests/backend/model_manager/load/test_wan_loader.py b/tests/backend/model_manager/load/test_wan_loader.py
index 30cf264281..0606651b1f 100644
--- a/tests/backend/model_manager/load/test_wan_loader.py
+++ b/tests/backend/model_manager/load/test_wan_loader.py
@@ -1,4 +1,4 @@
-"""Tests for Wan loader helpers (native -> diffusers key conversion)."""
+"""Tests for the Wan GGUF and Diffusers loaders and the native -> diffusers key conversion."""
from contextlib import nullcontext
from pathlib import Path
@@ -14,7 +14,6 @@ from invokeai.backend.model_manager.load.model_loaders.wan import (
WanDiffusersModel,
WanGGUFCheckpointModel,
_convert_wan_native_to_diffusers,
- _unwrap_unquantized_to_compute_dtype,
)
from invokeai.backend.model_manager.taxonomy import ModelRepoVariant, SubModelType, WanVariantType
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
@@ -132,60 +131,6 @@ def test_non_string_keys_pass_through():
assert "condition_embedder.text_embedder.linear_1.weight" in out
-def _ggml(data: torch.Tensor, qtype: gguf.GGMLQuantizationType, compute_dtype: torch.dtype) -> GGMLTensor:
- return GGMLTensor(
- data=data,
- ggml_quantization_type=qtype,
- tensor_shape=data.shape,
- compute_dtype=compute_dtype,
- )
-
-
-class TestUnwrapUnquantized:
- """The QuantStack GGUFs store ``patch_embedding.bias`` as F16 while latents
- flow through the model as bf16. Conv3d isn't in GGMLTensor's dispatch table,
- so without unwrapping the F16 wrapper goes into conv3d as-is and crashes
- with ``Input type (c10::BFloat16) and bias type (c10::Half) should be the same``.
- These tests guard the unwrap step that prevents that."""
-
- def test_f16_compatible_qtype_is_unwrapped_and_cast(self):
- # F16 storage that should become bf16 plain tensor.
- f16_data = torch.zeros((4,), dtype=torch.float16)
- sd = {"bias": _ggml(f16_data, gguf.GGMLQuantizationType.F16, torch.bfloat16)}
- out = _unwrap_unquantized_to_compute_dtype(sd)
-
- result = out["bias"]
- assert not isinstance(result, GGMLTensor)
- assert result.dtype == torch.bfloat16
-
- def test_f32_compatible_qtype_is_unwrapped_and_cast(self):
- # patch_embedding.weight in QuantStack is F32 — same path.
- f32_data = torch.zeros((4,), dtype=torch.float32)
- sd = {"weight": _ggml(f32_data, gguf.GGMLQuantizationType.F32, torch.bfloat16)}
- out = _unwrap_unquantized_to_compute_dtype(sd)
-
- result = out["weight"]
- assert not isinstance(result, GGMLTensor)
- assert result.dtype == torch.bfloat16
-
- def test_quantized_tensor_stays_wrapped(self):
- # Q4_K and friends must remain GGMLTensor so on-demand dequant works
- # via the linear/addmm dispatch path. The byte storage shape is fake
- # but irrelevant for this test.
- q4_data = torch.zeros((1,), dtype=torch.uint8)
- sd = {"linear.weight": _ggml(q4_data, gguf.GGMLQuantizationType.Q4_K, torch.bfloat16)}
- out = _unwrap_unquantized_to_compute_dtype(sd)
-
- assert isinstance(out["linear.weight"], GGMLTensor)
- assert out["linear.weight"]._ggml_quantization_type == gguf.GGMLQuantizationType.Q4_K
-
- def test_plain_torch_tensor_passes_through(self):
- plain = torch.zeros((4,), dtype=torch.bfloat16)
- sd = {"plain": plain}
- out = _unwrap_unquantized_to_compute_dtype(sd)
- assert out["plain"] is plain
-
-
def _run_gguf_loader(extra_keys: list[str], native_layout: bool = False) -> dict:
"""Drive WanGGUFCheckpointModel over a state dict carrying `extra_keys`.
@@ -227,13 +172,10 @@ def _run_gguf_loader(extra_keys: list[str], native_layout: bool = False) -> dict
)
config = SimpleNamespace(path="/models/wan.gguf", variant=WanVariantType.T2V_A14B)
loader = object.__new__(WanGGUFCheckpointModel)
+ loader._ram_cache = MagicMock()
with (
patch("invokeai.backend.model_manager.load.model_loaders.wan.gguf_sd_loader", return_value=state_dict),
- patch(
- "invokeai.backend.model_manager.load.model_loaders.wan._unwrap_unquantized_to_compute_dtype",
- side_effect=lambda value: value,
- ),
patch("invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_torch_device"),
patch(
"invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_bfloat16_safe_dtype",
@@ -247,6 +189,120 @@ def _run_gguf_loader(extra_keys: list[str], native_layout: bool = False) -> dict
return model.load_state_dict.call_args.args[0]
+def _tiny_wan_state_dict() -> dict[str, torch.Tensor]:
+ """Random weights of a one-block, one-head Wan transformer the config inference can size."""
+ from diffusers import WanTransformer3DModel
+
+ torch.manual_seed(0)
+ model = WanTransformer3DModel(
+ patch_size=(1, 2, 2),
+ in_channels=16,
+ out_channels=16,
+ num_layers=1,
+ attention_head_dim=128,
+ num_attention_heads=1,
+ ffn_dim=256,
+ text_dim=64,
+ )
+ return {key: torch.randn_like(value) * 0.1 for key, value in model.state_dict().items()}
+
+
+def _q8_0(weight: torch.Tensor) -> GGMLTensor:
+ packed = gguf.quants.quantize(weight.numpy(), gguf.GGMLQuantizationType.Q8_0)
+ return GGMLTensor(
+ torch.from_numpy(packed),
+ ggml_quantization_type=gguf.GGMLQuantizationType.Q8_0,
+ tensor_shape=weight.shape,
+ compute_dtype=torch.float32,
+ )
+
+
+def test_gguf_loader_unpacks_bf16_and_quantized_condition_embedder_weights() -> None:
+ """A release storing the embedders as BF16 (or Q8_0) loaded them packed, and their uint8 storage dtype leaked out.
+
+ diffusers' `WanTimeTextImageEmbedding` reads the time embedder's dtype off its first weight and casts the
+ timestep to it, so a packed weight turned the timestep into uint8 and the linear failed with "mat1 and mat2
+ must have the same dtype, but got Byte and ...". The block Linears must stay packed.
+ """
+ reference = _tiny_wan_state_dict()
+ time_1 = "condition_embedder.time_embedder.linear_1.weight"
+ time_2 = "condition_embedder.time_embedder.linear_2.weight"
+ text_1 = "condition_embedder.text_embedder.linear_1.weight"
+ block_q = "blocks.0.attn1.to_q.weight"
+
+ sd: dict[str, torch.Tensor] = dict(reference)
+ bf16_values = {key: reference[key].to(torch.bfloat16) for key in (time_1, text_1)}
+ for key, values in bf16_values.items():
+ sd[key] = GGMLTensor(
+ values.contiguous().view(torch.uint8).reshape(values.shape[0], -1),
+ ggml_quantization_type=gguf.GGMLQuantizationType.BF16,
+ tensor_shape=values.shape,
+ compute_dtype=torch.float32,
+ )
+ sd[time_2] = _q8_0(reference[time_2])
+ sd[block_q] = _q8_0(reference[block_q])
+ # QuantStack-style files store the Conv3d patch embedding, the modulation table and the norms unquantized (F16/F32).
+ # conv3d is not in GGMLTensor's dispatch table, so an F16 bias reaching it crashed against the latents' dtype.
+ unquantized = {
+ key: GGMLTensor(
+ value.to(storage),
+ ggml_quantization_type=qtype,
+ tensor_shape=value.shape,
+ compute_dtype=torch.float32,
+ )
+ for key, value in reference.items()
+ for storage, qtype in [
+ (torch.float16, gguf.GGMLQuantizationType.F16)
+ if key.startswith("patch_embedding.") or key == "scale_shift_table"
+ else (torch.float32, gguf.GGMLQuantizationType.F32)
+ ]
+ if key.startswith("patch_embedding.") or key == "scale_shift_table" or ".norm" in key
+ }
+ assert "patch_embedding.bias" in unquantized and any(".norm" in key for key in unquantized)
+ sd.update(unquantized)
+
+ config = SimpleNamespace(path="/models/wan.gguf", variant=WanVariantType.T2V_A14B)
+ loader = object.__new__(WanGGUFCheckpointModel)
+ loader._ram_cache = MagicMock()
+ with (
+ patch("invokeai.backend.model_manager.load.model_loaders.wan.gguf_sd_loader", return_value=sd),
+ patch("invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_torch_device"),
+ patch(
+ "invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_bfloat16_safe_dtype",
+ return_value=torch.float32,
+ ),
+ ):
+ model = loader._load_from_singlefile(config)
+
+ params = dict(model.named_parameters())
+ for key in (time_1, time_2, text_1):
+ assert not isinstance(params[key], GGMLTensor), key
+ assert params[key].dtype == torch.float32, key
+ assert torch.equal(params[time_1].detach(), bf16_values[time_1].float())
+ assert torch.equal(params[text_1].detach(), bf16_values[text_1].float())
+ q8_expected = torch.from_numpy(
+ gguf.quants.dequantize(
+ gguf.quants.quantize(reference[time_2].numpy(), gguf.GGMLQuantizationType.Q8_0),
+ gguf.GGMLQuantizationType.Q8_0,
+ )
+ )
+ torch.testing.assert_close(params[time_2].detach(), q8_expected, rtol=0, atol=5e-4)
+ assert isinstance(params[block_q], GGMLTensor)
+
+ temb, timestep_proj, encoder_hidden_states, _ = model.condition_embedder(
+ torch.tensor([500.0]), torch.randn(1, 3, 64)
+ )
+ assert torch.isfinite(temb).all() and torch.isfinite(timestep_proj).all()
+ assert encoder_hidden_states.dtype == torch.float32
+
+ for key in unquantized:
+ assert not isinstance(params[key], GGMLTensor), key
+ assert params[key].dtype == torch.float32, key
+ output = model(torch.randn(1, 16, 1, 4, 4), torch.tensor([500.0]), torch.randn(1, 3, 64)).sample
+ assert output.shape == (1, 16, 1, 4, 4)
+ assert torch.isfinite(output).all()
+
+
def test_gguf_loader_drops_all_in_one_bundled_components_before_loading() -> None:
"""The "all-in-one" GGUF convention bundles the VAE and text encoder alongside the
transformer — befox/WAN2.2-14B-Rapid-AllInOne-GGUF ships ~110 such files, converted
@@ -324,13 +380,10 @@ def test_gguf_loader_rejects_missing_model_parameter() -> None:
)
config = SimpleNamespace(path="/models/wan.gguf", variant=WanVariantType.T2V_A14B)
loader = object.__new__(WanGGUFCheckpointModel)
+ loader._ram_cache = MagicMock()
with (
patch("invokeai.backend.model_manager.load.model_loaders.wan.gguf_sd_loader", return_value=state_dict),
- patch(
- "invokeai.backend.model_manager.load.model_loaders.wan._unwrap_unquantized_to_compute_dtype",
- side_effect=lambda value: value,
- ),
patch("invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_torch_device"),
patch(
"invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_bfloat16_safe_dtype",