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
fix: answer the bfloat16 dtype question without allocating
Lincoln Steind67a912ccb3f
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 5ecf42aa83..460dc28781 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -155,7 +155,7 @@ class FluxVAELoader(ModelLoader):# VAE is broken in float16, which mps defaults toif self._torch_dtype == torch.float16:try:- vae_dtype = torch.tensor([1.0], dtype=torch.bfloat16, device=self._torch_device).dtype+ vae_dtype = torch.empty(0, dtype=torch.bfloat16, device=self._torch_device).dtypeexcept TypeError:vae_dtype = torch.float32else:@@ -181,7 +181,7 @@ class Flux2VAEDiffusersLoader(ModelLoader):# VAE is broken in float16, which mps defaults toif self._torch_dtype == torch.float16:try:- vae_dtype = torch.tensor([1.0], dtype=torch.bfloat16, device=self._torch_device).dtype+ vae_dtype = torch.empty(0, dtype=torch.bfloat16, device=self._torch_device).dtypeexcept TypeError:vae_dtype = torch.float32else:@@ -281,7 +281,7 @@ class Flux2VAELoader(ModelLoader):# VAE is broken in float16, which mps defaults toif self._torch_dtype == torch.float16:try:- vae_dtype = torch.tensor([1.0], dtype=torch.bfloat16, device=self._torch_device).dtype+ vae_dtype = torch.empty(0, dtype=torch.bfloat16, device=self._torch_device).dtypeexcept TypeError:vae_dtype = torch.float32else:diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.pyindex 7a28973344..ff2e9da8c9 100644--- a/invokeai/backend/util/devices.py+++ b/invokeai/backend/util/devices.py@@ -469,23 +469,33 @@ class TorchDevice:This is useful for models that require bfloat16 precision (e.g., Z-Image, Flux)but need to run on hardware that may not support bfloat16.+ Asking costs no device memory. A device that cannot be reached at all still raises, as+ it did before: that is a broken device, not a verdict on dtypes, and it belongs to the+ caller.+Args:device: The target device. If None, uses choose_torch_device().Returns:- torch.bfloat16 if supported, torch.float16 for CUDA without bfloat16 support,- or torch.float32 for CPU/MPS.+ torch.bfloat16 if supported, torch.float16 for CUDA that rejects bfloat16, or+ torch.float32 for any other device that rejects it (CPU, MPS, XPU)."""device = device or cls.choose_torch_device()try:- # Test if bfloat16 is supported on this device- torch.tensor([1.0], dtype=torch.bfloat16, device=device)- return torch.bfloat16+ # Zero elements, because this is a question about the dtype and not about memory. A+ # backend rejects an unsupported dtype from a size-independent check it runs before+ # it reaches its allocator, and an allocator is asked for nothing at all: torch's+ # `empty_mps` gates bfloat16 on the macOS version above the allocate() call, and the+ # MPS allocator skips the Metal buffer entirely for zero bytes. Probing with a real+ # element instead put an allocation between a caller and its dtype -- 256 bytes that+ # a full GPU can refuse, failing a run where no memory had been asked for yet.+ torch.empty(0, dtype=torch.bfloat16, device=device)except TypeError:# bfloat16 not supported - fallback based on device typeif device.type == "cuda":return torch.float16return torch.float32+ return torch.bfloat16@classmethoddef choose_anima_inference_dtype(cls, device: Optional[torch.device] = None) -> torch.dtype:diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.pyindex b4716084ae..cb42672138 100644--- a/tests/backend/util/test_devices.py+++ b/tests/backend/util/test_devices.py@@ -278,6 +278,71 @@ def test_legacy_precision_name():assert "float32" == choose_precision(torch.device("cpu"))+# ===== choose_bfloat16_safe_dtype (a dtype question, not a memory one) =====+++def _record_constructors(monkeypatch) -> list[dict]:+ """Capture what the dtype probe asks the backend for, without changing the answer.++ Stubs return a CPU tensor so a device the test machine does not have can still be asked+ about. Covers the constructors a probe would plausibly use; a probe that asks some other+ way records nothing, which the assertions treat as asking for nothing.+ """+ asked: list[dict] = []+ real_empty = torch.empty++ def stub(*args, **kwargs):+ asked.append({"size": args[0] if args else None, "device": kwargs.get("device")})+ return real_empty(0, dtype=kwargs.get("dtype"))++ for name in ("empty", "zeros", "ones", "tensor"):+ monkeypatch.setattr(torch, name, stub)+ return asked+++def test_the_bfloat16_probe_asks_the_named_device_for_nothing(monkeypatch):+ """Two properties at once, because each one alone is satisfiable by a broken probe: whatever+ it asks for must be empty -- a real element is an allocation a full GPU can refuse, which is+ how a dtype query once failed a run -- and it must be asked of the device in question, not of+ whichever device is convenient."""+ asked = _record_constructors(monkeypatch)+ device = torch.device("cuda:0")++ assert TorchDevice.choose_bfloat16_safe_dtype(device) is torch.bfloat16+ assert all(request["size"] in (0, (), []) for request in asked)+ assert all(request["device"] == device for request in asked)+++def test_an_unreachable_device_still_raises_rather_than_guessing(monkeypatch):+ """A device that cannot be reached -- an out-of-range ordinal, a backend this build lacks --+ is a broken configuration, not a dtype verdict. Answering it with a plausible dtype buries+ the real error in whichever loader allocates first."""++ def invalid_device(*args, **kwargs):+ raise RuntimeError("CUDA error: invalid device ordinal")++ monkeypatch.setattr(torch, "empty", invalid_device)++ with pytest.raises(RuntimeError, match="invalid device ordinal"):+ TorchDevice.choose_bfloat16_safe_dtype(torch.device("cuda:9"))+++ ("device_name", "expected"),+ [("cuda", torch.float16), ("mps", torch.float32), ("xpu", torch.float32)],+)+def test_a_backend_that_rejects_bfloat16_falls_back_by_device(monkeypatch, device_name, expected):+ """A rejected dtype is a verdict, unlike a device that cannot answer, and the fallback is+ half-width on CUDA but full-width everywhere else."""++ def unsupported(*args, **kwargs):+ raise TypeError("BFloat16 is not supported on this device")++ monkeypatch.setattr(torch, "empty", unsupported)++ assert TorchDevice.choose_bfloat16_safe_dtype(torch.device(device_name)) is expected++# ===== choose_anima_inference_dtype (config.precision honoring) ============