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: compute device partial load (#9375)

Alexander Eichhorn68b90174aafe
diff --git a/invokeai/app/invocations/anima_latents_to_image.py b/invokeai/app/invocations/anima_latents_to_image.py
index 04f966c8d4..8131f9bc4e 100644
--- a/invokeai/app/invocations/anima_latents_to_image.py
+++ b/invokeai/app/invocations/anima_latents_to_image.py
@@ -28,7 +28,6 @@ from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import (
estimate_vae_working_memory_anima,
@@ -127,8 +126,10 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
raise TypeError(f"Expected AutoencoderKLWan or FluxAutoEncoder, got {type(vae).__name__}.")
vae_dtype = next(iter(vae.parameters())).dtype
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- latents = latents.to(device=get_effective_device(vae), dtype=vae_dtype)
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ latents = latents.to(device=vae_info.compute_device, dtype=vae_dtype)
TorchDevice.empty_cache()
diff --git a/invokeai/app/invocations/anima_text_encoder.py b/invokeai/app/invocations/anima_text_encoder.py
index 8d0c360179..1d5b6c0ff8 100644
--- a/invokeai/app/invocations/anima_text_encoder.py
+++ b/invokeai/app/invocations/anima_text_encoder.py
@@ -125,7 +125,10 @@ class AnimaTextEncoderInvocation(BaseInvocation):
(_, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())
(_, tokenizer) = exit_stack.enter_context(tokenizer_info.model_on_device())
- device = text_encoder.device
+ # Use the encoder's intended compute device, not its current parameter residency: partial loading may
+ # have temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU (see
+ # #9373). Qwen3 is fully autocast-capable, so nothing pins it to the compute device otherwise.
+ device = text_encoder_info.compute_device
# Apply LoRA models to the text encoder
lora_dtype = TorchDevice.choose_anima_inference_dtype(device)
diff --git a/invokeai/app/invocations/cogview4_latents_to_image.py b/invokeai/app/invocations/cogview4_latents_to_image.py
index bc9d208b66..5d5f7fbb8c 100644
--- a/invokeai/app/invocations/cogview4_latents_to_image.py
+++ b/invokeai/app/invocations/cogview4_latents_to_image.py
@@ -17,7 +17,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_cogview4
@@ -55,8 +54,10 @@ class CogView4LatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
):
context.util.signal_progress("Running VAE")
assert isinstance(vae, (AutoencoderKL))
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- latents = latents.to(get_effective_device(vae))
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ latents = latents.to(vae_info.compute_device)
vae.disable_tiling()
diff --git a/invokeai/app/invocations/cogview4_text_encoder.py b/invokeai/app/invocations/cogview4_text_encoder.py
index 13234889fb..dbd6318ff2 100644
--- a/invokeai/app/invocations/cogview4_text_encoder.py
+++ b/invokeai/app/invocations/cogview4_text_encoder.py
@@ -6,7 +6,6 @@ from invokeai.app.invocations.fields import FieldDescriptions, Input, InputField
from invokeai.app.invocations.model import GlmEncoderField
from invokeai.app.invocations.primitives import CogView4ConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
CogView4ConditioningInfo,
ConditioningFieldData,
@@ -52,8 +51,11 @@ class CogView4TextEncoderInvocation(BaseInvocation):
glm_text_encoder_info.model_on_device() as (_, glm_text_encoder),
context.models.load(self.glm_encoder.tokenizer).model_on_device() as (_, glm_tokenizer),
):
+ # Repair any required tensors left on the CPU by a previous interrupted run, then run on the encoder's
+ # intended compute device. Do NOT infer the device from current parameter residency: partial loading may
+ # have temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.
repaired_tensors = glm_text_encoder_info.repair_required_tensors_on_device()
- device = get_effective_device(glm_text_encoder)
+ device = glm_text_encoder_info.compute_device
if repaired_tensors > 0:
context.logger.warning(
f"Recovered {repaired_tensors} required GLM tensor(s) onto {device} after a partial device mismatch."
diff --git a/invokeai/app/invocations/compel.py b/invokeai/app/invocations/compel.py
index 99373531d8..79a2451017 100644
--- a/invokeai/app/invocations/compel.py
+++ b/invokeai/app/invocations/compel.py
@@ -19,7 +19,6 @@ from invokeai.app.invocations.model import CLIPField
from invokeai.app.invocations.primitives import ConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.app.util.ti_utils import generate_ti_list
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.model_patcher import ModelPatcher
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
@@ -104,7 +103,7 @@ class CompelInvocation(BaseInvocation):
textual_inversion_manager=ti_manager,
dtype_for_device_getter=TorchDevice.choose_torch_dtype,
truncate_long_prompts=False,
- device=get_effective_device(text_encoder),
+ device=text_encoder_info.compute_device,
split_long_text_mode=SplitLongTextMode.SENTENCES,
)
@@ -213,7 +212,7 @@ class SDXLPromptInvocationBase:
truncate_long_prompts=False, # TODO:
returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED, # TODO: clip skip
requires_pooled=get_pooled,
- device=get_effective_device(text_encoder),
+ device=text_encoder_info.compute_device,
split_long_text_mode=SplitLongTextMode.SENTENCES,
)
diff --git a/invokeai/app/invocations/flux2_klein_text_encoder.py b/invokeai/app/invocations/flux2_klein_text_encoder.py
index b2728d1d7c..33290868f7 100644
--- a/invokeai/app/invocations/flux2_klein_text_encoder.py
+++ b/invokeai/app/invocations/flux2_klein_text_encoder.py
@@ -25,7 +25,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import Qwen3EncoderField
from invokeai.app.invocations.primitives import FluxConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_T5_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
@@ -101,8 +100,11 @@ class Flux2KleinTextEncoderInvocation(BaseInvocation):
tokenizer_info = context.models.load(self.qwen3_encoder.tokenizer)
(_, tokenizer) = exit_stack.enter_context(tokenizer_info.model_on_device())
+ # Repair any required tensors left on the CPU by a previous interrupted run, then run on the encoder's
+ # intended compute device. Do NOT infer the device from current parameter residency: partial loading may
+ # have temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.
repaired_tensors = text_encoder_info.repair_required_tensors_on_device()
- device = get_effective_device(text_encoder)
+ device = text_encoder_info.compute_device
if repaired_tensors > 0:
context.logger.warning(
f"Recovered {repaired_tensors} required Qwen3 tensor(s) onto {device} after a partial device mismatch."
diff --git a/invokeai/app/invocations/flux2_vae_decode.py b/invokeai/app/invocations/flux2_vae_decode.py
index 25ada40687..58297ec1ae 100644
--- a/invokeai/app/invocations/flux2_vae_decode.py
+++ b/invokeai/app/invocations/flux2_vae_decode.py
@@ -20,7 +20,6 @@ from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.model_manager.load.load_base import LoadedModel
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.util.devices import TorchDevice
@@ -52,8 +51,10 @@ class Flux2VaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
"""
with vae_info.model_on_device() as (_, vae):
vae_dtype = next(iter(vae.parameters())).dtype
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- device = get_effective_device(vae)
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ device = vae_info.compute_device
latents = latents.to(device=device, dtype=vae_dtype)
# Decode using diffusers API
diff --git a/invokeai/app/invocations/flux_text_encoder.py b/invokeai/app/invocations/flux_text_encoder.py
index ea5841764d..5559cb86de 100644
--- a/invokeai/app/invocations/flux_text_encoder.py
+++ b/invokeai/app/invocations/flux_text_encoder.py
@@ -115,7 +115,9 @@ class FluxTextEncoderInvocation(BaseInvocation):
)
)
- t5_encoder = HFEncoder(t5_text_encoder, t5_tokenizer, False, self.t5_max_seq_len)
+ t5_encoder = HFEncoder(
+ t5_text_encoder, t5_tokenizer, False, self.t5_max_seq_len, device=t5_encoder_info.compute_device
+ )
if context.config.get().log_tokenization:
self._log_t5_tokenization(context, t5_tokenizer)
@@ -158,7 +160,9 @@ class FluxTextEncoderInvocation(BaseInvocation):
# There are currently no supported CLIP quantized models. Add support here if needed.
raise ValueError(f"Unsupported model format: {clip_text_encoder_config.format}")
- clip_encoder = HFEncoder(clip_text_encoder, clip_tokenizer, True, 77)
+ clip_encoder = HFEncoder(
+ clip_text_encoder, clip_tokenizer, True, 77, device=clip_text_encoder_info.compute_device
+ )
if context.config.get().log_tokenization:
self._log_clip_tokenization(context, clip_tokenizer)
diff --git a/invokeai/app/invocations/flux_vae_decode.py b/invokeai/app/invocations/flux_vae_decode.py
index 400e36bff4..f81e7cd715 100644
--- a/invokeai/app/invocations/flux_vae_decode.py
+++ b/invokeai/app/invocations/flux_vae_decode.py
@@ -16,7 +16,6 @@ from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.modules.autoencoder import AutoEncoder
from invokeai.backend.model_manager.load.load_base import LoadedModel
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
@@ -48,8 +47,10 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
assert isinstance(vae, AutoEncoder)
vae_dtype = next(iter(vae.parameters())).dtype
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- latents = latents.to(device=get_effective_device(vae), dtype=vae_dtype)
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ latents = latents.to(device=vae_info.compute_device, dtype=vae_dtype)
img = vae.decode(latents)
img = img.clamp(-1, 1)
diff --git a/invokeai/app/invocations/latents_to_image.py b/invokeai/app/invocations/latents_to_image.py
index 5bd094c186..ebd3a93db9 100644
--- a/invokeai/app/invocations/latents_to_image.py
+++ b/invokeai/app/invocations/latents_to_image.py
@@ -18,7 +18,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.stable_diffusion.vae_tiling import patch_vae_tiling_params
from invokeai.backend.util.devices import TorchDevice
@@ -70,8 +69,10 @@ class LatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
):
context.util.signal_progress("Running VAE decoder")
assert isinstance(vae, (AutoencoderKL, AutoencoderTiny))
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- device = get_effective_device(vae)
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ device = vae_info.compute_device
latents = latents.to(device)
# Force fp32 when running on CPU (e.g. when the VAE is configured cpu_only). fp16 conv does run on CPU with
# the pinned torch, but it's much slower than fp32 there, and SD/SDXL VAE has known fp16 overflow issues
diff --git a/invokeai/app/invocations/qwen_image_latents_to_image.py b/invokeai/app/invocations/qwen_image_latents_to_image.py
index 68c92be331..5ff81eb3ca 100644
--- a/invokeai/app/invocations/qwen_image_latents_to_image.py
+++ b/invokeai/app/invocations/qwen_image_latents_to_image.py
@@ -17,7 +17,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image
@@ -54,8 +53,10 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)
):
context.util.signal_progress("Running VAE")
assert isinstance(vae, AutoencoderKLQwenImage)
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- latents = latents.to(device=get_effective_device(vae), dtype=vae.dtype)
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ latents = latents.to(device=vae_info.compute_device, dtype=vae.dtype)
vae.disable_tiling()
diff --git a/invokeai/app/invocations/qwen_image_text_encoder.py b/invokeai/app/invocations/qwen_image_text_encoder.py
index d2aecd9f22..aec3e920aa 100644
--- a/invokeai/app/invocations/qwen_image_text_encoder.py
+++ b/invokeai/app/invocations/qwen_image_text_encoder.py
@@ -14,7 +14,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import QwenVLEncoderField
from invokeai.app.invocations.primitives import QwenImageConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
ConditioningFieldData,
QwenImageConditioningInfo,
@@ -264,7 +263,9 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
text_encoder_info = context.models.load(self.qwen_vl_encoder.text_encoder)
ctx = text_encoder_info.model_on_device()
_, text_encoder = ctx.__enter__()
- device = get_effective_device(text_encoder)
+ # Use the encoder's intended compute device, not its current parameter residency: partial loading may have
+ # temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.
+ device = text_encoder_info.compute_device
assert isinstance(text_encoder, Qwen2_5_VLForConditionalGeneration)
return text_encoder, device, lambda: ctx.__exit__(None, None, None)
diff --git a/invokeai/app/invocations/sd3_latents_to_image.py b/invokeai/app/invocations/sd3_latents_to_image.py
index 38c93305df..9d7eab5d9d 100644
--- a/invokeai/app/invocations/sd3_latents_to_image.py
+++ b/invokeai/app/invocations/sd3_latents_to_image.py
@@ -17,7 +17,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_sd3
@@ -57,8 +56,10 @@ class SD3LatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
):
context.util.signal_progress("Running VAE")
assert isinstance(vae, (AutoencoderKL))
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- latents = latents.to(get_effective_device(vae))
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ latents = latents.to(vae_info.compute_device)
vae.disable_tiling()
diff --git a/invokeai/app/invocations/sd3_text_encoder.py b/invokeai/app/invocations/sd3_text_encoder.py
index b9763e5a21..c6278e3dcf 100644
--- a/invokeai/app/invocations/sd3_text_encoder.py
+++ b/invokeai/app/invocations/sd3_text_encoder.py
@@ -15,7 +15,6 @@ from invokeai.app.invocations.fields import FieldDescriptions, Input, InputField
from invokeai.app.invocations.model import CLIPField, T5EncoderField
from invokeai.app.invocations.primitives import SD3ConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.model_manager.taxonomy import ModelFormat
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_CLIP_PREFIX
@@ -96,14 +95,17 @@ class Sd3TextEncoderInvocation(BaseInvocation):
assert self.t5_encoder is not None
prompt = [self.prompt]
+ t5_text_encoder_info = context.models.load(self.t5_encoder.text_encoder)
with (
- context.models.load(self.t5_encoder.text_encoder) as t5_text_encoder,
+ t5_text_encoder_info as t5_text_encoder,
context.models.load(self.t5_encoder.tokenizer) as t5_tokenizer,
):
context.util.signal_progress("Running T5 encoder")
assert isinstance(t5_text_encoder, T5EncoderModel)
assert isinstance(t5_tokenizer, T5Tokenizer)
- t5_device = get_effective_device(t5_text_encoder)
+ # Use the encoder's intended compute device, not its current parameter residency: partial loading may
+ # have temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.
+ t5_device = t5_text_encoder_info.compute_device
text_inputs = t5_tokenizer(
prompt,
@@ -145,7 +147,9 @@ class Sd3TextEncoderInvocation(BaseInvocation):
context.util.signal_progress("Running CLIP encoder")
assert isinstance(clip_text_encoder, (CLIPTextModel, CLIPTextModelWithProjection))
assert isinstance(clip_tokenizer, CLIPTokenizer)
- clip_device = get_effective_device(clip_text_encoder)
+ # Use the encoder's intended compute device, not its current parameter residency: partial loading may
+ # have temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.
+ clip_device = clip_text_encoder_info.compute_device
clip_text_encoder_config = clip_text_encoder_info.config
assert clip_text_encoder_config is not None
diff --git a/invokeai/app/invocations/z_image_latents_to_image.py b/invokeai/app/invocations/z_image_latents_to_image.py
index 6ba34632d4..3ad07de4b7 100644
--- a/invokeai/app/invocations/z_image_latents_to_image.py
+++ b/invokeai/app/invocations/z_image_latents_to_image.py
@@ -19,7 +19,6 @@ from invokeai.app.invocations.model import VAEField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
@@ -76,8 +75,10 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
)
vae_dtype = next(iter(vae.parameters())).dtype
- # Use the VAE's actual device (may be CPU if the model is configured cpu_only).
- latents = latents.to(device=get_effective_device(vae), dtype=vae_dtype)
+ # Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from
+ # current param residency: partial loading may have temporarily offloaded all weights to RAM, which would
+ # wrongly place the latents (and thus the whole decode) on the CPU (see #9373).
+ latents = latents.to(device=vae_info.compute_device, dtype=vae_dtype)
# Disable tiling for AutoencoderKL
if isinstance(vae, AutoencoderKL):
diff --git a/invokeai/app/invocations/z_image_text_encoder.py b/invokeai/app/invocations/z_image_text_encoder.py
index 71af6085d0..bb14d508cf 100644
--- a/invokeai/app/invocations/z_image_text_encoder.py
+++ b/invokeai/app/invocations/z_image_text_encoder.py
@@ -16,7 +16,6 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import Qwen3EncoderField
from invokeai.app.invocations.primitives import ZImageConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.lora_conversions.z_image_lora_constants import Z_IMAGE_LORA_QWEN3_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
@@ -80,10 +79,11 @@ class ZImageTextEncoderInvocation(BaseInvocation):
(cached_weights, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())
(_, tokenizer) = exit_stack.enter_context(tokenizer_info.model_on_device())
- # Use the device that the text encoder is effectively executing on, and repair any required tensors left on
- # the CPU by a previous interrupted run.
+ # Repair any required tensors left on the CPU by a previous interrupted run, then run on the encoder's
+ # intended compute device. Do NOT infer the device from current parameter residency: partial loading may
+ # have temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.
repaired_tensors = text_encoder_info.repair_required_tensors_on_device()
- device = get_effective_device(text_encoder)
+ device = text_encoder_info.compute_device
if repaired_tensors > 0:
context.logger.warning(
f"Recovered {repaired_tensors} required Qwen3 tensor(s) onto {device} after a partial device mismatch."
diff --git a/invokeai/backend/flux/modules/conditioner.py b/invokeai/backend/flux/modules/conditioner.py
index d48d78cd4a..e90e5b1a51 100644
--- a/invokeai/backend/flux/modules/conditioner.py
+++ b/invokeai/backend/flux/modules/conditioner.py
@@ -1,5 +1,6 @@
# Initially pulled from https://github.com/black-forest-labs/flux
+import torch
from torch import Tensor, nn
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
@@ -13,6 +14,7 @@ class HFEncoder(nn.Module):
tokenizer: PreTrainedTokenizer | PreTrainedTokenizerFast,
is_clip: bool,
max_length: int,
+ device: torch.device | None = None,
):
super().__init__()
self.max_length = max_length
@@ -21,6 +23,10 @@ class HFEncoder(nn.Module):
self.tokenizer = tokenizer
self.hf_module = encoder
self.hf_module = self.hf_module.eval().requires_grad_(False)
+ # The intended compute device for the encoder. Prefer passing this explicitly (e.g. the loaded model's
+ # compute_device): with partial loading, inferring the device from current parameter residency can wrongly
+ # return CPU when all weights are temporarily offloaded to RAM, running the whole encode on the CPU (#9373).
+ self.device = device
def forward(self, text: list[str]) -> Tensor:
batch_encoding = self.tokenizer(
@@ -33,8 +39,9 @@ class HFEncoder(nn.Module):
return_tensors="pt",
)
- # Move inputs to the same device as the model to support cpu_only models
- model_device = get_effective_device(self.hf_module)
+ # Move inputs to the same device as the model to support cpu_only models. Fall back to inferring the device
+ # from parameter residency only when an explicit device was not provided.
+ model_device = self.device if self.device is not None else get_effective_device(self.hf_module)
outputs = self.hf_module(
input_ids=batch_encoding["input_ids"].to(model_device),
diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.py
index 4609a2e92a..527056399a 100644
--- a/invokeai/backend/model_manager/load/load_base.py
+++ b/invokeai/backend/model_manager/load/load_base.py
@@ -89,6 +89,17 @@ class LoadedModelWithoutConfig:
"""Return the model without locking it."""
return self._cache_record.cached_model.model
+ @property
+ def compute_device(self) -> torch.device:
+ """Return the model's intended compute device.
+
+ This is the device the model is meant to execute on (typically CUDA/MPS, or CPU when the model is configured
+ cpu_only or the whole install is CPU-only). Unlike inferring the device from current parameter residency (e.g.
+ `get_effective_device`), this is stable even when partial loading has temporarily offloaded all of the model's
+ weights to RAM, so it is the correct device to place inputs on before running the model.
+ """
+ return self._cache_record.cached_model.compute_device
+
def repair_required_tensors_on_device(self) -> int:
"""Repair required tensors that should be resident on the cached model's execution device."""
cached_model = self._cache_record.cached_model
diff --git a/tests/app/invocations/test_anima_text_encoder.py b/tests/app/invocations/test_anima_text_encoder.py
new file mode 100644
index 0000000000..4d92c69ce0
--- /dev/null
+++ b/tests/app/invocations/test_anima_text_encoder.py
@@ -0,0 +1,107 @@
+from contextlib import contextmanager, nullcontext
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import torch
+
+from invokeai.app.invocations.anima_text_encoder import AnimaTextEncoderInvocation
+
+
+class FakeQwen3Encoder(torch.nn.Module):
+ """Mimics the Qwen3 0.6B encoder.
+
+ Its `.device` property reports CPU (as HF `PreTrainedModel.device` would when partial loading has offloaded
+ every weight to RAM), while the intended compute device is carried separately by the LoadedModel. The forward
+ records the device of its inputs so the test can assert where the encode actually ran.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.register_parameter("cpu_param", torch.nn.Parameter(torch.ones(1)))
+ self.forward_input_device: torch.device | None = None
+
+ @property
+ def device(self) -> torch.device:
+ return torch.device("cpu")
+
+ def forward(self, input_ids: torch.Tensor, attention_mask=None, output_hidden_states: bool = False):
+ assert output_hidden_states
+ self.forward_input_device = input_ids.device
+ hidden = input_ids.unsqueeze(-1).float()
+ return SimpleNamespace(hidden_states=[hidden, hidden + 1])
+
+
+class FakeQwen3Tokenizer:
+ pad_token_id = 0
+ eos_token_id = 0
+
+ def __call__(self, prompt, **kwargs):
+ del prompt, kwargs
+ return SimpleNamespace(
+ input_ids=torch.tensor([[1, 2, 3]], dtype=torch.long),
+ attention_mask=torch.tensor([[1, 1, 1]], dtype=torch.long),
+ )
+
+
+class FakeT5Tokenizer:
+ def __call__(self, prompt, **kwargs):
+ del prompt, kwargs
+ return SimpleNamespace(input_ids=torch.tensor([[1, 2, 3]], dtype=torch.long))
+
+
+class FakeLoadedModel:
+ def __init__(self, model, compute_device=torch.device("cpu")):
+ self._model = model
+ self._compute_device = compute_device
+
+ @property
+ def compute_device(self) -> torch.device:
+ return self._compute_device
+
+ @contextmanager
+ def model_on_device(self):
+ yield (None, self._model)
+
+
+def _run_encode(monkeypatch, compute_device: torch.device) -> FakeQwen3Encoder:
+ module_path = "invokeai.app.invocations.anima_text_encoder"
+ text_encoder = FakeQwen3Encoder()
+ tokenizer = FakeQwen3Tokenizer()
+
+ mock_context = MagicMock()
+ mock_context.models.load.side_effect = [
+ FakeLoadedModel(text_encoder, compute_device=compute_device),
+ FakeLoadedModel(tokenizer),
+ ]
+ mock_context.util.signal_progress = MagicMock()
+
+ # isinstance() guards in the invocation must accept the fakes.
+ monkeypatch.setattr(f"{module_path}.PreTrainedModel", FakeQwen3Encoder)
+ monkeypatch.setattr(f"{module_path}.PreTrainedTokenizerBase", FakeQwen3Tokenizer)
+ monkeypatch.setattr(f"{module_path}.LayerPatcher.apply_smart_model_patches", lambda **kwargs: nullcontext())
+ # Step 2 tokenizes with the bundled T5-XXL tokenizer; avoid touching the real bundled files.
+ monkeypatch.setattr(f"{module_path}.load_bundled_t5_tokenizer", lambda: FakeT5Tokenizer())
+
+ invocation = AnimaTextEncoderInvocation.model_construct(
+ prompt="test prompt",
+ qwen3_encoder=SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace(), loras=[]),
+ mask=None,
+ )
+
+ invocation._encode_prompt(mock_context)
+ return text_encoder
+
+
+def test_anima_qwen3_encode_uses_compute_device(monkeypatch):
+ # Regression test for #9373: the encoder's weights are offloaded to CPU (`.device` == CPU), but its intended
+ # compute device is the accelerator. The encode must run on the intended compute device, not the current
+ # residency, or the whole encode silently runs on the CPU.
+ compute_device = torch.device("meta")
+ text_encoder = _run_encode(monkeypatch, compute_device)
+ assert text_encoder.forward_input_device == compute_device
+
+
+def test_anima_qwen3_encode_uses_cpu_for_cpu_only_model(monkeypatch):
+ # A cpu_only encoder has compute_device == CPU; the encode must run on the CPU.
+ text_encoder = _run_encode(monkeypatch, torch.device("cpu"))
+ assert text_encoder.forward_input_device == torch.device("cpu")
diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.py
index 7f139dd91c..492619560b 100644
--- a/tests/app/invocations/test_anima_vae.py
+++ b/tests/app/invocations/test_anima_vae.py
@@ -87,6 +87,9 @@ def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor):
vae_info = MagicMock()
vae_info.model = vae
+ # The invocation places latents on the VAE's intended compute device (see #9373), so this
+ # must be a real torch.device rather than a MagicMock for `latents.to(device=...)` to work.
+ vae_info.compute_device = torch.device("cpu")
cm = MagicMock()
cm.__enter__ = MagicMock(return_value=(None, vae))
cm.__exit__ = MagicMock(return_value=None)
diff --git a/tests/app/invocations/test_cogview4_text_encoder.py b/tests/app/invocations/test_cogview4_text_encoder.py
index 81741d4138..df20371792 100644
--- a/tests/app/invocations/test_cogview4_text_encoder.py
+++ b/tests/app/invocations/test_cogview4_text_encoder.py
@@ -37,9 +37,14 @@ class FakeTokenizer:
class FakeLoadedModel:
- def __init__(self, model):
+ def __init__(self, model, compute_device=torch.device("cpu")):
self._model = model
self.repair_calls = 0
+ self._compute_device = compute_device
+
+ @property
+ def compute_device(self) -> torch.device:
+ return self._compute_device
@contextmanager
def model_on_device(self):
diff --git a/tests/app/invocations/test_compel.py b/tests/app/invocations/test_compel.py
index d08f4dfc3c..ba89702e85 100644
--- a/tests/app/invocations/test_compel.py
+++ b/tests/app/invocations/test_compel.py
@@ -24,9 +24,14 @@ class FakeTokenizer:
class FakeLoadedModel:
- def __init__(self, model, config=None):
+ def __init__(self, model, config=None, compute_device=torch.device("cpu")):
self._model = model
self.config = config
+ self._compute_device = compute_device
+
+ @property
+ def compute_device(self) -> torch.device:
+ return self._compute_device
@contextmanager
def model_on_device(self):
@@ -64,12 +69,17 @@ def fake_apply_ti(tokenizer, text_encoder, ti_list):
yield tokenizer, object()
-def test_sdxl_run_clip_compel_uses_effective_device_for_partially_loaded_model(monkeypatch):
+def test_sdxl_run_clip_compel_uses_compute_device_for_partially_loaded_model(monkeypatch):
+ # Regression test for #9373: the encoder's weights are all offloaded to CPU (effective device == CPU), but its
+ # intended compute device is the accelerator. compel must build on the intended compute device, not the current
+ # residency, or the whole encode silently runs on the CPU.
module_path = "invokeai.app.invocations.compel"
- effective_device = torch.device("meta")
- text_encoder = FakeClipTextEncoder(effective_device=effective_device)
+ compute_device = torch.device("meta")
+ text_encoder = FakeClipTextEncoder(effective_device=torch.device("cpu"))
tokenizer = FakeTokenizer()
- text_encoder_info = FakeLoadedModel(text_encoder, config=SimpleNamespace(base="sdxl"))
+ text_encoder_info = FakeLoadedModel(
+ text_encoder, config=SimpleNamespace(base="sdxl"), compute_device=compute_device
+ )
tokenizer_info = FakeLoadedModel(tokenizer)
mock_context = MagicMock()
@@ -98,16 +108,19 @@ def test_sdxl_run_clip_compel_uses_effective_device_for_partially_loaded_model(m
zero_on_empty=False,
)
- assert FakeCompel.last_init_device == effective_device
+ assert FakeCompel.last_init_device == compute_device
assert cond.shape == (1, 4, 4)
assert pooled is None
-def test_sdxl_run_clip_compel_uses_cpu_for_fully_cpu_model(monkeypatch):
+def test_sdxl_run_clip_compel_uses_cpu_for_cpu_only_model(monkeypatch):
+ # A cpu_only text encoder has compute_device == CPU; compel must build on the CPU.
module_path = "invokeai.app.invocations.compel"
text_encoder = FakeClipTextEncoder(effective_device=torch.device("cpu"))
tokenizer = FakeTokenizer()
- text_encoder_info = FakeLoadedModel(text_encoder, config=SimpleNamespace(base="sdxl"))
+ text_encoder_info = FakeLoadedModel(
+ text_encoder, config=SimpleNamespace(base="sdxl"), compute_device=torch.device("cpu")
+ )
tokenizer_info = FakeLoadedModel(tokenizer)
mock_context = MagicMock()
diff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.py
index f3dfbe970d..39689b1f98 100644
--- a/tests/app/invocations/test_qwen_image_working_memory.py
+++ b/tests/app/invocations/test_qwen_image_working_memory.py
@@ -66,6 +66,9 @@ class TestQwenImageWorkingMemory:
# Create mock vae_info with a model_on_device context manager yielding (None, vae)
mock_vae_info = MagicMock()
mock_vae_info.model = mock_vae
+ # Decode places latents on the VAE's intended compute device (see #9373); this must be a
+ # real torch.device so `latents.to(device=...)` works instead of raising TypeError.
+ mock_vae_info.compute_device = torch.device("cpu")
mock_cm = MagicMock()
mock_cm.__enter__ = MagicMock(return_value=(None, mock_vae))
diff --git a/tests/app/invocations/test_sd3_text_encoder.py b/tests/app/invocations/test_sd3_text_encoder.py
index b8c47a8373..feca0b10a3 100644
--- a/tests/app/invocations/test_sd3_text_encoder.py
+++ b/tests/app/invocations/test_sd3_text_encoder.py
@@ -71,9 +71,14 @@ class FakeT5Tokenizer:
class FakeLoadedModel:
- def __init__(self, model, config=None):
+ def __init__(self, model, config=None, compute_device=torch.device("cpu")):
self._model = model
self.config = config
+ self._compute_device = compute_device
+
+ @property
+ def compute_device(self) -> torch.device:
+ return self._compute_device
@contextmanager
def model_on_device(self):
@@ -86,10 +91,12 @@ class FakeLoadedModel:
return False
-def test_sd3_clip_encode_uses_effective_device(monkeypatch):
+def test_sd3_clip_encode_uses_compute_device(monkeypatch):
+ # Regression test for #9373: the encoder's weights are offloaded to CPU, but its intended compute device is the
+ # accelerator. The encode must run on the intended compute device, not the current residency.
module_path = "invokeai.app.invocations.sd3_text_encoder"
- effective_device = torch.device("meta")
- text_encoder = FakeSd3ClipTextEncoder(effective_device)
+ compute_device = torch.device("meta")
+ text_encoder = FakeSd3ClipTextEncoder(effective_device=torch.device("cpu"))
tokenizer = FakeClipTokenizer()
def forward(input_ids: torch.Tensor, output_hidden_states: bool = False):
@@ -102,7 +109,9 @@ def test_sd3_clip_encode_uses_effective_device(monkeypatch):
mock_context = MagicMock()
mock_context.models.load.side_effect = [
- FakeLoadedModel(text_encoder, config=SimpleNamespace(format=ModelFormat.Diffusers)),
+ FakeLoadedModel(
+ text_encoder, config=SimpleNamespace(format=ModelFormat.Diffusers), compute_device=compute_device
+ ),
FakeLoadedModel(tokenizer),
]
mock_context.util.signal_progress = MagicMock()
@@ -124,17 +133,21 @@ def test_sd3_clip_encode_uses_effective_device(monkeypatch):
clip_model=SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace(), loras=[]),
)
- assert text_encoder.forward_input_device == effective_device
+ assert text_encoder.forward_input_device == compute_device
-def test_sd3_t5_encode_uses_effective_device(monkeypatch):
+def test_sd3_t5_encode_uses_compute_device(monkeypatch):
+ # Regression test for #9373: same as the CLIP case, for the T5 encode path.
module_path = "invokeai.app.invocations.sd3_text_encoder"
- effective_device = torch.device("meta")
- text_encoder = FakeSd3T5Encoder(effective_device)
+ compute_device = torch.device("meta")
+ text_encoder = FakeSd3T5Encoder(effective_device=torch.device("cpu"))
tokenizer = FakeT5Tokenizer()
mock_context = MagicMock()
- mock_context.models.load.side_effect = [FakeLoadedModel(text_encoder), FakeLoadedModel(tokenizer)]
+ mock_context.models.load.side_effect = [
+ FakeLoadedModel(text_encoder, compute_device=compute_device),
+ FakeLoadedModel(tokenizer),
+ ]
mock_context.util.signal_progress = MagicMock()
mock_context.logger.warning = MagicMock()
@@ -150,4 +163,4 @@ def test_sd3_t5_encode_uses_effective_device(monkeypatch):
invocation._t5_encode(mock_context, max_seq_len=16)
- assert text_encoder.forward_input_device == effective_device
+ assert text_encoder.forward_input_device == compute_device
diff --git a/tests/app/invocations/test_z_image_working_memory.py b/tests/app/invocations/test_z_image_working_memory.py
index c3f953ae52..74d8f83538 100644
--- a/tests/app/invocations/test_z_image_working_memory.py
+++ b/tests/app/invocations/test_z_image_working_memory.py
@@ -31,6 +31,9 @@ class TestZImageWorkingMemory:
# Create mock vae_info
mock_vae_info = MagicMock()
mock_vae_info.model = mock_vae
+ # Decode places latents on the VAE's intended compute device (see #9373); this must be a
+ # real torch.device so `latents.to(device=...)` works instead of raising TypeError.
+ mock_vae_info.compute_device = torch.device("cpu")
# Create mock context manager return value
mock_cm = MagicMock()
diff --git a/tests/backend/flux/modules/test_conditioner.py b/tests/backend/flux/modules/test_conditioner.py
index 9ccc366c8d..c2204a4822 100644
--- a/tests/backend/flux/modules/test_conditioner.py
+++ b/tests/backend/flux/modules/test_conditioner.py
@@ -35,7 +35,8 @@ class FakePartiallyLoadedEncoder(torch.nn.Module):
return FakeEncoderOutput(pooler_output=torch.ones((1, 4), dtype=torch.float32))
-def test_hf_encoder_uses_effective_device_for_partially_loaded_models():
+def test_hf_encoder_uses_effective_device_when_no_device_given():
+ # Backwards-compatible fallback: with no explicit device, HFEncoder infers it from parameter residency.
effective_device = torch.device("meta")
encoder = FakePartiallyLoadedEncoder(effective_device=effective_device)
hf_encoder = HFEncoder(encoder=encoder, tokenizer=FakeTokenizer(), is_clip=True, max_length=77)
@@ -43,3 +44,17 @@ def test_hf_encoder_uses_effective_device_for_partially_loaded_models():
hf_encoder(["test prompt"])
assert encoder.forward_input_device == effective_device
+
+
+def test_hf_encoder_prefers_explicit_device():
+ # Regression test for #9373: when all weights are offloaded to CPU, inferring the device would yield CPU and run
+ # the whole encode there. An explicit compute device (as the invocation now passes) must take precedence.
+ encoder = FakePartiallyLoadedEncoder(effective_device=torch.device("cpu"))
+ compute_device = torch.device("meta")
+ hf_encoder = HFEncoder(
+ encoder=encoder, tokenizer=FakeTokenizer(), is_clip=True, max_length=77, device=compute_device
+ )
+
+ hf_encoder(["test prompt"])
+
+ assert encoder.forward_input_device == compute_device
diff --git a/tests/backend/model_manager/load/test_loaded_model_compute_device.py b/tests/backend/model_manager/load/test_loaded_model_compute_device.py
new file mode 100644
index 0000000000..7fd911a111
--- /dev/null
+++ b/tests/backend/model_manager/load/test_loaded_model_compute_device.py
@@ -0,0 +1,133 @@
+"""Regression tests for issue #9373.
+
+When partial loading is active and VRAM pressure has temporarily offloaded *all* of a model's weights back to
+RAM, `get_effective_device(model)` reports CPU (it only inspects current parameter residency). The VAE decode
+invocations used to move the latents to that inferred device, so the whole decode silently ran on the CPU even
+though the model's intended compute device was CUDA. The text-encoder invocations shared the same trap for models
+whose modules are all autocast-capable (e.g. CLIP), where `repair_required_tensors_on_device()` pins nothing to
+the compute device.
+
+The fix is to place the inputs on the model's *intended* compute device, exposed via
+`LoadedModel.compute_device` (which is stable regardless of partial-load residency and still respects cpu_only).
+These tests pin down both the plumbing and the underlying mechanism.
+"""
+
+import torch
+
+from invokeai.backend.model_manager.load.load_base import LoadedModelWithoutConfig
+from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecord
+from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_with_partial_load import (
+ CachedModelWithPartialLoad,
+)
+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_cache.utils import get_effective_device
+from tests.backend.model_manager.load.model_cache.cached_model.utils import (
+ parameterize_mps_and_cuda,
+)
+
+
+class _ConvModule(torch.nn.Module):
+ """A tiny conv stack mirroring how a VAE decoder consumes latents.
+
+ Unlike the shared DummyModule, this has no non-persistent buffers, so offloading really moves every tensor to
+ the CPU — which is the residency state that triggers #9373.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.conv_in = torch.nn.Conv2d(4, 8, 3, padding=1)
+ self.conv_out = torch.nn.Conv2d(8, 3, 3, padding=1)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.conv_out(torch.relu(self.conv_in(x)))
+
+
+class _FullyAutocastEncoder(torch.nn.Module):
+ """Mimics a CLIP-style text encoder: only Embedding / Linear / LayerNorm, all autocast-capable.
+
+ Because every module supports autocast, `repair_required_tensors_on_device()` finds nothing to pin to the
+ compute device, so after a full offload `get_effective_device` still reports CPU — the text-encoder variant of
+ #9373.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.embed = torch.nn.Embedding(100, 16)
+ self.linear = torch.nn.Linear(16, 16)
+ self.norm = torch.nn.LayerNorm(16)
+
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
+ return self.norm(self.linear(self.embed(ids)))
+
+
+def _make_loaded_model(
+ compute_device: str, model: torch.nn.Module | None = None
+) -> tuple[LoadedModelWithoutConfig, CachedModelWithPartialLoad]:
+ model = _ConvModule() if model is None else model
+ apply_custom_layers_to_model(model)
+ cached_model = CachedModelWithPartialLoad(
+ model=model, compute_device=torch.device(compute_device), keep_ram_copy=True
+ )
+ record = CacheRecord(key="test", cached_model=cached_model)
+ # The compute_device property only reads through the cache record, so the cache itself is not needed here.
+ loaded_model = LoadedModelWithoutConfig(cache_record=record, cache=None) # type: ignore[arg-type]
+ return loaded_model, cached_model
+
+
+def test_loaded_model_compute_device_reflects_intended_device():
+ """LoadedModel.compute_device surfaces the cached model's intended compute device (respects cpu_only)."""
+ loaded_model, _ = _make_loaded_model("cpu")
+ assert loaded_model.compute_device == torch.device("cpu")
+
+
+@parameterize_mps_and_cuda
+def test_compute_device_stable_when_all_weights_offloaded(device: str):
+ """Reproduces #9373: with every weight offloaded to RAM, effective-device inference falls back to CPU, but the
+ intended compute device (and thus where the decode should run) stays on the accelerator."""
+ loaded_model, cached_model = _make_loaded_model(device)
+
+ # Simulate VRAM pressure: fully load, then push everything back to RAM (as the cache does when working memory
+ # leaves no room for the model's weights).
+ cached_model.full_load_to_vram()
+ cached_model.full_unload_from_vram()
+ assert all(p.device.type == "cpu" for p in cached_model.model.parameters())
+
+ # The trap the invocations used to fall into: inferring the device from residency yields CPU...
+ assert get_effective_device(cached_model.model) == torch.device("cpu")
+ # ...while the intended compute device is preserved. This is what the decode invocations now use.
+ assert loaded_model.compute_device == torch.device(device)
+
+ # And it matters: the custom autocast layers cast their weights to the *input's* device, so the input device
+ # dictates where the whole forward runs. Placing the input on compute_device keeps the decode on the accelerator.
+ x = torch.randn(1, 4, 8, 8)
+ out_on_compute_device = cached_model.model(x.to(loaded_model.compute_device))
+ assert out_on_compute_device.device.type == device
+
+ # Conversely, following the (wrong) effective device runs the forward entirely on the CPU — the bug.
+ out_on_effective_device = cached_model.model(x.to(get_effective_device(cached_model.model)))
+ assert out_on_effective_device.device.type == "cpu"
+
+
+@parameterize_mps_and_cuda
+def test_compute_device_stable_for_fully_autocast_text_encoder(device: str):
+ """Text-encoder variant of #9373: a fully autocast-capable model (CLIP-like) has no tensors for
+ repair_required_tensors_on_device() to pin, so effective-device inference still falls back to CPU after a full
+ offload — but compute_device correctly stays on the accelerator."""
+ loaded_model, cached_model = _make_loaded_model(device, model=_FullyAutocastEncoder())
+
+ cached_model.full_load_to_vram()
+ cached_model.full_unload_from_vram()
+
+ # repair has nothing to do here (every module is autocast-capable), so it does not rescue the effective device.
+ assert cached_model.repair_required_tensors_on_compute_device() == 0
+ assert get_effective_device(cached_model.model) == torch.device("cpu")
+ assert loaded_model.compute_device == torch.device(device)
+
+ ids = torch.randint(0, 100, (1, 8))
+ out_on_compute_device = cached_model.model(ids.to(loaded_model.compute_device))
+ assert out_on_compute_device.device.type == device
+
+ out_on_effective_device = cached_model.model(ids.to(get_effective_device(cached_model.model)))
+ assert out_on_effective_device.device.type == "cpu"