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(model-manager): run Diffusers and GGUF T5 encoders in float32 on CPU (#10216)

Alexander Eichhorn52f4f96df435
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
index d50a86dbb8..bfc02e4c7e 100644
--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
@@ -90,8 +90,13 @@ The single-file T5-XXL builds are ComfyUI's `t5xxl_fp16`, `t5xxl_fp8_e4m3fn` and
fp8 builds keep their weights in fp8 on a GPU that can hold them, about 4.9 GB instead of about 9.5 GB. Prefer
`t5xxl_fp8_e4m3fn_scaled` over `t5xxl_fp8_e4m3fn`: the unscaled build stores every tensor in fp8, its layer norms
included, and its prompt embeddings stray measurably further from the full-precision encoder. Wan's UMT5 file looks
-similar but is not a T5-XXL and is not recognized as one. A single-file T5 run on the CPU is held in float32 (about 19 GB of RAM for
-T5-XXL).
+similar but is not a T5-XXL and is not recognized as one.
+
+A standalone T5 encoder (single-file, Diffusers folder or GGUF) that runs on the CPU (`cpu_only`, or an install without
+a GPU) is held and computed in float32: bf16 matrix multiplication on the CPU faults on some machines and is emulated
+slowly where the CPU has no native bf16 support. That takes about 19 GB of RAM for a single-file or Diffusers T5-XXL, so
+if the RAM cache (`max_cache_ram_gb`) is smaller than that, raise it or use a GGUF T5. A GGUF T5 keeps its quantized
+weights packed; only its dequantized embeddings and the per-layer dequantization transients are float32.
The single-file CLIP builds are ComfyUI's `clip_l` and `clip_g`, as used by FLUX.1 and SD 3. SD and SDXL take their
CLIP encoders from the main model only, so a separate CLIP file does not change them. A CLIP-G file needs its
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
index 6e3ede52de..de6026dcf6 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx
@@ -82,8 +82,9 @@ components. Installing a starter model installs them as dependencies:
You can also install the T5 encoder ComfyUI uses as a single file (`t5xxl_fp16`, or `t5xxl_fp8_e4m3fn_scaled` for
about half the VRAM) and select it here; see
-[Model Format Support](/users-guide/models/model-format-support/#text-encoders). A single-file T5 run on the CPU is
-held in float32 (about 19 GB of RAM for T5-XXL).
+[Model Format Support](/users-guide/models/model-format-support/#text-encoders). A T5 encoder run on the CPU is held in
+float32 in the single-file, Diffusers-folder and GGUF formats (about 19 GB of RAM for T5-XXL, except GGUF, which stays
+quantized); details on that page.
Select them in the **Components** section next to the model. The SDNQ pipeline carries its own encoders
and VAE, so its component pickers stay empty.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/sd-3.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/sd-3.mdx
index 3baaa07740..7a0d072458 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/sd-3.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/sd-3.mdx
@@ -59,8 +59,9 @@ you can replace any of them with a model you have installed separately:
- **VAE**: only SD3 VAEs are offered
The T5 encoder can also be one of the single files ComfyUI uses: `t5xxl_fp16`, or `t5xxl_fp8_e4m3fn_scaled` for
-about half the VRAM. A single-file T5 run on the CPU is held in float32 (about 19 GB of RAM for
-T5-XXL).
+about half the VRAM. A standalone T5 encoder (single-file, Diffusers folder or GGUF) run on the CPU is held in float32
+(about 19 GB of RAM for T5-XXL, except GGUF, which stays quantized); see
+[Model Format Support](/users-guide/models/model-format-support/#text-encoders).
The CLIP encoders can also be the single files ComfyUI uses, `clip_l` and `clip_g`; SD 3 then still tokenizes
with the main model's tokenizers.
diff --git a/invokeai/app/invocations/text_encoder/flux_text_encoder.py b/invokeai/app/invocations/text_encoder/flux_text_encoder.py
index 748676b226..ca40c7133d 100644
--- a/invokeai/app/invocations/text_encoder/flux_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/flux_text_encoder.py
@@ -23,7 +23,7 @@ from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_L
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, FLUXConditioningInfo
-from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.t5.t5_encoder import t5_dtype_for_device
from invokeai.backend.util.fp8 import peak_fp8_cast_transient_bytes
@@ -86,7 +86,7 @@ class FluxTextEncoderInvocation(BaseInvocation):
# A GGUF build dequantizes each Linear per forward and a retained-FP8 build widens each one, transients
# its resident size does not cover; both are zero for other builds.
- compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(t5_encoder_info.compute_device)
+ compute_dtype = t5_dtype_for_device(t5_encoder_info.compute_device)
dequant_bytes = peak_dequant_transient_bytes(
t5_encoder_info.model, compute_dtype
) + peak_fp8_cast_transient_bytes(t5_encoder_info.model, compute_dtype)
diff --git a/invokeai/app/invocations/text_encoder/sd3_text_encoder.py b/invokeai/app/invocations/text_encoder/sd3_text_encoder.py
index 7d795243c6..9c8562e0f4 100644
--- a/invokeai/app/invocations/text_encoder/sd3_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/sd3_text_encoder.py
@@ -21,7 +21,7 @@ from invokeai.backend.patches.lora_conversions.sd3_lora_constants import SD3_LOR
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, SD3ConditioningInfo
-from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.t5.t5_encoder import t5_dtype_for_device
from invokeai.backend.util.fp8 import peak_fp8_cast_transient_bytes
# The SD3 T5 Max Sequence Length set based on the default in diffusers.
@@ -102,7 +102,7 @@ class Sd3TextEncoderInvocation(BaseInvocation):
t5_text_encoder_info = context.models.load(self.t5_encoder.text_encoder)
# A GGUF build dequantizes each Linear per forward and a retained-FP8 build widens each one, transients
# its resident size does not cover; both are zero for other builds.
- compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(t5_text_encoder_info.compute_device)
+ compute_dtype = t5_dtype_for_device(t5_text_encoder_info.compute_device)
dequant_bytes = peak_dequant_transient_bytes(
t5_text_encoder_info.model, compute_dtype
) + peak_fp8_cast_transient_bytes(t5_text_encoder_info.model, compute_dtype)
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 3ad5fa00e4..e75f38bebd 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -1,5 +1,7 @@
"""Class for Flux model loading in InvokeAI."""
+import json
+import math
from pathlib import Path
from typing import Any, Optional
@@ -80,6 +82,7 @@ from invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils im
convert_flux2_vae_bfl_to_diffusers,
)
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
+from invokeai.backend.model_manager.model_on_disk import read_safetensors_header
from invokeai.backend.model_manager.taxonomy import (
AnyModel,
BaseModelType,
@@ -132,8 +135,11 @@ from invokeai.backend.quantization.int8_convrot import (
from invokeai.backend.quantization.load_plan import reserve_for_load
from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder
from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loader
-from invokeai.backend.t5.t5_encoder import infer_t5_encoder_config, make_t5_feed_forward_safe
-from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.t5.t5_encoder import (
+ infer_t5_encoder_config,
+ make_t5_feed_forward_safe,
+ t5_dtype_for_device,
+)
from invokeai.backend.util.logging import InvokeAILogger
from invokeai.backend.util.silence_warnings import SilenceWarnings
from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras
@@ -490,9 +496,53 @@ class BnbQuantizedLlmInt8bCheckpointModel(ModelLoader):
model.tie_weights()
+class _T5DtypeByDevice(ModelLoader):
+ """Holds a T5 encoder in the dtype of the device it runs on (`t5_dtype_for_device`) and keys the cache by it.
+
+ The dtype is decided once per loader (a fresh one serves each load), so the cache key and the built model
+ agree. Device caches share one canonical CPU copy per key: a device must not adopt weights of a dtype it
+ would not have built itself.
+ """
+
+ def _t5_dtype(self, config: AnyModelConfig, submodel_type: Optional[SubModelType]) -> torch.dtype:
+ device = self._get_execution_device(config, submodel_type) or self._torch_device
+ decisions: dict[torch.device, torch.dtype] = self.__dict__.setdefault("_t5_dtype_decisions", {})
+ if device not in decisions:
+ decisions[device] = t5_dtype_for_device(device)
+ return decisions[device]
+
+ def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:
+ if submodel_type in (SubModelType.TextEncoder2, SubModelType.TextEncoder3):
+ return str(self._t5_dtype(config, submodel_type)).removeprefix("torch.")
+ return ""
+
+
@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.T5Encoder, format=ModelFormat.T5Encoder)
-class T5EncoderCheckpointModel(ModelLoader):
- """Class to load main models."""
+class T5EncoderCheckpointModel(_T5DtypeByDevice):
+ """Load a T5 encoder from a Diffusers folder, in float32 on the CPU and `choose_bfloat16_safe_dtype`'s dtype
+ elsewhere, whatever dtype the folder stores."""
+
+ def get_size_fs(
+ self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None
+ ) -> int:
+ if submodel_type in (SubModelType.TextEncoder2, SubModelType.TextEncoder3):
+ # The cache makes room for this size before the build, so it is sized at the dtype the encoder is built in
+ # (`_t5_dtype`), whatever the folder stores: a bf16 folder built in float32 on the CPU is twice its size on
+ # disk. The headers give the element counts.
+ folder = model_path / "text_encoder_2"
+ index = folder / "model.safetensors.index.json"
+ if index.is_file():
+ shards = sorted(set(json.loads(index.read_text(encoding="utf-8"))["weight_map"].values()))
+ else:
+ shards = ["model.safetensors"]
+ if all((folder / shard).is_file() for shard in shards):
+ elements = sum(
+ math.prod(info["shape"])
+ for shard in shards
+ for info in read_safetensors_header(folder / shard).values()
+ )
+ return elements * self._t5_dtype(config, submodel_type).itemsize
+ return super().get_size_fs(config, model_path, submodel_type)
def _load_model(
self,
@@ -510,7 +560,7 @@ class T5EncoderCheckpointModel(ModelLoader):
case SubModelType.TextEncoder2 | SubModelType.TextEncoder3:
return T5EncoderModel.from_pretrained(
Path(config.path) / "text_encoder_2",
- torch_dtype="auto",
+ torch_dtype=self._t5_dtype(config, submodel_type),
low_cpu_mem_usage=True,
local_files_only=True,
)
@@ -574,12 +624,13 @@ class T5EncoderSDNQLoader(ModelLoader):
@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.T5Encoder, format=ModelFormat.GGUFQuantized)
-class T5EncoderGGUFModel(ModelLoader):
+class T5EncoderGGUFModel(_T5DtypeByDevice):
"""Class to load GGUF-quantized T5 text encoders (single .gguf file, llama.cpp naming).
The transformer weights are kept as GGMLTensors so the model cache's quantized-autocast layers can
- dequantize them on-the-fly during inference. Embedding weights (token embeddings and the relative
- attention bias) are dequantized eagerly since embedding lookups can't operate on quantized tensors.
+ dequantize them on-the-fly during inference, into float32 on the CPU and `choose_bfloat16_safe_dtype`'s dtype
+ elsewhere. Embedding weights (token embeddings and the relative attention bias) are dequantized eagerly, in
+ that dtype, since embedding lookups can't operate on quantized tensors.
"""
def _load_model(
@@ -594,7 +645,7 @@ class T5EncoderGGUFModel(ModelLoader):
case SubModelType.Tokenizer2 | SubModelType.Tokenizer3:
return self._load_tokenizer()
case SubModelType.TextEncoder2 | SubModelType.TextEncoder3:
- return self._load_from_gguf(config)
+ return self._load_from_gguf(config, submodel_type)
raise ValueError(
f"Only Tokenizer and TextEncoder submodels are currently supported. Received: {submodel_type.value if submodel_type else 'None'}"
@@ -609,13 +660,12 @@ class T5EncoderGGUFModel(ModelLoader):
tokenizer.model_max_length = 512
return tokenizer
- def _load_from_gguf(self, config: T5Encoder_GGUF_Config) -> AnyModel:
+ def _load_from_gguf(self, config: T5Encoder_GGUF_Config, submodel_type: SubModelType) -> AnyModel:
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
model_path = Path(config.path)
- # HACK(ryand): We shouldn't be hard-coding the compute_dtype here.
- sd = gguf_sd_loader(model_path, compute_dtype=torch.bfloat16)
+ sd = gguf_sd_loader(model_path, compute_dtype=self._t5_dtype(config, submodel_type))
if has_per_layer_relative_bias(sd):
# Identification files these under Wan, but a record made by an earlier version can still point
@@ -675,8 +725,8 @@ class T5EncoderSingleFileLoader(ModelLoader):
elsewhere the scales are folded and everything is cast, as on a device without float8. Kept weights are
dequantized per forward and never multiplied in fp8, whatever `fp8_compute` says.
- Everything else is held in `choose_bfloat16_safe_dtype`'s dtype, except on CPU, which holds float32 (twice the
- bf16 size): CPU bf16 GEMM is unreliable on part of the Windows fleet.
+ Everything else is held in `t5_dtype_for_device`'s dtype: float32 on the CPU, `choose_bfloat16_safe_dtype`'s
+ elsewhere.
"""
def get_size_fs(
@@ -695,15 +745,12 @@ class T5EncoderSingleFileLoader(ModelLoader):
Decided once per loader (a fresh one serves each load): the cache key and the stored format must agree,
and the capability probes can flip between the key computation and the build under the load lock.
- CPU holds float32: bf16 GEMM on CPU faults with an illegal instruction on part of the Windows fleet, and
- `choose_bfloat16_safe_dtype` only checks that a bf16 tensor can be allocated.
"""
device = self._get_execution_device(config, submodel_type) or self._torch_device
decisions = self.__dict__.setdefault("_storage_format_decisions", {})
if device not in decisions:
keep_fp8 = should_keep_fp8_weights(device) or _device_supports_fp8_storage(device, self._logger)
- dtype = torch.float32 if device.type == "cpu" else TorchDevice.choose_bfloat16_safe_dtype(device)
- decisions[device] = (keep_fp8, dtype)
+ decisions[device] = (keep_fp8, t5_dtype_for_device(device))
return decisions[device]
def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:
diff --git a/invokeai/backend/t5/t5_encoder.py b/invokeai/backend/t5/t5_encoder.py
index c9cb17ee4d..bbad299c65 100644
--- a/invokeai/backend/t5/t5_encoder.py
+++ b/invokeai/backend/t5/t5_encoder.py
@@ -14,6 +14,17 @@ import torch
from transformers import T5Config
from invokeai.backend.quantization.fp8_scaled import FP8_WEIGHT_DTYPES
+from invokeai.backend.util.devices import TorchDevice
+
+
+def t5_dtype_for_device(device: torch.device) -> torch.dtype:
+ """The dtype a T5 encoder is held and computed in on ``device``.
+
+ float32 on the CPU, twice the bf16 size: bf16 GEMM on the CPU faults with an illegal instruction on part of
+ the Windows fleet and is emulated slowly without a native bf16 unit, and ``choose_bfloat16_safe_dtype`` only
+ checks that a bf16 tensor can be allocated there. Any other device takes ``choose_bfloat16_safe_dtype``.
+ """
+ return torch.float32 if device.type == "cpu" else TorchDevice.choose_bfloat16_safe_dtype(device)
def infer_t5_encoder_config(sd: dict[str, Any]) -> T5Config:
diff --git a/tests/backend/model_manager/load/test_t5_diffusers_loader.py b/tests/backend/model_manager/load/test_t5_diffusers_loader.py
new file mode 100644
index 0000000000..672f5aee5f
--- /dev/null
+++ b/tests/backend/model_manager/load/test_t5_diffusers_loader.py
@@ -0,0 +1,201 @@
+"""Loading a T5 encoder from a Diffusers folder (``text_encoder_2/``), the layout FLUX.1 and SD3 ship it in.
+
+The folder stores bf16, as the real ones do. Which dtype the loader holds it in depends on the device the
+encoder runs on: float32 on the CPU (bf16 GEMM faults on part of the Windows fleet), otherwise whatever
+``choose_bfloat16_safe_dtype`` picks, which these tests patch to float16 so a GPU decision shows.
+
+Forwards run in float32: CPU bf16 matmuls fault on part of the hosted Windows fleet.
+"""
+
+import json
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+from transformers import T5Config, T5EncoderModel
+
+from invokeai.backend.model_manager.configs.t5_encoder import T5Encoder_T5Encoder_Config
+from invokeai.backend.model_manager.load.load_default import put_in_eval_mode
+from invokeai.backend.model_manager.load.model_loaders.flux import T5EncoderCheckpointModel
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType, SubModelType
+from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.logging import InvokeAILogger
+
+
+def _write_bf16_folder(root: Path, max_shard_size: str | None = None) -> T5EncoderModel:
+ """A tiny T5 v1.1 saved in bf16 under ``root/text_encoder_2``, split into shards of at most ``max_shard_size``
+ when given; returns the model as stored (bf16 values)."""
+ torch.manual_seed(0)
+ config = T5Config(
+ vocab_size=32,
+ d_model=16,
+ d_kv=4,
+ d_ff=32,
+ num_layers=2,
+ num_heads=4,
+ feed_forward_proj="gated-gelu",
+ is_gated_act=True,
+ dense_act_fn="gelu_new",
+ use_cache=False,
+ )
+ model = T5EncoderModel(config).eval()
+ with torch.no_grad():
+ for param in model.parameters():
+ param.copy_(torch.randn_like(param) * 0.5)
+ shard_kwargs = {} if max_shard_size is None else {"max_shard_size": max_shard_size}
+ model.to(torch.bfloat16).save_pretrained(root / "text_encoder_2", **shard_kwargs)
+ return model
+
+
+def _config(path: Path, cpu_only: bool | None = None) -> T5Encoder_T5Encoder_Config:
+ return T5Encoder_T5Encoder_Config.model_construct(
+ key="t5", path=str(path), name="t5", base=BaseModelType.Any, type=ModelType.T5Encoder, cpu_only=cpu_only
+ )
+
+
+def loader() -> T5EncoderCheckpointModel:
+ loader = object.__new__(T5EncoderCheckpointModel)
+ loader._ram_cache = MagicMock()
+ loader._logger = InvokeAILogger.get_logger("test")
+ loader._torch_device = torch.device("cpu")
+ return loader
+
+
+def _load_encoder(loader: T5EncoderCheckpointModel, config: T5Encoder_T5Encoder_Config) -> T5EncoderModel:
+ return put_in_eval_mode(loader._load_model(config, SubModelType.TextEncoder2))
+
+
+def test_a_cpu_load_holds_float32_and_encodes_like_the_stored_weights(
+ loader: T5EncoderCheckpointModel, tmp_path: Path
+) -> None:
+ stored = _write_bf16_folder(tmp_path)
+
+ model = _load_encoder(loader, _config(tmp_path))
+
+ assert all(p.dtype == torch.float32 for p in model.parameters())
+ # The stored bf16 values widen exactly, so a float32 forward over them is the expected output.
+ expected = T5EncoderModel(stored.config).eval()
+ expected.load_state_dict({k: v.float() for k, v in stored.state_dict().items()}, strict=False)
+ input_ids = torch.tensor([[3, 7, 1, 30, 12, 0]])
+ with torch.no_grad():
+ torch.testing.assert_close(
+ model(input_ids=input_ids).last_hidden_state, expected(input_ids=input_ids).last_hidden_state
+ )
+
+
+def test_a_cpu_only_t5_on_a_gpu_box_holds_float32(
+ loader: T5EncoderCheckpointModel, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # `cpu_only` runs the encoder on the CPU while the loader's own device is the GPU: the dtype follows the
+ # execution device, not `_torch_device`.
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float16))
+ _write_bf16_folder(tmp_path)
+ loader._torch_device = torch.device("cuda:0")
+ config = _config(tmp_path, cpu_only=True)
+
+ assert loader._cache_key_variant(config, SubModelType.TextEncoder2) == "float32"
+ model = _load_encoder(loader, config)
+ assert all(p.dtype == torch.float32 for p in model.parameters())
+
+
+def test_a_gpu_box_holds_the_dtype_the_device_picks_and_keys_the_cache_by_it(
+ loader: T5EncoderCheckpointModel, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float16))
+ _write_bf16_folder(tmp_path)
+ loader._torch_device = torch.device("cuda:0")
+ config = _config(tmp_path)
+
+ assert loader._cache_key_variant(config, SubModelType.TextEncoder2) == "float16"
+ assert loader._cache_key_variant(config, SubModelType.Tokenizer2) == ""
+ model = _load_encoder(loader, config)
+ # transformers keeps T5's `wo` in float32 under float16 (its activations overflow); the rest follows the device.
+ dtypes = {n: p.dtype for n, p in model.named_parameters() if not n.endswith("DenseReluDense.wo.weight")}
+ assert set(dtypes.values()) == {torch.float16}
+
+
+def _device_loader(store, budget, device: str, tmp_path: Path) -> T5EncoderCheckpointModel:
+ """A loader on its own device cache that shares `store` with the others."""
+ from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+
+ cache = ModelCache(
+ execution_device_working_mem_gb=1.0,
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=True,
+ execution_device="cpu",
+ storage_device="cpu",
+ logger=InvokeAILogger.get_logger("test"),
+ shared_cpu_weights=store,
+ ram_budget=budget,
+ )
+ loader = object.__new__(T5EncoderCheckpointModel)
+ loader._app_config = MagicMock(log_memory_usage=False, models_path=tmp_path)
+ loader._logger = InvokeAILogger.get_logger("test")
+ loader._ram_cache = cache
+ loader._torch_device = torch.device(device)
+ return loader
+
+
[email protected]("cpu_first", [True, False], ids=["cpu_loads_first", "cuda_loads_first"])
+def test_device_caches_do_not_share_weights_of_different_dtypes(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cpu_first: bool
+) -> None:
+ # CPU holds float32 and a CUDA device without bf16 holds float16: the shared CPU store must not hand one
+ # device the other's dtype.
+ from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
+ from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
+
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float16))
+ _write_bf16_folder(tmp_path)
+ config = _config(Path("."))
+ config.path = "." # relative to the loaders' `models_path`
+ store = SharedCpuWeightsStore()
+ budget = RamBudget(max_bytes=10**12, shared_store=store)
+
+ loaders = {} # a device's cache entry holds the shared weights only while its cache lives
+
+ def weight_dtype(device: str) -> torch.dtype:
+ loaders[device] = _device_loader(store, budget, device, tmp_path)
+ record, _claim = loaders[device]._load_and_cache(config, SubModelType.TextEncoder2)
+ return record.cached_model.model.encoder.block[0].layer[0].SelfAttention.q.weight.dtype
+
+ dtypes = {}
+ for name, device in [("cpu", "cpu"), ("cuda", "cuda:0")] if cpu_first else [("cuda", "cuda:0"), ("cpu", "cpu")]:
+ dtypes[name] = weight_dtype(device)
+
+ assert dtypes == {"cpu": torch.float32, "cuda": torch.float16}
+
+
[email protected]("sharded", [False, True], ids=["single_file", "sharded"])
+def test_a_cold_cpu_load_makes_room_for_the_float32_encoder_not_the_bf16_folder(tmp_path: Path, sharded: bool) -> None:
+ # The folder stores bf16 but the CPU builds float32, twice the folder: reserving the folder's size would let a
+ # cold load overshoot the RAM budget by about a file. Real FLUX.1/SD3 folders shard the encoder, so the size has
+ # to come from every shard the index names.
+ from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
+ from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
+
+ _write_bf16_folder(tmp_path, max_shard_size="4KB" if sharded else None)
+ if sharded:
+ index = json.loads((tmp_path / "text_encoder_2" / "model.safetensors.index.json").read_text(encoding="utf-8"))
+ assert len(set(index["weight_map"].values())) > 1
+ config = _config(Path("."))
+ config.path = "." # relative to the loader's `models_path`
+ store = SharedCpuWeightsStore()
+ loader = _device_loader(store, RamBudget(max_bytes=10**12, shared_store=store), "cpu", tmp_path)
+ reservations: list[int] = []
+ make_room = loader._ram_cache.make_room
+
+ def recording_make_room(needed: int):
+ reservations.append(needed)
+ return make_room(needed)
+
+ loader._ram_cache.make_room = recording_make_room
+
+ record, _claim = loader._load_and_cache(config, SubModelType.TextEncoder2)
+
+ model = record.cached_model.model
+ tensors = {t.untyped_storage().data_ptr(): t for t in [*model.parameters(), *model.buffers()]}
+ held = sum(t.nbytes for t in tensors.values())
+ assert max(reservations) >= held
diff --git a/tests/backend/model_manager/load/test_t5_gguf_loader.py b/tests/backend/model_manager/load/test_t5_gguf_loader.py
index c566e6ac88..38c36289cd 100644
--- a/tests/backend/model_manager/load/test_t5_gguf_loader.py
+++ b/tests/backend/model_manager/load/test_t5_gguf_loader.py
@@ -3,15 +3,28 @@
Its llama.cpp key mapping and feed-forward patch are shared with the Wan UMT5 loader and tested in
``tests/backend/model_manager/util/test_llamacpp_t5.py``. Its config inference is shared with the
single-file loader and tested in ``tests/backend/t5/test_t5_encoder.py``.
+
+Forwards run in float32: CPU bf16 matmuls fault on part of the hosted Windows fleet.
"""
+from pathlib import Path
from unittest.mock import MagicMock
+import gguf
+import numpy as np
import pytest
+import torch
+from gguf.quants import dequantize, quantize
+from transformers import T5Config, T5EncoderModel
from invokeai.backend.model_manager.configs.t5_encoder import T5Encoder_GGUF_Config
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
from invokeai.backend.model_manager.load.model_loaders.flux import T5EncoderGGUFModel
from invokeai.backend.model_manager.taxonomy import SubModelType
+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from invokeai.backend.util.devices import TorchDevice
from tests.backend.model_manager.load.umt5_gguf_fixture import write_tiny_umt5_gguf
@@ -24,7 +37,154 @@ def test_a_umt5_gguf_recorded_as_a_flux_t5_encoder_is_refused_with_the_way_out(t
write_tiny_umt5_gguf(path)
loader = object.__new__(T5EncoderGGUFModel)
loader._ram_cache = MagicMock()
+ loader._torch_device = torch.device("cpu")
config = T5Encoder_GGUF_Config.model_construct(path=str(path), name="umt5-xxl-encoder-Q8_0")
with pytest.raises(ValueError, match="UMT5.*Re-identify model"):
loader._load_model(config, SubModelType.TextEncoder2)
+
+
+# A tiny T5 v1.1 in llama.cpp naming. T5 v1.1 learns one relative attention bias, in block 0 (the UMT5 fixture
+# above has one per block and is refused). Q8_0 and F16 matrices, F32 norms and bias, as city96's builds mix them.
+D_MODEL = 64 # Q8_0 packs blocks of 32 along a row.
+NUM_LAYERS = 2
+VOCAB_SIZE = 32
+
+
+def _llamacpp_t5_names() -> dict[str, str]:
+ names = {"shared.weight": "token_embd.weight", "encoder.final_layer_norm.weight": "enc.output_norm.weight"}
+ for block in range(NUM_LAYERS):
+ attn, ffn = f"encoder.block.{block}.layer.0", f"encoder.block.{block}.layer.1"
+ names.update(
+ {
+ f"{attn}.SelfAttention.q.weight": f"enc.blk.{block}.attn_q.weight",
+ f"{attn}.SelfAttention.k.weight": f"enc.blk.{block}.attn_k.weight",
+ f"{attn}.SelfAttention.v.weight": f"enc.blk.{block}.attn_v.weight",
+ f"{attn}.SelfAttention.o.weight": f"enc.blk.{block}.attn_o.weight",
+ f"{attn}.layer_norm.weight": f"enc.blk.{block}.attn_norm.weight",
+ f"{ffn}.DenseReluDense.wi_0.weight": f"enc.blk.{block}.ffn_gate.weight",
+ f"{ffn}.DenseReluDense.wi_1.weight": f"enc.blk.{block}.ffn_up.weight",
+ f"{ffn}.DenseReluDense.wo.weight": f"enc.blk.{block}.ffn_down.weight",
+ f"{ffn}.layer_norm.weight": f"enc.blk.{block}.ffn_norm.weight",
+ }
+ )
+ names["encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight"] = "enc.blk.0.attn_rel_b.weight"
+ return names
+
+
+def _write_tiny_t5_gguf(path: Path) -> tuple[T5EncoderModel, dict[str, np.ndarray]]:
+ """Write the GGUF; return the dense float32 model it encodes and the packed bytes written per llama.cpp name.
+
+ The reference weights are the stored ones run back through gguf-py's own dequantizer, so nothing the tests
+ compare against comes from the loader.
+ """
+ torch.manual_seed(0)
+ config = T5Config(
+ vocab_size=VOCAB_SIZE,
+ d_model=D_MODEL,
+ d_kv=32,
+ d_ff=128,
+ num_layers=NUM_LAYERS,
+ num_heads=2,
+ feed_forward_proj="gated-gelu",
+ is_gated_act=True,
+ dense_act_fn="gelu_new",
+ tie_word_embeddings=False,
+ use_cache=False,
+ )
+ reference = T5EncoderModel(config).eval()
+ writer = gguf.GGUFWriter(str(path), "t5encoder")
+ writer.add_uint32("t5encoder.block_count", NUM_LAYERS)
+ writer.add_uint32("t5encoder.embedding_length", D_MODEL)
+ packed_bytes: dict[str, np.ndarray] = {}
+ state_dict = reference.state_dict()
+ with torch.no_grad():
+ for hf_name, gguf_name in _llamacpp_t5_names().items():
+ tensor = state_dict[hf_name]
+ data = tensor.numpy().astype(np.float32)
+ if data.ndim == 2 and "relative_attention_bias" not in hf_name:
+ qtype = gguf.GGMLQuantizationType.F16 if "wi_" in hf_name else gguf.GGMLQuantizationType.Q8_0
+ packed = quantize(data, qtype)
+ writer.add_tensor(gguf_name, packed, raw_shape=packed.shape, raw_dtype=qtype)
+ packed_bytes[gguf_name] = packed
+ tensor.copy_(torch.from_numpy(dequantize(packed, qtype).reshape(data.shape)))
+ else:
+ writer.add_tensor(gguf_name, data)
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+ return reference, packed_bytes
+
+
+def _t5_loader(device: str = "cpu") -> T5EncoderGGUFModel:
+ loader = object.__new__(T5EncoderGGUFModel)
+ loader._ram_cache = MagicMock()
+ loader._torch_device = torch.device(device)
+ return loader
+
+
+def _gguf_config(path: Path, cpu_only: bool | None = None) -> T5Encoder_GGUF_Config:
+ return T5Encoder_GGUF_Config.model_construct(path=str(path), name="tiny t5", cpu_only=cpu_only)
+
+
+def _assert_float32_throughout(model: T5EncoderModel, reference: T5EncoderModel, packed: dict[str, np.ndarray]) -> None:
+ ggml_params = {n: p for n, p in model.named_parameters() if isinstance(p, GGMLTensor)}
+ # The Linear weights and norms stay packed; the token embedding and relative bias are dequantized.
+ assert ggml_params
+ assert {p.compute_dtype for p in ggml_params.values()} == {torch.float32}
+ assert model.shared.weight.dtype == torch.float32
+ assert model.encoder.embed_tokens.weight is model.shared.weight
+ rel_bias = model.encoder.block[0].layer[0].SelfAttention.relative_attention_bias.weight
+ assert not isinstance(rel_bias, GGMLTensor) and rel_bias.dtype == torch.float32
+ q_weight = model.encoder.block[0].layer[0].SelfAttention.q.weight
+ assert isinstance(q_weight, GGMLTensor)
+ assert np.array_equal(q_weight.quantized_data.numpy(), packed["enc.blk.0.attn_q.weight"])
+
+ model.eval() # `ModelLoader.load_model` does this for every load
+ apply_custom_layers_to_model(model)
+ input_ids = torch.tensor([[3, 7, 1, 30, 12, 0]])
+ with torch.no_grad():
+ actual = model(input_ids=input_ids).last_hidden_state
+ expected = reference(input_ids=input_ids).last_hidden_state
+ assert actual.dtype == torch.float32
+ # The runtime's Q8_0 dequantizer scales in float16, gguf-py's reference in float32.
+ torch.testing.assert_close(actual, expected, rtol=1e-2, atol=1e-2)
+ torch.testing.assert_close(model.shared.weight, reference.shared.weight, rtol=1e-2, atol=1e-2)
+
+
+def test_a_cpu_load_dequantizes_and_computes_in_float32(tmp_path: Path) -> None:
+ path = tmp_path / "t5-tiny.gguf"
+ reference, packed = _write_tiny_t5_gguf(path)
+ loader = _t5_loader()
+ config = _gguf_config(path)
+
+ assert loader._cache_key_variant(config, SubModelType.TextEncoder2) == "float32"
+ _assert_float32_throughout(loader._load_model(config, SubModelType.TextEncoder2), reference, packed)
+
+
+def test_a_cpu_only_t5_on_a_gpu_box_computes_in_float32(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ # The dtype follows the execution device `cpu_only` selects, not the loader's own `_torch_device`. The device's
+ # dtype choice is patched to float16 so a GPU decision would show.
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device=None: torch.float16))
+ path = tmp_path / "t5-tiny.gguf"
+ reference, packed = _write_tiny_t5_gguf(path)
+ loader = _t5_loader("cuda:0")
+ config = _gguf_config(path, cpu_only=True)
+
+ assert loader._cache_key_variant(config, SubModelType.TextEncoder2) == "float32"
+ _assert_float32_throughout(loader._load_model(config, SubModelType.TextEncoder2), reference, packed)
+
+
+def test_a_gpu_box_dequantizes_to_the_dtype_the_device_picks(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device=None: torch.float16))
+ path = tmp_path / "t5-tiny.gguf"
+ _write_tiny_t5_gguf(path)
+ loader = _t5_loader("cuda:0")
+ config = _gguf_config(path)
+
+ assert loader._cache_key_variant(config, SubModelType.TextEncoder2) == "float16"
+ assert loader._cache_key_variant(config, SubModelType.Tokenizer2) == ""
+ model = loader._load_model(config, SubModelType.TextEncoder2)
+ assert model.shared.weight.dtype == torch.float16
+ assert {p.compute_dtype for p in model.parameters() if isinstance(p, GGMLTensor)} == {torch.float16}
diff --git a/tests/backend/model_manager/load/test_t5_single_file_loader.py b/tests/backend/model_manager/load/test_t5_single_file_loader.py
index 72bf4952e7..6143e731af 100644
--- a/tests/backend/model_manager/load/test_t5_single_file_loader.py
+++ b/tests/backend/model_manager/load/test_t5_single_file_loader.py
@@ -24,6 +24,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch
)
from invokeai.backend.model_manager.load.model_loaders.flux import T5EncoderSingleFileLoader
from invokeai.backend.model_manager.taxonomy import SubModelType
+from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
FP8 = torch.float8_e4m3fn
@@ -251,7 +252,7 @@ def test_device_caches_share_weights_only_with_a_device_that_builds_the_same_for
from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
- monkeypatch.setattr(loader_module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float32))
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float32))
monkeypatch.setattr(loader_module, "should_keep_fp8_weights", lambda device: device.type == "cuda")
monkeypatch.setattr(loader_module, "_device_supports_fp8_storage", lambda device, _logger=None: False)
path = tmp_path / "t5xxl.safetensors"
@@ -305,7 +306,7 @@ def test_a_cpu_only_t5_on_a_gpu_box_holds_float32(
) -> None:
# `cpu_only` runs the encoder on the CPU while the loader's own device is the GPU; the dtype follows the
# execution device, not `_torch_device`. The dtype choice is patched to float16 so a GPU decision shows.
- monkeypatch.setattr(loader_module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float16))
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float16))
_keep_fp8(monkeypatch, False)
path = tmp_path / "t5xxl.safetensors"
_write_fp16(_tiny_reference(), path)
@@ -327,7 +328,7 @@ def test_device_caches_do_not_share_folded_weights_of_different_dtypes(
from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
- monkeypatch.setattr(loader_module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float16))
+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float16))
_keep_fp8(monkeypatch, False)
path = tmp_path / "t5xxl.safetensors"
_write_scaled_fp8(_tiny_reference(), path)