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
chore: merge upstream/main
Josh Corbett7119b3cd476d
diff --cc invokeai/app/api/routers/videos.pyindex aa3924b54f,2d1dd69054..e41a049415--- a/invokeai/app/api/routers/videos.py+++ b/invokeai/app/api/routers/videos.py@@@ -212,11 -215,14 +212,15 @@@ class _VideoUploadStreamParserself._header_value = bytearray()self._headers: dict[bytes, bytes] = {}self._part_name: Optional[bytes] = None- self._metadata_chunks: list[bytes] = []- self._metadata_size = 0+ # A bytearray, not a list of per-callback chunks: the parser hands the metadata+ # field over in whatever pieces the client sent it, and one `bytes` object per+ # piece would let a client that dribbles the field in 2-byte pieces hold ~22x the+ # size cap in memory. `len(self._metadata)` is the retained size, so the cap+ # below bounds memory, not just payload.+ self._metadata = bytearray()self.filename: Optional[str] = Noneself.content_type: Optional[str] = None+ self.upload_kind: Optional[str] = Noneself.metadata: Optional[str] = Noneself.file_size = 0self.saw_file_part = Falsediff --cc invokeai/app/invocations/text_encoder/qwen_image_text_encoder.pyindex 1044826255,0000000000..b02bbfed16mode 100644,000000..100644--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py@@@ -1,332 -1,0 +1,493 @@@- from typing import Literal++import gc++import json++import mmap++import traceback++from pathlib import Path++from typing import Any, Callable, Literal++import torch+from PIL import Image as PILImage++from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation+from invokeai.app.invocations.fields import (+ FieldDescriptions,+ ImageField,+ Input,+ InputField,+ UIComponent,+)+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.model_manager.load.model_cache.model_cache import MB, MODEL_LOAD_LOCK++from invokeai.backend.model_manager.load.model_util import calc_model_size_by_fs+from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (+ ConditioningFieldData,+ QwenImageConditioningInfo,+)+from invokeai.backend.util.devices import TorchDevice++# Prompt templates and drop indices for the two Qwen Image model modes.+# These are taken directly from the diffusers pipelines.++# Image editing mode (QwenImagePipeline)+_EDIT_SYSTEM_PROMPT = (+ "Describe the key features of the input image (color, shape, size, texture, objects, background), "+ "then explain how the user's text instruction should alter or modify the image. "+ "Generate a new image that meets the user's requirements while maintaining consistency "+ "with the original input where appropriate."+)+_EDIT_DROP_IDX = 64++# Text-to-image mode (QwenImagePipeline)+_GENERATE_SYSTEM_PROMPT = (+ "Describe the image by detailing the color, shape, size, texture, quantity, "+ "text, spatial relationships of the objects and background:"+)+_GENERATE_DROP_IDX = 34+++# Fraction of the on-disk (bf16) encoder that stays resident after BitsAndBytes quantization. Linear weights++# shrink to 8 or 4 bits, but embeddings, norms, biases and the (excluded) lm_head stay in bf16, and nf4 carries++# per-block absmax scales, so the ratios sit above the pure 1/2 and 1/4. Over-estimating only offloads a little++# more of the cached models to RAM, whereas under-estimating leaves the encoder without enough VRAM, so both++# values are deliberately conservative.++_QUANTIZED_SIZE_RATIO: dict[str, float] = {"int8": 0.6, "nf4": 0.4}+++_IMAGE_PLACEHOLDER = "<|vision_start|><|image_pad|><|vision_end|>"+++# The encoder as handed from a loader to `_encode`: the model, the device to run it on, and a callback that releases++# it when `_encode` is done.++_LoadedEncoder = tuple[torch.nn.Module, torch.device, Callable[[], None]]++++++def _read_checkpoint(encoder_path: Path) -> dict[str, torch.Tensor] | None:++ """Map the encoder's safetensors shards and pull their pages into memory.++++ Returns `None` when the checkpoint has no safetensors shards (e.g. a `.bin` one); the caller then lets transformers++ read it. The tensors are zero-copy views onto the mapped files, so holding all of them costs page cache rather++ than RAM. Touching one byte per page is what makes the disk read happen *here*, outside the model-load lock,++ instead of lazily inside `from_pretrained`, which has to run under it: with the pages already cached the touch is++ nearly free (~60 ms for the 16 GB Qwen2.5-VL-7B checkpoint), and cold it runs at the disk's sequential speed.++ Call it *after* offloading cached models to RAM, not before: the offload's anonymous memory is what would evict++ freshly read pages on a RAM-constrained host, forcing a second read under the lock.++ """++ from safetensors.torch import load_file++++ index_path = encoder_path / "model.safetensors.index.json"++ if index_path.is_file():++ with open(index_path) as index_file:++ shard_names = sorted(set(json.load(index_file)["weight_map"].values()))++ elif (encoder_path / "model.safetensors").is_file():++ shard_names = ["model.safetensors"]++ else:++ return None++++ state_dict: dict[str, torch.Tensor] = {}++ for shard_name in shard_names:++ state_dict.update(load_file(encoder_path / shard_name))++ for tensor in state_dict.values():++ # A strided read of one byte per page faults the whole tensor in through the very mapping transformers will++ # read from; the sum itself is discarded.++ tensor.reshape(-1).view(torch.uint8)[:: mmap.PAGESIZE].sum()++ return state_dict++++def _build_prompt(user_prompt: str, num_images: int) -> str:+ """Build the full prompt with the appropriate template based on whether reference images are provided."""+ if num_images > 0:+ # Edit mode: include vision placeholders for reference images+ image_tokens = _IMAGE_PLACEHOLDER * num_images+ return (+ f"<|im_start|>system\n{_EDIT_SYSTEM_PROMPT}<|im_end|>\n"+ f"<|im_start|>user\n{image_tokens}{user_prompt}<|im_end|>\n"+ "<|im_start|>assistant\n"+ )+ else:+ # Generate mode: text-only prompt+ return (+ f"<|im_start|>system\n{_GENERATE_SYSTEM_PROMPT}<|im_end|>\n"+ f"<|im_start|>user\n{user_prompt}<|im_end|>\n"+ "<|im_start|>assistant\n"+ )+++@invocation(+ "qwen_image_text_encoder",+ title="Prompt - Qwen Image",+ tags=["prompt", "conditioning", "qwen_image"],+ category="conditioning",+ version="1.2.0",+ classification=Classification.Prototype,+ idle_gpu_offloadable=True,+)+class QwenImageTextEncoderInvocation(BaseInvocation):+ """Encodes text and reference images for Qwen Image using Qwen2.5-VL."""++ prompt: str = InputField(description="Text prompt describing the desired edit.", ui_component=UIComponent.Textarea)+ reference_images: list[ImageField] = InputField(+ default=[],+ description="Reference images to guide the edit. The model can use multiple reference images.",+ )+ qwen_vl_encoder: QwenVLEncoderField = InputField(+ title="Qwen VL Encoder",+ description=FieldDescriptions.qwen_vl_encoder,+ input=Input.Connection,+ )+ quantization: Literal["none", "int8", "nf4"] = InputField(+ default="none",+ description="Quantize the Qwen VL encoder to reduce VRAM usage. "+ "'nf4' (4-bit) saves the most memory, 'int8' (8-bit) is a middle ground.",+ )++ @staticmethod+ def _resize_for_vl_encoder(image: PILImage.Image, target_pixels: int = 512 * 512) -> PILImage.Image:+ """Resize image to fit within target_pixels while preserving aspect ratio.++ Matches the diffusers pipeline's calculate_dimensions logic: the image is resized+ so its total pixel count is approximately target_pixels, with dimensions rounded to+ multiples of 32. This prevents large images from producing too many vision tokens+ which can overwhelm the text prompt.+ """+ w, h = image.size+ aspect = w / h+ # Compute dimensions that preserve aspect ratio at ~target_pixels total+ new_w = int((target_pixels * aspect) ** 0.5)+ new_h = int(target_pixels / new_w)+ # Round to multiples of 32+ new_w = max(32, (new_w // 32) * 32)+ new_h = max(32, (new_h // 32) * 32)+ if new_w != w or new_h != h:+ image = image.resize((new_w, new_h), resample=PILImage.LANCZOS)+ return image++ @torch.no_grad()+ def invoke(self, context: InvocationContext) -> QwenImageConditioningOutput:+ # Load and resize reference images to ~1M pixels (matching diffusers pipeline)+ pil_images: list[PILImage.Image] = []+ for img_field in self.reference_images:+ pil_img = context.images.get_pil(img_field.image_name)+ pil_img = self._resize_for_vl_encoder(pil_img.convert("RGB"))+ pil_images.append(pil_img)++ prompt_embeds, prompt_mask = self._encode(context, pil_images)+ prompt_embeds = prompt_embeds.detach().to("cpu")+ prompt_mask = prompt_mask.detach().to("cpu") if prompt_mask is not None else None++ conditioning_data = ConditioningFieldData(+ conditionings=[QwenImageConditioningInfo(prompt_embeds=prompt_embeds, prompt_embeds_mask=prompt_mask)]+ )+ conditioning_name = context.conditioning.save(conditioning_data)+ return QwenImageConditioningOutput.build(conditioning_name)++ def _encode(+ self, context: InvocationContext, images: list[PILImage.Image]+ ) -> tuple[torch.Tensor, torch.Tensor | None]:+ """Encode text prompt and reference images using Qwen2.5-VL.++ Matches the diffusers QwenImagePipeline._get_qwen_prompt_embeds logic:+ 1. Format prompt with the edit-specific system template+ 2. Run through Qwen2.5-VL to get hidden states+ 3. Extract valid (non-padding) tokens and drop the system prefix+ 4. Return padded embeddings + attention mask+ """+ from transformers import AutoTokenizer, Qwen2_5_VLProcessor++ try:+ from transformers import Qwen2_5_VLImageProcessor as _ImageProcessorCls+ except ImportError:+ from transformers.models.qwen2_vl.image_processing_qwen2_vl import ( # type: ignore[no-redef]+ Qwen2VLImageProcessor as _ImageProcessorCls,+ )++ try:+ from transformers import Qwen2_5_VLVideoProcessor as _VideoProcessorCls+ except ImportError:+ from transformers.models.qwen2_vl.video_processing_qwen2_vl import ( # type: ignore[no-redef]+ Qwen2VLVideoProcessor as _VideoProcessorCls,+ )++ # Format the prompt with one vision placeholder per reference image+ text = _build_prompt(self.prompt, len(images))++ # Build the processor+ tokenizer_config = context.models.get_config(self.qwen_vl_encoder.tokenizer)+ model_root = context.models.get_absolute_path(tokenizer_config)++ # Single-file checkpoints (e.g. ComfyUI fp8_scaled): model_root is the+ # safetensors file itself, so there's no tokenizer/processor folder+ # alongside it. Fall back to the canonical Qwen2.5-VL repo on HF (small+ # ~10 MB download for tokenizer+processor configs, cached for offline use).+ if model_root.is_file():+ HF_REPO = "Qwen/Qwen2.5-VL-7B-Instruct"+ try:+ tokenizer = AutoTokenizer.from_pretrained(HF_REPO, local_files_only=True)+ except OSError:+ tokenizer = AutoTokenizer.from_pretrained(HF_REPO)+ try:+ image_processor = _ImageProcessorCls.from_pretrained(HF_REPO, local_files_only=True)+ except OSError:+ try:+ image_processor = _ImageProcessorCls.from_pretrained(HF_REPO)+ except Exception:+ image_processor = _ImageProcessorCls()+ else:+ tokenizer_dir = model_root / "tokenizer"+ tokenizer = AutoTokenizer.from_pretrained(str(tokenizer_dir), local_files_only=True)++ image_processor = None+ for search_dir in [model_root / "processor", tokenizer_dir, model_root, model_root / "image_processor"]:+ if (search_dir / "preprocessor_config.json").exists():+ image_processor = _ImageProcessorCls.from_pretrained(str(search_dir), local_files_only=True)+ break+ if image_processor is None:+ image_processor = _ImageProcessorCls()++ processor = Qwen2_5_VLProcessor(+ tokenizer=tokenizer,+ image_processor=image_processor,+ video_processor=_VideoProcessorCls(),+ )++ context.util.signal_progress("Running Qwen2.5-VL text/vision encoder")++ if self.quantization != "none":+ text_encoder, device, cleanup = self._load_quantized_encoder(context)+ else:+ text_encoder, device, cleanup = self._load_cached_encoder(context)++ try:+ model_inputs = processor(+ text=[text],+ images=images if images else None,+ padding=True,+ return_tensors="pt",+ ).to(device=device)++ prompt_embeds, encoder_attention_mask = self._run_encoder(text_encoder, model_inputs, bool(images))++ except BaseException as exc:++ # The in-flight traceback references the forward's frames, and through their locals the activations++ # (the full-vocabulary logits and every layer's hidden states, hundreds of MB at prompt length) and,++ # on the quantized path, the model itself - so the release below would otherwise be a no-op exactly++ # when VRAM is scarcest (an OOM inside the forward is the likeliest error here). Clearing the finished++ # frames drops those references while keeping the traceback's line information, which is all the++ # error report uses. This applies to the cache-owned encoder too: the cache keeps the model, but the++ # activations are the forward's alone.++ traceback.clear_frames(exc.__traceback__)++ raise++ finally:++ # Drop this frame's references before `cleanup` runs: the quantized encoder is only released once++ # nothing holds it, and `cleanup` calls empty_cache() right after. With the model still alive here,++ # that empty_cache() ran too early and ~9 GB of encoder weights stayed *reserved* by torch after the++ # node finished. The cache budgets from allocated + driver-free VRAM, so reserved-but-unused memory++ # looked like it was in use and the next model (the transformer) was needlessly partial-loaded. The++ # activations live in `_run_encoder`'s frame and are gone by now for the same reason.++ del text_encoder++ cleanup()+- outputs = text_encoder(- input_ids=model_inputs.input_ids,- attention_mask=model_inputs.attention_mask,- pixel_values=getattr(model_inputs, "pixel_values", None),- image_grid_thw=getattr(model_inputs, "image_grid_thw", None),- output_hidden_states=True,- )++ # If all tokens are valid (no padding), mask is not needed++ if encoder_attention_mask.all():++ encoder_attention_mask = None+- # Use last hidden state (matching diffusers pipeline)- hidden_states = outputs.hidden_states[-1]++ return prompt_embeds, encoder_attention_mask+- # Extract valid (non-padding) tokens using the attention mask,- # then drop the system prompt prefix tokens.- # The drop index differs between edit mode (64) and generate mode (34).- drop_idx = _EDIT_DROP_IDX if images else _GENERATE_DROP_IDX++ @staticmethod++ def _run_encoder(++ text_encoder: torch.nn.Module, model_inputs: Any, edit_mode: bool++ ) -> tuple[torch.Tensor, torch.Tensor]:++ """Run the encoder and build the padded embeddings + mask.++++ Kept out of `_encode` on purpose: the full-vocabulary logits and per-layer hidden states the forward returns++ are only referenced by this frame, so they are released as soon as it returns (or is cleared on error),++ before `_encode` empties the CUDA cache.++ """++ device = model_inputs.input_ids.device++ outputs = text_encoder(++ input_ids=model_inputs.input_ids,++ attention_mask=model_inputs.attention_mask,++ pixel_values=getattr(model_inputs, "pixel_values", None),++ image_grid_thw=getattr(model_inputs, "image_grid_thw", None),++ output_hidden_states=True,++ )+- attn_mask = model_inputs.attention_mask- bool_mask = attn_mask.bool()- valid_lengths = bool_mask.sum(dim=1)- selected = hidden_states[bool_mask]- split_hidden = torch.split(selected, valid_lengths.tolist(), dim=0)++ # Use last hidden state (matching diffusers pipeline)++ hidden_states = outputs.hidden_states[-1]+- # Drop system prefix tokens and build padded output- trimmed = [h[drop_idx:] for h in split_hidden]- attn_mask_list = [torch.ones(h.size(0), dtype=torch.long, device=device) for h in trimmed]- max_seq_len = max(h.size(0) for h in trimmed)++ # Extract valid (non-padding) tokens using the attention mask,++ # then drop the system prompt prefix tokens.++ # The drop index differs between edit mode (64) and generate mode (34).++ drop_idx = _EDIT_DROP_IDX if edit_mode else _GENERATE_DROP_IDX+- prompt_embeds = torch.stack(- [torch.cat([h, h.new_zeros(max_seq_len - h.size(0), h.size(1))]) for h in trimmed]- )- encoder_attention_mask = torch.stack(- [torch.cat([m, m.new_zeros(max_seq_len - m.size(0))]) for m in attn_mask_list]- )++ attn_mask = model_inputs.attention_mask++ bool_mask = attn_mask.bool()++ valid_lengths = bool_mask.sum(dim=1)++ selected = hidden_states[bool_mask]++ split_hidden = torch.split(selected, valid_lengths.tolist(), dim=0)+- prompt_embeds = prompt_embeds.to(dtype=torch.bfloat16)- finally:- if cleanup is not None:- cleanup()++ # Drop system prefix tokens and build padded output++ trimmed = [h[drop_idx:] for h in split_hidden]++ attn_mask_list = [torch.ones(h.size(0), dtype=torch.long, device=device) for h in trimmed]++ max_seq_len = max(h.size(0) for h in trimmed)+- # If all tokens are valid (no padding), mask is not needed- if encoder_attention_mask.all():- encoder_attention_mask = None++ prompt_embeds = torch.stack([torch.cat([h, h.new_zeros(max_seq_len - h.size(0), h.size(1))]) for h in trimmed])++ encoder_attention_mask = torch.stack(++ [torch.cat([m, m.new_zeros(max_seq_len - m.size(0))]) for m in attn_mask_list]++ )+- return prompt_embeds, encoder_attention_mask++ return prompt_embeds.to(dtype=torch.bfloat16), encoder_attention_mask+- def _load_cached_encoder(self, context: InvocationContext):- """Load the text encoder through the model cache (no quantization)."""++ def _load_cached_encoder(self, context: InvocationContext) -> _LoadedEncoder:++ """Load the text encoder through the model cache (no quantization). The cache stays the model's owner."""+ from transformers import Qwen2_5_VLForConditionalGeneration++ text_encoder_info = context.models.load(self.qwen_vl_encoder.text_encoder)+ ctx = text_encoder_info.model_on_device()+ _, text_encoder = ctx.__enter__()+ # 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)+- def _load_quantized_encoder(self, context: InvocationContext):++ def release() -> None:++ ctx.__exit__(None, None, None)++++ return text_encoder, device, release++++ def _load_quantized_encoder(self, context: InvocationContext) -> _LoadedEncoder:+ """Load the text encoder with BitsAndBytes quantization, bypassing the model cache.++ BnB-quantized models are pinned to GPU and can't be moved between devices,+ so they can't go through the standard model cache. The model is loaded fresh+ each time and freed after use via the cleanup callback.++++ Because the load bypasses the cache, it also bypasses the cache's usual++ make-room-for-the-model-being-locked step, so this path has to ask the cache++ for VRAM explicitly. Without that, whatever the resident transformer/VAE left++ free is all the encoder gets: `device_map="auto"` then silently plans to spill++ layers to the CPU, which BnB int8 refuses with "Some modules are dispatched on++ the CPU or the disk" (issue #9147).+ """- import gc+ import warnings+- from transformers import BitsAndBytesConfig, Qwen2_5_VLForConditionalGeneration++ from transformers import BitsAndBytesConfig, Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration++ encoder_config = context.models.get_config(self.qwen_vl_encoder.text_encoder)+ model_root = context.models.get_absolute_path(encoder_config)+ if model_root.is_file():+ # Single-file checkpoint (e.g. ComfyUI fp8_scaled): BnB can't load from+ # a single file, and the checkpoint is already FP8-compressed anyway.+ # Fall back to the cached path; the user effectively gets fp8 instead of+ # int8/nf4, which is comparable in size.+ return self._load_cached_encoder(context)+ encoder_path = model_root / "text_encoder"++ if self.quantization == "nf4":+ bnb_config = BitsAndBytesConfig(+ load_in_4bit=True,+ bnb_4bit_compute_dtype=torch.bfloat16,+ bnb_4bit_quant_type="nf4",+ )+ else: # int8+ bnb_config = BitsAndBytesConfig(load_in_8bit=True)+- context.util.signal_progress("Loading Qwen2.5-VL encoder (quantized)")- # Torch module construction is not thread-safe process-wide (see- # _ModelLoadReadWriteLock); serialize with the model-load machinery. The lock is- # the OUTER context on purpose: warnings.catch_warnings() swaps the process-global- # filter list, so holding it across an unbounded wait for the lock would leave this- # thread's filter installed — and clobberable by any other thread's- # SilenceWarnings — for the whole duration of someone else's model load.- with MODEL_LOAD_LOCK.write_lock(), 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,++ # Load onto this worker's execution device, never `device_map="auto"`: "auto" sizes its plan from whatever++ # VRAM is free *right now* and quietly spills to the CPU when the cached models fill the card, and it shards++ # across every visible GPU - in multi-GPU mode onto cards that belong to other workers, whose caches never++ # learn of the intrusion. The encoder therefore lives on this session's device only, and a genuine shortfall++ # surfaces as an OOM carrying the numbers (below) instead of a misleading offload error.++ device = TorchDevice.choose_torch_device()++ quantized_bytes = int(calc_model_size_by_fs(encoder_path) * _QUANTIZED_SIZE_RATIO[self.quantization])++ if quantized_bytes == 0:++ context.logger.warning(++ f"Could not determine the size of the Qwen2.5-VL encoder weights in {encoder_path}, so no room will "++ "be made for the quantized encoder in VRAM; the load may fail if the cached models fill the device."+ )+- device = next(text_encoder.parameters()).device++ context.util.signal_progress("Loading Qwen2.5-VL encoder (quantized)")+- def cleanup():- nonlocal text_encoder- del text_encoder++ # Three steps, each under the lock its kind of work requires (see MODEL_LOAD_LOCK), so that the process-global++ # lock is held no longer than necessary - while a writer holds it, or waits for it, every VRAM move on every++ # worker stalls, and every reader delays every cold model construction:++ # 1. the offload is a VRAM move like any other (`load_state_dict(assign=True)` -> `register_parameter`), so it++ # takes the read lock, acquired *before* the cache lock `make_room_in_vram` takes, per the lock-ordering++ # contract;++ # 2. the checkpoint read takes no lock: it creates no parameters and touches no global state, and it is the++ # slow part on anything but NVMe. It runs after the offload so the offload's RAM cannot evict its pages;++ # 3. the construction takes the WRITE lock, like every construction. It cannot run alongside another++ # construction: `from_pretrained` builds under process-global save/restore patches (`torch.set_default_dtype`,++ # `PreTrainedModel.tie_weights`, `torch.linspace`), which two overlapping builds would restore in the wrong++ # order and leave installed. It cannot run alongside VRAM moves either, in either direction: a cache++ # construction's `accelerate.init_empty_weights` patch would strand the weights it assigns (through++ # `setattr` -> `register_parameter`) on the meta device, and its own `torch.set_default_dtype` would change++ # what a concurrent move allocates. TestTransformersLoadPathAssumptions pins both facts against the++ # installed transformers.++ vram_available: int | None = None++ state_dict: dict[str, torch.Tensor] | None = None++ try:++ # A CPU execution device has no VRAM to make room in (recent bitsandbytes can quantize on the CPU).++ if quantized_bytes > 0 and device.type != "cpu":++ with MODEL_LOAD_LOCK.read_lock():++ vram_available = context.models.make_room_in_vram(quantized_bytes)++ if vram_available < quantized_bytes:++ context.logger.warning(++ f"Only {max(vram_available, 0) / MB:.0f} MB of VRAM could be made available on {device} for "++ f"the {self.quantization}-quantized Qwen2.5-VL encoder (~{quantized_bytes / MB:.0f} MB); "++ "locked (in-use) models cannot be offloaded. The load may run out of memory."++ )++++ model_config = Qwen2_5_VLConfig.from_pretrained(str(encoder_path), local_files_only=True)++ state_dict = _read_checkpoint(encoder_path)++++ with MODEL_LOAD_LOCK.write_lock(), 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(++ None if state_dict is not None else str(encoder_path),++ config=model_config,++ state_dict=state_dict,++ quantization_config=bnb_config,++ device_map={"": device},++ dtype=torch.bfloat16,++ local_files_only=True,++ )++ except BaseException as exc:++ # A failed load (an OOM is the expected way) leaves the partially built model referenced only by the++ # in-flight traceback's frames. Without releasing it here its weights stay allocated until the session++ # processor drops the exception, and *reserved* by torch after that, so the next load under-budgets -++ # the very leak `_encode` guards against on the success path. This frame is still executing and is++ # skipped by `clear_frames`, hence the explicit drop of the checkpoint.++ traceback.clear_frames(exc.__traceback__)++ state_dict = None++ gc.collect()++ try:++ TorchDevice.empty_cache()++ except Exception as cache_exc:++ # A sick device context fails here too; the original error is the one worth reporting.++ context.logger.warning(f"Could not empty the device cache after the failed load: {cache_exc}")++ if isinstance(exc, torch.OutOfMemoryError):++ raise torch.OutOfMemoryError(self._oom_message(device, quantized_bytes, vram_available)) from exc++ raise++++ # Hand the model out without keeping a reference in this closure, so that once `_encode` drops its own the++ # weights are actually free by the time empty_cache() runs.++ def cleanup() -> None:+ gc.collect()+ TorchDevice.empty_cache()++ return text_encoder, device, cleanup++++ def _oom_message(self, device: torch.device, quantized_bytes: int, vram_available: int | None) -> str:++ if quantized_bytes == 0:++ sizing = "its size could not be estimated, so no room was made for it"++ elif vram_available is None:++ sizing = (++ f"it needs about {quantized_bytes / MB:.0f} MB, and offloading the cached models to make room failed"++ )++ else:++ sizing = (++ f"it needs about {quantized_bytes / MB:.0f} MB and {vram_available / MB:.0f} MB was available after "++ "offloading the cached models (locked, in-use models cannot be offloaded)"++ )++ return (++ f"Not enough VRAM on {device} for the {self.quantization}-quantized Qwen2.5-VL encoder: {sizing}. Try "++ "'nf4' quantization, or 'none', which loads the encoder through the model cache and can partially "++ "offload it. In a multi-GPU setup the encoder is loaded onto this session's device only."++ )diff --cc invokeai/backend/model_manager/load/model_cache/model_cache.pyindex ae883c3eb9,19926f1d13..3c1dce5641--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@@ -2283,16 -2109,16 +2283,19 @@@ class ModelCachekeep_required_weights_in_vram=keep_required_weights_in_vram,)-- def _get_vram_available(self, working_mem_bytes: Optional[int]) -> int:++ def _get_vram_available(self, working_mem_bytes: Optional[int], honor_cap: bool = True) -> int:"""Calculate the amount of additional VRAM available for the cache to use (takes into account the workingmemory).++++ `honor_cap=False` measures the device instead of `max_vram_cache_size_gb`: see++ `_get_physical_vram_available`."""working_mem_bytes_default = int(self._execution_device_working_mem_gb * GB)working_mem_bytes = max(working_mem_bytes or working_mem_bytes_default, working_mem_bytes_default)# An explicit cache cap limits model residency, but operation-specific working# memory still must remain free for activations and temporary tensors.-- if self._max_vram_cache_size_gb is not None:++ if honor_cap and self._max_vram_cache_size_gb is not None:vram_total_available_to_cache = int(self._max_vram_cache_size_gb * GB) - working_mem_bytesreturn vram_total_available_to_cache - self._get_vram_in_use()@@@ -2332,35 -2152,39 +2335,51 @@@vram_cur_available_to_cache = vram_total_available_to_cache - self._get_vram_in_use()return vram_cur_available_to_cache+ def _get_reclaimable_allocator_bytes(self) -> int:+ """Bytes the torch caching allocator holds for this device but is not using, excluding+ inactive-split slack (free space inside partially-occupied segments, which cannot serve a+ large contiguous allocation and which empty_cache() cannot return to the driver).++ Best-effort: 0 when the backend does not expose allocator stats, and 0 under+ expandable-segments mode — there, freed blocks inside a segment are NOT counted as+ inactive splits, empty_cache() reclaims nothing, and a large allocation cannot use the+ holes, so the whole (reserved - allocated) figure is untrustworthy (a measured hard OOM+ on an allocation the credited budget claimed would fit).+ """+ if _expandable_segments_enabled():+ return 0+ try:+ if self._execution_device.type == "cuda":+ reserved = torch.cuda.memory_reserved(self._execution_device)+ allocated = torch.cuda.memory_allocated(self._execution_device)+ stats = torch.cuda.memory_stats(self._execution_device)+ elif self._execution_device.type == "xpu":+ reserved = torch.xpu.memory_reserved(self._execution_device)+ allocated = torch.xpu.memory_allocated(self._execution_device)+ stats = torch.xpu.memory_stats(self._execution_device)+ else:+ return 0+ inactive_split = int(stats.get("inactive_split_bytes.all.current", 0))+ return max(0, int(reserved) - int(allocated) - inactive_split)+ except Exception:+ return 0++ def _get_physical_vram_available(self) -> int:+ """VRAM a load *outside* the cache can still take on the execution device, less the configured working-memory+ reserve.++ Unlike `_get_vram_available`, this ignores `max_vram_cache_size_gb`: the cap limits how much of the card the+ cache may occupy, but an out-of-cache model (e.g. the BitsAndBytes-quantized Qwen encoder) is not subject to+ it - its only limit is what the device physically has free. Measuring the cap here would report a shortfall+ on every run and offload every unlocked model regardless of how much room the card has.+- Memory the torch allocator holds reserved-but-unallocated counts as available too: that is where offloaded- weights go until the offload's trailing `empty_cache()`, and the allocator reuses it for the next allocation,- so the offload loop can see its progress.++ The device measurement is the same one `lock()` budgets from, including its credit for the allocator's++ reclaimable reserve (`_get_reclaimable_allocator_bytes`), where offloaded weights sit until the offload's++ trailing `empty_cache()`. Crediting the raw reserved-minus-allocated figure instead over-reports under++ expandable segments and by intra-segment slack — the measured-OOM cases that helper exists to exclude.+ """- working_mem_bytes = int(self._execution_device_working_mem_gb * GB)- device = self._execution_device- if device.type == "cuda":- vram_free, _vram_total = torch.cuda.mem_get_info(device)- reusable = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)- elif device.type == "xpu" and _has_dedicated_vram(device):- vram_free, _vram_total = TorchDevice.xpu_mem_get_info(device)- reusable = torch.xpu.memory_reserved(device) - torch.xpu.memory_allocated(device)- elif device.type in ("mps", "xpu"):- # Shared-memory devices: "VRAM" is system RAM, and the device allocator's cached-but-unused memory is- # still the pool an offloaded model's weights land in (as in `_get_vram_available`).- vram_free = psutil.virtual_memory().available- if device.type == "mps":- reusable = torch.mps.driver_allocated_memory() - torch.mps.current_allocated_memory()- else:- reusable = torch.xpu.memory_reserved(device) - torch.xpu.memory_allocated(device)- else:- raise ValueError(f"Unsupported execution device: {device.type}")- return vram_free + reusable - working_mem_bytes++ return self._get_vram_available(None, honor_cap=False)+def _get_vram_in_use(self) -> int:"""Get the amount of VRAM currently in use by the cache."""if self._execution_device.type == "cuda":diff --cc invokeai/backend/model_manager/load/model_loaders/anima.pyindex 9af0d2c24c,5689665c11..faf8632df2--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@@ -19,23 -19,9 +19,24 @@@ from invokeai.backend.model_manager.taxModelType,SubModelType,)+from invokeai.backend.quantization.fp8_scaled import (+ attach_fp8_scales,+ cast_state_dict,+ dequantize_fp8_scaled,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ full_precision_hints_respected,+ parse_quantization_metadata,+ predict_cast_state_dict_size,+ read_safetensors_metadata,+ should_keep_fp8_weights,+ split_fp8_scaled_layers,+ strip_layer_path_prefix,+ warn_on_unattached_scales,+)from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILogger+ from invokeai.backend.util.state_dict_loading import log_unexpected_keys, reject_incomplete_loadlogger = InvokeAILogger.get_logger(__name__)@@@ -203,40 -162,27 +204,36 @@@ class AnimaCheckpointModel(ModelLoader)with accelerate.init_empty_weights():model = AnimaTransformer(**ANIMA_TRANSFORMER_CONFIG)- # Determine safe dtype- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_anima_inference_dtype(target_device)-- # Handle memory management- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())- self._ram_cache.make_room(new_sd_size)+ skip_patterns = _model_declared_skip_patterns(model)+ # Layers the cast would dequantize anyway are folded here, scale applied, so the cast never+ # strips a scale that can no longer be put back.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would+ # charge those 1 byte/element and arrive at 2.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ scaled_layers=fp8_layers,+ )+ )- # Convert to target dtype (skip non-float tensors like embedding indices)- for k in sd.keys():- if sd[k].is_floating_point():- sd[k] = sd[k].to(model_dtype)+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)load_result = model.load_state_dict(sd, assign=True, strict=False)- if load_result.unexpected_keys:- raise RuntimeError(- f"Checkpoint contains {len(load_result.unexpected_keys)} unexpected keys. "- f"This may indicate a corrupted or incompatible checkpoint. "- f"First 5 unexpected keys: {load_result.unexpected_keys[:5]}"- )- if load_result.missing_keys:- logger.warning(- f"Checkpoint is missing {len(load_result.missing_keys)} keys "- f"(expected for inv_freq buffers). First 5: {load_result.missing_keys[:5]}"- )+ log_unexpected_keys("Anima transformer checkpoint", load_result.unexpected_keys)+ # `missing_keys` alone cannot police completeness here: AnimaTransformer's only three buffers+ # are registered `persistent=False`, so they never appear in it (the old warning claiming+ # otherwise was misleading). Sweep for tensors the checkpoint left on the meta device instead+ # — that is the failure worth catching, and it is what the removed unexpected-key+ # `RuntimeError` was really standing in for.+ reject_incomplete_load(model, what="Anima transformer checkpoint")# Without this the `fp8_storage` toggle is shown for Anima models but does nothing. The# state dict was cast to a single `model_dtype` above, so the layerwise cast has onediff --cc invokeai/backend/model_manager/load/model_loaders/flux.pyindex 7e1dfc9a8a,f31f58710c..65360d2dca--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@@ -738,77 -720,12 +743,77 @@@ class FluxCheckpointModel(ModelLoader)sd = load_file(model_path)if "model.diffusion_model.double_blocks.0.img_attn.norm.key_norm.scale" in sd:sd = convert_bundle_to_flux_transformer_checkpoint(sd)- new_sd_size = sum([ten.nelement() * torch.bfloat16.itemsize for ten in sd.values()])- self._ram_cache.make_room(new_sd_size)- for k in sd.keys():- # We need to cast to bfloat16 due to it being the only currently supported dtype for inference- sd[k] = sd[k].to(torch.bfloat16)++ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight, optionally an input+ # scale). Read *after* the bundle conversion: the scale keys carry the same+ # `model.diffusion_model.` prefix as the weights and only line up with the module tree once+ # it has been stripped. Until now the loader had no idea these keys existed and+ # `load_state_dict` rejected the checkpoint outright as unexpected keys.+ #+ # Unlike FLUX.2 there is no key conversion here: the checkpoint is already in the BFL+ # layout this model implements, and `qkv` stays one fused Linear, so a per-tensor scale+ # attaches to exactly the module it was computed for.+ #+ # Hints ship either in the safetensors header or as per-layer `.comfy_quant` markers; the+ # header wins on the rare checkpoint carrying both.+ metadata = read_safetensors_metadata(model_path, self._logger)+ # Header names still carry the checkpoint prefix that was stripped off `sd`; strip it from+ # them too, or every per-layer flag matches nothing.+ layer_hints = {+ **extract_comfy_quant_hints(sd),+ **strip_layer_path_prefix(parse_quantization_metadata(metadata)),+ }+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)++ # A checkpoint that ships raw fp8 weights (fp8 tensors, no weight_scale) keeps them when the+ # fp8 matmul is available; casting them to bf16 here would throw away both the VRAM saving+ # and the tensor cores before the model is ever built.+ keep_fp8 = should_keep_fp8_weights(self._torch_device)+ if fp8_layers and not keep_fp8:+ # Without the matmul, keeping them quantized would halve VRAM but dequantize on every+ # forward. Fold the scale into the weight instead — the legacy result, except the scale+ # is now actually applied rather than dropped.+ dequantize_fp8_scaled(sd, fp8_layers, torch.bfloat16)+ fp8_layers = {}++ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so+ # `cast_state_dict` never strips a scale that can no longer be put back.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would+ # charge those 1 byte/element and arrive at 2.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(+ sd,+ torch.bfloat16,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ scaled_layers=fp8_layers,+ )+ )++ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns)+ # Everything else is cast to bfloat16, the only dtype currently supported for inference.+ kept = cast_state_dict(sd, torch.bfloat16, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)- model.load_state_dict(sd, assign=True)+ load_state_dict_ignoring_extras(model, sd, source="FLUX transformer checkpoint", assign=True)++ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ self._logger.info(f"FLUX: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")+ warn_on_unattached_scales(self._logger, "FLUX", attached, fp8_layers)+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)+ if marked and full_precision_hints_respected():+ self._logger.info(+ f"FLUX: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "+ "and will dequantize per forward. Set fp8_compute_full_precision_hints=false to run "+ "them on the fp8 tensor cores instead."+ )+ elif kept:+ self._logger.info(f"FLUX: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")+return model@@@ -1180,45 -1068,16 +1185,45 @@@ class Flux2CheckpointModel(ModelLoader)out_features2, in_features2, dtype=torch.bfloat16)- # Convert to bfloat16 and load- for k in converted_sd.keys():- converted_sd[k] = converted_sd[k].to(torch.bfloat16)+ # Convert to bfloat16 and load, leaving raw fp8 weights quantized when the tensor cores can+ # take them (the scaled-fp8 path above has already folded any weight_scale it found). The+ # model's own precision-sensitive list is honored — see the Z-Image loader for why that is+ # a correctness requirement and not just a quality nicety.+ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers the cast would dequantize anyway are folded here, scale applied, so+ # `cast_state_dict` never strips a scale that can no longer be put back.+ fp8_layers = split_fp8_scaled_layers(+ converted_sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns+ )++ kept = cast_state_dict(+ converted_sd,+ torch.bfloat16,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )# Load the state dict - guidance weights were already initialized above if missing- model.load_state_dict(converted_sd, assign=True)+ load_state_dict_ignoring_extras(model, converted_sd, source="FLUX.2 transformer checkpoint", assign=True)+ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ self._logger.info(f"FLUX.2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")+ warn_on_unattached_scales(self._logger, "FLUX.2", attached, fp8_layers)+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)+ if marked and full_precision_hints_respected():+ self._logger.info(+ f"FLUX.2: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "+ "and will dequantize per forward. Set fp8_compute_full_precision_hints=false to run "+ "them on the fp8 tensor cores instead."+ )+ elif kept:+ self._logger.info(f"FLUX.2: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")+return model- def _dequantize_fp8_weights(self, sd: dict) -> dict:+ def _dequantize_fp8_weights(self, sd: dict, keep_fp8: bool = False) -> dict:"""Dequantize FP8 quantized weights in the state dict.ComfyUI and some FLUX.2 models store quantized weights as:diff --cc invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 96ea1a0c70,e6b0b55475..051a41d9af--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@@ -28,41 -24,23 +28,42 @@@ from invokeai.backend.model_manager.taxModelType,SubModelType,)+from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_config+from invokeai.backend.quantization.fp8_scaled import (+ attach_fp8_scales,+ cast_state_dict,+ dequantize_fp8_scaled,+ detach_layer_sidechannel,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ full_precision_hints_respected,+ parse_quantization_metadata,+ predict_cast_state_dict_size,+ read_safetensors_metadata,+ reattach_layer_sidechannel,+ should_keep_fp8_weights,+ split_fp8_scaled_layers,+ strip_layer_path_prefix,+ warn_on_unattached_scales,+)from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from invokeai.backend.quantization.int8_convrot import (+ cast_unquantized,+ drop_unconsumed_quantization_sidecars,+ extract_int8_convrot_markers,+ predict_int8_cast_size,+ reject_foreign_quantization_scales,+ reject_unmarked_int8_weights,+ resolve_quantized_module_paths,+ split_int8_convrot_layers,+ swap_in_int8_linears,+)from invokeai.backend.util.devices import TorchDevice+ from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, reject_incomplete_load-if TYPE_CHECKING:- # torch is imported lazily inside the helpers below; this is annotations-only.- import torch---def _normalize_qwen3vl_rope_config(config: Any) -> Any:- """Mirror Qwen3-VL rope_parameters into rope_scaling for Transformers compatibility."""- text_config = getattr(config, "text_config", None)- if text_config is not None:- rope_params = getattr(text_config, "rope_parameters", None)- if getattr(text_config, "rope_scaling", None) is None and rope_params is not None:- text_config.rope_scaling = rope_params- return config+# Kept as a module-level alias: this helper moved to model_manager.util.qwen3_vl so the MiniMax H3+# loader can share it without importing across family loaders.+_normalize_qwen3vl_rope_config = normalize_qwen3vl_rope_configdef _strip_comfyui_prefix(sd: dict[str, Any]) -> dict[str, Any]:@@@ -465,69 -364,14 +466,71 @@@ class Krea2CheckpointModel(ModelLoader)with accelerate.init_empty_weights():model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())- self._ram_cache.make_room(new_sd_size)- for k in sd.keys():- sd[k] = sd[k].to(model_dtype)+ if int8_markers:+ # Honor the model's own precision-sensitive list here too, not only on the fp8 side.+ # Krea-2 declares `time_embed` and the `norm*` modules; `time_embed.linear_1/linear_2`+ # are ordinary quantized Linears in a ComfyUI export, and a module that reads its own+ # weight's dtype finds `torch.int8` on an `Int8ConvrotLinear`.+ skip_patterns = _model_declared_skip_patterns(model)++ # Before anything is cast: a scale left over from another scheme means its weight is+ # about to be cast without it, and the orphan disappears into `strict=False` below.+ # After the model exists, so a merged file's bundled submodels -- which this loader does+ # not prefix-filter out and never loads -- cannot fail a checkpoint that works.+ reject_foreign_quantization_scales(sd, quantized, "Krea-2", model)++ # Reserve before the split, not after: the split dequantizes the layers it widens, so+ # reserving afterwards lets that transient land on an unreserved cache. The prediction+ # is given the same inputs, so it charges those layers the compute dtype's width and+ # the int8 payloads their actual one byte -- reserving two would ask the cache to free+ # ~12 GB that this load never uses.+ self._ram_cache.make_room(+ predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns)+ )+ quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)+ cast_unquantized(sd, model_dtype, quantized)+ swap_in_int8_linears(model, sd, quantized)+ # The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.+ fp8_layers = {}+ kept = 0+ else:+ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers the cast would dequantize anyway (skip patterns, non-Linear weights) are+ # folded here, with their scale applied. Left to `cast_state_dict` they would be cast+ # *without* it and `attach_fp8_scales` would then skip them for no longer being fp8 —+ # a weight silently off by 1/weight_scale. Krea-2's `time_embed.linear_1/linear_2` are+ # ordinary quantized Linears in a ComfyUI export and match the model's `time_embed` pattern.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would+ # charge those 1 byte/element and arrive at 2.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ scaled_layers=fp8_layers,+ )+ )++ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ # A checkpoint with raw fp8 weights (fp8 tensors and no weight_scale) yields no fp8_layers at+ # all, but its weights are still usable on the tensor cores, so the same `keep_fp8` covers+ # both kinds.+ kept = cast_state_dict(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )- model.load_state_dict(sd, assign=True, strict=False)+ load_state_dict_ignoring_extras(+ model, sd, source="Krea-2 single-file checkpoint", assign=True, allow_missing=True+ )_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")# `assign=True` aliases every param to its `sd` tensor. Drop the dict's references before# the FP8 cast, or each param's `model_dtype` original stays reachable while its fp8 copy is@@@ -858,95 -589,16 +847,97 @@@ class Qwen3VLEncoderCheckpointLoader(Mowith accelerate.init_empty_weights():model = Qwen3VLModel._from_config(te_config)- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())- self._ram_cache.make_room(new_sd_size)- for k in sd.keys():- sd[k] = sd[k].to(model_dtype)+ if int8_markers:+ # `Qwen3VLModel` declares no precision-sensitive modules, but read them rather than+ # assume: the split is also what keeps a marker on a non-Linear (a "quantize+ # everything" repack's 1-D norms) out of `swap_in_int8_linears`.+ skip_patterns = _model_declared_skip_patterns(model)++ # Before anything is cast: a scale left over from another scheme means its weight is+ # about to be cast without it, and the orphan disappears into `strict=False` below.+ reject_foreign_quantization_scales(sd, quantized, "Qwen3-VL encoder", model)++ # Reserve before the split -- it dequantizes the layers it widens -- and charge the int8+ # payloads their actual one byte rather than the compute dtype's two.+ self._ram_cache.make_room(+ predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns)+ )+ quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)+ cast_unquantized(sd, model_dtype, quantized)+ swap_in_int8_linears(model, sd, quantized)+ else:+ # Same ordering contract as every other loader in this series: split *before* the cast.+ # A per-key `if dtype is not FP8_DTYPE` cast looks equivalent and is not — it keeps every+ # fp8 tensor quantized, including the ones that must not stay:+ #+ # - a 1-D fp8 norm (checkpoints that "quantize everything" ship these) would keep its+ # scale as an unused buffer on a non-Linear and the forward would compute on the raw+ # fp8 codes, i.e. off by 1/weight_scale with nothing logged;+ # - an e5m2 scaled weight would be cast *without* its scale, since only e4m3fn is spared;+ # - a block-wise scale would reach `scaled_mm_linear` unchecked and raise mid-generation.+ #+ # `split_fp8_scaled_layers` applies exactly those filters and dequantizes the affected+ # layers *with* their scale, so what remains is what the matmul can actually consume.+ # The storage path below re-quantizes to fp8 anyway, so casting the raw fp8 Linears to+ # `model_dtype` here would double both this reservation and the host-RAM peak (~4.4 -> ~8.9+ # GiB on the 4B encoder) for a round trip that ends where it started -- e4m3fn is a subset+ # of bf16, so it is value-exact. Keep them for either consumer.+ use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)+ keep_fp8 = keep_matmul_fp8 or use_fp8_storage+ # Reserve before the split: it dequantizes its unusable subset through fp32, so reserving+ # afterwards lets that transient peak land on an unreserved cache. `scaled_layers` keeps the+ # prediction in step with the split's own scale-layout filter.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, scaled_layers=fp8_layers)+ )+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)+ # No `skip_patterns` here on purpose: this model declares none, and the storage pass below+ # applies `_FP8_DEFAULT_SKIP_PATTERNS` itself. Those two lists used to have to not intersect+ # on a 2-D Linear -- such a weight would arrive fp8 from the state dict, be skipped by the+ # cast pass, and forward on raw fp8 codes. `_apply_fp8_to_nn_module` now restores the compute+ # dtype on the modules it skips, so the two lists are independent again.+ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)- model.load_state_dict(sd, assign=True, strict=False)+ load_state_dict_ignoring_extras(+ model, sd, source="Qwen3-VL encoder checkpoint", assign=True, allow_missing=True+ )_reject_incomplete_load(model, what="Qwen3-VL encoder checkpoint")+ if fp8_layers:+ # Keep the weights quantized and let CustomLinear run their matmuls on the fp8 tensor+ # cores. Same resident VRAM as the layerwise-casting path below, but without paying a+ # fp8->bf16 round trip on every forward.+ attached = attach_fp8_scales(model, fp8_layers)+ warn_on_unattached_scales(self._logger, f"Qwen3-VL encoder '{config.name}'", attached, fp8_layers)+ # The checkpoint quantizes only the language-model linears; the visual tower ships bf16+ # and would make the encoder ~0.4GB larger resident than the plain fp8_storage path. On a+ # GPU already holding a ~12GB transformer that is enough to push the transformer into+ # partial loading, so cast the rest to fp8 storage. Two exclusions:+ #+ # - anything carrying a `weight_scale`: those keep their scale and go through+ # _scaled_mm; the cast hooks would upcast them without it, i.e. a wrong weight.+ # - `nn.Embedding`: the token embedding table is this model's *input* representation+ # and it is large (389M params). Measured on qwen3vl_4b_fp8_scaled, quantizing it+ # doubles the encoder's error against bf16 (relative L2 0.0079 -> 0.0163) to save+ # 371MiB. That is a bad trade for a model whose entire job is text fidelity. (The+ # old fp8_storage path did cast it — this is strictly more accurate than before.)+ self._apply_fp8_to_nn_module(+ model,+ storage_dtype=torch.float8_e4m3fn,+ compute_dtype=model_dtype,+ skip=lambda _name, module: getattr(module, "weight_scale", None) is not None+ or isinstance(module, torch.nn.Embedding),+ )+ self._logger.info(+ f"FP8 compute enabled for Qwen3-VL encoder '{config.name}': kept {attached} layer(s) "+ f"quantized (storage=float8_e4m3fn, matmul=torch._scaled_mm, compute={model_dtype}); "+ "remaining layers cast to fp8 storage."+ )+ # The layerwise-casting path below exists to *produce* fp8 weights from full-precision+ # ones. These already are fp8, and its hooks would cast them to the compute dtype without+ # applying weight_scale — a silently wrong weight. It must not run here.+ return model+# Keep an fp8 encoder running in fp8 (storage=float8_e4m3fn, per-layer upcast to the compute# dtype during forward) on devices that support fp8 storage. `_should_use_fp8` deliberately# excludes text encoders (and the config has no fp8_storage toggle), so apply the hook-baseddiff --cc invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex d751a209e6,b933aebd6a..31a8743a02--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@@ -1000,14 -953,8 +1001,13 @@@ class MistralEncoderCheckpointLoader(Mowith accelerate.init_empty_weights():model = MistralModel(mistral_config)+ # Layers the cast would dequantize anyway are folded here, scale applied, so the cast never+ # strips a scale that can no longer be put back.+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)+ cast_state_dict(sd, model_dtype, keep_fp8=bool(fp8_layers), model=model)+missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)- if unexpected:- logger.debug(f"Mistral encoder: ignored {len(unexpected)} unexpected keys")+ log_unexpected_keys("Mistral encoder checkpoint", unexpected)if missing:# Re-initialize any RMSNorm weights that may have been pruned during repackaging.for name in missing:diff --cc invokeai/backend/model_manager/load/model_loaders/z_image.pyindex d008478129,a01c854ccf..60e8b269d3--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@@ -72,32 -39,9 +72,33 @@@ from invokeai.backend.quantization.sdnqfrom invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loaderfrom invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizerfrom invokeai.backend.util.devices import TorchDevice+ from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, log_unexpected_keys+def _remap_z_image_layer_paths(layer_names: Any) -> dict[str, list[str]]:+ """Map native Z-Image layer paths to their diffusers equivalents.++ ``_quantization_metadata`` names its layers in the checkpoint's own scheme, but the scales are+ extracted after the state dict has been renamed. Rather than restating the rename rules — which+ would drift — each name is pushed through the real converter as a lone ``<name>.weight`` entry+ and the resulting keys are read back. A fused ``qkv`` maps to *three* diffusers layers, so the+ mapping is one-to-many.+ """+ mapping: dict[str, list[str]] = {}+ for name in layer_names:+ if not isinstance(name, str):+ continue+ try:+ # 3 rows so the qkv split is well-defined; the values themselves are never read.+ converted = _convert_z_image_gguf_to_diffusers({f"{name}.weight": torch.empty(3, 1)})+ except Exception:+ continue+ targets = [k[: -len(".weight")] for k in converted if isinstance(k, str) and k.endswith(".weight")]+ if targets:+ mapping[name] = targets+ return mapping++def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:"""Convert Z-Image GGUF state dict keys to diffusers format.@@@ -546,107 -474,15 +547,107 @@@ class ZImageCheckpointModel(ModelLoaderfor k in keys_to_remove:del sd[k]- # Handle memory management and dtype conversion- new_sd_size = sum([ten.nelement() * model_dtype.itemsize for ten in sd.values()])- self._ram_cache.make_room(new_sd_size)+ # Two ComfyUI side-channel formats reach this loader, and a checkpoint carries one or the+ # other: `comfy_quant` names its format per layer, and `int8_tensorwise` never appears in a+ # file that also ships fp8 weight scales. Deciding once, up front, keeps the two casts from+ # having to understand each other -- `cast_unquantized` treats int8 payloads as opaque,+ # `cast_state_dict` reasons about fp8 matmul eligibility, and neither is correct for the+ # other's tensors.+ int8_markers = extract_int8_convrot_markers(sd)++ # Outside the branch on purpose -- see the helper, which explains why.+ reject_unmarked_int8_weights(sd, int8_markers, "Z-Image")++ if int8_markers:+ # Markers are read *after* the key conversion above, which carries them (and their+ # scales) through the fused-QKV split onto the module names the model actually has --+ # so no re-keying is needed here.+ #+ # Filtered in place rather than rebound: the `sd.clear()` below has to reach the same+ # dict the checkpoint was read into, or the originals stay alive through it and peak+ # RAM overshoots the `make_room()` reservation (see+ # test_state_dict_is_released_before_the_fp8_cast).+ kept_sd = drop_unconsumed_quantization_sidecars(sd)+ sd.clear()+ sd.update(kept_sd)+ del kept_sd++ # Honor the model's own precision-sensitive list here too, not only on the fp8 side.+ # Z-Image declares ["t_embedder", "cap_embedder"] because+ # `ZImageTimestepEmbedder.forward` reads `self.mlp[0].weight.dtype` to pick the dtype+ # it casts its activations to; on an `Int8ConvrotLinear` that reads `torch.int8`, the+ # forward falls through to a `compute_dtype` attribute these modules do not have, and+ # the timestep branch silently runs in float32 into a bf16 model.+ skip_patterns = _model_declared_skip_patterns(model)++ # Reserve before the split, not after: the split dequantizes the layers it widens, so+ # reserving afterwards lets that transient land on an unreserved cache. The prediction+ # is given the same inputs, so it charges those layers the compute dtype's width and+ # the int8 payloads their actual one byte -- reserving two would ask the cache to free+ # memory this load never uses.+ self._ram_cache.make_room(+ predict_int8_cast_size(sd, model_dtype, int8_markers, model=model, skip_patterns=skip_patterns)+ )- # Convert to target dtype- for k in sd.keys():- sd[k] = sd[k].to(model_dtype)+ quantized = split_int8_convrot_layers(+ sd, int8_markers, model_dtype, model=model, skip_patterns=skip_patterns+ )+ cast_unquantized(sd, model_dtype, quantized)+ swap_in_int8_linears(model, sd, quantized)+ # The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.+ fp8_layers: dict[str, Any] = {}+ kept = 0+ else:+ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight). Until now the loader+ # deleted those scales and cast the weight — silently producing a weight off by+ # 1/weight_scale — and had no way to tell such a checkpoint from a raw fp8 one.+ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)++ # Handle memory management and dtype conversion. A checkpoint that ships raw fp8 weights+ # (fp8 tensors, no weight_scale) keeps them when the fp8 matmul is available — casting+ # them here would discard both the VRAM saving and the tensor cores before the model is+ # built.+ keep_fp8 = should_keep_fp8_weights(self._torch_device)+ if fp8_layers and not keep_fp8:+ # Legacy behavior, but now with the scale actually applied: fold it into the weight.+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)+ fp8_layers = {}++ # Honor the model's own precision-sensitive list. Z-Image declares+ # ["t_embedder", "cap_embedder"], and `TimestepEmbedder.forward` casts its activations to+ # `self.mlp[0].weight.dtype` — an fp8 weight there turns the activations fp8 and the+ # forward dies in `x.abs()`. Those layers must be dequantized even though the rest stays+ # quantized.+ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so+ # `cast_state_dict` never strips a scale it cannot put back.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens+ # layers whose scale layout `scaled_mm` cannot apply, and without the mapping the+ # prediction would charge those 1 byte/element and arrive at 2.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ scaled_layers=fp8_layers,+ )+ )++ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ kept = cast_state_dict(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )- model.load_state_dict(sd, assign=True)+ load_state_dict_ignoring_extras(model, sd, source="Z-Image transformer checkpoint", assign=True)# `assign=True` aliases every param to its `sd` tensor, so the dict keeps the whole model# alive a second time. The FP8 cast below allocates the fp8 copy per param while the# `model_dtype` original is still reachable through `sd`, pushing peak RAM to ~1.5x whatdiff --cc invokeai/backend/quantization/fp8_scaled.pyindex b59a03a45e,0000000000..599023e4efmode 100644,000000..100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@@ -1,1038 -1,0 +1,1059 @@@+"""Shared handling for ComfyUI-style "scaled fp8" checkpoints.++These checkpoints store each quantized Linear as:++ <path>.weight float8_e4m3fn+ <path>.weight_scale float32 (usually a scalar; per-output-channel also occurs)+ <path>.input_scale float32 (optional; a calibrated *static* activation scale)++so that ``w_real ≈ weight.to(float) * weight_scale``. Some producers use ``.scale_weight`` instead+of ``.weight_scale``. A ``_quantization_metadata`` entry in the safetensors header may additionally+mark individual layers with ``full_precision_matrix_mult``, meaning the producer determined that+this layer must not be multiplied in fp8.++Historically InvokeAI dequantized these to bf16 at load time (three near-identical implementations+in the FLUX.2, Z-Image and Qwen-Image loaders). That throws away both the VRAM saving and the+ability to run the matmul on the fp8 tensor cores. This module keeps the quantization intact so+that :class:`CustomLinear` can decide per forward what to do with it.+"""++from dataclasses import dataclass+from logging import Logger+from pathlib import Path+from typing import Any, Iterable, Mapping++import torch++FP8_DTYPE = torch.float8_e4m3fn++# Every float8 dtype a checkpoint may store weights in. Scale *recovery* must cover all of them:+# only `float8_e4m3fn` can stay quantized (see `can_stay_quantized`), but an `e5m2` weight still+# needs its `weight_scale` folded in on the way to bf16. Gating extraction on e4m3fn alone dropped+# the scale key and then cast the weight unscaled — off by `1/weight_scale`, silently.+FP8_WEIGHT_DTYPES = (torch.float8_e4m3fn, torch.float8_e5m2)++WEIGHT_SCALE_SUFFIXES = (".weight_scale", ".scale_weight")+# Both spellings occur, exactly as for the weight scale. ComfyUI normalizes `.scale_input` to+# `.input_scale` on load (comfy/utils.py, convert_old_quants); reading only one of them means a+# calibrated activation scale is silently discarded and every forward pays the amax reduction.+INPUT_SCALE_SUFFIXES = (".input_scale", ".scale_input")++QUANT_METADATA_KEY = "_quantization_metadata"++# Per-layer marker tensor written by ComfyUI exports that do not use the header entry above.+COMFY_QUANT_SUFFIX = ".comfy_quant"++# Standalone marker keys some producers emit alongside the tensors. They carry no per-layer data.+STRAY_METADATA_KEYS = ("scaled_fp8",)+++@dataclass+class Fp8ScaledLayer:+ """The quantization parameters recovered for a single Linear."""++ weight_scale: torch.Tensor+ """Scalar, or shape ``(out_features,)`` for per-output-channel quantization."""++ input_scale: torch.Tensor | None = None+ """Calibrated static activation scale, if the checkpoint ships one."""++ full_precision_matmul: bool = False+ """The producer marked this layer as unsafe for an fp8 matmul; only dequantized use is allowed."""++ def is_per_tensor(self) -> bool:+ return self.weight_scale.numel() == 1+++def read_safetensors_metadata(path: Path, logger: Logger | None = None) -> dict[str, str] | None:+ """Read the safetensors header metadata, or None if it cannot be read.++ Only used to enrich fp8 handling (per-layer ``full_precision_matrix_mult`` hints), so an+ unreadable header must not fail the model load. It is warned about rather than swallowed: without+ the hints, layers the quantizer marked as unsafe would silently be multiplied in fp8.+ """+ try:+ from safetensors import safe_open++ with safe_open(path, framework="pt") as f:+ return f.metadata()+ except Exception as e:+ if logger is not None:+ logger.warning(f"Could not read safetensors metadata from {path.name} ({e}); fp8 layer hints unavailable.")+ return None+++def parse_quantization_metadata(metadata: Mapping[str, Any] | None) -> dict[str, dict[str, Any]]:+ """Parse the safetensors ``_quantization_metadata`` header entry into a per-layer mapping.++ Returns an empty dict when the entry is absent or unparseable - the scales themselves are the+ source of truth, the metadata only adds per-layer hints.+ """+ if not metadata:+ return {}+ raw = metadata.get(QUANT_METADATA_KEY)+ if not raw:+ return {}+ if isinstance(raw, (bytes, bytearray)):+ raw = raw.decode("utf-8", errors="replace")+ if isinstance(raw, str):+ import json++ try:+ raw = json.loads(raw)+ except ValueError:+ return {}+ if not isinstance(raw, dict):+ return {}+ layers = raw.get("layers")+ return layers if isinstance(layers, dict) else {}+++def extract_comfy_quant_hints(sd: dict[str, Any]) -> dict[str, dict[str, Any]]:+ """Decode per-layer ``<path>.comfy_quant`` markers into the same mapping+ :func:`parse_quantization_metadata` produces, popping them out of ``sd``.++ ComfyUI writes the per-layer quantization flags in one of two places. Newer exports use the+ safetensors *header* (``_quantization_metadata``); others store one uint8 JSON blob per+ quantized layer as an ordinary tensor, e.g.::++ model.layers.0.mlp.down_proj.comfy_quant+ -> {"format": "float8_e4m3fn", "full_precision_matrix_mult": false}++ Both forms carry ``full_precision_matrix_mult`` - the producer's instruction that a layer must+ not be multiplied in fp8. A loader that reads only the header therefore *silently ignores that+ instruction* on a checkpoint using the per-tensor form, and runs an fp8 matmul the producer+ measured as unsafe. Checkpoints using the per-tensor form and marking layers this way exist in+ the wild, so both forms must be read.++ Malformed blobs are skipped rather than raised on: the marker is an optimization hint, and the+ scales themselves remain the source of truth.+ """+ import json++ hints: dict[str, dict[str, Any]] = {}+ for key in list(sd.keys()):+ if not isinstance(key, str) or not key.endswith(COMFY_QUANT_SUFFIX):+ continue+ raw = sd.pop(key)+ path = key[: -len(COMFY_QUANT_SUFFIX)]+ try:+ # A uint8 tensor holding UTF-8 JSON, sometimes NUL-padded to a fixed width.+ blob = bytes(raw.flatten().tolist()).decode("utf-8", errors="replace").rstrip("\x00")+ parsed = json.loads(blob)+ except Exception:+ continue+ if isinstance(parsed, dict):+ hints[path] = parsed+ return hints+++# Key prefixes redistributors wrap a transformer in. Loaders strip these off the state dict before+# anything else, so `_quantization_metadata` — which is read from the file and still carries them —+# has to be stripped the same way.+TRANSFORMER_KEY_PREFIXES = ("model.diffusion_model.", "diffusion_model.", "net.")+++def strip_layer_path_prefix(+ layer_hints: Mapping[str, Any],+ prefixes: Iterable[str] = TRANSFORMER_KEY_PREFIXES,+) -> dict[str, Any]:+ """Re-key ``layer_hints`` as if the checkpoint prefix had been stripped from their names.++ ``_quantization_metadata`` lives in the safetensors header, so its layer names are in the+ file's own scheme — ``model.diffusion_model.blocks.0.attn.wq`` — while the state dict has had+ that prefix removed before the scales are extracted. A hint whose name still carries the prefix+ matches no layer, so ``full_precision_matrix_mult`` is silently ignored and the producer's+ "do not multiply this one in fp8" instruction is disregarded: exactly the failure the hint+ plumbing exists to prevent.++ Names that carry none of ``prefixes`` are passed through unchanged. Dropping them instead — as+ running the names through a strip function that filters by prefix would — turns a+ partially-prefixed header into a silently truncated one, and can abort the load.+ """+ out: dict[str, Any] = {}+ for name, hints in layer_hints.items():+ if isinstance(name, str):+ for prefix in prefixes:+ if name.startswith(prefix):+ name = name[len(prefix) :]+ break+ out[name] = hints+ return out+++# Every per-layer side-channel suffix that belongs to a module rather than being a tensor of its+# own. Used by the detach/reattach pair below.+LAYER_SIDECHANNEL_SUFFIXES = WEIGHT_SCALE_SUFFIXES + INPUT_SCALE_SUFFIXES + (COMFY_QUANT_SUFFIX,)+++def detach_layer_sidechannel(sd: dict[str, Any]) -> dict[str, list[tuple[str, Any]]]:+ """Pop every per-layer quantization side-channel entry, keyed by the module path it belongs to.++ For loaders that rename checkpoint keys. Key converters are written against ``.weight`` — they+ match it as a substring, or test whole keys for equality — so a sibling ``.scale_weight`` or+ ``.input_scale`` is *not* carried along, and neither is any scale on a key the converter renames+ by equality. The scale is then orphaned under its old path while its weight moves, and+ :func:`extract_fp8_scaled_layers` drops it because no fp8 weight sits at the old path any more.+ The weight stays quantized with no scale attached and is off by ``1/weight_scale``, in silence:+ the layer never enters ``fp8_layers``, so :func:`warn_on_unattached_scales` cannot see it either.++ Take the side channel out of the way, convert, then :func:`reattach_layer_sidechannel`.+ """+ detached: dict[str, list[tuple[str, Any]]] = {}+ for key in list(sd.keys()):+ if not isinstance(key, str):+ continue+ for suffix in LAYER_SIDECHANNEL_SUFFIXES:+ if key.endswith(suffix):+ detached.setdefault(key[: -len(suffix)], []).append((suffix, sd.pop(key)))+ break+ return detached+++def reattach_layer_sidechannel(+ sd: dict[str, Any],+ detached: Mapping[str, list[tuple[str, Any]]],+ path_map: Mapping[str, str],+) -> list[str]:+ """Put detached side-channel entries back under their renamed module paths.++ Returns the module paths that could not be placed. A path with no entry in ``path_map`` had no+ destination in the converted state dict — usually because the converter drops that module+ outright — so its scale is dropped with it. Returning them rather than swallowing them lets the+ caller say so: a *silently* dropped scale is exactly the failure this pair exists to prevent.++ A destination counts as present when *any* tensor sits under it, not specifically a+ ``<path>.weight``. Requiring that name assumes every quantizable module stores its parameter as+ ``weight``, which is not true of the norms: a producer that quantizes them (the+ "quantizes everything" class documented in :func:`can_stay_quantized`) writes ``<path>.scale``,+ and the guard would reject the destination for the wrong reason and drop a scale it could have+ placed.+ """+ present_modules = {key.rsplit(".", 1)[0] for key in sd if isinstance(key, str) and "." in key}+ orphaned: list[str] = []+ for path, entries in detached.items():+ destination = path_map.get(path, path)+ if destination not in present_modules:+ orphaned.append(path)+ continue+ for suffix, value in entries:+ sd[f"{destination}{suffix}"] = value+ return orphaned+++def iter_weight_scale_pairs(sd: Mapping[str, Any]) -> Iterable[tuple[str, str]]:+ """Yield ``(weight_key, scale_key)`` for every weight scale in ``sd``, in either spelling.++ For loaders that fold the scale into the weight themselves instead of going through+ :func:`extract_fp8_scaled_layers`. Matching only ``.weight_scale`` is the failure that keeps+ recurring: a ``.scale_weight`` checkpoint then either loses its scales silently (if the loader+ strips both spellings afterwards, leaving the weight off by ``1/weight_scale``) or trips+ ``load_state_dict(..., strict=True)`` on the leftover key. Pairs whose ``.weight`` is absent are+ skipped, so a stray scale cannot invent one.+ """+ for key in list(sd.keys()):+ if not isinstance(key, str):+ continue+ for suffix in WEIGHT_SCALE_SUFFIXES:+ if key.endswith(suffix):+ weight_key = f"{key[: -len(suffix)]}.weight"+ if weight_key in sd:+ yield weight_key, key+ break+++# Per-layer quantization side-channel entries that sit next to a fused `qkv.weight` and therefore+# have to be carried through a split of it. The scale spellings are the ones this module accepts;+# the marker is a JSON blob describing the layer, identical for all three parts of the split.+QKV_SPLIT_SIDECHANNEL_SUFFIXES = ("weight_scale", "scale_weight", "input_scale", "scale_input", "comfy_quant")+++def split_qkv_sidechannel(key: str, value: Any) -> tuple[Any, Any, Any]:+ """Split a fused-QKV scale/marker into the parts belonging to Q, K and V.++ A per-tensor scale (and any marker blob) describes the whole fused tensor, so each third+ inherits it unchanged. A per-output-channel scale has one entry per row and is split exactly+ like the weight.++ Getting this wrong is silent: a scale left on the fused path is keyed on a module the split+ model does not have, so `attach_fp8_scales` finds nothing and the three weights stay quantized+ but *unscaled* -- off by 1/weight_scale, with no error anywhere.+ """+ tensor = torch.as_tensor(value) if hasattr(value, "shape") else value+ if not hasattr(tensor, "shape") or tensor.dim() == 0 or tensor.shape[0] == 1:+ return (tensor, tensor, tensor)+ if tensor.numel() == 1 or key.endswith(("comfy_quant", "input_scale", "scale_input")):+ # A marker blob is a 1-D byte string, not a per-channel vector -- never split it.+ return (tensor, tensor, tensor)+ if tensor.shape[0] % 3 != 0:+ raise ValueError(+ f"Cannot split fused QKV quantization data '{key}': first dimension ({tensor.shape[0]}) is "+ "neither 1 nor divisible by 3, so it matches neither a per-tensor nor a per-channel scale."+ )+ third = tensor.shape[0] // 3+ return (tensor[:third], tensor[third : 2 * third], tensor[2 * third :])+++def is_scale_metadata_key(key: Any) -> bool:+ """Whether ``key`` is fp8 scale/quantization metadata rather than a model tensor.++ Covers both spellings of the weight and input scales plus the marker keys producers emit, so+ callers strip exactly what they were able to interpret.+ """+ if not isinstance(key, str):+ return False+ return (+ key.endswith(WEIGHT_SCALE_SUFFIXES)+ or key.endswith(INPUT_SCALE_SUFFIXES)+ or COMFY_QUANT_SUFFIX.strip(".") in key+ or key in STRAY_METADATA_KEYS+ )+++def _strip_scale_suffix(key: str) -> tuple[str, bool] | None:+ """Return ``(module path, is_input_scale)``, or None if ``key`` is not a scale key."""+ for suffix in WEIGHT_SCALE_SUFFIXES:+ if key.endswith(suffix):+ return key[: -len(suffix)], False+ for suffix in INPUT_SCALE_SUFFIXES:+ if key.endswith(suffix):+ return key[: -len(suffix)], True+ return None+++def _usable_input_scale(scale: torch.Tensor | None) -> torch.Tensor | None:+ """A calibrated static activation scale, or None to fall back to per-forward ``amax`` scaling.++ An ``input_scale`` of exactly 1.0 is a placeholder: the producer wrote the field without+ calibrating it. Taking it at face value replaces the dynamic scale with *no scaling at all*, so+ every activation above the fp8 maximum saturates — far worse than the dynamic path it+ suppresses. ComfyUI drops the key in exactly this case (comfy/utils.py, convert_old_quants).++ Non-finite and non-positive scales are rejected for the same reason: they cannot be a valid+ divisor, and using one would produce inf/NaN activations instead of a slightly worse image.++ A multi-element ``input_scale`` is dropped rather than raising. ``scaled_mm_linear`` scales the+ activations by a single value, so there is nothing to do with a per-channel or per-block+ activation scale, and the dynamic per-forward ``amax`` path is a correct fallback. Reshaping it+ to a scalar unconditionally turned such a checkpoint into a `RuntimeError: shape '[]' is invalid+ for input of size N` at load time -- the one malformed side-channel in this module that neither+ skipped nor explained itself.+ """+ if scale is None:+ return None+ scale = scale.float()+ if scale.numel() != 1:+ return None+ scale = scale.reshape(())+ if not torch.isfinite(scale) or scale <= 0 or scale.item() == 1.0:+ return None+ return scale+++# OCP Microscaling (MXFP8) stores one E8M0 exponent per 32-element block. safetensors has no E8M0+# dtype, so producers write the exponents as `uint8`.+#+# We refuse such checkpoints rather than guessing at them. Decoding the byte as `2**(v-127)` and+# expanding it 32-wide is *not* sufficient, established against a real file: the MXFP8 and the+# scaled-fp8 build of `krea2TurboOfficialComfy` share all 174 bf16 tensors bit-for-bit, so the+# scaled build is an exact reference for the same weights -- and against it the decoded weights+# reach a correlation of only 0.60, producing pure noise end to end. The measured per-block scale+# has no monotonic relation to the byte (112 and 116 yield the same true scale), which points at a+# swizzled scale layout rather than a wrong exponent bias. Supporting it means implementing that+# de-swizzle, not adding a constant.+#+# Refusing is the point: with the block-wise expansion in place, such a file otherwise *loads* and+# generates a garbage image with nothing in the log.+_MX_SCALE_DTYPES = (torch.uint8,)++++def _reject_unparsed_scales(sd: Mapping[str, Any]) -> None:++ """Refuse a scale spelling this module does not parse when it sits beside an fp8 weight.++++ Loaders ignore unexpected keys (logged at DEBUG), so a leftover ``.weight_scale_inv``-style++ key would otherwise let its weight load unscaled and generate noise instead of failing here.++ """++ unparsed = sorted(++ key++ for key in sd++ if isinstance(key, str)++ and "scale" in key.rsplit(".", 1)[-1]++ and getattr(sd.get(f"{key.rsplit('.', 1)[0]}.weight"), "dtype", None) in FP8_WEIGHT_DTYPES++ )++ if unparsed:++ raise NotImplementedError(++ f"Unsupported fp8 scale layout: {unparsed[:8]}{' ...' if len(unparsed) > 8 else ''}. InvokeAI reads "++ f"{WEIGHT_SCALE_SUFFIXES + INPUT_SCALE_SUFFIXES}; use the scaled-fp8 or bf16 build of this checkpoint."++ )+++++def _reject_mx_scale(path: str) -> None:+ raise NotImplementedError(+ f"'{path}' carries an MXFP8 (OCP Microscaling) block scale, which InvokeAI cannot decode "+ "yet: the exponents are stored in a swizzled layout. Use the scaled-fp8 or bf16 build of "+ "this checkpoint instead. Loading it anyway would produce a noise image, not a warning."+ )+++def _normalize_weight_scale(scale: torch.Tensor) -> torch.Tensor:+ """Canonical float32 form of a weight scale, preserving its layout.++ Per-tensor scales become 0-d and per-output-channel scales 1-D, so downstream code can branch on+ ``numel()``. A scale with more than one dimension is *block-wise* — one entry per block of+ weight elements — and is returned with its shape intact: flattening it destroys the block+ geometry that :func:`expand_weight_scale` needs to line it back up with the weight.+ """+ scale = scale.float()+ if scale.numel() == 1:+ return scale.reshape(())+ if scale.dim() > 1:+ return scale+ return scale.flatten()+++def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:+ """Broadcast ``scale`` to line up with ``weight`` for an elementwise multiply.++ Handles the three layouts producers emit:++ - per-tensor (0-d / single element) — returned unchanged, broadcasting handles it;+ - per-output-channel (one entry per row) — reshaped to ``(rows, 1, ...)``;+ - block-wise (one entry per block along one or more dims) — each axis is+ ``repeat_interleave``d by that axis' block size.++ Without the block-wise case a 2-D scale reaches the multiply as-is and raises a shape error, so+ a checkpoint using that layout fails to load outright. That is the layout ComfyUI's own+ dequantizer expands, and the FLUX.2 loader used to expand before this module centralized the+ logic.+ """+ if scale.numel() == 1:+ return scale+ if scale.dim() <= 1:+ if scale.numel() != weight.shape[0]:+ # A 1-D scale is per-output-channel by definition, so any other length means the file+ # does not describe this weight — most likely a block-wise scale flattened by the+ # producer, whose block structure is not recoverable from the tensor alone. Say so:+ # left to broadcast, torch raises "size of tensor a (32) must match tensor b (7)" from+ # inside the multiply, which names neither the layer nor the file.+ raise ValueError(+ f"fp8 weight_scale has {scale.numel()} entries but the weight has {weight.shape[0]} output "+ "channels; the scale is neither per-tensor nor per-output-channel and cannot be applied. "+ "The checkpoint's quantization metadata appears to be malformed."+ )+ return scale.reshape(-1, *([1] * (weight.dim() - 1)))+ for dim in range(weight.dim()):+ if dim < scale.dim() and scale.shape[dim] != weight.shape[dim]:+ block = weight.shape[dim] // scale.shape[dim]+ if block > 1:+ scale = scale.repeat_interleave(block, dim=dim)+ return scale+++def is_matmul_usable_scale(weight: Any, scale: torch.Tensor) -> bool:+ """Whether ``scaled_mm_linear`` can apply ``scale`` without materializing the weight.++ It handles exactly two layouts: a per-tensor scalar, which goes into the ``_scaled_mm`` call,+ and a per-output-channel vector, which is applied to the *result* (scaling weight row ``j``+ scales output column ``j``). A block-wise scale is separable in neither sense, so such a layer+ has to be dequantized up front instead of failing mid-generation inside the kernel.+ """+ if scale.numel() == 1:+ return True+ rows = getattr(weight, "shape", (None,))[0]+ return scale.dim() == 1 and scale.numel() == rows+++def extract_fp8_scaled_layers(+ sd: dict[str, Any],+ metadata: Mapping[str, Any] | None = None,+ layer_hints: Mapping[str, Mapping[str, Any]] | None = None,+) -> dict[str, Fp8ScaledLayer]:+ """Pop the quantization side-channel out of ``sd`` and return it keyed by module path.++ ``sd`` is modified in place: scale and marker keys are removed so the remaining state dict+ loads cleanly into a model that knows nothing about fp8. The ``.weight`` tensors are left as+ float8 - the caller decides whether to keep or dequantize them.++ Only layers whose ``.weight`` is actually float8 are reported; a stray scale without a matching+ fp8 weight is dropped rather than silently mis-scaling a bf16 weight.++ ``layer_hints`` overrides the parsed metadata. Loaders that rename checkpoint keys (native →+ diffusers) must pass hints keyed by the *renamed* paths, otherwise the per-layer flags -+ including ``full_precision_matrix_mult`` - silently match nothing.+ """+ layer_meta = dict(layer_hints) if layer_hints is not None else parse_quantization_metadata(metadata)++ weight_scales: dict[str, torch.Tensor] = {}+ input_scales: dict[str, torch.Tensor] = {}+ for key in list(sd.keys()):+ if not isinstance(key, str):+ continue+ parsed = _strip_scale_suffix(key)+ if parsed is None:+ continue+ path, is_input_scale = parsed+ if is_input_scale:+ input_scales[path] = sd.pop(key)+ else:+ weight_scales[path] = sd.pop(key)++ for key in list(sd.keys()):+ if isinstance(key, str) and (key in STRAY_METADATA_KEYS or "comfy_quant" in key):+ del sd[key]++ _reject_unparsed_scales(sd)++ layers: dict[str, Fp8ScaledLayer] = {}+ for path, scale in weight_scales.items():+ weight = sd.get(f"{path}.weight")+ if weight is None or getattr(weight, "dtype", None) not in FP8_WEIGHT_DTYPES:+ # A scale without an fp8 weight means the weight was already dequantized (or the key+ # naming does not line up). Applying the scale later would corrupt it, so drop it.+ continue+ if getattr(scale, "dtype", None) in _MX_SCALE_DTYPES:+ _reject_mx_scale(path)+ hints = layer_meta.get(path, {})+ layers[path] = Fp8ScaledLayer(+ weight_scale=_normalize_weight_scale(scale),+ input_scale=_usable_input_scale(input_scales.get(path)),+ full_precision_matmul=bool(hints.get("full_precision_matrix_mult", False)),+ )+ return layers+++def dequantize_fp8_scaled(+ sd: dict[str, Any],+ layers: Mapping[str, Fp8ScaledLayer],+ dtype: torch.dtype = torch.bfloat16,+) -> dict[str, Any]:+ """Fold the scales back into the weights, producing a plain ``dtype`` state dict.++ This is the legacy behavior, kept as the fallback for models/devices that cannot use the fp8+ path. The multiply runs in float32 for precision but the result is stored as ``dtype``+ immediately, so a cold load never holds the whole model in float32.+ """+ for path, layer in layers.items():+ key = f"{path}.weight"+ weight = sd.get(key)+ if weight is None:+ continue+ weight = weight.float()+ sd[key] = (weight * expand_weight_scale(weight, layer.weight_scale)).to(dtype)+ return sd+++def attach_fp8_scales(+ model: torch.nn.Module,+ layers: Mapping[str, Fp8ScaledLayer],+ module_paths: Iterable[str] | None = None,+) -> int:+ """Register the recovered scales as buffers on the matching modules.++ ``CustomLinear`` looks for ``weight_scale`` / ``input_scale`` buffers and a+ ``_fp8_full_precision_matmul`` flag. The buffers are non-persistent: they must never end up in+ ``state_dict()`` output, or a re-save would produce a checkpoint that gets scaled twice.++ The producer's ``full_precision_matrix_mult`` markers are applied here rather than dropped at+ parse time, so the recovered metadata stays inspectable, and are suppressed when the user has+ turned the hints off (see :func:`full_precision_hints_respected`).++ Returns the number of modules that were annotated. A caller that expects *every* recovered+ layer to be annotated should check that count with :func:`warn_on_unattached_scales`.+ """+ wanted = set(module_paths) if module_paths is not None else None+ respect_hints = full_precision_hints_respected()+ count = 0+ for path, layer in layers.items():+ if wanted is not None and path not in wanted:+ continue+ try:+ module = model.get_submodule(path) if path else model+ except AttributeError:+ continue+ weight = getattr(module, "weight", None)+ if weight is None or weight.dtype != FP8_DTYPE:+ continue+ module.register_buffer("weight_scale", layer.weight_scale.to(weight.device), persistent=False)+ if layer.input_scale is not None:+ module.register_buffer("input_scale", layer.input_scale.to(weight.device), persistent=False)+ module._fp8_full_precision_matmul = layer.full_precision_matmul and respect_hints+ count += 1+ return count+++def warn_on_unattached_scales(logger: Logger, what: str, attached: int, layers: Mapping[str, Any]) -> None:+ """Complain when :func:`attach_fp8_scales` annotated fewer modules than there were layers.++ Every recovered layer should reach a module: :func:`split_fp8_scaled_layers` has already folded+ the ones that cannot stay quantized. A shortfall therefore means a scale went nowhere, and a+ weight is now off by ``1/weight_scale`` — visually a broken or washed-out generation, with+ nothing in the log to point at it. Loaders otherwise report ``attached`` as if it were the whole+ story, which reads as success.+ """+ missing = len(layers) - attached+ if missing > 0:+ logger.warning(+ f"{what}: {missing} of {len(layers)} scaled fp8 layer(s) did not receive their weight_scale. "+ "Those weights are quantized but unscaled, which will degrade output. This is a bug — "+ "please report the checkpoint."+ )+++# ----------------------------------------------------------------------------------- runtime path++FP8_MAX = torch.finfo(FP8_DTYPE).max++# torch._scaled_mm requires every GEMM dimension to be a multiple of 16.+_MM_ALIGNMENT = 16++_fp8_mm_supported: dict[int, bool] = {}++# fp8 compute quantizes the *activations* as well, so it changes numerics: an existing install would+# start producing different images at the same seed. It is therefore opt-in (`fp8_compute` in+# invokeai.yaml) for one release before becoming the default.+#+# The same flag also decides whether scaled fp8 checkpoints stay quantized at load. Keeping them+# quantized without the fp8 matmul would halve VRAM but make generation *slower* (the dequantize+# round trip costs more than it saves), so the two must be switched together.+_fp8_matmul_override: bool | None = None+++def set_fp8_matmul_enabled(enabled: bool | None) -> None:+ """Override the configured setting process-wide. Pass ``None`` to revert to the config value."""+ global _fp8_matmul_override+ _fp8_matmul_override = enabled+++def is_fp8_matmul_enabled() -> bool:+ if _fp8_matmul_override is not None:+ return _fp8_matmul_override+ try:+ from invokeai.app.services.config.config_default import get_config++ return bool(get_config().fp8_compute)+ except Exception:+ # Backend code may run outside a configured app (scripts, tests). Default to the safe path.+ return False+++_full_precision_hints_override: bool | None = None+++def set_full_precision_hints_respected(respected: bool | None) -> None:+ """Override the configured setting process-wide. Pass ``None`` to revert to the config value."""+ global _full_precision_hints_override+ _full_precision_hints_override = respected+++def full_precision_hints_respected() -> bool:+ """Whether ``full_precision_matrix_mult`` markers are obeyed.++ Honoring a marker means that layer dequantizes on every forward instead of using the fp8 tensor+ cores, and that is not cheap: on a checkpoint that marks the attention output, gate and FFN-down+ projections (a common choice) the marked layers can be ~40% of the quantized weights, and+ measurably erase most of the fp8_compute speedup. Whether that trade is worth it depends on how+ much the producer's flags actually buy in a given checkpoint, so it is a user-facing setting+ rather than a hard-coded policy.+ """+ if _full_precision_hints_override is not None:+ return _full_precision_hints_override+ try:+ from invokeai.app.services.config.config_default import get_config++ return bool(get_config().fp8_compute_full_precision_hints)+ except Exception:+ # Backend code may run outside a configured app (scripts, tests). Default to obeying them.+ return True+++# Wordings torch uses when `_scaled_mm` is genuinely unavailable on the hardware, as opposed to+# having failed under load. Kept narrow on purpose: anything not matched here is treated as+# transient and re-probed, which is the safe direction (see `_probe_fp8_matmul`).+_UNSUPPORTED_MM_MARKERS = ("compute capability", "not supported", "no kernel image", "not implemented")+++def _is_definitive_unsupported_error(exc: BaseException) -> bool:+ """Whether ``exc`` says the device cannot do fp8 matmul at all, rather than not right now."""+ message = str(exc).lower()+ return any(marker in message for marker in _UNSUPPORTED_MM_MARKERS)+++def _probe_fp8_matmul(index: int) -> bool | None:+ """Run one minimal ``_scaled_mm`` on device ``index`` and report whether it worked.++ Asking the device is the only reliable test. ``get_device_capability`` reports the *gfx arch*+ on ROCm, not an SM version, so an RDNA3 card (gfx1100) answers ``(11, 0)`` and sails past a+ ``>= (8, 9)`` check — then every forward raises ``torch._scaled_mm is only supported on CUDA+ devices with compute capability >= 9.0 or 8.9, or ROCm MI300+``. The whole point of the+ capability gate is to *fall back* rather than raise mid-generation, so it must not itself be a+ guess. The probe is one 16x16 matmul, run once per device and cached.++ Returns ``None`` when the probe could not be *carried out* rather than having established that+ the operation is unsupported. The probe runs during a model load, i.e. under real VRAM pressure+ and alongside whatever else the driver is doing, and caching a momentary failure as "this GPU+ cannot do fp8" would disable the fp8 matmul for the rest of the process. Same reasoning as+ `_device_supports_fp8_storage`, which also refuses to cache a transient failure.++ A ``RuntimeError`` is therefore treated as inconclusive *unless* it names the support+ constraint. Listing the transient wordings instead would be the wrong way round: an OOM and a+ cuBLAS workspace failure are only two of the ways a loaded machine can fail this call, and every+ wording not on such a list would be cached as permanent. The definitive answer has one stable+ shape — torch says the op needs a given compute capability — so match that and treat the open+ set as inconclusive.++ An inconclusive answer costs one 16x16 matmul on the next load; a wrongly cached one costs the+ fp8 path for the lifetime of the process.+ """+ try:+ device = torch.device("cuda", index)+ # Column-major right operand, i.e. exactly the layout `scaled_mm_linear` feeds it.+ lhs = torch.zeros((_MM_ALIGNMENT, _MM_ALIGNMENT), device=device, dtype=FP8_DTYPE)+ rhs = torch.zeros((_MM_ALIGNMENT, _MM_ALIGNMENT), device=device, dtype=FP8_DTYPE).t()+ scale = torch.ones((1, 1), device=device, dtype=torch.float32)+ torch._scaled_mm(lhs, rhs, scale, scale, out_dtype=torch.bfloat16)+ except torch.OutOfMemoryError:+ return None+ except RuntimeError as e:+ return False if _is_definitive_unsupported_error(e) else None+ except Exception:+ # Not a RuntimeError: a missing op or a rejected dtype, i.e. structural rather than+ # situational. Those do not become true on a less busy machine.+ return False+ return True+++def device_supports_fp8_matmul(device: torch.device) -> bool:+ """Whether ``torch._scaled_mm`` can run on this device (Ada/SM 8.9 and newer, or MI300+)."""+ if device.type != "cuda" or not torch.cuda.is_available():+ return False+ index = device.index if device.index is not None else torch.cuda.current_device()+ cached = _fp8_mm_supported.get(index)+ if cached is not None:+ return cached+ # The capability check is only a cheap pre-filter that spares older CUDA cards the probe;+ # it is deliberately not trusted on its own (see `_probe_fp8_matmul`).+ if not (torch.version.hip is not None or torch.cuda.get_device_capability(index) >= (8, 9)):+ _fp8_mm_supported[index] = False+ return False+ probed = _probe_fp8_matmul(index)+ if probed is None:+ # Inconclusive: answer this call conservatively but leave the cache empty so the next load+ # re-probes instead of the process being stuck without fp8 after one transient OOM.+ return False+ _fp8_mm_supported[index] = probed+ return probed+++def reset_fp8_matmul_support_cache() -> None:+ """Forget the probed per-device support. For tests; the answer cannot change at runtime."""+ _fp8_mm_supported.clear()+++def should_keep_fp8_weights(device: torch.device) -> bool:+ """Whether fp8 weights in a checkpoint should survive the load instead of being dequantized.++ Only true when the fp8 matmul is both enabled and usable, because keeping weights quantized+ without it is the worst of both worlds: the same VRAM as fp8 but a dequantize round trip on+ every forward (measured slower than plain bf16).+ """+ return is_fp8_matmul_enabled() and device_supports_fp8_matmul(device)+++def _is_fp8_matmul_weight(key: str, tensor: Any, model: torch.nn.Module | None) -> bool:+ """Whether this state-dict entry is a weight `scaled_mm_linear` can actually consume.++ Only the ``.weight`` of an ``nn.Linear`` qualifies. This matters because checkpoints exist that+ quantize *everything* — biases, norm weights, even learned pad tokens. Keeping those in fp8 does+ not save anything worth having and actively breaks inference: an fp8 norm or pad token flows+ into the activations, and the next Linear then receives an fp8 *input*, which dies in+ ``x.abs()`` with ``"abs_cuda" not implemented for 'Float8_e4m3fn'``. Observed on a Z-Image+ checkpoint where 243 of 453 fp8 tensors were 1-D.+ """+ if not key.endswith(".weight") or getattr(tensor, "dim", None) is None or tensor.dim() < 2:+ return False+ if model is None:+ # No model to resolve against: the 2-D + `.weight` shape test above is the safe subset.+ return True+ try:+ module = model.get_submodule(key[: -len(".weight")])+ except AttributeError:+ return False+ return isinstance(module, torch.nn.Linear)+++def can_stay_quantized(+ key: str,+ tensor: Any,+ model: torch.nn.Module | None,+ skip_patterns: Iterable[str] = (),+) -> bool:+ """Whether this state-dict entry may be left in fp8 by :func:`cast_state_dict`.++ Single source of truth for that decision: the loaders reserve RAM against it+ (:func:`predict_cast_state_dict_size`) and decide which scaled layers survive with it+ (:func:`split_fp8_scaled_layers`), so the three must never drift apart.++ Only ``float8_e4m3fn`` qualifies. ``float8_e5m2`` is always cast because+ :func:`scaled_mm_linear` cannot use it as the weight operand on Ada, so keeping it quantized+ would buy VRAM at the cost of a per-forward dequantize.++ ``skip_patterns`` are substrings of the state-dict key whose weights must be dequantized even+ when the rest stays fp8. Pass the model's ``_skip_layerwise_casting_patterns``: diffusers uses+ it to mark precision-sensitive modules, and some of them *read their own weight's dtype and cast+ their activations to it*. Z-Image's ``TimestepEmbedder.forward`` does exactly that+ (``t_freq.to(self.mlp[0].weight.dtype)``), so leaving its weight in fp8 hands the next Linear an+ fp8 activation and the forward dies in ``x.abs()`` with+ ``"abs_cuda" not implemented for 'Float8_e4m3fn'``.+ """+ return (+ getattr(tensor, "dtype", None) is FP8_DTYPE+ and _is_fp8_matmul_weight(key, tensor, model)+ and not any(pattern in key for pattern in skip_patterns)+ )+++def scaled_layer_for(key: Any, scaled_layers: Mapping[str, "Fp8ScaledLayer"] | None) -> "Fp8ScaledLayer | None":+ """The recovered scale for the module whose ``.weight`` this key is, if there is one."""+ if not scaled_layers or not isinstance(key, str) or not key.endswith(".weight"):+ return None+ return scaled_layers.get(key[: -len(".weight")])+++def survives_split_and_cast(+ key: str,+ tensor: Any,+ model: torch.nn.Module | None,+ skip_patterns: Iterable[str] = (),+ layer: "Fp8ScaledLayer | None" = None,+) -> bool:+ """Whether this entry is *still* fp8 after both :func:`split_fp8_scaled_layers` and+ :func:`cast_state_dict` have run over it.++ :func:`can_stay_quantized` answers only for the cast. The split applies one filter more — a+ scale layout :func:`scaled_mm_linear` cannot use — so a block-wise-scaled 2-D Linear weight+ passes ``can_stay_quantized`` and is nonetheless widened to ``dtype``. Predicting RAM with the+ weaker predicate therefore charges 1 byte/element for a tensor that ends up at 2, and the loaders+ reserve half of what they need. This is the predicate both the split and the prediction use, so+ the two cannot drift.++ ``layer`` is None for a raw fp8 weight (no ``weight_scale`` at all); there is no layout to+ reject, and the tensor-core path takes it with unit scaling.+ """+ if not can_stay_quantized(key, tensor, model, skip_patterns):+ return False+ return layer is None or is_matmul_usable_scale(tensor, layer.weight_scale)+++def is_castable_float(tensor: Any) -> bool:+ """Whether ``tensor`` is a floating-point payload that may be cast to the compute dtype.++ Public because the int8 path's own cast (``int8_convrot.cast_unquantized``) owes the state dict+ the same guarantee and must not carry a second copy of this predicate: the two casts differ in+ which *quantized* payloads they pin, never in what counts as a float.+ """+ is_floating_point = getattr(tensor, "is_floating_point", None)+ if not callable(is_floating_point):+ return False+ try:+ return bool(is_floating_point())+ except Exception:+ return False+++def cast_state_dict(+ sd: dict[str, Any],+ dtype: torch.dtype,+ *,+ keep_fp8: bool,+ model: torch.nn.Module | None = None,+ skip_patterns: Iterable[str] = (),+) -> int:+ """Cast every tensor in ``sd`` to ``dtype`` in place, optionally leaving fp8 weights quantized.++ Loaders historically cast the whole state dict unconditionally, which silently dequantizes a+ checkpoint that ships raw fp8 weights (fp8 tensors with no ``weight_scale`` alongside them) —+ the VRAM saving and the tensor cores are both thrown away before the model is ever built.++ A *scaled* fp8 weight must never reach this function still carrying an unapplied scale: the+ plain ``tensor.to(dtype)`` below drops the scale silently, leaving the weight off by+ ``1/weight_scale``. Run :func:`split_fp8_scaled_layers` first — it folds the scale into exactly+ those layers this function would cast.++ Returns the number of tensors left in fp8.+ """+ patterns = tuple(skip_patterns)+ kept = 0+ for key in sd:+ tensor = sd[key]+ if keep_fp8 and can_stay_quantized(key, tensor, model, patterns):+ kept += 1+ continue+ if not is_castable_float(tensor):+ # Integer payloads (embedding indices, packed buffers) are not weights and must keep+ # their dtype. Loaders used to guard this themselves; centralizing it here means a+ # loader that switches to `cast_state_dict` does not silently lose the guard.+ continue+ sd[key] = tensor.to(dtype)+ return kept+++def predict_cast_state_dict_size(+ sd: Mapping[str, Any],+ dtype: torch.dtype,+ *,+ keep_fp8: bool,+ model: torch.nn.Module | None = None,+ skip_patterns: Iterable[str] = (),+ scaled_layers: Mapping[str, Fp8ScaledLayer] | None = None,+) -> int:+ """Bytes the state dict will occupy once the split and :func:`cast_state_dict` have run over it.++ Loaders call this to size their ``make_room()`` reservation. Charging 1 byte/element for every+ fp8 tensor is wrong in the direction that hurts: only 2-D ``nn.Linear`` weights outside the skip+ patterns stay quantized, and everything else — biases, norms, learned pad tokens, the+ deliberately-dequantized precision-sensitive Linears — lands at ``dtype.itemsize``. On a+ checkpoint that quantized all 453 of its tensors that under-count is most of the difference.++ ``scaled_layers`` is the mapping the caller is about to hand :func:`split_fp8_scaled_layers`.+ Pass it: the reservation is made *before* the split (so the split's own fp32 transient lands on+ a reserved cache), and the split widens every layer whose scale layout ``scaled_mm`` cannot+ apply. Without the mapping those layers are predicted at 1 byte/element and arrive at 2 — on a+ block-wise-scaled checkpoint that is the entire quantized-Linear set.+ """+ patterns = tuple(skip_patterns)+ total = 0+ for key, tensor in sd.items():+ stays = keep_fp8 and survives_split_and_cast(key, tensor, model, patterns, scaled_layer_for(key, scaled_layers))+ if stays or not is_castable_float(tensor):+ total += tensor.nelement() * tensor.element_size()+ else:+ total += tensor.nelement() * dtype.itemsize+ return total+++def split_fp8_scaled_layers(+ sd: dict[str, Any],+ layers: Mapping[str, Fp8ScaledLayer],+ dtype: torch.dtype,+ *,+ model: torch.nn.Module | None = None,+ skip_patterns: Iterable[str] = (),+) -> dict[str, Fp8ScaledLayer]:+ """Dequantize the scaled layers that cannot stay quantized; return the ones that can.++ Every filter that keeps a weight *out* of fp8 — a skip pattern, a weight that is not a 2-D+ ``nn.Linear.weight`` — is a filter that would otherwise let :func:`cast_state_dict` do a plain+ ``.to(dtype)`` on a scaled weight, i.e. drop its ``weight_scale`` and leave the weight off by+ ``1/weight_scale``. :func:`attach_fp8_scales` cannot repair that afterwards: it skips any module+ whose weight is no longer fp8, so the scale is lost for good. Krea-2 hits this on ordinary+ ComfyUI exports, where ``time_embed.linear_1/linear_2`` are quantized like any other Linear and+ match the model's ``time_embed`` skip pattern.++ So the filters are applied here instead, *before* the cast, and the affected layers go through+ :func:`dequantize_fp8_scaled`, which applies the scale properly. They are then dropped from the+ returned mapping — they are no longer fp8, so there is nothing left to attach.++ A scale layout :func:`scaled_mm_linear` cannot apply — block-wise, or a vector that does not+ match the weight's row count — is dequantized here too. Left quantized it would fail inside the+ kernel mid-generation instead. That filter lives here rather than in :func:`can_stay_quantized`+ because it needs the recovered scale, which the cast never sees. The RAM prediction runs+ *before* this function, so it has to account for the same widening — it does, via the shared+ :func:`survives_split_and_cast`, provided the caller passes it ``scaled_layers``.++ ``float8_e5m2`` layers land here by way of :func:`can_stay_quantized`, which admits only+ ``float8_e4m3fn`` — they are dequantized *with* their scale applied rather than losing it.+ """+ patterns = tuple(skip_patterns)+ usable: dict[str, Fp8ScaledLayer] = {}+ unusable: dict[str, Fp8ScaledLayer] = {}+ for path, layer in layers.items():+ key = f"{path}.weight"+ tensor = sd.get(key)+ if tensor is not None and survives_split_and_cast(key, tensor, model, patterns, layer):+ usable[path] = layer+ else:+ unusable[path] = layer+ if unusable:+ dequantize_fp8_scaled(sd, unusable, dtype)+ return usable+++def count_fp8_weights(model: torch.nn.Module) -> int:+ """Number of parameters already stored as ``float8_e4m3fn``.++ Used to tell a checkpoint that arrived quantized apart from one this loader is about to+ quantize itself — the two must not both happen (see `ModelLoader._apply_fp8_layerwise_casting`).+ """+ return sum(1 for p in model.parameters() if p.dtype is FP8_DTYPE)+++def dequantize_weight(weight: torch.Tensor, weight_scale: torch.Tensor | None, dtype: torch.dtype) -> torch.Tensor:+ """Cast an fp8 weight up to ``dtype``, applying its scale if it has one.++ Used by the fallback path. Casting *without* the scale - which is what a plain ``.to(dtype)``+ does - silently produces a wrongly-scaled weight, so every dequantization of a scaled fp8+ weight must go through here.+ """+ out = weight.to(dtype)+ if weight_scale is None:+ return out+ scale = weight_scale.to(device=out.device, dtype=dtype)+ return out * expand_weight_scale(out, scale)+++def scaled_mm_linear(+ input: torch.Tensor,+ weight: torch.Tensor,+ weight_scale: torch.Tensor | None,+ bias: torch.Tensor | None = None,+ input_scale: torch.Tensor | None = None,+) -> torch.Tensor:+ """``F.linear`` executed on the fp8 tensor cores via ``torch._scaled_mm``.++ ``weight`` stays float8 and is never materialized in a wider dtype - that is where both the+ VRAM and the speed come from.++ Scaling notes:+ - The activation scale is per-tensor. Ada rejects per-row activation scaling outright, and+ a static ``input_scale`` from the checkpoint is used when available (calibrated, and it saves+ the per-forward ``amax`` reduction).+ - A per-output-channel weight scale cannot be handed to ``_scaled_mm`` on Ada either, but it is+ separable: scaling row ``j`` of the weight scales output column ``j``, so it is applied to the+ result instead. Per-tensor scales go straight into the kernel.+ """+ orig_shape = input.shape+ x = input.reshape(-1, orig_shape[-1])++ # The transpose must be produced here rather than cached: a stored transposed view stops being a+ # view the moment the tensor is moved between devices (which partial loading does constantly),+ # silently doubling the weight memory.+ weight_t = weight.t()++ pad = (-x.shape[0]) % _MM_ALIGNMENT+ if pad:+ x = torch.nn.functional.pad(x, (0, 0, 0, pad))++ if input_scale is not None:+ x_scale = input_scale.to(device=x.device, dtype=torch.float32).reshape(1, 1)+ x_fp8 = (x / x_scale.to(x.dtype)).clamp(-FP8_MAX, FP8_MAX).to(FP8_DTYPE)+ else:+ amax = x.abs().amax().clamp(min=1e-12)+ x_scale = (amax / FP8_MAX).float().reshape(1, 1)+ x_fp8 = (x / x_scale.to(x.dtype)).to(FP8_DTYPE)++ per_tensor = weight_scale is not None and weight_scale.numel() == 1+ if per_tensor:+ w_scale = weight_scale.to(device=x.device, dtype=torch.float32).reshape(1, 1)+ else:+ w_scale = torch.ones(1, 1, device=x.device, dtype=torch.float32)++ out = torch._scaled_mm(x_fp8.contiguous(), weight_t, x_scale, w_scale, out_dtype=input.dtype)++ if pad:+ out = out[: x.shape[0] - pad]+ if weight_scale is not None and not per_tensor:+ out = out * weight_scale.to(device=out.device, dtype=out.dtype).reshape(1, -1)++ out = out.reshape(*orig_shape[:-1], weight.shape[0])+ if bias is not None:+ out = out + bias.to(dtype=out.dtype)+ return outdiff --cc tests/app/api/test_video_upload_limits.pyindex 085c165cfe,ca5941822b..56338d30ff--- a/tests/app/api/test_video_upload_limits.py+++ b/tests/app/api/test_video_upload_limits.py@@@ -8,10 -8,10 +8,12 @@@ straight into one temp file, enforcing"""import asyncio+ import gcimport tempfileimport time+ import tracemalloc+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Anydiff --cc tests/app/invocations/test_qwen_image_text_encoder.pyindex f842e425bf,c4a786d02a..a2791f631f--- a/tests/app/invocations/test_qwen_image_text_encoder.py+++ b/tests/app/invocations/test_qwen_image_text_encoder.py@@@ -1,11 -1,29 +1,29 @@@"""Tests for the Qwen Image text encoder prompt building and image resizing."""+ import gc+ import json+ import threading+ import traceback+ import weakref+ from pathlib import Path+ from unittest.mock import MagicMock, patch++ import pytest+ import torchfrom PIL import Image+ from safetensors.torch import save_file+ from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+ from invokeai.app.invocations.model import ModelIdentifierField, QwenVLEncoderField-from invokeai.app.invocations.qwen_image_text_encoder import (+from invokeai.app.invocations.text_encoder.qwen_image_text_encoder import (+ _GENERATE_DROP_IDX,QwenImageTextEncoderInvocation,_build_prompt,+ _read_checkpoint,)+ from invokeai.backend.model_manager.load.model_cache.model_cache import MB, MODEL_LOAD_LOCK+ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType+ from invokeai.backend.util.devices import TorchDeviceclass TestBuildPrompt:@@@ -122,3 -140,538 +140,540 @@@ class TestResizeForVLEncoderresized = QwenImageTextEncoderInvocation._resize_for_vl_encoder(img, target_pixels=512 * 512)w, h = resized.sizeassert w > h # should remain landscape+++ def _read_lock_held() -> bool:+ return MODEL_LOAD_LOCK._readers > 0 and not MODEL_LOAD_LOCK._writer_active+++ def _write_lock_held() -> bool:+ return MODEL_LOAD_LOCK._writer_active+++ def _tiny_config() -> Qwen2_5_VLConfig:+ """A Qwen2.5-VL config small enough to build and load on the CPU in well under a second."""+ return Qwen2_5_VLConfig(+ text_config={+ "hidden_size": 64,+ "intermediate_size": 128,+ "num_hidden_layers": 2,+ "num_attention_heads": 4,+ "num_key_value_heads": 2,+ "vocab_size": 512,+ "max_position_embeddings": 256,+ "tie_word_embeddings": False,+ "rope_scaling": {"type": "mrope", "mrope_section": [2, 3, 3]},+ },+ vision_config={+ "depth": 2,+ "hidden_size": 32,+ "intermediate_size": 64,+ "num_heads": 4,+ "out_hidden_size": 64,+ "patch_size": 14,+ "spatial_merge_size": 2,+ "temporal_patch_size": 2,+ "in_channels": 3,+ "window_size": 112,+ "fullatt_block_indexes": [1],+ },+ )+++ def _write_sharded_checkpoint(text_encoder_dir: Path, total_size: int) -> dict[str, torch.Tensor]:+ """A two-shard safetensors checkpoint small enough to be read for real, with a config so the loader can build+ the model config from it. `total_size` is what `calc_model_size_by_fs` reports for it."""+ text_encoder_dir.mkdir(parents=True)+ _tiny_config().save_pretrained(text_encoder_dir)+ tensors = {+ "a.weight": torch.arange(6, dtype=torch.bfloat16).reshape(2, 3),+ "b.bias": torch.ones(4, dtype=torch.bfloat16),+ }+ save_file({"a.weight": tensors["a.weight"]}, text_encoder_dir / "model-00001-of-00002.safetensors")+ save_file({"b.bias": tensors["b.bias"]}, text_encoder_dir / "model-00002-of-00002.safetensors")+ index = {+ "metadata": {"total_size": total_size},+ "weight_map": {"a.weight": "model-00001-of-00002.safetensors", "b.bias": "model-00002-of-00002.safetensors"},+ }+ (text_encoder_dir / "model.safetensors.index.json").write_text(json.dumps(index))+ return tensors+++ class TestReadCheckpoint:+ def test_reads_every_shard_named_by_the_index(self, tmp_path: Path):+ tensors = _write_sharded_checkpoint(tmp_path / "text_encoder", total_size=1)++ state_dict = _read_checkpoint(tmp_path / "text_encoder")++ assert state_dict is not None and set(state_dict) == set(tensors)+ assert all(torch.equal(state_dict[k], tensors[k]) for k in tensors)++ def test_reads_an_unsharded_checkpoint(self, tmp_path: Path):+ (tmp_path / "text_encoder").mkdir()+ save_file({"w": torch.zeros(3)}, tmp_path / "text_encoder" / "model.safetensors")++ state_dict = _read_checkpoint(tmp_path / "text_encoder")++ assert state_dict is not None and list(state_dict) == ["w"]++ def test_returns_none_without_safetensors_shards(self, tmp_path: Path):+ """A `.bin` checkpoint is left to transformers to read (under the lock, as before)."""+ (tmp_path / "text_encoder").mkdir()+ (tmp_path / "text_encoder" / "pytorch_model.bin").write_bytes(b"")++ assert _read_checkpoint(tmp_path / "text_encoder") is None+++ class TestQuantizedEncoderLoad:+ """The BitsAndBytes path bypasses the model cache, so it must ask the cache for VRAM itself and load onto the+ worker's execution device explicitly (issue #9147: `device_map="auto"` spilled to the CPU because the cached+ transformer and VAE still filled the card, and BnB int8 refused to run that way).+ """++ TOTAL_SIZE = 16 * 2**30 # bf16 Qwen2.5-VL-7B on disk++ @staticmethod+ def _make_invocation(quantization: str) -> QwenImageTextEncoderInvocation:+ encoder = ModelIdentifierField(+ key="enc", hash="h", name="qwen-vl", base=BaseModelType.QwenImage, type=ModelType.QwenVLEncoder+ )+ return QwenImageTextEncoderInvocation(+ prompt="a cat",+ qwen_vl_encoder=QwenVLEncoderField(tokenizer=encoder, text_encoder=encoder),+ quantization=quantization,+ )++ def _make_context(+ self, tmp_path: Path, events: list[str], single_file: bool = False, vram_available: int | None = None+ ) -> tuple[MagicMock, dict[str, torch.Tensor]]:+ """`vram_available` is what `make_room_in_vram` reports after offloading; by default the request is met."""+ tensors: dict[str, torch.Tensor] = {}+ if single_file:+ model_root = tmp_path / "encoder.safetensors"+ model_root.write_bytes(b"")+ else:+ model_root = tmp_path / "qwen-vl"+ tensors = _write_sharded_checkpoint(model_root / "text_encoder", total_size=self.TOTAL_SIZE)++ context = MagicMock()+ context.models.get_absolute_path.return_value = model_root++ def make_room(vram_bytes_needed: int) -> int:+ # The offload is a VRAM move like any other, so it runs under the model-load *read* lock.+ events.append("make_room" if _read_lock_held() else "make_room(wrong lock)")+ return vram_bytes_needed if vram_available is None else vram_available++ context.models.make_room_in_vram.side_effect = make_room+ return context, tensors++ @pytest.mark.parametrize(("quantization", "ratio"), [("int8", 0.6), ("nf4", 0.4)])+ def test_makes_room_in_vram_before_loading_onto_the_execution_device(+ self, tmp_path: Path, quantization: str, ratio: float+ ):+ events: list[str] = []+ context, tensors = self._make_context(tmp_path, events)+ fake_model = MagicMock()+ device = torch.device("cuda:1")+ seen: dict = {}++ def fake_from_pretrained(path, **kwargs):+ events.append("from_pretrained")+ seen.update(kwargs)+ seen["path"] = path+ # The construction must run under the model-load *write* lock: it installs process-global patches no+ # other construction may overlap, and a concurrent cache construction would hijack its parameter+ # assignment onto the meta device (see TestTransformersLoadPathAssumptions).+ seen["write_locked"] = _write_lock_held()+ return fake_model++ with (+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained", side_effect=fake_from_pretrained),+ patch.object(TorchDevice, "choose_torch_device", return_value=device),+ ):+ text_encoder, returned_device, cleanup = self._make_invocation(quantization)._load_quantized_encoder(+ context+ )++ assert events == ["make_room", "from_pretrained"]+ context.models.make_room_in_vram.assert_called_once_with(int(self.TOTAL_SIZE * ratio))+ assert seen["device_map"] == {"": device}, "must never use device_map='auto'"+ assert seen["write_locked"]+ # The checkpoint is read by the invocation (outside the lock) and handed over, not read by transformers.+ assert seen["path"] is None+ assert set(seen["state_dict"]) == set(tensors)+ assert all(torch.equal(seen["state_dict"][k], tensors[k]) for k in tensors)+ assert isinstance(seen["config"], Qwen2_5_VLConfig)+ assert seen["quantization_config"].load_in_8bit == (quantization == "int8")+ assert seen["quantization_config"].load_in_4bit == (quantization == "nf4")+ assert text_encoder is fake_model+ assert returned_device == device+ context.logger.warning.assert_not_called()+ cleanup()++ def test_checkpoint_is_read_outside_the_model_load_lock(self, tmp_path: Path):+ """The disk read is the slow part of the load on anything but NVMe, and while MODEL_LOAD_LOCK is held (or+ wanted by a writer) other workers' VRAM moves and cold constructions wait. Only the offload and the+ construction may run under it; a construction elsewhere must be able to take the write lock while the+ checkpoint is read. The read also comes *after* the offload, so the offload's RAM cannot evict its pages."""+ events: list[str] = []+ context, _ = self._make_context(tmp_path, events)+ writer_acquired = threading.Event()+ acquired_during_read: list[bool] = []++ def fake_read(encoder_path: Path):+ events.append("read" if not (_read_lock_held() or _write_lock_held()) else "read(locked)")++ def construction_on_another_worker():+ with MODEL_LOAD_LOCK.write_lock():+ writer_acquired.set()++ threading.Thread(target=construction_on_another_worker).start()+ acquired_during_read.append(writer_acquired.wait(timeout=5))+ return {}++ def fake_from_pretrained(path, **kwargs):+ events.append("from_pretrained" if _write_lock_held() else "from_pretrained(wrong lock)")+ return MagicMock()++ with (- patch("invokeai.app.invocations.qwen_image_text_encoder._read_checkpoint", side_effect=fake_read),++ patch(++ "invokeai.app.invocations.text_encoder.qwen_image_text_encoder._read_checkpoint", side_effect=fake_read++ ),+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained", side_effect=fake_from_pretrained),+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cuda")),+ ):+ self._make_invocation("int8")._load_quantized_encoder(context)++ assert acquired_during_read == [True], "a construction was blocked for the duration of the checkpoint read"+ assert events == ["make_room", "read", "from_pretrained"]++ def test_warns_when_less_than_the_estimate_could_be_made_available(self, tmp_path: Path):+ """`make_room_in_vram` cannot offload locked models, so it reports what is actually available after+ offloading; a shortfall must be visible in the log rather than surfacing only as a later OOM."""+ events: list[str] = []+ context, _ = self._make_context(tmp_path, events, vram_available=1000 * MB)++ with (+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained", return_value=MagicMock()),+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cuda:0")),+ ):+ self._make_invocation("int8")._load_quantized_encoder(context)++ context.logger.warning.assert_called_once()+ message = context.logger.warning.call_args.args[0]+ assert "1000 MB" in message+ assert f"{int(self.TOTAL_SIZE * 0.6) / MB:.0f} MB" in message+ assert "cuda:0" in message++ @pytest.mark.parametrize(+ ("error_type", "error_message"), [(torch.OutOfMemoryError, "CUDA out of memory"), (ValueError, "bad shard")]+ )+ def test_failed_load_releases_the_partial_model_before_the_error_escapes(+ self, tmp_path: Path, error_type: type[Exception], error_message: str+ ):+ """When `from_pretrained` raises, the partially built model is referenced only by the traceback's frames.+ Left alone, its weights stay allocated until the session processor drops the exception and *reserved* by+ torch after that, so the next load under-budgets - the same leak `_encode` guards against on the success+ path. An OOM additionally comes back with the numbers the user needs to act on."""+ events: list[str] = []+ context, _ = self._make_context(tmp_path, events, vram_available=4000 * MB)+ partial_ref: list[weakref.ref] = []+ alive_at_empty_cache: list[bool] = []++ def fake_from_pretrained(path, **kwargs):+ partial_model = torch.nn.Linear(2, 2) # referenced only by this frame once we raise+ partial_model.cycle = partial_model # real models carry cycles (hooks, recorders): refcounting won't do+ partial_ref.append(weakref.ref(partial_model))+ raise error_type(error_message)++ def empty_cache():+ alive_at_empty_cache.append(partial_ref[0]() is not None)++ with (+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained", side_effect=fake_from_pretrained),+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cuda:0")),+ patch.object(TorchDevice, "empty_cache", side_effect=empty_cache),+ pytest.raises(error_type) as excinfo,+ ):+ self._make_invocation("int8")._load_quantized_encoder(context)++ assert alive_at_empty_cache == [False], "empty_cache() ran while the traceback still referenced the model"+ assert partial_ref[0]() is None+ # The loader's own frame outlives the failure (it is in the traceback), so it must have dropped the mapped+ # checkpoint itself - `clear_frames` cannot clear an executing frame.+ loader_locals = next(+ f.f_locals for f, _ in traceback.walk_tb(excinfo.tb) if f.f_code.co_name == "_load_quantized_encoder"+ )+ assert loader_locals["state_dict"] is None+ if error_type is torch.OutOfMemoryError:+ assert isinstance(excinfo.value.__cause__, torch.OutOfMemoryError)+ assert error_message in str(excinfo.value.__cause__)+ message = str(excinfo.value)+ assert "cuda:0" in message+ assert f"{int(self.TOTAL_SIZE * 0.6) / MB:.0f} MB" in message+ assert "4000 MB" in message+ assert "nf4" in message+ else:+ assert str(excinfo.value) == error_message, "only an OOM is re-described"++ def test_cpu_execution_device_makes_no_room_and_logs_no_shortfall(self, tmp_path: Path):+ """A CPU execution device has no VRAM to make room in (the cache's `make_room_in_vram` reports 0 there), and+ recent bitsandbytes can quantize on the CPU, so the load proceeds without a spurious shortfall warning."""+ events: list[str] = []+ context, _ = self._make_context(tmp_path, events)+ seen: dict = {}++ def fake_from_pretrained(path, **kwargs):+ seen.update(kwargs)+ return MagicMock()++ with (+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained", side_effect=fake_from_pretrained),+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),+ ):+ self._make_invocation("int8")._load_quantized_encoder(context)++ context.models.make_room_in_vram.assert_not_called()+ context.logger.warning.assert_not_called()+ assert seen["device_map"] == {"": torch.device("cpu")}++ def test_unsizeable_checkpoint_warns_instead_of_silently_requesting_zero_bytes(self, tmp_path: Path):+ """`calc_model_size_by_fs` reports 0 for weights it cannot size, and a request for 0 bytes is a silent no-op+ that brings issue #9147 straight back. Such a checkpoint has no safetensors shards either, so transformers+ reads it itself."""+ model_root = tmp_path / "qwen-vl"+ text_encoder_dir = model_root / "text_encoder"+ text_encoder_dir.mkdir(parents=True)+ _tiny_config().save_pretrained(text_encoder_dir)+ (text_encoder_dir / "pytorch_model.pth").write_bytes(b"\0" * 16)+ context = MagicMock()+ context.models.get_absolute_path.return_value = model_root+ seen: dict = {}++ def fake_from_pretrained(path, **kwargs):+ seen.update(kwargs)+ seen["path"] = path+ return MagicMock()++ with (+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained", side_effect=fake_from_pretrained),+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cuda:0")),+ ):+ self._make_invocation("int8")._load_quantized_encoder(context)++ context.models.make_room_in_vram.assert_not_called()+ context.logger.warning.assert_called_once()+ assert str(text_encoder_dir) in context.logger.warning.call_args.args[0]+ assert seen["path"] == str(text_encoder_dir)+ assert seen["state_dict"] is None++ def test_single_file_checkpoint_falls_back_to_the_cache_without_making_room(self, tmp_path: Path):+ """A single-file encoder cannot be BnB-quantized; it goes through the cache, which makes its own room."""+ events: list[str] = []+ context, _ = self._make_context(tmp_path, events, single_file=True)+ invocation = self._make_invocation("int8")+ sentinel = (MagicMock(), torch.device("cuda"), lambda: None)++ with (+ patch.object(invocation, "_load_cached_encoder", return_value=sentinel) as cached,+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained") as from_pretrained,+ ):+ result = invocation._load_quantized_encoder(context)++ assert result is sentinel+ cached.assert_called_once_with(context)+ from_pretrained.assert_not_called()+ context.models.make_room_in_vram.assert_not_called()+++ @pytest.fixture(scope="module")+ def tiny_qwen_checkpoint(tmp_path_factory: pytest.TempPathFactory) -> Path:+ path = tmp_path_factory.mktemp("tiny-qwen")+ torch.manual_seed(0)+ Qwen2_5_VLForConditionalGeneration(_tiny_config()).to(torch.bfloat16).save_pretrained(path, safe_serialization=True)+ return path+++ def _transformers_4_key(name: str) -> str:+ """The key layout the Qwen-Image `text_encoder/` folders on disk use (they predate transformers 5)."""+ for v5_prefix, v4_prefix in (("model.language_model.", "model."), ("model.visual.", "visual.")):+ if name.startswith(v5_prefix):+ return v4_prefix + name[len(v5_prefix) :]+ return name+++ class TestTransformersLoadPathAssumptions:+ """`_load_quantized_encoder` runs `from_pretrained` under MODEL_LOAD_LOCK's *write* lock and reads the checkpoint+ under no lock. The two facts below are why; if either test fails after a transformers bump, the lock scoping in+ `_load_quantized_encoder` has to be revisited rather than the test.+ """++ @staticmethod+ def _load(path: Path) -> Qwen2_5_VLForConditionalGeneration:+ # The exact call shape production uses (minus the device map and quantization, which need a GPU).+ return Qwen2_5_VLForConditionalGeneration.from_pretrained(+ None,+ config=Qwen2_5_VLConfig.from_pretrained(str(path), local_files_only=True),+ state_dict=_read_checkpoint(path),+ dtype=torch.bfloat16,+ local_files_only=True,+ )++ def test_the_lock_is_load_bearing_a_concurrent_construction_strands_the_weights_on_meta(+ self, tiny_qwen_checkpoint: Path+ ):+ """Why the construction must exclude the cache's constructions: transformers assigns every loaded weight+ through `setattr` -> `register_parameter`, which a cache construction on another worker patches process-wide+ (`accelerate.init_empty_weights`) to route new parameters to the meta device."""+ from accelerate import init_empty_weights++ entered, release = threading.Event(), threading.Event()++ def construction_on_another_worker():+ with init_empty_weights():+ entered.set()+ release.wait()++ worker = threading.Thread(target=construction_on_another_worker)+ worker.start()+ entered.wait()+ try:+ model = self._load(tiny_qwen_checkpoint)+ finally:+ release.set()+ worker.join()++ assert any(p.device.type == "meta" for p in model.parameters()), (+ "the loaded weights no longer pass through register_parameter; revisit which lock the construction needs"+ )++ def test_the_construction_mutates_process_global_state_so_it_needs_the_write_lock(self, tiny_qwen_checkpoint: Path):+ """Why the construction takes the *write* lock rather than running as one more reader: `from_pretrained`+ builds under process-global save/restore patches - the default dtype among them - so two overlapping+ constructions would restore each other's state in the wrong order and leave a patch installed for the life+ of the process, and a concurrent VRAM move would allocate under the changed default."""+ original = torch.set_default_dtype+ set_during_load: list[torch.dtype] = []++ def spy(dtype: torch.dtype) -> None:+ set_during_load.append(dtype)+ original(dtype)++ with patch.object(torch, "set_default_dtype", spy):+ self._load(tiny_qwen_checkpoint)++ assert torch.bfloat16 in set_during_load, "the load no longer changes the process default dtype"+ assert torch.get_default_dtype() == torch.float32++ def test_transformers_4_key_layout_is_converted_on_the_state_dict_path(self, tmp_path: Path):+ """The checkpoints in production folders carry the transformers-4 names (`model.*`, `visual.*`); the+ state-dict entry point must run the same key conversion the path-based load does, or unmatched weights+ would be freshly initialised with only a load warning and the encoder would silently produce garbage."""+ torch.manual_seed(0)+ source = Qwen2_5_VLForConditionalGeneration(_tiny_config()).to(torch.bfloat16).state_dict()+ v4_names = {_transformers_4_key(name) for name in source}+ assert v4_names != set(source) and not any(name.startswith("model.language_model.") for name in v4_names)+ _tiny_config().save_pretrained(tmp_path)+ save_file(+ {_transformers_4_key(name): tensor for name, tensor in source.items()}, tmp_path / "model.safetensors"+ )++ loaded = self._load(tmp_path).state_dict()++ assert set(loaded) == set(source)+ assert all(torch.equal(loaded[name], source[name]) for name in source)+++ class TestQuantizedEncoderRelease:+ """The quantized encoder lives outside the cache, so `_encode` is its only owner. Its cleanup callback empties+ the CUDA cache, which only returns the ~9 GB of encoder weights to the driver if nothing still references the+ model at that point - otherwise they stay reserved by torch and the cache under-budgets the next load.+ """++ HIDDEN = 3584++ class _FakeEncoder(torch.nn.Module):+ def __init__(self, hidden: int):+ super().__init__()+ self.hidden = hidden++ def forward(self, input_ids, attention_mask, **_):+ hidden_states = torch.zeros(input_ids.shape[0], input_ids.shape[1], self.hidden)+ return MagicMock(hidden_states=[hidden_states])++ class _ExplodingEncoder(torch.nn.Module):+ def forward(self, input_ids, attention_mask, **_):+ raise RuntimeError("CUDA out of memory (simulated)")++ def _run_encode(self, tmp_path: Path, encoder: torch.nn.Module, alive_at_cleanup: list[bool], cached: bool = False):+ """Run `_encode` as the sole owner of `encoder` (or, with `cached=True`, as a borrower of a cache-owned one),+ recording into `alive_at_cleanup` whether it was still alive when cleanup ran (recorded through the argument+ so the record survives an `_encode` that raises)."""+ model_root = tmp_path / "qwen-vl"+ (model_root / "tokenizer").mkdir(parents=True, exist_ok=True)+ context = MagicMock()+ context.models.get_absolute_path.return_value = model_root++ encoder_ref = weakref.ref(encoder)++ def cleanup():+ gc.collect() # as production does; the frame local under test is a strong root gc cannot clear+ alive_at_cleanup.append(encoder_ref() is not None)++ seq_len = _GENERATE_DROP_IDX + 5+ model_inputs = MagicMock()+ model_inputs.input_ids = torch.zeros(1, seq_len, dtype=torch.long)+ model_inputs.attention_mask = torch.ones(1, seq_len, dtype=torch.long)+ model_inputs.to.return_value = model_inputs+ processor = MagicMock(return_value=model_inputs)++ # Hand the encoder over through a one-shot side effect: a `return_value` tuple would keep the mock holding a+ # strong reference of its own and mask the ownership being tested.+ handoff = [encoder]+ del encoder+ invocation = TestQuantizedEncoderLoad._make_invocation("none" if cached else "int8")+ loader = "_load_cached_encoder" if cached else "_load_quantized_encoder"+ with (+ patch.object(+ invocation,+ loader,+ side_effect=lambda _ctx: (handoff.pop(), torch.device("cpu"), cleanup),+ ),+ patch("transformers.AutoTokenizer.from_pretrained", return_value=MagicMock()),+ patch("transformers.Qwen2_5_VLProcessor", return_value=processor),+ ):+ return invocation._encode(context, images=[])++ @staticmethod+ def _run_encoder_frame_locals(tb) -> dict:+ return next(frame.f_locals for frame, _ in traceback.walk_tb(tb) if frame.f_code.co_name == "_run_encoder")++ def test_encoder_is_released_before_cleanup_runs(self, tmp_path: Path):+ alive_at_cleanup: list[bool] = []+ prompt_embeds, mask = self._run_encode(tmp_path, self._FakeEncoder(self.HIDDEN), alive_at_cleanup)++ assert alive_at_cleanup == [False], "cleanup ran while the encoder was still referenced"+ assert prompt_embeds.shape == (1, 5, self.HIDDEN)+ assert mask is None++ def test_encoder_is_released_before_cleanup_runs_when_the_forward_raises(self, tmp_path: Path):+ """An OOM inside the forward is the likeliest failure here. The in-flight traceback holds the forward's+ frames, whose locals reference the model, so without clearing them the release is a no-op exactly when+ VRAM is scarcest - and the next generation starts from a mis-budgeted cache."""+ alive_at_cleanup: list[bool] = []+ with pytest.raises(RuntimeError, match="simulated") as excinfo:+ self._run_encode(tmp_path, self._ExplodingEncoder(), alive_at_cleanup)+ assert alive_at_cleanup == [False], "cleanup ran while the traceback still referenced the encoder"+ # The traceback is still useful for the error report: the raising line is intact, only the locals are gone.+ assert "simulated" in "".join(traceback.format_tb(excinfo.tb))+ assert "text_encoder" not in self._run_encoder_frame_locals(excinfo.tb)++ def test_forward_frames_are_cleared_on_the_cached_path_too(self, tmp_path: Path):+ """On the (default) unquantized path the cache keeps the encoder, but the forward's frames still hold its+ activations (the full-vocabulary logits and every layer's hidden states) on the GPU for as long as the+ exception lives. The error report only formats the traceback, which clearing preserves."""+ alive_at_cleanup: list[bool] = []+ with pytest.raises(RuntimeError, match="simulated") as excinfo:+ self._run_encode(tmp_path, self._ExplodingEncoder(), alive_at_cleanup, cached=True)+ assert "simulated" in "".join(traceback.format_tb(excinfo.tb))+ assert "model_inputs" not in self._run_encoder_frame_locals(excinfo.tb)diff --cc tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.pyindex 84d7882667,0000000000..2274fb0109mode 100644,000000..100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py@@@ -1,156 -1,0 +1,189 @@@+"""Tests for the VRAM budget arithmetic behind lock()/partial loads.++`_get_vram_available` must count every byte this process can actually obtain: driver-free memory+PLUS the torch caching allocator's reserved-but-unused blocks (the allocator reuses those+directly, and `empty_cache()` returns whole unoccupied segments to the driver). Budgeting on+driver-free alone under-reported by whatever earlier stages freed without an `empty_cache()`+— observed in the wild as a fully-evictable multi-GB reserve pushing a 20 GB transformer down+to 0% VRAM residency while the allocator happily reused the "missing" memory for activations.+"""++import logging+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache++GB = 1024**3+MB = 1024**2++requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA.")+++class BigModule(torch.nn.Module):+ """A module whose single parameter is `mb` MiB of fp32."""++ def __init__(self, mb: int):+ super().__init__()+ self.weight = torch.nn.Parameter(torch.zeros(mb * MB // 4, dtype=torch.float32))++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return x+++def _make_cache(logger: logging.Logger | MagicMock | None = None) -> ModelCache:+ if logger is None:+ logger = MagicMock()+ logger.getEffectiveLevel.return_value = logging.INFO+ return ModelCache(+ execution_device_working_mem_gb=0.1,+ enable_partial_loading=True,+ keep_ram_copy_of_weights=True,+ execution_device="cuda:0",+ storage_device="cpu",+ logger=logger,+ shared_cpu_weights=None,+ )+++@requires_cuda+def test_lock_offloads_unlocked_models_under_working_memory_pressure():+ """A big working-memory reservation must evict resident-but-unlocked models so the locked+ model still loads fully (the freed bytes become budget via the allocator-reserve credit and+ the post-offload empty_cache)."""+ torch.cuda.empty_cache()+ cache = _make_cache()+ cache.put("A", BigModule(512))+ rec_a = cache.get("A")+ cache.lock(rec_a, None)+ cache.unlock(rec_a)+ assert rec_a.cached_model.cur_vram_bytes() >= 512 * MB++ free, _total = torch.cuda.mem_get_info(torch.device("cuda:0"))+ # Without offloading A there is only 128 MB of budget — far less than B needs.+ working = free - 128 * MB++ cache.put("B", BigModule(256))+ rec_b = cache.get("B")+ cache.lock(rec_b, working)+ try:+ assert rec_a.cached_model.cur_vram_bytes() == 0, "unlocked resident model was not offloaded"+ assert rec_b.cached_model.cur_vram_bytes() == rec_b.cached_model.total_bytes()+ finally:+ cache.unlock(rec_b)+++@requires_cuda+def test_get_vram_available_credits_reserved_but_free_allocator_blocks():+ """Freed-but-not-empty_cache'd allocator blocks are reclaimable and must count as available."""+ torch.cuda.empty_cache()+ cache = _make_cache()++ # Simulate a previous pipeline stage's freed activations: 1 GiB allocated then dropped, with+ # no empty_cache — the bytes stay in the allocator's reserve, invisible to mem_get_info.+ junk = torch.empty(1 * GB, dtype=torch.uint8, device="cuda:0")+ del junk++ free, _total = torch.cuda.mem_get_info(torch.device("cuda:0"))+ working = free - 128 * MB+ available = cache._get_vram_available(working)++ # Driver-free alone would report ~128 MB; the credited reserve must dominate. The margin+ # tolerates concurrent allocations by other processes on a shared dev GPU.+ assert available >= 900 * MB, f"reserved-but-free blocks not credited (available={available / MB:.0f}MB)"++ torch.cuda.empty_cache()+++@requires_cuda+def test_negative_budget_warns_and_names_locked_residents():+ """When the budget stays short after offloading, the first-pass warning must name what is+ still occupying the device — locked entries especially, since the offload cannot touch them."""+ torch.cuda.empty_cache()+ logger = MagicMock()+ logger.getEffectiveLevel.return_value = logging.INFO+ cache = _make_cache(logger)++ cache.put("stuck", BigModule(256))+ rec_stuck = cache.get("stuck")+ cache.lock(rec_stuck, None) # deliberately left locked++ free, _total = torch.cuda.mem_get_info(torch.device("cuda:0"))+ impossible_working = free + 10 * GB++ cache.put("victim", BigModule(64))+ rec_victim = cache.get("victim")+ cache.lock(rec_victim, impossible_working)+ try:+ # ModelCache wraps its logger in a PrefixedLoggerAdapter, so adapter.warning() reaches+ # the underlying (mock) logger as .log(WARNING, msg).+ warnings = [str(call.args[0]) for call in logger.warning.call_args_list]+ warnings += [+ str(call.args[1])+ for call in logger.log.call_args_list+ if call.args and call.args[0] == logging.WARNING and len(call.args) > 1+ ]+ budget_warnings = [message for message in warnings if "VRAM budget for 'victim' is short by" in message]++ assert budget_warnings, f"no budget-short warning emitted; warnings: {warnings}"+ assert "stuck=" in budget_warnings[0]+ assert "[locked]" in budget_warnings[0]+ finally:+ cache.unlock(rec_victim)+ cache.unlock(rec_stuck)+ torch.cuda.empty_cache()+++@requires_cuda+def test_reclaimable_credit_withheld_under_expandable_segments(monkeypatch: pytest.MonkeyPatch):+ """Under expandable-segments mode the (reserved - allocated) figure counts intra-segment+ holes that empty_cache cannot reclaim and a large allocation cannot use — the credit must be+ withheld entirely (the env parse is authoritative: the mode is fixed before torch import)."""+ cache = _make_cache()++ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")+ assert cache._get_reclaimable_allocator_bytes() == 0++ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:512")+ monkeypatch.setenv("PYTORCH_HIP_ALLOC_CONF", "expandable_segments: true")+ assert cache._get_reclaimable_allocator_bytes() == 0++ monkeypatch.delenv("PYTORCH_HIP_ALLOC_CONF")+ monkeypatch.delenv("PYTORCH_CUDA_ALLOC_CONF")+ # With no allocator config the credit path is active again (>= 0 by construction).+ assert cache._get_reclaimable_allocator_bytes() >= 0++++++def test_physical_availability_shares_the_reclaimable_credit_policy(monkeypatch: pytest.MonkeyPatch):++ """`_get_physical_vram_available` (out-of-cache loads, `make_room_in_vram`) must budget from the++ same device measurement as `lock()`: ignoring the cache cap, but still crediting the allocator++ reserve only through `_get_reclaimable_allocator_bytes` — never the raw reserved-minus-allocated++ figure, which over-reports under expandable segments."""++ cache = ModelCache(++ execution_device_working_mem_gb=1.0,++ enable_partial_loading=True,++ keep_ram_copy_of_weights=True,++ execution_device="cpu",++ storage_device="cpu",++ logger=MagicMock(),++ shared_cpu_weights=None,++ max_vram_cache_size_gb=1.0,++ )++ cache._execution_device = torch.device("cuda") # policy only; every VRAM query below is patched out++ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device: (4 * GB, 24 * GB))++ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device: 2 * GB)++ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda device: 5 * GB)++ monkeypatch.setattr(torch.cuda, "memory_stats", lambda device: {"inactive_split_bytes.all.current": GB})++ monkeypatch.delenv("PYTORCH_CUDA_ALLOC_CONF", raising=False)++ monkeypatch.delenv("PYTORCH_ALLOC_CONF", raising=False)++ monkeypatch.delenv("PYTORCH_HIP_ALLOC_CONF", raising=False)++++ # The cap governs the cache's own budget (1 GB cap - 1 GB working - 2 GB in use)...++ assert cache._get_vram_available(None) == -2 * GB++ # ...but not an out-of-cache load: 4 GB free + (5 - 2 - 1 inactive-split) GB reclaimable - 1 GB working.++ assert cache._get_physical_vram_available() == 5 * GB++++ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")++ assert cache._get_physical_vram_available() == 3 * GBdiff --cc tests/backend/quantization/test_fp8_scaled.pyindex 22fa9cb4d5,0000000000..414d7ce180mode 100644,000000..100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@@ -1,1296 -1,0 +1,1309 @@@+import contextlib+import logging+from unittest import mock++import pytest+import torch++from invokeai.backend.quantization.fp8_scaled import (+ FP8_DTYPE,+ Fp8ScaledLayer,+ attach_fp8_scales,+ cast_state_dict,+ count_fp8_weights,+ dequantize_fp8_scaled,+ dequantize_weight,+ detach_layer_sidechannel,+ device_supports_fp8_matmul,+ expand_weight_scale,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ is_matmul_usable_scale,+ is_scale_metadata_key,+ iter_weight_scale_pairs,+ parse_quantization_metadata,+ predict_cast_state_dict_size,+ reattach_layer_sidechannel,+ reset_fp8_matmul_support_cache,+ scaled_mm_linear,+ set_fp8_matmul_enabled,+ set_full_precision_hints_respected,+ split_fp8_scaled_layers,+ strip_layer_path_prefix,+ warn_on_unattached_scales,+)++cuda_fp8 = pytest.mark.skipif(+ not (torch.cuda.is_available() and device_supports_fp8_matmul(torch.device("cuda"))),+ reason="requires a CUDA device with fp8 tensor cores (SM 8.9+)",+)+++def _fp8_weight(out_f: int, in_f: int, per_channel: bool = False):+ w = torch.randn(out_f, in_f, dtype=torch.bfloat16) * 0.02+ if per_channel:+ scale = (w.abs().amax(dim=1) / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)+ q = (w / scale.reshape(-1, 1)).to(FP8_DTYPE)+ else:+ scale = (w.abs().amax() / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)+ q = (w / scale).to(FP8_DTYPE)+ return q, scale+++class TestExtract:+ def test_pops_scales_and_keys_layer_by_path(self):+ q, scale = _fp8_weight(32, 16)+ sd = {"blk.0.lin.weight": q, "blk.0.lin.weight_scale": scale, "blk.0.lin.bias": torch.zeros(32)}+ layers = extract_fp8_scaled_layers(sd)+ assert set(layers) == {"blk.0.lin"}+ assert "blk.0.lin.weight_scale" not in sd, "scale keys must be removed so the sd loads cleanly"+ assert sd["blk.0.lin.weight"].dtype == FP8_DTYPE, "weights must stay quantized"++ def test_accepts_scale_weight_suffix(self):+ q, scale = _fp8_weight(32, 16)+ sd = {"lin.weight": q, "lin.scale_weight": scale}+ assert set(extract_fp8_scaled_layers(sd)) == {"lin"}++ def test_input_scale_is_captured(self):+ q, scale = _fp8_weight(32, 16)+ sd = {"lin.weight": q, "lin.weight_scale": scale, "lin.input_scale": torch.tensor(0.5)}+ assert extract_fp8_scaled_layers(sd)["lin"].input_scale == pytest.approx(0.5)++ def test_scale_without_fp8_weight_is_dropped(self):+ """A scale applied to an already-dequantized weight would corrupt it."""+ sd = {"lin.weight": torch.randn(32, 16, dtype=torch.bfloat16), "lin.weight_scale": torch.tensor(2.0)}+ assert extract_fp8_scaled_layers(sd) == {}+ assert "lin.weight_scale" not in sd+++ def test_unparsed_scale_beside_fp8_weight_is_refused(self):++ """Loaders now drop unexpected keys at DEBUG, so a scale spelling the extractor does not read++ must fail here instead of letting the weight load unscaled."""++ q, scale = _fp8_weight(32, 16)++ sd = {"lin.weight": q, "lin.weight_scale_inv": scale}++ with pytest.raises(NotImplementedError, match="lin.weight_scale_inv"):++ extract_fp8_scaled_layers(sd)++++ def test_scale_like_key_beside_non_fp8_weight_is_not_a_scale(self):++ sd = {"norm.weight": torch.ones(16, dtype=torch.bfloat16), "norm.scale_shift": torch.ones(16)}++ assert extract_fp8_scaled_layers(sd) == {}++ assert "norm.scale_shift" in sd+++ def test_strips_stray_marker_keys(self):+ q, scale = _fp8_weight(32, 16)+ sd = {+ "lin.weight": q,+ "lin.weight_scale": scale,+ "scaled_fp8": torch.tensor(0.0),+ "comfy_quant_x": torch.tensor(1),+ }+ extract_fp8_scaled_layers(sd)+ assert set(sd) == {"lin.weight"}++ def test_full_precision_hint_from_metadata(self):+ q, scale = _fp8_weight(32, 16)+ sd = {"a.weight": q, "a.weight_scale": scale, "b.weight": q.clone(), "b.weight_scale": scale.clone()}+ meta = {"_quantization_metadata": '{"layers": {"a": {"full_precision_matrix_mult": true}, "b": {}}}'}+ layers = extract_fp8_scaled_layers(sd, meta)+ assert layers["a"].full_precision_matmul is True+ assert layers["b"].full_precision_matmul is False++ def test_malformed_metadata_is_ignored(self):+ assert parse_quantization_metadata({"_quantization_metadata": "not json"}) == {}+ assert parse_quantization_metadata(None) == {}++ def test_layer_hints_override_metadata(self):+ q, scale = _fp8_weight(32, 16)+ sd = {"renamed.lin.weight": q, "renamed.lin.weight_scale": scale}+ # Metadata uses the pre-rename path, so only the explicitly remapped hints can match.+ meta = {"_quantization_metadata": '{"layers": {"native.lin": {"full_precision_matrix_mult": true}}}'}+ layers = extract_fp8_scaled_layers(+ dict(sd), metadata=meta, layer_hints={"renamed.lin": {"full_precision_matrix_mult": True}}+ )+ assert layers["renamed.lin"].full_precision_matmul is True++ # Without the remap the flag silently matches nothing - the regression this guards against.+ layers = extract_fp8_scaled_layers(dict(sd), metadata=meta)+ assert layers["renamed.lin"].full_precision_matmul is False+++def _comfy_quant_blob(full_precision: bool):+ """The per-layer marker some ComfyUI exports write instead of the header entry."""+ payload = f'{{"format": "float8_e4m3fn", "full_precision_matrix_mult": {"true" if full_precision else "false"}}}'+ return torch.tensor(list(payload.encode("utf-8")), dtype=torch.uint8)+++class TestRawFp8:+ """Checkpoints that ship fp8 weights with no weight_scale at all."""++ def test_cast_state_dict_preserves_fp8_when_asked(self):+ q, _ = _fp8_weight(32, 16)+ sd = {"lin.weight": q, "lin.bias": torch.zeros(32), "norm.weight": torch.ones(16)}+ kept = cast_state_dict(sd, torch.bfloat16, keep_fp8=True)+ assert kept == 1+ assert sd["lin.weight"].dtype is FP8_DTYPE, "raw fp8 must survive the load"+ assert sd["lin.bias"].dtype is torch.bfloat16+ assert sd["norm.weight"].dtype is torch.bfloat16++ def test_cast_state_dict_dequantizes_when_matmul_unavailable(self):+ """Without the matmul, staying quantized costs a dequantize per forward for no gain."""+ q, _ = _fp8_weight(32, 16)+ sd = {"lin.weight": q}+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=False) == 0+ assert sd["lin.weight"].dtype is torch.bfloat16++ def test_e5m2_is_never_preserved(self):+ """scaled_mm cannot take e5m2 as the weight operand on Ada, so keeping it buys nothing."""+ sd = {"lin.weight": torch.zeros(32, 16).to(torch.float8_e5m2)}+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True) == 0+ assert sd["lin.weight"].dtype is torch.bfloat16++ def test_only_linear_weights_stay_quantized(self):+ """The regression an end-to-end run caught: checkpoints exist that quantize *everything*.++ A Z-Image checkpoint had 243 of its 453 fp8 tensors 1-D — biases, norm weights, a learned+ pad token. Keeping those quantized saves nothing usable and breaks inference: the fp8 value+ flows into the activations and the next Linear receives an fp8 *input*, which dies in+ `x.abs()` with `"abs_cuda" not implemented for 'Float8_e4m3fn'`.+ """+ model = torch.nn.Sequential()+ model.add_module("lin", torch.nn.Linear(16, 32))+ model.add_module("norm", torch.nn.LayerNorm(32))+ q, _ = _fp8_weight(32, 16)+ sd = {+ "lin.weight": q, # keep: a Linear weight the matmul can use+ "lin.bias": torch.zeros(32).to(FP8_DTYPE), # dequantize: bias+ "norm.weight": torch.ones(32).to(FP8_DTYPE), # dequantize: 1-D norm+ "pad_token": torch.zeros(1, 32).to(FP8_DTYPE), # dequantize: not a module weight+ }+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model) == 1+ assert sd["lin.weight"].dtype is FP8_DTYPE+ for key in ("lin.bias", "norm.weight", "pad_token"):+ assert sd[key].dtype is torch.bfloat16, f"{key} must not stay fp8"++ def test_skip_patterns_dequantize_named_modules(self):+ """Modules a model marks precision-sensitive must be dequantized even if they are Linears.++ Z-Image declares `_skip_layerwise_casting_patterns = ["t_embedder", "cap_embedder"]`, and+ `TimestepEmbedder.forward` casts its activations to `self.mlp[0].weight.dtype` — an fp8+ weight there makes the activations fp8.+ """+ model = torch.nn.Sequential()+ model.add_module("t_embedder", torch.nn.Linear(16, 32))+ model.add_module("blocks", torch.nn.Linear(16, 32))+ q, _ = _fp8_weight(32, 16)+ sd = {"t_embedder.weight": q, "blocks.weight": q.clone()}+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model, skip_patterns=["t_embedder"]) == 1+ assert sd["t_embedder.weight"].dtype is torch.bfloat16+ assert sd["blocks.weight"].dtype is FP8_DTYPE++ def test_count_fp8_weights(self):+ model = torch.nn.Sequential(torch.nn.Linear(16, 32, bias=False), torch.nn.Linear(32, 16, bias=False))+ assert count_fp8_weights(model) == 0+ model[0].weight = torch.nn.Parameter(_fp8_weight(32, 16)[0], requires_grad=False)+ assert count_fp8_weights(model) == 1++ @cuda_fp8+ def test_fp8_weight_without_scale_uses_the_tensor_cores(self):+ """The runtime already supports scale-less fp8 — `weight_scale` is optional in+ `scaled_mm_linear`, and `_can_use_fp8_matmul` only requires the fp8 dtype. This pins that+ down so a future change cannot quietly make a scale mandatory."""+ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+ )++ torch.manual_seed(0)+ net = torch.nn.Sequential(torch.nn.Linear(64, 64, bias=False)).cuda()+ net[0].weight.data = (net[0].weight.data * 0.02).to(FP8_DTYPE)+ apply_custom_layers_to_model(net)+ lin = net[0]+ x = torch.randn(1, 32, 64, device="cuda", dtype=torch.bfloat16)++ set_fp8_matmul_enabled(True)+ try:+ assert getattr(lin, "weight_scale", None) is None+ assert lin._can_use_fp8_matmul(x) is True+ out = net(x)+ finally:+ set_fp8_matmul_enabled(None)++ reference = torch.nn.functional.linear(x, dequantize_weight(lin.weight, None, x.dtype))+ rel = ((out.float() - reference.float()).norm() / reference.float().norm()).item()+ assert torch.isfinite(out).all()+ assert rel < 0.1, f"unit-scaled fp8 matmul drifted too far from bf16: {rel:.4f}"+++class TestInputScale:+ def test_calibrated_scale_is_kept(self):+ q, scale = _fp8_weight(32, 16)+ sd = {"lin.weight": q, "lin.weight_scale": scale, "lin.input_scale": torch.tensor(0.017)}+ layer = extract_fp8_scaled_layers(sd)["lin"]+ assert layer.input_scale is not None+ assert pytest.approx(layer.input_scale.item()) == 0.017+ assert "lin.input_scale" not in sd++ def test_scale_input_spelling_is_accepted(self):+ """`.scale_input` is the other spelling in the wild; ignoring it discards the calibration."""+ q, scale = _fp8_weight(32, 16)+ sd = {"lin.weight": q, "lin.scale_weight": scale, "lin.scale_input": torch.tensor(0.017)}+ layer = extract_fp8_scaled_layers(sd)["lin"]+ assert pytest.approx(layer.input_scale.item()) == 0.017+ assert not [k for k in sd if "scale_input" in k], "must be popped, not left for load_state_dict"++ @pytest.mark.parametrize(+ "value", [1.0, 0.0, -0.5, float("nan"), float("inf")], ids=["placeholder", "zero", "negative", "nan", "inf"]+ )+ def test_unusable_scales_fall_back_to_dynamic(self, value: float):+ """A 1.0 input_scale is an uncalibrated placeholder. Using it means *no* activation scaling,+ so everything above the fp8 max saturates -- strictly worse than the per-forward amax it+ would replace. Zero/negative/non-finite cannot be a divisor at all."""+ q, scale = _fp8_weight(32, 16)+ sd = {"lin.weight": q, "lin.weight_scale": scale, "lin.input_scale": torch.tensor(value)}+ assert extract_fp8_scaled_layers(sd)["lin"].input_scale is None++ @cuda_fp8+ def test_placeholder_scale_saturates_activations_above_the_fp8_range(self):+ """End-to-end cost of trusting a 1.0 placeholder.++ fp8_e4m3 is a floating-point format, so a scale factor does not buy relative precision the+ way it would for int8 — for activations inside +/-448 both paths are equivalent. The damage+ appears only above the representable range, where an unscaled cast clamps hard while the+ dynamic amax scale maps the whole tensor into range. Transformer activations do reach that+ regime, which is why a calibrated input_scale exists at all.+ """+ torch.manual_seed(0)+ q, scale = _fp8_weight(64, 64)+ q, scale = q.cuda(), scale.cuda()+ x = (torch.randn(32, 64, dtype=torch.bfloat16, device="cuda") * 2000.0).unsqueeze(0)+ assert x.abs().max() > 448, "test must exercise the saturating regime"+ reference = torch.nn.functional.linear(x, dequantize_weight(q, scale, x.dtype))++ def err(got: torch.Tensor) -> float:+ return ((got.float() - reference.float()).norm() / reference.float().norm()).item()++ dynamic = scaled_mm_linear(x, q, scale, None, input_scale=None)+ unscaled = scaled_mm_linear(x, q, scale, None, input_scale=torch.tensor(1.0, device="cuda"))+ assert err(dynamic) < err(unscaled) / 2, f"dynamic={err(dynamic):.4f} unscaled={err(unscaled):.4f}"+++class TestComfyQuantHints:+ def test_reads_per_layer_markers_and_pops_them(self):+ sd = {+ "blk.0.lin.weight": _fp8_weight(32, 16)[0],+ "blk.0.lin.comfy_quant": _comfy_quant_blob(True),+ "blk.1.lin.comfy_quant": _comfy_quant_blob(False),+ }+ hints = extract_comfy_quant_hints(sd)+ assert hints["blk.0.lin"]["full_precision_matrix_mult"] is True+ assert hints["blk.1.lin"]["full_precision_matrix_mult"] is False+ assert not [k for k in sd if "comfy_quant" in k], "markers must not reach load_state_dict"++ def test_full_precision_flag_reaches_the_layer(self):+ """The regression this guards: a checkpoint carrying the flags *only* in per-layer markers+ had them silently ignored, so layers the producer marked unsafe were multiplied in fp8."""+ q, scale = _fp8_weight(32, 16)+ sd = {"blk.0.lin.weight": q, "blk.0.lin.weight_scale": scale, "blk.0.lin.comfy_quant": _comfy_quant_blob(True)}+ hints = extract_comfy_quant_hints(sd)+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)+ assert layers["blk.0.lin"].full_precision_matmul is True++ # Reading only the header (no hints) is what used to happen - the flag matches nothing.+ sd2 = {"blk.0.lin.weight": q, "blk.0.lin.weight_scale": scale, "blk.0.lin.comfy_quant": _comfy_quant_blob(True)}+ assert extract_fp8_scaled_layers(sd2).get("blk.0.lin").full_precision_matmul is False++ def test_nul_padded_and_malformed_blobs(self):+ padded = torch.cat([_comfy_quant_blob(True), torch.zeros(8, dtype=torch.uint8)])+ sd = {+ "a.comfy_quant": padded,+ "b.comfy_quant": torch.tensor(list(b"not json"), dtype=torch.uint8),+ }+ hints = extract_comfy_quant_hints(sd)+ assert hints["a"]["full_precision_matrix_mult"] is True+ # A malformed marker is a lost hint, never a failed load.+ assert "b" not in hints+ assert not sd+++class TestQwen3VLKeyRemap:+ def test_scale_keys_and_hint_paths_land_on_the_same_module(self):+ """attach_fp8_scales resolves hint paths against the *model*, so the state-dict remap and the+ hint remap must agree - otherwise every recovered scale silently matches nothing."""+ from invokeai.backend.model_manager.load.model_loaders.krea2 import (+ _qwen3vl_target_key,+ _remap_qwen3vl_singlefile_keys,+ )++ q, scale = _fp8_weight(32, 16)+ sd = _remap_qwen3vl_singlefile_keys(+ {+ "model.layers.0.mlp.down_proj.weight": q,+ "model.layers.0.mlp.down_proj.weight_scale": scale,+ "model.visual.blocks.0.attn.qkv.weight": torch.zeros(16, 16),+ }+ )+ assert "language_model.layers.0.mlp.down_proj.weight_scale" in sd+ assert "visual.blocks.0.attn.qkv.weight" in sd++ hints = {_qwen3vl_target_key("model.layers.0.mlp.down_proj"): {"full_precision_matrix_mult": True}}+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)+ assert set(layers) == {"language_model.layers.0.mlp.down_proj"}+ assert layers["language_model.layers.0.mlp.down_proj"].full_precision_matmul is True+++class TestFullPrecisionHintToggle:+ def test_marker_is_applied_by_default(self):+ q, scale = _fp8_weight(32, 16)+ module = torch.nn.Linear(16, 32, bias=False)+ module.weight = torch.nn.Parameter(q, requires_grad=False)+ model = torch.nn.Sequential()+ model.add_module("lin", module)+ attach_fp8_scales(model, {"lin": Fp8ScaledLayer(weight_scale=scale, full_precision_matmul=True)})+ assert module._fp8_full_precision_matmul is True++ def test_marker_suppressed_when_hints_are_off(self):+ """Turning the hints off must reach the module flag CustomLinear reads, not just the parse."""+ q, scale = _fp8_weight(32, 16)+ module = torch.nn.Linear(16, 32, bias=False)+ module.weight = torch.nn.Parameter(q, requires_grad=False)+ model = torch.nn.Sequential()+ model.add_module("lin", module)+ set_full_precision_hints_respected(False)+ try:+ attach_fp8_scales(model, {"lin": Fp8ScaledLayer(weight_scale=scale, full_precision_matmul=True)})+ finally:+ set_full_precision_hints_respected(None)+ assert module._fp8_full_precision_matmul is False+++class TestKrea2MetadataRemap:+ def test_native_layer_paths_are_remapped_like_the_state_dict(self):+ """The quantization metadata names layers natively; the scales are keyed after renaming."""+ from invokeai.backend.model_manager.load.model_loaders.krea2 import _remap_native_layer_paths++ mapping = _remap_native_layer_paths(+ ["blocks.0.attn.wq", "blocks.0.attn.wo", "blocks.3.mlp.down", "txtfusion.refiner_blocks.1.attn.wk"]+ )+ assert mapping["blocks.0.attn.wq"] == "transformer_blocks.0.attn.to_q"+ assert mapping["blocks.0.attn.wo"] == "transformer_blocks.0.attn.to_out.0"+ assert mapping["blocks.3.mlp.down"] == "transformer_blocks.3.ff.down"+ assert mapping["txtfusion.refiner_blocks.1.attn.wk"] == "text_fusion.refiner_blocks.1.attn.to_k"+++class TestSplitScaledLayers:+ """A scaled layer must never reach `cast_state_dict` still holding an unapplied scale."""++ def _model(self):+ model = torch.nn.Sequential()+ model.add_module("time_embed", torch.nn.Sequential())+ model.time_embed.add_module("linear_2", torch.nn.Linear(16, 32))+ model.add_module("attn", torch.nn.Linear(16, 32))+ return model++ def test_skip_pattern_layer_is_dequantized_with_its_scale(self):+ """The Krea-2 regression: `time_embed` matches the model's skip patterns, so the cast would+ turn its fp8 weight into bf16 *codes* — the scale silently dropped, the weight off by+ 1/weight_scale, and `attach_fp8_scales` unable to repair it afterwards."""+ model = self._model()+ w = torch.randn(32, 16, dtype=torch.bfloat16) * 0.02+ scale = (w.abs().amax() / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)+ q = (w / scale).to(FP8_DTYPE)+ sd = {"time_embed.linear_2.weight": q, "attn.weight": q.clone()}+ layers = {+ "time_embed.linear_2": Fp8ScaledLayer(weight_scale=scale),+ "attn": Fp8ScaledLayer(weight_scale=scale),+ }++ remaining = split_fp8_scaled_layers(+ sd, layers, torch.bfloat16, model=model, skip_patterns=["time_embed", "norm"]+ )++ assert set(remaining) == {"attn"}, "only the layer that can stay quantized is left to attach"+ assert sd["time_embed.linear_2.weight"].dtype is torch.bfloat16+ rel = ((sd["time_embed.linear_2.weight"].float() - w.float()).norm() / w.float().norm()).item()+ assert rel < 0.05, f"the scale was not applied on the way down: rel-err {rel:.4f}"++ # And the survivor is untouched by the subsequent cast, so its scale still attaches.+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model, skip_patterns=["time_embed"]) == 1+ model.load_state_dict(sd, assign=True, strict=False)+ assert attach_fp8_scales(model, remaining) == 1+ assert torch.equal(model.attn.weight_scale, scale)++ def test_non_linear_scaled_weight_is_dequantized_with_its_scale(self):+ """Same failure without any skip pattern: a scaled tensor that is not an nn.Linear weight+ fails `_is_fp8_matmul_weight`, so the cast would strip its scale."""+ model = self._model()+ q, scale = _fp8_weight(32, 16)+ sd = {"pad_token.weight": q}+ remaining = split_fp8_scaled_layers(+ sd, {"pad_token": Fp8ScaledLayer(weight_scale=scale)}, torch.bfloat16, model=model+ )+ assert remaining == {}+ assert torch.equal(sd["pad_token.weight"], dequantize_weight(q, scale, torch.bfloat16))++ def test_warns_when_a_scale_finds_no_module(self):+ logger = logging.getLogger("fp8-test")+ with mock.patch.object(logger, "warning") as warn:+ warn_on_unattached_scales(logger, "Krea-2", 1, {"a": object(), "b": object()})+ assert warn.call_count == 1+ assert "1 of 2" in warn.call_args[0][0]++ def test_silent_when_every_scale_landed(self):+ logger = logging.getLogger("fp8-test")+ with mock.patch.object(logger, "warning") as warn:+ warn_on_unattached_scales(logger, "Krea-2", 2, {"a": object(), "b": object()})+ assert warn.call_count == 0+++class TestPredictedSize:+ def test_matches_what_cast_state_dict_actually_leaves(self):+ """`make_room` reserves against this, so a mismatch is a silent under-reservation."""+ model = torch.nn.Sequential()+ model.add_module("lin", torch.nn.Linear(16, 32))+ model.add_module("t_embedder", torch.nn.Linear(16, 32))+ model.add_module("norm", torch.nn.LayerNorm(32))+ q, _ = _fp8_weight(32, 16)+ sd = {+ "lin.weight": q,+ "lin.bias": torch.zeros(32).to(FP8_DTYPE),+ "t_embedder.weight": q.clone(),+ "norm.weight": torch.ones(32).to(FP8_DTYPE),+ "pad_token": torch.zeros(1, 32).to(FP8_DTYPE),+ }+ kwargs = {"model": model, "skip_patterns": ["t_embedder"]}+ # What the loaders used to reserve: 1 byte/element for *every* fp8 tensor.+ naive = sum(t.nelement() * (t.element_size() if t.dtype is FP8_DTYPE else 2) for t in sd.values())++ predicted = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, **kwargs)+ cast_state_dict(sd, torch.bfloat16, keep_fp8=True, **kwargs)+ actual = sum(t.nelement() * t.element_size() for t in sd.values())+ assert predicted == actual++ # Only `lin.weight` stays 1 byte/element; the rest lands at 2, so the old sum under-counted.+ assert naive < actual++ def test_all_dequantized_when_keep_fp8_is_off(self):+ q, _ = _fp8_weight(32, 16)+ sd = {"lin.weight": q}+ assert predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=False) == q.nelement() * 2+++class TestDeviceSupport:+ def test_probe_decides_rather_than_the_capability_number(self):+ """ROCm reports the gfx arch from `get_device_capability`, so RDNA3 (gfx1100 -> (11, 0))+ passes a `>= (8, 9)` test and then raises on every forward. The probe is what decides."""+ reset_fp8_matmul_support_cache()+ with mock.patch("torch.cuda.is_available", return_value=True):+ with mock.patch("torch.cuda.get_device_capability", return_value=(11, 0)):+ with mock.patch(+ "invokeai.backend.quantization.fp8_scaled._probe_fp8_matmul", return_value=False+ ) as probe:+ assert device_supports_fp8_matmul(torch.device("cuda", 0)) is False+ assert probe.called+ reset_fp8_matmul_support_cache()++ def test_probe_result_is_cached_per_device(self):+ reset_fp8_matmul_support_cache()+ with mock.patch("torch.cuda.is_available", return_value=True):+ with mock.patch("torch.cuda.get_device_capability", return_value=(8, 9)):+ with mock.patch(+ "invokeai.backend.quantization.fp8_scaled._probe_fp8_matmul", return_value=True+ ) as probe:+ assert device_supports_fp8_matmul(torch.device("cuda", 0)) is True+ assert device_supports_fp8_matmul(torch.device("cuda", 0)) is True+ assert probe.call_count == 1+ reset_fp8_matmul_support_cache()++ def test_non_cuda_never_probes(self):+ reset_fp8_matmul_support_cache()+ with mock.patch("invokeai.backend.quantization.fp8_scaled._probe_fp8_matmul") as probe:+ assert device_supports_fp8_matmul(torch.device("cpu")) is False+ assert not probe.called+++class TestDequantize:+ @pytest.mark.parametrize("per_channel", [False, True])+ def test_roundtrip_close_to_original(self, per_channel: bool):+ w = torch.randn(64, 32, dtype=torch.bfloat16) * 0.02+ scale_src = w.abs().amax(dim=1) if per_channel else w.abs().amax()+ scale = (scale_src / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)+ q = (w / (scale.reshape(-1, 1) if per_channel else scale)).to(FP8_DTYPE)++ out = dequantize_weight(q, scale, torch.bfloat16)+ assert out.dtype == torch.bfloat16+ assert ((out.float() - w.float()).norm() / w.float().norm()).item() < 0.05++ def test_missing_scale_is_a_plain_cast(self):+ """fp8_storage layerwise casting produces scale-free fp8 weights."""+ q = torch.randn(8, 8, dtype=torch.bfloat16).to(FP8_DTYPE)+ assert torch.equal(dequantize_weight(q, None, torch.bfloat16), q.to(torch.bfloat16))++ def test_state_dict_dequantization_matches_helper(self):+ q, scale = _fp8_weight(64, 32)+ sd = {"lin.weight": q}+ layers = {"lin": Fp8ScaledLayer(weight_scale=scale)}+ dequantize_fp8_scaled(sd, layers)+ assert torch.equal(sd["lin.weight"], dequantize_weight(q, scale, torch.bfloat16))+++class TestAttach:+ def test_registers_non_persistent_buffers(self):+ lin = torch.nn.Linear(16, 32, bias=False)+ q, scale = _fp8_weight(32, 16)+ lin.weight = torch.nn.Parameter(q, requires_grad=False)+ model = torch.nn.Sequential(lin)++ assert attach_fp8_scales(model, {"0": Fp8ScaledLayer(weight_scale=scale, full_precision_matmul=True)}) == 1+ assert torch.equal(model[0].weight_scale, scale)+ assert model[0]._fp8_full_precision_matmul is True+ # Re-saving a model whose scales landed in state_dict() would double-scale on reload.+ assert "0.weight_scale" not in model.state_dict()++ def test_skips_non_fp8_modules(self):+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))+ assert attach_fp8_scales(model, {"0": Fp8ScaledLayer(weight_scale=torch.tensor(1.0))}) == 0+++@cuda_fp8+class TestScaledMm:+ @pytest.mark.parametrize("per_channel", [False, True])+ @pytest.mark.parametrize("tokens", [64, 100]) # 100 is deliberately not a multiple of 16+ def test_matches_reference_linear(self, per_channel: bool, tokens: int):+ dev = torch.device("cuda")+ q, scale = _fp8_weight(256, 128, per_channel)+ q, scale = q.to(dev), scale.to(dev)+ w_ref = dequantize_weight(q, scale, torch.bfloat16)+ x = torch.randn(tokens, 128, device=dev, dtype=torch.bfloat16)++ got = scaled_mm_linear(x, q, scale)+ expected = torch.nn.functional.linear(x, w_ref)++ assert got.shape == expected.shape+ rel = ((got.float() - expected.float()).norm() / expected.float().norm()).item()+ assert rel < 0.08, f"relative error {rel:.4f} too high"++ def test_preserves_leading_dims_and_bias(self):+ dev = torch.device("cuda")+ q, scale = _fp8_weight(64, 32)+ q, scale = q.to(dev), scale.to(dev)+ bias = torch.randn(64, device=dev, dtype=torch.bfloat16)+ x = torch.randn(2, 48, 32, device=dev, dtype=torch.bfloat16)++ got = scaled_mm_linear(x, q, scale, bias)+ expected = torch.nn.functional.linear(x, dequantize_weight(q, scale, torch.bfloat16), bias)+ assert got.shape == (2, 48, 64)+ assert ((got.float() - expected.float()).norm() / expected.float().norm()).item() < 0.08++ def test_static_input_scale_path(self):+ dev = torch.device("cuda")+ q, scale = _fp8_weight(64, 32)+ q, scale = q.to(dev), scale.to(dev)+ x = torch.randn(32, 32, device=dev, dtype=torch.bfloat16)+ static = (x.abs().amax() / torch.finfo(FP8_DTYPE).max).float()++ got = scaled_mm_linear(x, q, scale, input_scale=static)+ expected = torch.nn.functional.linear(x, dequantize_weight(q, scale, torch.bfloat16))+ assert ((got.float() - expected.float()).norm() / expected.float().norm()).item() < 0.08+++class TestCustomLinearIntegration:+ """The fp8 matmul must be opt-in and must degrade to the dequantized path, never raise."""++ @pytest.fixture(autouse=True)+ def _restore_matmul_override(self):+ """Clear the override after each test, rather than leaving it pinned to ``False``.++ These tests reset with ``set_fp8_matmul_enabled(False)``, which is not the neutral state --+ it is an explicit "off" that outlives the class and silently overrides the config for+ anything that runs later in the same process.+ """+ yield+ set_fp8_matmul_enabled(None)++ def _module(self, device: torch.device, in_f=64, out_f=128, device_autocasting: bool = False):+ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+ )++ lin = torch.nn.Linear(in_f, out_f, bias=False)+ q, scale = _fp8_weight(out_f, in_f)+ lin.weight = torch.nn.Parameter(q.to(device), requires_grad=False)+ lin.register_buffer("weight_scale", scale.to(device), persistent=False)+ model = torch.nn.Sequential(lin).to(device)+ apply_custom_layers_to_model(model, device_autocasting_enabled=device_autocasting)+ return model++ @cuda_fp8+ @pytest.mark.parametrize("device_autocasting", [False, True])+ def test_fp8_path_runs_regardless_of_device_autocasting(self, device_autocasting: bool):+ """`apply_custom_layers_to_model` leaves autocasting off for fully-resident models.++ A fp8 check that only lives in `_autocast_forward` is therefore skipped in the common case:+ `forward` falls through to the dtype-mismatch branch and silently dequantizes instead. This+ regression cost the entire speedup while every other test stayed green.+ """+ dev = torch.device("cuda")+ model = self._module(dev, device_autocasting=device_autocasting)+ x = torch.randn(32, 64, device=dev, dtype=torch.bfloat16)+ custom = model[0]++ calls = []+ original = custom._maybe_fp8_forward+ custom._maybe_fp8_forward = lambda inp: (calls.append(1), original(inp))[1]++ set_fp8_matmul_enabled(True)+ try:+ out = model(x)+ finally:+ set_fp8_matmul_enabled(False)+ custom._maybe_fp8_forward = original++ assert calls, "the fp8 branch was never consulted"+ assert out.shape == (32, 128)+ # And it must actually have taken the fp8 path, not just been asked.+ w_ref = dequantize_weight(custom.weight, custom.weight_scale, torch.bfloat16)+ assert not torch.equal(out, torch.nn.functional.linear(x, w_ref)), (+ "output is bit-identical to the dequantized path, so _scaled_mm did not run"+ )++ def test_disabled_by_default_uses_scaled_dequant(self):+ """With the matmul off, the weight must still be dequantized *with* its scale."""+ set_fp8_matmul_enabled(False)+ dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")+ # CPU inference is float32 in the product (TorchDevice.choose_torch_dtype). A bf16 input+ # here would also hit an illegal-instruction fault (0xC000001D) in the Windows CPU torch+ # build's bf16 GEMM on some GitHub runner CPUs, taking the whole xdist worker down.+ dtype = torch.bfloat16 if dev.type == "cuda" else torch.float32+ model = self._module(dev)+ x = torch.randn(32, 64, device=dev, dtype=dtype)++ got = model(x)+ w_ref = dequantize_weight(model[0].weight, model[0].weight_scale, dtype)+ expected = torch.nn.functional.linear(x, w_ref)+ assert torch.equal(got, expected)++ @cuda_fp8+ def test_full_precision_flag_forces_fallback(self):+ set_fp8_matmul_enabled(True)+ try:+ dev = torch.device("cuda")+ model = self._module(dev)+ model[0]._fp8_full_precision_matmul = True+ x = torch.randn(32, 64, device=dev, dtype=torch.bfloat16)++ got = model(x)+ w_ref = dequantize_weight(model[0].weight, model[0].weight_scale, torch.bfloat16)+ assert torch.equal(got, torch.nn.functional.linear(x, w_ref))+ finally:+ set_fp8_matmul_enabled(False)++ @cuda_fp8+ def test_sidecar_patched_fp8_layer_uses_the_fp8_matmul(self):+ """LoRAs on fp8 weights are force-routed to sidecar patching (layer_patcher), and the+ sidecar wrapper calls `_autocast_forward`. The fp8 branch must survive that route, and the+ LoRA residual must still be added on top."""+ from invokeai.backend.patches.layers.lora_layer import LoRALayer++ dev = torch.device("cuda")+ model = self._module(dev)+ custom = model[0]+ rank = 8+ lora = LoRALayer(+ up=torch.randn(custom.out_features, rank, device=dev, dtype=torch.bfloat16) * 0.05,+ mid=None,+ down=torch.randn(rank, custom.in_features, device=dev, dtype=torch.bfloat16) * 0.05,+ alpha=float(rank),+ bias=None,+ )+ custom.add_patch(lora, 1.0)+ x = torch.randn(32, 64, device=dev, dtype=torch.bfloat16)++ set_fp8_matmul_enabled(True)+ try:+ patched = model(x)+ finally:+ set_fp8_matmul_enabled(False)+ unpatched_ref = torch.nn.functional.linear(+ x, dequantize_weight(custom.weight, custom.weight_scale, torch.bfloat16)+ )++ assert patched.shape == (32, 128)+ # The patch must actually change the output...+ assert not torch.allclose(patched, unpatched_ref, atol=1e-2)+ # ...and the base contribution must still be roughly the fp8 linear, not garbage.+ residual = (lora.get_weight(1.0) * lora.scale()).to(torch.bfloat16)+ expected = unpatched_ref + torch.nn.functional.linear(x, residual)+ rel = ((patched.float() - expected.float()).norm() / expected.float().norm()).item()+ assert rel < 0.1, f"sidecar-patched fp8 output diverges by {rel:.4f}"++ @cuda_fp8+ def test_unaligned_features_fall_back(self):+ set_fp8_matmul_enabled(True)+ try:+ dev = torch.device("cuda")+ model = self._module(dev, in_f=60, out_f=120) # not multiples of 16+ x = torch.randn(16, 60, device=dev, dtype=torch.bfloat16)+ assert model(x).shape == (16, 120) # must not raise+ finally:+ set_fp8_matmul_enabled(False)++ @cuda_fp8+ def test_enabled_path_agrees_with_fallback(self):+ dev = torch.device("cuda")+ model = self._module(dev)+ x = torch.randn(48, 64, device=dev, dtype=torch.bfloat16)++ set_fp8_matmul_enabled(False)+ baseline = model(x)+ set_fp8_matmul_enabled(True)+ try:+ fp8 = model(x)+ finally:+ set_fp8_matmul_enabled(False)++ rel = ((fp8.float() - baseline.float()).norm() / baseline.float().norm()).item()+ assert rel < 0.1, f"fp8 matmul diverges from the dequantized path by {rel:.4f}"+++class TestScaleSpellingHelpers:+ """Both spellings of the weight scale must be handled everywhere.++ Reading only `.weight_scale` is the mistake that keeps recurring in the per-loader dequant+ helpers. Depending on what the loader strips afterwards it either deletes a `.scale_weight`+ without applying it — leaving the weight off by `1/weight_scale`, silently — or leaves the key+ behind for `load_state_dict(..., strict=True)` to reject.+ """++ @pytest.mark.parametrize("spelling", [".weight_scale", ".scale_weight"])+ def test_pairs_are_found_in_either_spelling(self, spelling: str) -> None:+ sd = {"blk.weight": torch.ones(2, 2), f"blk{spelling}": torch.tensor(0.5)}++ assert list(iter_weight_scale_pairs(sd)) == [("blk.weight", f"blk{spelling}")]++ def test_a_scale_without_its_weight_is_not_paired(self) -> None:+ # Pairing it would invent a weight key the checkpoint never had.+ sd = {"other.weight": torch.ones(1), "blk.weight_scale": torch.tensor(0.5)}++ assert list(iter_weight_scale_pairs(sd)) == []++ def test_non_string_keys_are_ignored(self) -> None:+ # `.pt`/`.ckpt` sources can carry int keys; `endswith` would raise on them.+ assert list(iter_weight_scale_pairs({0: torch.ones(1)})) == []++ @pytest.mark.parametrize(+ "key",+ [".weight_scale", ".scale_weight", ".input_scale", ".scale_input"],+ )+ def test_metadata_keys_are_recognized_in_either_spelling(self, key: str) -> None:+ assert is_scale_metadata_key(f"blk{key}")++ @pytest.mark.parametrize("key", ["blk.comfy_quant", "scaled_fp8"])+ def test_marker_keys_are_recognized(self, key: str) -> None:+ assert is_scale_metadata_key(key)++ @pytest.mark.parametrize("key", ["blk.weight", "blk.bias", "norm.scale", 0])+ def test_model_tensors_are_not_mistaken_for_metadata(self, key: object) -> None:+ # `norm.scale` is a real learned parameter in several architectures - stripping it would+ # delete weights, and it is why this cannot just match "scale" anywhere in the key.+ assert not is_scale_metadata_key(key)+++def _fp8(rows: int = 4, cols: int = 4, value: float = 1.0) -> torch.Tensor:+ return (torch.ones(rows, cols) * value).to(FP8_DTYPE)+++class _Linear(torch.nn.Module):+ def __init__(self, out_features: int = 4, in_features: int = 4) -> None:+ super().__init__()+ self.lin = torch.nn.Linear(in_features, out_features, bias=False)+++class TestE5m2ScaleRecovery:+ """`float8_e5m2` may not stay quantized, but it must not lose its scale on the way to bf16."""++ def test_the_scale_is_recovered_and_folded(self) -> None:+ # Gating extraction on e4m3fn alone popped the scale key and then dropped it, so+ # `cast_state_dict` did a plain `.to(bf16)` and the weight came out off by 1/weight_scale.+ sd = {"lin.weight": (torch.ones(4, 4) * 2).to(torch.float8_e5m2), "lin.weight_scale": torch.tensor(0.25)}++ layers = extract_fp8_scaled_layers(sd)+ assert "lin" in layers++ dequantize_fp8_scaled(sd, layers, torch.bfloat16)+ assert torch.allclose(sd["lin.weight"].float(), torch.full((4, 4), 0.5))++ def test_it_is_never_left_quantized(self) -> None:+ """`scaled_mm_linear` cannot take e5m2 as the weight operand, so it must be widened."""+ sd = {"lin.weight": (torch.ones(4, 4) * 2).to(torch.float8_e5m2), "lin.weight_scale": torch.tensor(0.25)}++ kept = split_fp8_scaled_layers(sd, extract_fp8_scaled_layers(sd), torch.bfloat16, model=_Linear())++ assert kept == {}+ assert sd["lin.weight"].dtype is torch.bfloat16+ assert torch.allclose(sd["lin.weight"].float(), torch.full((4, 4), 0.5))+++class TestBlockWiseScale:+ """A 2-D ``weight_scale`` has one entry per *block* of weight elements, not per row."""++ def test_the_layout_survives_extraction(self) -> None:+ # Flattening it destroys the block geometry, and the multiply then fails on shape.+ sd = {"b.weight": _fp8(64, 128), "b.weight_scale": torch.full((64, 2), 0.5)}++ layers = extract_fp8_scaled_layers(sd)++ assert tuple(layers["b"].weight_scale.shape) == (64, 2)++ def test_it_is_expanded_rather_than_raising(self) -> None:+ # Before: `RuntimeError: The size of tensor a (64) must match the size of tensor b (128)`,+ # i.e. with fp8_compute off - the default - the model failed to load at all.+ sd = {"b.weight": _fp8(64, 128), "b.weight_scale": torch.full((64, 2), 0.5)}++ dequantize_fp8_scaled(sd, extract_fp8_scaled_layers(sd), torch.bfloat16)++ assert sd["b.weight"].shape == (64, 128)+ assert torch.allclose(sd["b.weight"].float(), torch.full((64, 128), 0.5))++ def test_it_is_never_left_quantized(self) -> None:+ """`scaled_mm_linear` can apply a per-tensor or per-row scale and nothing else.++ Left quantized, the mismatch surfaces mid-generation inside the kernel instead.+ Dequantizing here - before `predict_cast_state_dict_size` runs - also keeps the RAM+ reservation honest.+ """+ sd = {"lin.weight": _fp8(4, 4), "lin.weight_scale": torch.full((4, 2), 0.5)}++ kept = split_fp8_scaled_layers(sd, extract_fp8_scaled_layers(sd), torch.bfloat16, model=_Linear())++ assert kept == {}+ assert sd["lin.weight"].dtype is torch.bfloat16++ def test_a_per_row_scale_still_stays_quantized(self) -> None:+ sd = {"lin.weight": _fp8(4, 4), "lin.weight_scale": torch.full((4,), 0.5)}++ kept = split_fp8_scaled_layers(sd, extract_fp8_scaled_layers(sd), torch.bfloat16, model=_Linear())++ assert set(kept) == {"lin"}+ assert sd["lin.weight"].dtype is FP8_DTYPE+++class TestSidechannelDetachReattach:+ """Key converters rename ``.weight``; the side channel has to be carried across separately."""++ def test_entries_follow_their_module_to_the_new_path(self) -> None:+ sd = {+ "old.linear.weight": _fp8(),+ "old.linear.weight_scale": torch.tensor(0.5),+ "old.linear.input_scale": torch.tensor(0.25),+ }++ detached = detach_layer_sidechannel(sd)+ assert list(sd) == ["old.linear.weight"], "scales must be out of the converter's way"++ converted = {"new.linear.weight": sd["old.linear.weight"]}+ orphaned = reattach_layer_sidechannel(converted, detached, {"old.linear": "new.linear"})++ assert orphaned == []+ layers = extract_fp8_scaled_layers(converted)+ assert set(layers) == {"new.linear"}+ assert layers["new.linear"].input_scale is not None++ def test_a_module_the_converter_drops_is_reported_not_swallowed(self) -> None:+ """A silently dropped scale is exactly the failure this pair exists to prevent."""+ sd = {"gone.weight": _fp8(), "gone.weight_scale": torch.tensor(0.5)}++ detached = detach_layer_sidechannel(sd)+ orphaned = reattach_layer_sidechannel({}, detached, {})++ assert orphaned == ["gone"]++ def test_both_scale_spellings_are_detached(self) -> None:+ sd = {+ "a.weight": _fp8(),+ "a.scale_weight": torch.tensor(0.5),+ "b.weight": _fp8(),+ "b.weight_scale": torch.tensor(0.5),+ }++ detached = detach_layer_sidechannel(sd)++ assert set(detached) == {"a", "b"}+++class TestStripLayerPathPrefix:+ """`_quantization_metadata` is read from the file header, so its names keep the prefix."""++ def test_the_checkpoint_prefix_is_removed(self) -> None:+ hints = {"model.diffusion_model.blocks.0.attn.wq": {"full_precision_matrix_mult": True}}++ assert strip_layer_path_prefix(hints) == {"blocks.0.attn.wq": {"full_precision_matrix_mult": True}}++ def test_unprefixed_names_are_passed_through_not_dropped(self) -> None:+ """Running the names through a prefix *filter* truncated a partially-prefixed header, and+ the strict-zip that read the result back aborted the whole load with a ValueError."""+ hints = {"net.blocks.0.attn.q_proj": {}, "final_layer.linear": {}}++ assert set(strip_layer_path_prefix(hints)) == {"blocks.0.attn.q_proj", "final_layer.linear"}+++class TestNonFloatTensorsAreNotCast:+ """Integer payloads are not weights; casting them to the compute dtype corrupts them."""++ def test_cast_state_dict_leaves_them_alone(self) -> None:+ sd = {"w.weight": torch.ones(2, 2), "ids": torch.arange(4, dtype=torch.int64)}++ cast_state_dict(sd, torch.bfloat16, keep_fp8=False)++ assert sd["w.weight"].dtype is torch.bfloat16+ assert sd["ids"].dtype is torch.int64++ def test_the_size_prediction_agrees(self) -> None:+ sd = {"ids": torch.arange(4, dtype=torch.int64)}++ assert predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=False) == 4 * 8+++def _probe_on_cpu():+ """Let `_probe_fp8_matmul` run its allocations on CPU so the caching policy can be tested.++ The probe allocates real tensors on the device *before* it reaches `torch._scaled_mm`. On a+ CPU-only runner that allocation raises first, the mocked matmul never runs, and the test+ measures the wrong thing — it passed on a CUDA box and failed on CI for exactly this reason.+ float8 tensors are allocatable on CPU, so dropping the device argument is enough.+ """+ real_zeros, real_ones = torch.zeros, torch.ones++ def on_cpu(real):+ def alloc(*args, **kwargs):+ kwargs.pop("device", None)+ return real(*args, **kwargs)++ return alloc++ with (+ mock.patch("torch.cuda.is_available", return_value=True),+ mock.patch("torch.cuda.get_device_capability", return_value=(8, 9)),+ mock.patch("torch.cuda.current_device", return_value=0),+ mock.patch("torch.zeros", on_cpu(real_zeros)),+ mock.patch("torch.ones", on_cpu(real_ones)),+ ):+ yield+++class TestProbeFailureCaching:+ """The probe runs during a model load, i.e. under real VRAM pressure."""++ def test_an_allocation_failure_is_not_cached(self) -> None:+ reset_fp8_matmul_support_cache()+ device = torch.device("cuda", 0)+ with _probe_on_cpu():+ with mock.patch("torch._scaled_mm", side_effect=torch.OutOfMemoryError("transient")):+ assert device_supports_fp8_matmul(device) is False+ # A momentary OOM must not disable fp8 for the rest of the process.+ with mock.patch("torch._scaled_mm", return_value=torch.zeros(1)):+ assert device_supports_fp8_matmul(device) is True+ reset_fp8_matmul_support_cache()++ def test_a_genuine_unsupported_op_is_cached(self) -> None:+ reset_fp8_matmul_support_cache()+ device = torch.device("cuda", 0)+ with _probe_on_cpu():+ with mock.patch("torch._scaled_mm", side_effect=RuntimeError("not supported on this device")):+ assert device_supports_fp8_matmul(device) is False+ # No second probe: the answer cannot change at runtime.+ with mock.patch("torch._scaled_mm", side_effect=AssertionError("must not be probed again")):+ assert device_supports_fp8_matmul(device) is False+ reset_fp8_matmul_support_cache()+++class TestMxfp8IsRefused:+ """MXFP8 block scales are refused rather than guessed at.++ Established against a real pair of checkpoints: the MXFP8 and the scaled-fp8 build of+ `krea2TurboOfficialComfy` share all 174 bf16 tensors bit-for-bit, so the scaled build is an+ exact reference. Decoding the uint8 exponents as `2**(v-127)` and expanding them 32-wide+ reaches a correlation of only 0.60 against it and generates a pure-noise image; the measured+ per-block scale has no monotonic relation to the byte (112 and 116 give the same true scale),+ which points at a swizzled scale layout.++ Refusing matters because the block-wise expansion is what makes such a file *loadable*: without+ a guard it produces garbage silently, which is strictly worse than the shape error it used to+ raise.+ """++ def test_a_uint8_block_scale_is_rejected_with_an_actionable_message(self) -> None:+ sd = {+ "lin.weight": torch.full((4, 64), 2.0).to(FP8_DTYPE),+ "lin.weight_scale": torch.full((4, 2), 125, dtype=torch.uint8),+ }++ with pytest.raises(NotImplementedError) as excinfo:+ extract_fp8_scaled_layers(sd)++ message = str(excinfo.value)+ assert "lin" in message, "the failing layer must be named"+ assert "MXFP8" in message+ assert "noise" in message, "say what happens if it were loaded anyway"++ def test_float_scales_are_unaffected(self) -> None:+ """The guard keys off the dtype, so ordinary scaled-fp8 checkpoints must still load."""+ sd = {+ "lin.weight": torch.full((4, 64), 2.0).to(FP8_DTYPE),+ "lin.weight_scale": torch.full((4, 2), 0.25),+ }++ layers = extract_fp8_scaled_layers(sd)++ assert tuple(layers["lin"].weight_scale.shape) == (4, 2)+++class TestNonScalarInputScale:+ """A multi-element ``input_scale`` is dropped, not raised on.++ `scaled_mm_linear` scales activations by one value, so there is nothing to do with a+ per-channel or per-block activation scale -- but reshaping it to a scalar unconditionally+ turned such a checkpoint into a shape error at load time. Every other malformed side-channel in+ this module is either skipped or refused with an actionable message; this one was neither.+ """++ def _sd(self, input_scale: torch.Tensor) -> dict[str, torch.Tensor]:+ return {+ "blocks.0.attn.weight": torch.zeros(16, 16, dtype=torch.float32).to(FP8_DTYPE),+ "blocks.0.attn.weight_scale": torch.tensor(2.0),+ "blocks.0.attn.input_scale": input_scale,+ }++ def test_a_per_channel_input_scale_does_not_abort_the_load(self) -> None:+ layers = extract_fp8_scaled_layers(self._sd(torch.full((16,), 0.5)))++ assert set(layers) == {"blocks.0.attn"}+ # Dropped, so the forward falls back to the dynamic amax path -- which is correct.+ assert layers["blocks.0.attn"].input_scale is None+ # The weight scale is unaffected by the unusable activation scale.+ assert layers["blocks.0.attn"].weight_scale is not None++ def test_a_scalar_input_scale_is_still_kept(self) -> None:+ layers = extract_fp8_scaled_layers(self._sd(torch.tensor(0.5)))++ assert layers["blocks.0.attn"].input_scale is not None+++class TestMatmulUsableScale:+ """`is_matmul_usable_scale` decides what may reach `_scaled_mm` un-dequantized."""++ def test_a_per_tensor_scale_is_usable(self) -> None:+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.tensor(2.0)) is True++ def test_a_per_output_channel_scale_is_usable(self) -> None:+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.full((32,), 2.0)) is True++ def test_a_one_dimensional_scale_of_the_wrong_length_is_not(self) -> None:+ """The branch that keeps a mislabelled scale out of the kernel.++ A 1-D scale whose length is not the row count is neither per-tensor nor+ per-output-channel. Letting it through raises inside `_scaled_mm` mid-generation instead of+ dequantizing the layer up front, which is the whole point of asking.+ """+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.full((16,), 2.0)) is False++ def test_a_block_wise_scale_is_not(self) -> None:+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.full((4, 2), 2.0)) is False+++class TestReattachToNonWeightDestination:+ """The reattach guard must not assume every module stores its parameter as ``weight``.++ A producer that quantizes norms -- the "quantizes everything" class this module documents --+ writes ``<path>.scale``. Testing for ``<destination>.weight`` rejects such a destination for the+ wrong reason and drops a scale it could have placed, with only a log line to show for it.+ """++ def test_a_destination_whose_tensor_is_not_named_weight_still_receives_its_scale(self) -> None:+ sd = {"blocks.0.norm_q.scale": torch.zeros(16, dtype=torch.float32).to(FP8_DTYPE)}+ detached = {"blocks.0.qnorm": [(".weight_scale", torch.tensor(2.0))]}++ orphaned = reattach_layer_sidechannel(sd, detached, {"blocks.0.qnorm": "blocks.0.norm_q"})++ assert orphaned == []+ assert "blocks.0.norm_q.weight_scale" in sd++ def test_a_destination_absent_from_the_state_dict_is_still_reported(self) -> None:+ sd = {"blocks.0.attn.weight": torch.zeros(4, 4)}+ detached = {"blocks.0.dropped": [(".weight_scale", torch.tensor(2.0))]}++ orphaned = reattach_layer_sidechannel(sd, detached, {})++ assert orphaned == ["blocks.0.dropped"]+ assert not [k for k in sd if k.endswith(".weight_scale")]+++class TestProbeTransientFailures:+ """Only a definitively unsupported device may be cached; everything else re-probes.++ Listing the transient wordings is the wrong way round: an OOM and a cuBLAS workspace failure+ are two of the ways a loaded machine can fail this call, and any wording not on the list would+ be cached as permanent -- reproducing the failure the OOM branch was written to avoid.+ """++ def test_an_unrecognized_runtime_error_is_not_cached(self) -> None:+ reset_fp8_matmul_support_cache()+ device = torch.device("cuda", 0)+ with _probe_on_cpu():+ with mock.patch("torch._scaled_mm", side_effect=RuntimeError("CUDA driver reset")):+ assert device_supports_fp8_matmul(device) is False+ # Inconclusive, so the next load re-probes rather than the process losing fp8.+ with mock.patch("torch._scaled_mm", return_value=torch.zeros(1)):+ assert device_supports_fp8_matmul(device) is True+ reset_fp8_matmul_support_cache()++ def test_a_capability_error_is_cached(self) -> None:+ reset_fp8_matmul_support_cache()+ device = torch.device("cuda", 0)+ message = "torch._scaled_mm is only supported on CUDA devices with compute capability >= 8.9"+ with _probe_on_cpu():+ with mock.patch("torch._scaled_mm", side_effect=RuntimeError(message)):+ assert device_supports_fp8_matmul(device) is False+ with mock.patch("torch._scaled_mm", side_effect=AssertionError("must not be probed again")):+ assert device_supports_fp8_matmul(device) is False+ reset_fp8_matmul_support_cache()+++class TestExpandWeightScaleAxis:+ """A per-output-channel scale must scale rows, not columns.++ `(out, in) * (out,)` broadcasts on the *last* axis, so a bare multiply scales input channels --+ wrong on a square weight, a shape error on any other. Both legacy folds used to do exactly that.+ """++ def test_a_per_channel_scale_lines_up_with_the_rows(self) -> None:+ weight = torch.ones(3, 2)+ scale = torch.tensor([1.0, 2.0, 3.0])++ result = weight * expand_weight_scale(weight, scale)++ assert torch.equal(result, torch.tensor([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]))++ def test_a_non_square_weight_no_longer_raises(self) -> None:+ weight = torch.ones(4, 2)++ # Without the expansion this is a broadcast error, not merely a wrong number.+ assert (weight * expand_weight_scale(weight, torch.arange(4, dtype=torch.float32))).shape == (4, 2)+++class TestPredictionIsSplitAware:+ """`make_room` runs before `split_fp8_scaled_layers`, so the prediction has to account for what+ the split widens — not just for what the cast keeps.++ `can_stay_quantized` knows nothing about the scale *layout*. A block-wise-scaled 2-D+ `nn.Linear.weight` passes it, gets predicted at 1 byte/element, and is then dequantized to+ `dtype` by the split at 2 — the reservation is half the truth, and on a real checkpoint using+ that layout the shortfall is the whole quantized-Linear set.+ """++ def _model(self):+ model = torch.nn.Sequential()+ model.add_module("lin", torch.nn.Linear(16, 32))+ return model++ @pytest.mark.parametrize(+ "label, scale, stays_fp8",+ [+ ("per-tensor", torch.tensor(2.0), True),+ ("per-output-channel", torch.full((32,), 2.0), True),+ ("block-wise", torch.full((8, 2), 2.0), False),+ ],+ )+ def test_prediction_matches_the_bytes_left_after_split_and_cast(self, label, scale, stays_fp8):+ model = self._model()+ sd = {"lin.weight": torch.zeros(32, 16).to(FP8_DTYPE), "lin.weight_scale": scale}+ layers = extract_fp8_scaled_layers(sd)++ predicted = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)+ remaining = split_fp8_scaled_layers(sd, layers, torch.bfloat16, model=model)+ cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model)+ actual = sum(t.nelement() * t.element_size() for t in sd.values())++ assert predicted == actual, f"{label}: reserved {predicted}, needed {actual}"+ assert bool(remaining) is stays_fp8+ assert (sd["lin.weight"].dtype is FP8_DTYPE) is stays_fp8++ def test_without_the_mapping_the_block_wise_layer_is_under_counted(self):+ """The regression itself: omitting `scaled_layers` reverts to the weaker predicate."""+ model = self._model()+ sd = {"lin.weight": torch.zeros(32, 16).to(FP8_DTYPE), "lin.weight_scale": torch.full((8, 2), 2.0)}+ layers = extract_fp8_scaled_layers(sd)++ blind = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model)+ aware = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)+ assert aware == 2 * blind++ def test_raw_fp8_without_any_scale_is_unaffected(self):+ """A weight with no `weight_scale` has no layout to reject; it stays fp8 either way."""+ model = self._model()+ sd = {"lin.weight": torch.zeros(32, 16).to(FP8_DTYPE)}+ with_map = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers={})+ without = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model)+ assert with_map == without == 32 * 16+++class TestQwen3VlStyleSplit:+ """Pins the helper contract the Qwen3-VL encoder switched to.++ Its old per-key `if dtype is not FP8_DTYPE` loop kept *every* fp8 tensor quantized. The three+ things that got wrong are all visible without any `transformers` dependency, against a stub+ module tree.+ """++ def _model(self):+ model = torch.nn.Module()+ model.add_module("norm", torch.nn.LayerNorm(32))+ model.add_module("lin", torch.nn.Linear(16, 32))+ model.add_module("plain", torch.nn.Linear(16, 32))+ return model++ def test_scaled_norm_is_folded_and_block_wise_linear_is_dropped(self):+ model = self._model()+ norm_scale = torch.tensor(4.0)+ sd = {+ # A 1-D fp8 norm carrying a scale: not a matmul weight, so it must be folded, not kept.+ "norm.weight": torch.ones(32).to(FP8_DTYPE),+ "norm.weight_scale": norm_scale,+ # A Linear whose scale layout `scaled_mm` cannot apply: folded too.+ "lin.weight": torch.ones(32, 16).to(FP8_DTYPE),+ "lin.weight_scale": torch.full((8, 2), 2.0),+ # A Linear the matmul can take: survives, and is what `attach_fp8_scales` gets.+ "plain.weight": torch.ones(32, 16).to(FP8_DTYPE),+ "plain.weight_scale": torch.tensor(3.0),+ }+ layers = extract_fp8_scaled_layers(sd)+ assert set(layers) == {"norm", "lin", "plain"}++ remaining = split_fp8_scaled_layers(sd, layers, torch.bfloat16, model=model)+ cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model)++ assert set(remaining) == {"plain"}, "only the matmul-usable Linear may keep its scale"+ # The norm was dequantized *with* its scale applied — the old loop left it as raw fp8 codes.+ assert sd["norm.weight"].dtype is torch.bfloat16+ assert torch.allclose(sd["norm.weight"], torch.full((32,), 4.0, dtype=torch.bfloat16))+ assert sd["lin.weight"].dtype is torch.bfloat16+ assert sd["plain.weight"].dtype is FP8_DTYPE++ def test_e5m2_scaled_weight_keeps_its_scale_on_the_way_down(self):+ """Only e4m3fn may stay quantized, so an e5m2 weight must be folded rather than cast bare."""+ model = self._model()+ sd = {+ "plain.weight": torch.ones(32, 16).to(torch.float8_e5m2),+ "plain.weight_scale": torch.tensor(3.0),+ }+ layers = extract_fp8_scaled_layers(sd)+ remaining = split_fp8_scaled_layers(sd, layers, torch.bfloat16, model=model)++ assert remaining == {}+ assert torch.allclose(sd["plain.weight"], torch.full((32, 16), 3.0, dtype=torch.bfloat16))+++class TestMalformedWeightScale:+ def test_a_1d_scale_of_the_wrong_length_is_reported_not_broadcast(self):+ """Neither per-tensor nor per-output-channel. Left to torch, the multiply raises "size of+ tensor a (32) must match tensor b (7)" from inside the fold, naming neither layer nor file."""+ with pytest.raises(ValueError, match="neither per-tensor nor per-output-channel"):+ expand_weight_scale(torch.ones(32, 16), torch.full((7,), 2.0))