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: serialize remaining direct torch model constructions under MODEL_LOAD_LOCK

Lincoln Steinbd182dfd35a0
diff --git a/invokeai/app/invocations/qwen_image_text_encoder.py b/invokeai/app/invocations/qwen_image_text_encoder.py
index 0b64cdae5c..f078d88f67 100644
--- a/invokeai/app/invocations/qwen_image_text_encoder.py
+++ b/invokeai/app/invocations/qwen_image_text_encoder.py
@@ -14,6 +14,7 @@ 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.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
ConditioningFieldData,
QwenImageConditioningInfo,
@@ -305,13 +306,16 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
with warnings.catch_warnings():
# BnB int8 internally casts bfloat16→float16; the warning is harmless
warnings.filterwarnings("ignore", message="MatMul8bitLt.*cast.*float16")
- text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(
- str(encoder_path),
- quantization_config=bnb_config,
- device_map="auto",
- torch_dtype=torch.bfloat16,
- local_files_only=True,
- )
+ # Torch module construction is not thread-safe process-wide (see
+ # _ModelLoadReadWriteLock); serialize with the model-load machinery.
+ with MODEL_LOAD_LOCK.write_lock():
+ text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(
+ str(encoder_path),
+ quantization_config=bnb_config,
+ device_map="auto",
+ torch_dtype=torch.bfloat16,
+ local_files_only=True,
+ )
device = next(text_encoder.parameters()).device
diff --git a/invokeai/app/invocations/upscale.py b/invokeai/app/invocations/upscale.py
index 64e372a0f6..1520106d74 100644
--- a/invokeai/app/invocations/upscale.py
+++ b/invokeai/app/invocations/upscale.py
@@ -12,6 +12,7 @@ from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.image_util.basicsr.rrdbnet_arch import RRDBNet
from invokeai.backend.image_util.realesrgan.realesrgan import RealESRGAN
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
# TODO: Populate this from disk?
# TODO: Use model manager to load?
@@ -53,36 +54,41 @@ class ESRGANInvocation(BaseInvocation, WithMetadata, WithBoard):
"ESRGAN_SRx4_DF2KOST_official-ff704c30.pth",
]:
# x4 RRDBNet model
- rrdbnet_model = RRDBNet(
- num_in_ch=3,
- num_out_ch=3,
- num_feat=64,
- num_block=23,
- num_grow_ch=32,
- scale=4,
- )
+ # Torch module construction is not thread-safe process-wide (see
+ # _ModelLoadReadWriteLock); serialize with the model-load machinery.
+ with MODEL_LOAD_LOCK.write_lock():
+ rrdbnet_model = RRDBNet(
+ num_in_ch=3,
+ num_out_ch=3,
+ num_feat=64,
+ num_block=23,
+ num_grow_ch=32,
+ scale=4,
+ )
netscale = 4
elif self.model_name in ["RealESRGAN_x4plus_anime_6B.pth"]:
# x4 RRDBNet model, 6 blocks
- rrdbnet_model = RRDBNet(
- num_in_ch=3,
- num_out_ch=3,
- num_feat=64,
- num_block=6, # 6 blocks
- num_grow_ch=32,
- scale=4,
- )
+ with MODEL_LOAD_LOCK.write_lock():
+ rrdbnet_model = RRDBNet(
+ num_in_ch=3,
+ num_out_ch=3,
+ num_feat=64,
+ num_block=6, # 6 blocks
+ num_grow_ch=32,
+ scale=4,
+ )
netscale = 4
elif self.model_name in ["RealESRGAN_x2plus.pth"]:
# x2 RRDBNet model
- rrdbnet_model = RRDBNet(
- num_in_ch=3,
- num_out_ch=3,
- num_feat=64,
- num_block=23,
- num_grow_ch=32,
- scale=2,
- )
+ with MODEL_LOAD_LOCK.write_lock():
+ rrdbnet_model = RRDBNet(
+ num_in_ch=3,
+ num_out_ch=3,
+ num_feat=64,
+ num_block=23,
+ num_grow_ch=32,
+ scale=2,
+ )
netscale = 2
else:
msg = f"Invalid RealESRGAN model: {self.model_name}"
diff --git a/invokeai/backend/image_util/safety_checker.py b/invokeai/backend/image_util/safety_checker.py
index 1f2acc58c5..2b4ee89991 100644
--- a/invokeai/backend/image_util/safety_checker.py
+++ b/invokeai/backend/image_util/safety_checker.py
@@ -8,11 +8,13 @@ from pathlib import Path
import numpy as np
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
+from huggingface_hub import snapshot_download
from PIL import Image, ImageFilter
from transformers import AutoImageProcessor
import invokeai.backend.util.logging as logger
from invokeai.app.services.config.config_default import get_config
+from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.silence_warnings import SilenceWarnings
@@ -37,12 +39,20 @@ class SafetyChecker:
model_path = get_config().models_path / CHECKER_PATH
if model_path.exists():
cls.feature_extractor = AutoImageProcessor.from_pretrained(model_path)
- cls.safety_checker = StableDiffusionSafetyChecker.from_pretrained(model_path)
+ # Torch module construction is not thread-safe process-wide (see
+ # _ModelLoadReadWriteLock); serialize with the model-load machinery.
+ with MODEL_LOAD_LOCK.write_lock():
+ cls.safety_checker = StableDiffusionSafetyChecker.from_pretrained(model_path)
else:
model_path.mkdir(parents=True, exist_ok=True)
- cls.feature_extractor = AutoImageProcessor.from_pretrained(repo_id)
+ # Download before constructing: from_pretrained(repo_id) would
+ # otherwise hold the process-wide load lock across a multi-GB
+ # network transfer, stalling every other model load.
+ download_path = snapshot_download(repo_id)
+ cls.feature_extractor = AutoImageProcessor.from_pretrained(download_path)
cls.feature_extractor.save_pretrained(model_path)
- cls.safety_checker = StableDiffusionSafetyChecker.from_pretrained(repo_id)
+ with MODEL_LOAD_LOCK.write_lock():
+ cls.safety_checker = StableDiffusionSafetyChecker.from_pretrained(download_path)
cls.safety_checker.save_pretrained(model_path)
except Exception as e:
logger.warning(f"Could not load NSFW checker: {str(e)}")