Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(vae): run SDNQ VAEs in the dtype they compute in (#10292)
Alexander Eichhorn6bdc2c83d347
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex 12f246215e..bb74356feb 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -1068,7 +1068,7 @@ To write such an estimator (`invokeai/backend/util/vae_working_memory.py` has fi- Register an `EstimatorSpec` at module import, and list the module in `ESTIMATOR_MODULES` (`working_memory/spec.py`); the data test fails on a module that declares a spec without being listed.- Split the estimator in two. The impure part reads the model and the device and records every runtime decision (tile, the dtype the operation runs in, score-matrix bytes, a quantized model's dequantization transient) as a feature, and refuses a dtype the spec has no line for with a `ValueError` naming the estimator, dtype and platform. The pure `terms(features, values)` turns features and coefficient values into terms, building fitted terms with `WorkingMemoryTerm.fitted(...)`. The public function returns `SPEC.estimate(features, device)`.-- Record the dtype the operation will run in, not the one the cached model holds. The SD1/SDXL nodes cast the shared VAE with `sd_vae_run_dtype`: fp16 for every GPU run that does not ask for fp32 (bf16 never runs), fp32 when asked and for a CPU decode. Their estimate prices the same function's answer, plus what the in-place cast adds to the resident weights. Uncast VAEs compute in their first floating-point parameter wider than a byte, so fp8 or packed SDNQ storage does not count.+- Record the dtype the operation will run in, not the one the cached model holds. The SD1/SDXL nodes cast the shared VAE with `sd_vae_run_dtype`: fp16 for every GPU run that does not ask for fp32 (bf16 never runs), fp32 when asked and for a CPU decode. Their estimate prices the same function's answer, plus what the in-place cast adds to the resident weights. Uncast VAEs compute in their first floating-point parameter wider than a byte, so fp8 or packed SDNQ storage does not count; a packed SDNQ weight's `compute_dtype` takes precedence over every floating-point parameter, an fp32 bias included, because the SDNQ VAE loaders cast the parameters they leave unpacked to it (`cast_unpacked_floats`). `vae_compute_dtype` is the one answer, used by the estimators and by the nodes that cast their input to the VAE's dtype (FLUX.1, FLUX.2, Z-Image, SD3, CogView4, the FLUX.1 Kontext reference encode).- Declare the line the fitted terms price on with `line=` (a function returning a `fit.Line`): the suffix that names the line's coefficients, the operation's size on its x-axis, whether a measurement of these features fits the line, and how point ids label them. Every estimator declares it and nothing defaults it, so a new estimator cannot inherit another's line, and with it which of its measurements fit. The VAE estimators declare the AutoencoderKL convolution line in output pixels (`fit.convolution_line`), the Z-Image, FLUX.2, FLUX.3 and Krea-2 denoise ones in attended tokens. A line may sit on another (`Line.sits_on`, the line beneath and the operation's size on it): a tiled VAE operation prices its tile, clamped to the image per axis, on the untiled line and sits there, and its estimator's tiled line `tiled_<operation>_<dtype>`, in the image's pixels unless the estimator's `line` sizes it otherwise (Qwen-Image-2.1's, by the tile's area on MIOpen), prices what tiling adds on top. A line may also have a second phase that peaks apart from it (`Line.assembly`): a tiled decode assembles the image from its decoded tiles after the last one, priced on the assembly line `assembled_decode_<dtype>` in the image's pixels, and the estimate reserves the larger phase. The fit subtracts nothing else from a point's demand, so a line admits only measurements whose demand is the line's alone, or the line's above the line it sits on: an operation with a term of its own on top of the line (an in-place upcast, a batch, a ControlNet's hints, regional prompting's bias, LoRAs, a dequantization or fp8 cast transient, a materialized score matrix the estimate adds rather than takes the larger of) bounds its estimate but fits nothing.- Declare `legacy_formula=` where the terms are shaped unlike the hand-set formula they replace, so that a `legacy` entry's constants alone do not reproduce it (the Krea-2 denoise's CFG and style multipliers, its count-based LoRA term). Where the values are legacy-priced (`ResolvedCoefficients.legacy_priced`: a `legacy` entry, or an unmeasured platform raised to an entry's `unmeasured_floor`), the estimate adds what the formula gives beyond its terms, as a term `legacy_formula`; fitted values on a measured platform never read it.- Opt in with `user_calibrated=True` where a user's calibration may move the estimator: the five VAE estimators do. An estimator that does not is shipped-fit only; a calibration run still records its windows. The calibration summary and plan are built on pixel lines (they key sizes by `width` and `height`), so an estimator on another line, such as the Z-Image denoise's in tokens, must not opt in until they key sizes by `Line.size`.@@ -1213,7 +1213,7 @@ The reset, export and summary routes act on the current device class unless `dev- The provider answers from memory. `refresh_user_fits()` rebuilds that memory per GPU generation device. `DefaultSessionRunner.run()` calls it once when it starts any queue item, calibration items included; `get_plan` calls it first, so the case sizes price with the store as it is, and every reset calls it after its write, so a reset applies at once. It stats each device class's file and re-reads it only when the mtime, size or inode or the environment changed. Each refresh of a file with runs, and each model summary, reads the queue to judge the attempts. To tell which runs are running it reads the origins of the queue's unfinished calibration items (`get_unfinished_origins`): the queue finds those items by their status and tests the origin on their rows, so the read costs what the queue has pending or running, not its history; on SQLite about 0.05 ms beside a handful of unfinished items, whatever the history, and 3 ms beside 100 (34 ms beside 1000) pending items of 64 KB sessions, whose overflow pages the origin sits behind. Grouping the runs into attempts costs about 0.5 ms at 180 runs and 11 ms at 3600. To tell whether a settled attempt was stopped it reads by id (`get_queue_item_summaries_by_ids`, the primary key) the items the store records whose end the runner did not see. A finished item never changes, so its outcome is kept, per run and item id (a recreated or restored database can give two runs' items one id), until its run is removed, by a reset or by a creation that queued nothing, and each item is read once it finished; a run with an item the queue shows pending or in progress, a retry queued since the read for running items, holds its attempt back as running for that refresh. Every judgement of these outcomes (a refresh, the model summary, a new attempt's check, a reset), with its read of the store file, and every removal holds one lock of the service, taken before the file's lock, so a removal's runs leave no outcome behind. A row counts only while it carries the run's origin: a recreated or restored database gives the id to an unrelated item, and the run's own item is gone, so it reads as canceled. An unchanged file with an unchanged set of runs held back is not fitted again. A calibration item, a retry included, is in progress when the runner refreshes before it, so it is priced without its own attempt's windows. Nothing on the estimate path reads a file. Several generation devices each use their own class's fit; calibrating them is not supported.- Shared lines: on cuDNN the SD, SD3, FLUX.1 and FLUX.2 estimators borrow one entry, so an SDXL fp16 decode calibrates every estimator's fp16 decode there. The plan lists the installed models this affects.-The plan (`working_memory_calibration_plan.py`) covers the decode of SD1, SD2, SDXL, SD3, FLUX.1, FLUX.2, Z-Image and CogView4 main models, and standalone VAEs of those bases through an installed main model that accepts them (`VaeFacet`): through Generate's `vae` slot where the base has one (FLUX.1, FLUX.2, SD3, Z-Image), otherwise with the VAE the main model decodes with, its own or the default VAE its settings name, which prices on the same lines. Each case is a two-step `txt2img` graph-export case per size and decode dtype; the SD bases set `vaePrecision` to fp16 and to fp32, the others run the dtype their loader picks: SD3 the `precision` setting; a standalone FLUX.1 or FLUX.2 VAE, and the one Z-Image decodes with, the configured dtype except fp16, which becomes bf16 where the device has it and fp32 otherwise (`TorchDevice.dtype_avoiding_float16`, which the loaders use too), so `precision: float32` plans the fp32 line at the smaller sizes an fp32 decode fits untiled; a pipeline's own VAE what its loader yields: bf16 for a FLUX.2 Diffusers pipeline, the device's bf16-safe dtype for a Z-Image one, and fp32 for a self-contained SDNQ pipeline, whose loaders call `from_pretrained` without a dtype (bf16 for a FLUX.1 SDNQ pipeline's SDNQ-quantized VAE); `test_working_memory_calibration_plan.py` holds these to the loaders. A pipeline decodes with its own VAE while the `vae` slot is empty: a FLUX.2, SD3 or Z-Image Diffusers pipeline, and a self-contained SDNQ pipeline (`is_self_contained_sdnq_pipeline`, for FLUX.1 `is_self_contained_sdnq_flux1_pipeline`), except that the FLUX.2 [dev] model loader node takes components only from a Diffusers pipeline, so an SDNQ [dev] model is no pipeline of its own. The slot is not empty when the main model's default settings name an installed VAE it accepts (`default_vae`): selecting the model applies it (`getModelDefaultVae`), the SD, SD3, FLUX.1, FLUX.2 and Z-Image graphs decode with it, and the FLUX.2 and Z-Image model loader nodes take it over a pipeline's own VAE, so the plan sizes for that standalone VAE; the graph of a self-contained FLUX.1 SDNQ pipeline, and the CogView4 graph, send no VAE. Another FLUX.2 model decodes with the VAE of the component source Generate picks on its own among the installed FLUX.2 pipelines its model loader node takes components from (Diffusers ones only for [dev]): the first whose text encoder fits it ([dev] for [dev], else the Klein variant's Qwen3 size), else the first one; that graph keeps a pipeline that does not fit only beside a standalone encoder of the model's (a Mistral encoder for [dev], else a Qwen3 encoder of the Klein variant's size), which then encodes while the pipeline gives its VAE. Without a pipeline, and for every other FLUX.1 model and an SD3 GGUF, which holds the transformer alone, a standalone VAE decodes. The sizes are about 0.25, 0.5 and 1.0 of the largest square, in steps of 64 and at most 4096 px, whose calibration reservation (the estimate plus `max(1 GiB, 0.5 × estimate)`, and never below `device_working_mem_gb`, as the lock applies it) leaves the VAE fully resident (`decode_budget`): it must fit both 90% of the card (`VAE_PRETILE_VRAM_FRACTION`) and what the model cache can give on the device, each less 1 GiB for the VAE's weights. Nothing else stays beside it: inside a calibration scope, `model_on_device` first moves every other unlocked model on the device to RAM whole (`ModelCache.offload_unlocked_models_from_vram`, under the global load lock, inside the probe's lock interval; locked models, a window's co-locks among them, stay), and only then locks. The reason: a lock offloads only the shortfall it predicts and splits the last model it reaches, and a split can free a little less than predicted. On an RX 9060 XT, 9 of the 12 calibration decodes that had to split the SDXL UNet came up 35 to 55 MB short and ran the VAE partly resident, so their windows fit no line. Outside a calibration scope, locks are unchanged. That capacity is read when the plan is built, from the device's model cache: `ModelCache.calibration_capacity`, what the calibration's lock then gets from the same cache. It counts as `ModelCache._get_vram_available` counts a lock, through the same `TorchDevice.memory_available_to_process`, within `max_cache_vram_gb`, less `reserve_vram_gb`. On a dedicated card that is the driver's free memory plus what torch has allocated, so the models the pre-lock offload moves out count as available. On a device whose memory is system RAM (MPS, an integrated Intel GPU) it is the RAM the host has available plus what the backend holds for this process, less what the cache's models hold there now (`_get_vram_in_use`): the offload frees nothing on such a device, and the lock subtracts them too. The 90% share of its total would overstate what a decode finds there whenever the host is short of free memory. Memory other processes hold is thereby left out. What this process holds outside torch's allocator counts at the larger of what it holds now and the most a valid stored window of the current environment recorded at its baseline (the driver's figure for the process less torch's reserve, `recorded_outside_torch_bytes`), over the windows of the estimators a user calibration moves only, because it grows with the first generations: on a 16 GB RX 9060 XT under ROCm, HIP's retained pool and MIOpen's workspaces took about 0.3 GB in a fresh server and 2.6 GiB once it had decoded, and sized for the fresh reading its largest cases ran partly resident. A first calibration has no stored window and sizes for the reading alone, so on such a card its largest cases may run partly resident; those windows do not count, and the next plan sizes for what the first one recorded. The recorded figure comes from the store `refresh_user_fits` just read; `estimate_untiled_vae_decode` prices them with the decode nodes' own features. `DECODE_LINES` restates which estimator each base's decode node prices with; `test_working_memory_calibration_plan.py` holds it to the nodes in `invocations/vae/`. Each case runs once to warm up and twice more; `estimated_seconds` is a rough order of magnitude, not a measurement. Encodes are not planned: text-to-image runs none. Two settings of the machine leave nothing to measure, and the plan is then `supported: false` with the way out: under `force_tiled_decode` the SD, FLUX.1, Z-Image and FLUX.2 decode nodes tile every decode, so a case measures no untiled line and no estimate would read one (`FORCE_TILED_BASES`; the plan does not override the setting for calibration items); and a FLUX.1, FLUX.2, SD3 or Z-Image model that decodes with a standalone VAE needs a compatible one that runs on the GPU, since a decode on the CPU opens no window. A main model whose default VAE runs on the CPU gets a `vae` pick of the first accepted VAE on the GPU where its base has the slot, and is otherwise `supported: false` (the SD bases have no slot a case could pick through); a standalone SD VAE goes through a compatible main model whose default VAE does not run on the CPU. A FLUX.2 model that is no pipeline needs a text encoder Generate can use, a fitting pipeline's or a standalone one as above: without one no case compiles, and the plan is `supported: false` saying which encoder to install. An SD3 model that is no Diffusers pipeline needs a standalone T5, CLIP-L and CLIP-G encoder, which Generate fills in from the installed models: without all three no case compiles, and the plan says which to install. A standalone FLUX.2 or SD3 VAE goes through the first compatible main model whose graph compiles.+The plan (`working_memory_calibration_plan.py`) covers the decode of SD1, SD2, SDXL, SD3, FLUX.1, FLUX.2, Z-Image and CogView4 main models, and standalone VAEs of those bases through an installed main model that accepts them (`VaeFacet`): through Generate's `vae` slot where the base has one (FLUX.1, FLUX.2, SD3, Z-Image), otherwise with the VAE the main model decodes with, its own or the default VAE its settings name, which prices on the same lines. Each case is a two-step `txt2img` graph-export case per size and decode dtype; the SD bases set `vaePrecision` to fp16 and to fp32, the others run the dtype their loader picks: SD3 the `precision` setting; a standalone FLUX.1 or FLUX.2 VAE, and the one Z-Image decodes with, the configured dtype except fp16, which becomes bf16 where the device has it and fp32 otherwise (`TorchDevice.dtype_avoiding_float16`, which the loaders use too), so `precision: float32` plans the fp32 line at the smaller sizes an fp32 decode fits untiled; a pipeline's own VAE what its loader yields: bf16 for a FLUX.2 pipeline, Diffusers or self-contained SDNQ, and for a self-contained FLUX.1 SDNQ pipeline (`FluxSDNQDiffusersModel._load_vae` and `_load_sdnq_vae`; a FLUX.1 Diffusers pipeline decodes with a standalone VAE, never its own), and the device's bf16-safe dtype for a Z-Image one, Diffusers or SDNQ; `test_working_memory_calibration_plan.py` holds these to the loaders. A pipeline decodes with its own VAE while the `vae` slot is empty: a FLUX.2, SD3 or Z-Image Diffusers pipeline, and a self-contained SDNQ pipeline (`is_self_contained_sdnq_pipeline`, for FLUX.1 `is_self_contained_sdnq_flux1_pipeline`), except that the FLUX.2 [dev] model loader node takes components only from a Diffusers pipeline, so an SDNQ [dev] model is no pipeline of its own. The slot is not empty when the main model's default settings name an installed VAE it accepts (`default_vae`): selecting the model applies it (`getModelDefaultVae`), the SD, SD3, FLUX.1, FLUX.2 and Z-Image graphs decode with it, and the FLUX.2 and Z-Image model loader nodes take it over a pipeline's own VAE, so the plan sizes for that standalone VAE; the graph of a self-contained FLUX.1 SDNQ pipeline, and the CogView4 graph, send no VAE. Another FLUX.2 model decodes with the VAE of the component source Generate picks on its own among the installed FLUX.2 pipelines its model loader node takes components from (Diffusers ones only for [dev]): the first whose text encoder fits it ([dev] for [dev], else the Klein variant's Qwen3 size), else the first one; that graph keeps a pipeline that does not fit only beside a standalone encoder of the model's (a Mistral encoder for [dev], else a Qwen3 encoder of the Klein variant's size), which then encodes while the pipeline gives its VAE. Without a pipeline, and for every other FLUX.1 model and an SD3 GGUF, which holds the transformer alone, a standalone VAE decodes. The sizes are about 0.25, 0.5 and 1.0 of the largest square, in steps of 64 and at most 4096 px, whose calibration reservation (the estimate plus `max(1 GiB, 0.5 × estimate)`, and never below `device_working_mem_gb`, as the lock applies it) leaves the VAE fully resident (`decode_budget`): it must fit both 90% of the card (`VAE_PRETILE_VRAM_FRACTION`) and what the model cache can give on the device, each less 1 GiB for the VAE's weights. Nothing else stays beside it: inside a calibration scope, `model_on_device` first moves every other unlocked model on the device to RAM whole (`ModelCache.offload_unlocked_models_from_vram`, under the global load lock, inside the probe's lock interval; locked models, a window's co-locks among them, stay), and only then locks. The reason: a lock offloads only the shortfall it predicts and splits the last model it reaches, and a split can free a little less than predicted. On an RX 9060 XT, 9 of the 12 calibration decodes that had to split the SDXL UNet came up 35 to 55 MB short and ran the VAE partly resident, so their windows fit no line. Outside a calibration scope, locks are unchanged. That capacity is read when the plan is built, from the device's model cache: `ModelCache.calibration_capacity`, what the calibration's lock then gets from the same cache. It counts as `ModelCache._get_vram_available` counts a lock, through the same `TorchDevice.memory_available_to_process`, within `max_cache_vram_gb`, less `reserve_vram_gb`. On a dedicated card that is the driver's free memory plus what torch has allocated, so the models the pre-lock offload moves out count as available. On a device whose memory is system RAM (MPS, an integrated Intel GPU) it is the RAM the host has available plus what the backend holds for this process, less what the cache's models hold there now (`_get_vram_in_use`): the offload frees nothing on such a device, and the lock subtracts them too. The 90% share of its total would overstate what a decode finds there whenever the host is short of free memory. Memory other processes hold is thereby left out. What this process holds outside torch's allocator counts at the larger of what it holds now and the most a valid stored window of the current environment recorded at its baseline (the driver's figure for the process less torch's reserve, `recorded_outside_torch_bytes`), over the windows of the estimators a user calibration moves only, because it grows with the first generations: on a 16 GB RX 9060 XT under ROCm, HIP's retained pool and MIOpen's workspaces took about 0.3 GB in a fresh server and 2.6 GiB once it had decoded, and sized for the fresh reading its largest cases ran partly resident. A first calibration has no stored window and sizes for the reading alone, so on such a card its largest cases may run partly resident; those windows do not count, and the next plan sizes for what the first one recorded. The recorded figure comes from the store `refresh_user_fits` just read; `estimate_untiled_vae_decode` prices them with the decode nodes' own features. `DECODE_LINES` restates which estimator each base's decode node prices with; `test_working_memory_calibration_plan.py` holds it to the nodes in `invocations/vae/`. Each case runs once to warm up and twice more; `estimated_seconds` is a rough order of magnitude, not a measurement. Encodes are not planned: text-to-image runs none. Two settings of the machine leave nothing to measure, and the plan is then `supported: false` with the way out: under `force_tiled_decode` the SD, FLUX.1, Z-Image and FLUX.2 decode nodes tile every decode, so a case measures no untiled line and no estimate would read one (`FORCE_TILED_BASES`; the plan does not override the setting for calibration items); and a FLUX.1, FLUX.2, SD3 or Z-Image model that decodes with a standalone VAE needs a compatible one that runs on the GPU, since a decode on the CPU opens no window. A main model whose default VAE runs on the CPU gets a `vae` pick of the first accepted VAE on the GPU where its base has the slot, and is otherwise `supported: false` (the SD bases have no slot a case could pick through); a standalone SD VAE goes through a compatible main model whose default VAE does not run on the CPU. A FLUX.2 model that is no pipeline needs a text encoder Generate can use, a fitting pipeline's or a standalone one as above: without one no case compiles, and the plan is `supported: false` saying which encoder to install. An SD3 model that is no Diffusers pipeline needs a standalone T5, CLIP-L and CLIP-G encoder, which Generate fills in from the installed models: without all three no case compiles, and the plan says which to install. A standalone FLUX.2 or SD3 VAE goes through the first compatible main model whose graph compiles.### Emitting model loading eventsdiff --git a/invokeai/app/invocations/vae/cogview4_image_to_latents.py b/invokeai/app/invocations/vae/cogview4_image_to_latents.pyindex 3f52fb7b1e..031ca7f6a9 100644--- a/invokeai/app/invocations/vae/cogview4_image_to_latents.py+++ b/invokeai/app/invocations/vae/cogview4_image_to_latents.py@@ -16,7 +16,7 @@ from invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensor-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_cogview4+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_cogview4, vae_compute_dtype# TODO(ryand): This is effectively a copy of SD3ImageToLatentsInvocation and a subset of ImageToLatentsInvocation. We# should refactor to avoid this duplication.@@ -47,10 +47,11 @@ class CogView4ImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):vae.disable_tiling()- image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae.dtype)+ vae_dtype = vae_compute_dtype(vae)+ image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae_dtype)with torch.inference_mode():image_tensor_dist = vae.encode(image_tensor).latent_dist- latents: torch.Tensor = image_tensor_dist.mode().to(dtype=vae.dtype)+ latents: torch.Tensor = image_tensor_dist.mode().to(dtype=vae_dtype)latents = vae.config.scaling_factor * latentsdiff --git a/invokeai/app/invocations/vae/flux2_vae_decode.py b/invokeai/app/invocations/vae/flux2_vae_decode.pyindex 1646919437..34cf42de15 100644--- a/invokeai/app/invocations/vae/flux2_vae_decode.py+++ b/invokeai/app/invocations/vae/flux2_vae_decode.py@@ -23,7 +23,11 @@ from invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.oom import is_oom_errorfrom invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_vae_tiling-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux2, should_pretile_vae_decode+from invokeai.backend.util.vae_working_memory import (+ estimate_vae_working_memory_flux2,+ should_pretile_vae_decode,+ vae_compute_dtype,+)from invokeai.backend.working_memory.estimate import WorkingMemoryEstimate@@ -89,7 +93,7 @@ class Flux2VaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):estimated_working_memory = estimate(use_tiling)with vae_info.model_on_device(working_memory=estimated_working_memory) as (_, vae):- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)# Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from# current param residency: partial loading may have temporarily offloaded all weights to RAM, which would# wrongly place the latents (and thus the whole decode) on the CPU (see #9373).diff --git a/invokeai/app/invocations/vae/flux2_vae_encode.py b/invokeai/app/invocations/vae/flux2_vae_encode.pyindex 258ec074fd..24895926d3 100644--- a/invokeai/app/invocations/vae/flux2_vae_encode.py+++ b/invokeai/app/invocations/vae/flux2_vae_encode.py@@ -21,7 +21,7 @@ from invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_tfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.oom import is_oom_errorfrom invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_vae_tiling-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux2+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux2, vae_compute_dtype@invocation(@@ -101,7 +101,7 @@ class Flux2VaeEncodeInvocation(BaseInvocation):)with vae_info.model_on_device(working_memory=estimated_working_memory) as (_, vae):- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)image_tensor = image_tensor.to(device=device, dtype=vae_dtype)# The VAE is the cache's shared instance, so its tiling state is set for this encode only.diff --git a/invokeai/app/invocations/vae/flux_vae_decode.py b/invokeai/app/invocations/vae/flux_vae_decode.pyindex 342935997d..2e56fed7c0 100644--- a/invokeai/app/invocations/vae/flux_vae_decode.py+++ b/invokeai/app/invocations/vae/flux_vae_decode.py@@ -22,6 +22,7 @@ from invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_from invokeai.backend.util.vae_working_memory import (estimate_vae_working_memory_flux,should_pretile_vae_decode,+ vae_compute_dtype,)@@ -94,7 +95,7 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):with vae_info.model_on_device(working_memory=estimated_working_memory) as (_, vae):assert isinstance(vae, AutoencoderKL)- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)# Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from# current param residency: partial loading may have temporarily offloaded all weights to RAM, which would# wrongly place the latents (and thus the whole decode) on the CPU (see #9373).diff --git a/invokeai/app/invocations/vae/flux_vae_encode.py b/invokeai/app/invocations/vae/flux_vae_encode.pyindex a5a1090060..f8c3296636 100644--- a/invokeai/app/invocations/vae/flux_vae_encode.py+++ b/invokeai/app/invocations/vae/flux_vae_encode.py@@ -18,7 +18,7 @@ from invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_tfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.oom import is_oom_errorfrom invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_vae_tiling-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux, vae_compute_dtype@invocation(@@ -92,7 +92,7 @@ class FluxVaeEncodeInvocation(BaseInvocation):generator = torch.Generator(device=vae_info.compute_device).manual_seed(0)with vae_info.model_on_device(working_memory=estimated_working_memory) as (_, vae):assert isinstance(vae, AutoencoderKL)- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)# The VAE's own device, as in the decode nodes: a cpu_only VAE (or another worker's GPU)# is not the session device, and encoding there would fail or run on the wrong card (#9373).image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae_dtype)diff --git a/invokeai/app/invocations/vae/sd3_image_to_latents.py b/invokeai/app/invocations/vae/sd3_image_to_latents.pyindex a3bdd1628d..7f0e118d01 100644--- a/invokeai/app/invocations/vae/sd3_image_to_latents.py+++ b/invokeai/app/invocations/vae/sd3_image_to_latents.py@@ -16,7 +16,7 @@ from invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensor-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_sd3+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_sd3, vae_compute_dtype@invocation(@@ -43,10 +43,11 @@ class SD3ImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):vae.disable_tiling()- image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae.dtype)+ vae_dtype = vae_compute_dtype(vae)+ image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae_dtype)with torch.inference_mode():image_tensor_dist = vae.encode(image_tensor).latent_dist- latents: torch.Tensor = image_tensor_dist.mode().to(dtype=vae.dtype)+ latents: torch.Tensor = image_tensor_dist.mode().to(dtype=vae_dtype)latents = vae.config.scaling_factor * latentsdiff --git a/invokeai/app/invocations/vae/z_image_image_to_latents.py b/invokeai/app/invocations/vae/z_image_image_to_latents.pyindex 03a1f474f8..df294a882c 100644--- a/invokeai/app/invocations/vae/z_image_image_to_latents.py+++ b/invokeai/app/invocations/vae/z_image_image_to_latents.py@@ -17,7 +17,7 @@ from invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.stable_diffusion.diffusers_pipeline import image_resized_to_grid_as_tensorfrom invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_vae_tiling-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux, vae_compute_dtype@invocation(@@ -79,7 +79,7 @@ class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):f"Expected AutoencoderKL, got {type(vae).__name__}. VAE model type changed unexpectedly after loading.")- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)# The VAE's own device, as in the decode nodes: a cpu_only VAE (or another worker's GPU)# is not the session device, and encoding there would fail or run on the wrong card (#9373).image_tensor = image_tensor.to(device=vae_info.compute_device, dtype=vae_dtype)@@ -89,7 +89,7 @@ class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):# state is scoped and restored rather than switched off by hand and left behind.with torch.inference_mode(), scoped_vae_tiling(vae, effective_tile_size):latent_dist = vae.encode(image_tensor).latent_dist- latents: torch.Tensor = latent_dist.mode().to(dtype=vae.dtype)+ latents: torch.Tensor = latent_dist.mode().to(dtype=vae_dtype)# Apply scaling_factor and shift_factor from VAE config.# Z-Image uses: latents = (latents - shift_factor) * scaling_factordiff --git a/invokeai/app/invocations/vae/z_image_latents_to_image.py b/invokeai/app/invocations/vae/z_image_latents_to_image.pyindex 92f46ed5d0..ff5c0ac340 100644--- a/invokeai/app/invocations/vae/z_image_latents_to_image.py+++ b/invokeai/app/invocations/vae/z_image_latents_to_image.py@@ -22,6 +22,7 @@ from invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE, scoped_from invokeai.backend.util.vae_working_memory import (estimate_vae_working_memory_flux,should_pretile_vae_decode,+ vae_compute_dtype,)@@ -100,7 +101,7 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):"VAE model type changed unexpectedly after loading.")- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)# Use the VAE's intended compute device (CUDA/MPS, or CPU if configured cpu_only). Do NOT infer it from# current param residency: partial loading may have temporarily offloaded all weights to RAM, which would# wrongly place the latents (and thus the whole decode) on the CPU (see #9373).diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.pyindex 992bda51f9..dbc97948e3 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py@@ -13,7 +13,6 @@ from dataclasses import dataclassfrom functools import partialfrom itertools import chainfrom pathlib import Path-from types import SimpleNamespacefrom typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple, Optionalimport torch@@ -99,9 +98,6 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibration)from invokeai.app.util.misc import uuid_stringfrom invokeai.backend.model_manager.configs.factory import AnyModelConfig-from invokeai.backend.model_manager.load.load_default import resolve_submodel_path-from invokeai.backend.model_manager.taxonomy import SubModelType-from invokeai.backend.quantization.sdnq.detection import is_sdnq_folderfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.vae_working_memory import dtype_name, estimate_untiled_vae_decodefrom invokeai.backend.working_memory import fingerprint, user_fit@@ -212,18 +208,11 @@ class DeviceMemory:`capacity_bytes`, which counts the RAM the host has available."""-def _vae_dtypes(device: torch.device, models_path: Path) -> VaeDtypes:- """What the VAE loaders choose on `device`, by the loaders' own rules, for models installed under `models_path`."""-- def sdnq_quantized_vae(config: Any) -> bool:- # Where `FluxSDNQDiffusersModel._load_model` looks, with the path the loader makes absolute.- pipeline = SimpleNamespace(path=models_path / config.path, submodels=getattr(config, "submodels", None))- return is_sdnq_folder(resolve_submodel_path(pipeline, SubModelType.VAE, pipeline.path / SubModelType.VAE.value))-+def _vae_dtypes(device: torch.device) -> VaeDtypes:+ """What the VAE loaders choose on `device`, by the loaders' own rules."""return VaeDtypes(standalone_flux=dtype_name(TorchDevice.dtype_avoiding_float16(TorchDevice.choose_torch_dtype(device), device)),z_image_pipeline=dtype_name(TorchDevice.choose_bfloat16_safe_dtype(device)),- sdnq_quantized_vae=sdnq_quantized_vae,)@@ -567,7 +556,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):] = fingerprint.environment_for,untiled_decode_reservation: Callable[[str, int, int, str, torch.device], int] = _untiled_decode_reservation,device_memory: Optional[Callable[[torch.device], DeviceMemory]] = None,- vae_dtypes: Callable[[torch.device, Path], VaeDtypes] = _vae_dtypes,+ vae_dtypes: Callable[[torch.device], VaeDtypes] = _vae_dtypes,is_model_missing: Callable[[AnyModelConfig, Path], bool] = is_model_missing,) -> None:self._store = store@@ -1847,7 +1836,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):def _vae_dtypes_on(self, device: Optional[torch.device]) -> VaeDtypes:"""What the VAE loaders choose on `device`, by default the one models load onto."""- return self._vae_dtypes(device or TorchDevice.choose_torch_device(), self._services.configuration.models_path)+ return self._vae_dtypes(device or TorchDevice.choose_torch_device())def _cache_memory(self, device: torch.device) -> DeviceMemory:"""`DeviceMemory` for a GPU `device`: the capacity its model cache gives a calibration's lock, which that lockdiff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.pyindex bb07f075b0..e217a891b9 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py@@ -66,22 +66,14 @@ class VaeDtypes:"""A standalone FLUX.1 or FLUX.2 VAE, and the FLUX.1 VAE Z-Image decodes with: the configured dtype, except fp16(`TorchDevice.dtype_avoiding_float16`). A configured fp32 stays fp32."""z_image_pipeline: str- """The VAE of a Z-Image Diffusers pipeline: `TorchDevice.choose_bfloat16_safe_dtype`."""- sdnq_quantized_vae: Callable[[Any], bool]- """Whether the VAE folder of a FLUX.1 SDNQ pipeline holds SDNQ weights, as `FluxSDNQDiffusersModel._load_vae`- tells (`is_sdnq_folder`)."""+ """The VAE of a Z-Image Diffusers or SDNQ pipeline: `TorchDevice.choose_bfloat16_safe_dtype`."""-FLUX2_PIPELINE_VAE_DTYPE: Final = "bf16"-"""The VAE of a FLUX.2 Diffusers pipeline, which `Flux2DiffusersModel` loads in bf16 whatever the configured dtype."""--SDNQ_PIPELINE_VAE_DTYPE: Final = "fp32"-"""The VAE of a self-contained SDNQ pipeline, which `Flux2SDNQCheckpointModel._load_vae`,-`ZImageSDNQCheckpointModel._load_vae` and, for a VAE folder of plain weights, `FluxSDNQDiffusersModel._load_vae` load-through `from_pretrained` without a `torch_dtype`: fp32, whatever the weights on disk are."""--SDNQ_QUANTIZED_VAE_DTYPE: Final = "bf16"-"""A FLUX.1 SDNQ pipeline's SDNQ-quantized VAE, which `FluxSDNQDiffusersModel._load_sdnq_vae` dequantizes at bf16."""+FLUX_PIPELINE_VAE_DTYPE: Final = "bf16"+"""The VAE a FLUX.2 pipeline (Diffusers or self-contained SDNQ) or a self-contained FLUX.1 SDNQ pipeline decodes with,+which the loaders give bf16 whatever the configured dtype: `Flux2DiffusersModel`, `Flux2SDNQCheckpointModel._load_vae`,+and `FluxSDNQDiffusersModel._load_vae` and `_load_sdnq_vae` (a plain or an SDNQ-quantized VAE folder). A FLUX.1+Diffusers pipeline decodes with a standalone VAE, never its own."""_SD = DecodeLines("vae.sd", ("fp16", "fp32"), precision_setting=True)_FLUX = DecodeLines("vae.flux")@@ -413,11 +405,7 @@ def vae_source(model: ModelConfig, models: Sequence[ModelConfig]) -> Optional[Modef own_vae_dtype(pipeline: ModelConfig, vae: VaeDtypes) -> str:"""The dtype a pipeline's own VAE loads in (`vae_source`), as its loader yields it. Never asked for an SD3pipeline: its decode runs in the `precision` setting's dtype (`decode_dtypes`) whichever VAE decodes."""- if _is_diffusers(pipeline):- return vae.z_image_pipeline if pipeline.base == BaseModelType.ZImage else FLUX2_PIPELINE_VAE_DTYPE- if pipeline.base == BaseModelType.Flux and vae.sdnq_quantized_vae(pipeline):- return SDNQ_QUANTIZED_VAE_DTYPE- return SDNQ_PIPELINE_VAE_DTYPE+ return vae.z_image_pipeline if pipeline.base == BaseModelType.ZImage else FLUX_PIPELINE_VAE_DTYPEdef decode_dtypes(model: ModelConfig, precision: str, vae: VaeDtypes, models: Sequence[ModelConfig]) -> tuple[str, ...]:diff --git a/invokeai/backend/flux/extensions/kontext_extension.py b/invokeai/backend/flux/extensions/kontext_extension.pyindex 3bce624f61..bd3a711694 100644--- a/invokeai/backend/flux/extensions/kontext_extension.py+++ b/invokeai/backend/flux/extensions/kontext_extension.py@@ -11,7 +11,7 @@ from invokeai.backend.flux.sampling_utils import packfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.oom import is_oom_errorfrom invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux, vae_compute_dtypedef generate_img_ids_with_offset(@@ -140,7 +140,7 @@ class KontextExtension:with vae_info.model_on_device(working_memory=estimated_working_memory) as (_, vae):assert isinstance(vae, AutoencoderKL)- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)image_tensor = image_tensor.to(device=vae_device, dtype=vae_dtype)def encode_reference(x: torch.Tensor = image_tensor) -> torch.Tensor:diff --git a/invokeai/backend/flux2/ref_image_extension.py b/invokeai/backend/flux2/ref_image_extension.pyindex a0f7b783eb..8e56a6b82f 100644--- a/invokeai/backend/flux2/ref_image_extension.py+++ b/invokeai/backend/flux2/ref_image_extension.py@@ -27,6 +27,7 @@ from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.vae_working_memory import (estimate_vae_working_memory_flux2,flux2_vae_attention_materializes,+ vae_compute_dtype,)# Maximum pixel counts for reference images (matches BFL FLUX.2 sampling.py)@@ -133,7 +134,7 @@ def encode_reference_image()with vae_info.model_on_device(working_memory=estimated_working_memory) as (_, vae):- vae_dtype = next(iter(vae.parameters())).dtype+ vae_dtype = vae_compute_dtype(vae)image_tensor = image_tensor.to(device=device, dtype=vae_dtype)# Where SDPA materializes the encoder mid-block's attention matrix (ROCm, MPS), an untileddiff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex c3708a9daa..cca6e0212f 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -133,7 +133,11 @@ from invokeai.backend.quantization.int8_convrot import ()from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.quantization.sdnq.detection import is_sdnq_folder-from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loader+from invokeai.backend.quantization.sdnq.loaders import (+ cast_unpacked_floats,+ raise_on_incomplete_sdnq_load,+ sdnq_sd_loader,+)from invokeai.backend.t5.t5_encoder import (infer_t5_encoder_config,make_t5_feed_forward_safe,@@ -1786,9 +1790,11 @@ class Flux2SDNQCheckpointModel(ModelLoader):cls_name = AutoencoderKL.load_config(vae_dir, local_files_only=True).get("_class_name", "")except Exception:cls_name = ""+ # bf16 like `Flux2DiffusersModel`, which forces it for every FLUX.2 pipeline component; without a dtype+ # diffusers would load the bf16 weights on disk as fp32.if cls_name == "AutoencoderKLFlux2":- return AutoencoderKLFlux2.from_pretrained(vae_dir, local_files_only=True)- return AutoencoderKL.from_pretrained(vae_dir, local_files_only=True)+ return AutoencoderKLFlux2.from_pretrained(vae_dir, torch_dtype=torch.bfloat16, local_files_only=True)+ return AutoencoderKL.from_pretrained(vae_dir, torch_dtype=torch.bfloat16, local_files_only=True)def _load_from_singlefile(self, config: Main_SDNQ_Flux2_Config) -> AnyModel:from diffusers import Flux2Transformer2DModel@@ -2475,13 +2481,14 @@ class FluxSDNQDiffusersModel(ModelLoader):"""Load VAE - SDNQ or normal."""if _is_sdnq_folder(vae_path):return self._load_sdnq_vae(vae_path)- # Normal VAE- return AutoencoderKL.from_pretrained(vae_path, local_files_only=True)+ # Normal VAE, in bf16 like every component of `FluxDiffusersModel`.+ return AutoencoderKL.from_pretrained(vae_path, torch_dtype=torch.bfloat16, local_files_only=True)def _load_sdnq_vae(self, vae_path: Path) -> AnyModel:"""Load SDNQ-quantized VAE."""# Load SDNQ state dictsd = sdnq_sd_loader(vae_path, compute_dtype=torch.bfloat16)+ cast_unpacked_floats(sd, torch.bfloat16)# Load config and create modelwith accelerate.init_empty_weights():diff --git a/invokeai/backend/model_manager/load/model_loaders/vae.py b/invokeai/backend/model_manager/load/model_loaders/vae.pyindex d954de37ff..a6a2960334 100644--- a/invokeai/backend/model_manager/load/model_loaders/vae.py+++ b/invokeai/backend/model_manager/load/model_loaders/vae.py@@ -30,7 +30,11 @@ from invokeai.backend.model_manager.taxonomy import ()from invokeai.backend.quantization.fp8_scaled import reject_quantized_side_channelfrom invokeai.backend.quantization.sdnq.detection import is_sdnq_folder-from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loader+from invokeai.backend.quantization.sdnq.loaders import (+ cast_unpacked_floats,+ raise_on_incomplete_sdnq_load,+ sdnq_sd_loader,+)from invokeai.backend.sd3.vae import get_sd3_vae_diffusers_configfrom invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras@@ -270,7 +274,7 @@ class VAELoader(GenericDiffusersLoader):# Check if this is an SDNQ-quantized VAE folderif model_path.is_dir() and _is_sdnq_vae_folder(model_path):- return self._load_sdnq_vae(model_path)+ return self._load_sdnq_vae(model_path, config)if isinstance(config, VAE_Diffusers_QwenImage21_Config):from diffusers import AutoencoderKLQwenImage21@@ -533,8 +537,11 @@ class VAELoader(GenericDiffusersLoader):# NOTE: keep the `.eval()` at the end of this method in step with `_load_qwen_image_vae` above —# both build the module by hand instead of via `from_pretrained`, which would have done it.- def _load_sdnq_vae(self, model_path: Path) -> AnyModel:+ def _load_sdnq_vae(self, model_path: Path, config: AnyModelConfig) -> AnyModel:"""Load SDNQ-quantized VAE with on-the-fly dequantization."""+ # A FLUX autoencoder is broken in float16, which `precision: auto` picks on CUDA and MPS: it dequantizes to the+ # dtype every other FLUX.1 VAE path uses (the Z-Image decode shares this autoencoder).+ compute_dtype = self._torch_dtype_avoiding_float16() if config.base == BaseModelType.Flux else self._torch_dtype# Find the safetensors source. Prefer a single canonical file; otherwise hand the whole# directory to sdnq_sd_loader, which merges arbitrarily named / sharded safetensors files.model_file = model_path / "diffusion_pytorch_model.safetensors"@@ -543,7 +550,8 @@ class VAELoader(GenericDiffusersLoader):source = model_file if model_file.exists() else model_path# Load SDNQ state dict- sd = sdnq_sd_loader(source, compute_dtype=self._torch_dtype)+ sd = sdnq_sd_loader(source, compute_dtype=compute_dtype)+ cast_unpacked_floats(sd, compute_dtype)# Create empty model from configwith accelerate.init_empty_weights():diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex c8f72775e7..d08638c67f 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -883,7 +883,9 @@ class ZImageSDNQCheckpointModel(ModelLoader):from diffusers import AutoencoderKLvae_dir = resolve_submodel_path(config, SubModelType.VAE, Path(config.path) / "vae")- return AutoencoderKL.from_pretrained(vae_dir, local_files_only=True)+ # The dtype `ZImageDiffusersModel` gives every component of a Diffusers pipeline.+ dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ return AutoencoderKL.from_pretrained(vae_dir, torch_dtype=dtype, local_files_only=True)def _load_from_singlefile(self,diff --git a/invokeai/backend/quantization/sdnq/loaders.py b/invokeai/backend/quantization/sdnq/loaders.pyindex cfd0fd7c48..8428ef3704 100644--- a/invokeai/backend/quantization/sdnq/loaders.py+++ b/invokeai/backend/quantization/sdnq/loaders.py@@ -48,6 +48,20 @@ def raise_on_incomplete_sdnq_load(raise ValueError(f"Missing keys loading {model_name} (required parameters left on meta): {real_missing}")+def cast_unpacked_floats(state_dict: dict[str, Union[SDNQTensor, torch.Tensor]], dtype: torch.dtype) -> None:+ """Cast the floating-point tensors that are not packed (norms, biases, unquantized layers) to ``dtype``, in place.++ ``sdnq_sd_loader`` keeps them in the dtype on disk, while the packed weights dequantize to its ``compute_dtype``.+ A module that does not cast its input, such as a group norm, then meets an input of the compute dtype and a+ parameter of another one. ``from_pretrained(torch_dtype=...)`` makes the same cast for an ordinary model, but only+ where the model declares no ``_keep_in_fp32_modules``: such a model (T5, several transformers) needs those modules+ left wider, so this suits the VAEs, not every SDNQ load.+ """+ for key, value in state_dict.items():+ if not isinstance(value, SDNQTensor) and value.is_floating_point() and value.dtype != dtype:+ state_dict[key] = value.to(dtype)++def _parse_quantization_config(config_path: Path) -> dict[str, Any]:"""Parse quantization_config.json for SDNQ parameters."""if not config_path.exists():diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.pyindex 6eee86ffc0..41c4d33e82 100644--- a/invokeai/backend/util/vae_working_memory.py+++ b/invokeai/backend/util/vae_working_memory.py@@ -221,15 +221,15 @@ def dtype_name(dtype: torch.dtype) -> str:return name-def _compute_dtype(vae: torch.nn.Module) -> torch.dtype:- """The dtype a VAE no node casts computes in.+def vae_compute_dtype(vae: torch.nn.Module) -> torch.dtype:+ """The dtype a VAE computes in: what the nodes cast its input to, and what the estimators price it at.An SDNQ VAE computes in its packed weights' `compute_dtype`: they dequantize to it, and the layer casts every otheroperand to it, an fp32 bias included. Otherwise it is that of the first floating-point parameter wider than a byte:narrower weights (fp8 storage) are what a layer dequantizes from, not what its activations are.- A packed parameter's `compute_dtype` wins over any floating-point one, so an SDNQ VAE that kept whole layers- unquantized in fp32 would be priced below its real cost; that case is not verified for the shipped SDNQ VAEs.+ A packed parameter's `compute_dtype` wins over any floating-point one. That holds because the SDNQ VAE loaders cast+ the parameters they leave unpacked to the same dtype (`cast_unpacked_floats`), so no layer is left in another one."""first_wide_float: torch.dtype | None = Nonefor param in vae.parameters():@@ -644,7 +644,7 @@ def _single_pass_features(latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1height = latent_scale_factor_for_operation * image_tensor.shape[-2]width = latent_scale_factor_for_operation * image_tensor.shape[-1]- dtype = _compute_dtype(vae)+ dtype = vae_compute_dtype(vae)return {"operation": operation,"height": height,@@ -691,7 +691,7 @@ def estimate_vae_working_memory_cogview4("operation": operation,"height": latent_scale_factor_for_operation * image_tensor.shape[-2],"width": latent_scale_factor_for_operation * image_tensor.shape[-1],- "dtype": dtype_name(_compute_dtype(vae)),+ "dtype": dtype_name(vae_compute_dtype(vae)),}return _estimate(VAE_COGVIEW4_SPEC, features, device)@@ -708,8 +708,8 @@ def _flux_terms(features: Mapping[str, FeatureValue], values: Mapping[str, floatreturn _peak_of_two_phases(convolutions, cast(int, features["score_matrix_bytes"]))-# The FLUX.1 loaders avoid fp16, which this autoencoder is broken in, except one: an SDNQ VAE folder loads through the-# generic VAE loader and computes in the configured precision, which `auto` makes fp16 on CUDA.+# The FLUX.1 loaders avoid fp16, which this autoencoder is broken in, an SDNQ VAE folder included. The one way fp16+# reaches `vae.flux` is Z-Image's `choose_bfloat16_safe_dtype` fallback on a device without bf16.VAE_FLUX_SPEC = register(EstimatorSpec(id="vae.flux",@@ -750,7 +750,7 @@ def estimate_vae_working_memory_flux(backend's coefficients. Defaults to the session device."""latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1- dtype = _compute_dtype(vae)+ dtype = vae_compute_dtype(vae)device = device if device is not None else TorchDevice.choose_torch_device()batch_size = image_tensor.shape[0] if image_tensor.dim() >= 4 else 1@@ -836,7 +836,7 @@ def flux2_vae_attention_materializes(image_tensor: torch.Tensor, vae: Autoencodereturn (sdpa_score_matrix_bytes(device=device,- dtype=next(vae.parameters()).dtype,+ dtype=vae_compute_dtype(vae),num_heads=_FLUX2_VAE_MID_BLOCK_HEADS,head_dim=_FLUX2_VAE_MID_BLOCK_HEAD_DIM,seq_len=seq_len,@@ -898,7 +898,7 @@ def estimate_vae_working_memory_flux2(bound. The score matrix is shaped (batch, heads, S, S), so it scales the same way. The encodecall sites all pass batch 1 today; the shared estimator does not assume it."""- dtype = _compute_dtype(vae)+ dtype = vae_compute_dtype(vae)device = device if device is not None else TorchDevice.choose_torch_device()batch_size = image_tensor.shape[0] if image_tensor.dim() >= 4 else 1latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1diff --git a/tests/app/invocations/test_vae_nodes_sdnq_compute_dtype.py b/tests/app/invocations/test_vae_nodes_sdnq_compute_dtype.pynew file mode 100644index 0000000000..8ee5e2456d--- /dev/null+++ b/tests/app/invocations/test_vae_nodes_sdnq_compute_dtype.py@@ -0,0 +1,150 @@+"""The FLUX.1 and Z-Image VAE nodes feed an SDNQ VAE in the dtype it computes in.++An SDNQ VAE can lead with a packed weight, an `SDNQTensor` whose `dtype` is its integer storage. An image cast to+that dtype reaches the convolution as an integer tensor, and the run fails with "Input type (signed char) and bias type+(float) should be the same". The nodes read the dtype the way the working-memory estimator does (`vae_compute_dtype`).++The VAE is a real tiny `AutoencoderKL` whose first weight is replaced by a packed one. Its `encode` and `decode` are+recorded rather than run: a bf16 forward on the CPU is not what is under test, the dtype each node hands the VAE is.+"""++from contextlib import contextmanager+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.app.invocations.vae.cogview4_image_to_latents import CogView4ImageToLatentsInvocation+from invokeai.app.invocations.vae.flux_vae_decode import FluxVaeDecodeInvocation+from invokeai.app.invocations.vae.flux_vae_encode import FluxVaeEncodeInvocation+from invokeai.app.invocations.vae.sd3_image_to_latents import SD3ImageToLatentsInvocation+from invokeai.app.invocations.vae.z_image_image_to_latents import ZImageImageToLatentsInvocation+from invokeai.app.invocations.vae.z_image_latents_to_image import ZImageLatentsToImageInvocation+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor+from invokeai.backend.quantization.sdnq.utils import SDNQQuantizationType++COMPUTE_DTYPE = torch.bfloat16++[email protected](autouse=True)+def _pin_to_cpu(monkeypatch):+ monkeypatch.setattr(+ "invokeai.backend.util.devices.TorchDevice.choose_torch_device", staticmethod(lambda: torch.device("cpu"))+ )+++def _sdnq_vae(flux_shaped_vae):+ """A FLUX-shaped VAE whose first parameter is a packed int8 weight that dequantizes to bf16; `seen` records the+ dtype of what `encode` and `decode` are called with."""+ vae = flux_shaped_vae()+ weight = vae.encoder.conv_in.weight+ out_features = weight.shape[0]+ packed = SDNQTensor(+ data=torch.zeros(out_features, weight[0].numel(), dtype=torch.int8),+ quantization_type=SDNQQuantizationType.INT8_SYM,+ tensor_shape=weight.shape,+ compute_dtype=COMPUTE_DTYPE,+ scale=torch.ones(out_features, 1, dtype=torch.float32),+ )+ vae.encoder.conv_in.weight = torch.nn.Parameter(packed, requires_grad=False)+ first = next(vae.parameters())+ assert isinstance(first, SDNQTensor) and not first.is_floating_point(), "the fixture must lead with packed weights"++ seen: dict[str, torch.dtype] = {}++ def encode(x, return_dict=True):+ seen["encode"] = x.dtype+ dist = MagicMock()+ dist.sample.return_value = dist.mode.return_value = torch.zeros(1, 16, 8, 8)+ return MagicMock(latent_dist=dist)++ def decode(z, return_dict=True):+ seen["decode"] = z.dtype+ return (torch.zeros(1, 3, 64, 64),)++ vae.encode, vae.decode = encode, decode+ return vae, seen+++def _loaded(vae) -> MagicMock:+ loaded = MagicMock()+ loaded.model = vae+ loaded.compute_device = torch.device("cpu")++ @contextmanager+ def on_device(working_memory=None):+ yield (None, vae)++ loaded.model_on_device = on_device+ return loaded+++def _context() -> MagicMock:+ context = MagicMock()+ context.config.get.return_value.force_tiled_decode = False+ context.config.get.return_value.auto_tiled_decode = False+ return context+++def test_the_flux_encode_casts_the_image_to_the_compute_dtype_of_an_sdnq_vae(flux_shaped_vae) -> None:+ vae, seen = _sdnq_vae(flux_shaped_vae)++ FluxVaeEncodeInvocation.vae_encode(+ vae_info=_loaded(vae), image_tensor=torch.zeros(1, 3, 64, 64), tiled=False, tile_size=0+ )++ assert seen["encode"] is COMPUTE_DTYPE+++def test_the_z_image_encode_casts_the_image_and_returns_the_latents_in_the_compute_dtype(flux_shaped_vae) -> None:+ vae, seen = _sdnq_vae(flux_shaped_vae)++ latents = ZImageImageToLatentsInvocation.vae_encode(+ vae_info=_loaded(vae), image_tensor=torch.zeros(1, 3, 64, 64), tiled=False, tile_size=0+ )++ assert seen["encode"] is COMPUTE_DTYPE+ assert latents.dtype is COMPUTE_DTYPE+++def test_the_flux_decode_casts_the_latents_to_the_compute_dtype_of_an_sdnq_vae(flux_shaped_vae) -> None:+ vae, seen = _sdnq_vae(flux_shaped_vae)++ FluxVaeDecodeInvocation.model_construct()._vae_decode(+ context=_context(), vae_info=_loaded(vae), latents=torch.zeros(1, 16, 8, 8)+ )++ assert seen["decode"] is COMPUTE_DTYPE+++def test_the_z_image_decode_casts_the_latents_to_the_compute_dtype_of_an_sdnq_vae(flux_shaped_vae) -> None:+ vae, seen = _sdnq_vae(flux_shaped_vae)+ context = _context()+ context.tensors.load.return_value = torch.zeros(1, 16, 8, 8)+ context.models.load.return_value = _loaded(vae)+ context.images.save.return_value = MagicMock(image_name="out.png", width=64, height=64)+ node = ZImageLatentsToImageInvocation.model_construct(+ latents=MagicMock(latents_name="latents"),+ vae=MagicMock(vae=MagicMock(), seamless_axes=[]),+ tiled=False,+ tile_size=0,+ )++ node.invoke(context)++ assert seen["decode"] is COMPUTE_DTYPE++[email protected]("node", [SD3ImageToLatentsInvocation, CogView4ImageToLatentsInvocation])+def test_the_sd3_and_cogview4_encodes_cast_to_the_compute_dtype_not_the_first_float_parameter(+ flux_shaped_vae, node+) -> None:+ """diffusers' `vae.dtype` skips the packed weight and reads the first floating-point one, here an fp32 stored+ parameter, which is not what the packed layers dequantize to."""+ vae, seen = _sdnq_vae(flux_shaped_vae)+ assert vae.dtype is torch.float32++ latents = node.vae_encode(vae_info=_loaded(vae), image_tensor=torch.zeros(1, 3, 64, 64))++ assert seen["encode"] is COMPUTE_DTYPE+ assert latents.dtype is COMPUTE_DTYPEdiff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.pyindex 9f4dd64aab..d0655c4eae 100644--- a/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py@@ -18,13 +18,13 @@ from invokeai.app.services.model_records.missing_models import is_model_missingfrom invokeai.app.services.working_memory_calibration.working_memory_calibration_default import _vae_dtypesfrom invokeai.app.services.working_memory_calibration.working_memory_calibration_plan import (DECODE_LINES,- FLUX2_PIPELINE_VAE_DTYPE,+ FLUX_PIPELINE_VAE_DTYPE,FORCE_TILED_BASES,- SDNQ_PIPELINE_VAE_DTYPE,VAE_WEIGHTS_ALLOWANCE_BYTES,VaeDtypes,build_plan,case_sides,+ vae_source,)from invokeai.backend.model_manager.configs.base import ModelRolefrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache@@ -162,7 +162,7 @@ def test_each_covered_base_plans_the_lines_its_decode_runs(base, precision, estiassert all(bool(case.settings) == (base == BaseModelType.StableDiffusion1) for case in plan.cases)-FP32_VAES = VaeDtypes(standalone_flux="fp32", z_image_pipeline="bf16", sdnq_quantized_vae=lambda config: False)+FP32_VAES = VaeDtypes(standalone_flux="fp32", z_image_pipeline="bf16")"""`precision: float32`: the standalone FLUX VAE loaders keep it; a Z-Image pipeline's own VAE still loads in bf16."""@@ -236,28 +236,22 @@ def _lines_of(plan) -> set[tuple[str, tuple[tuple[str, str], ...]]]:[(_model("klein", BaseModelType.Flux2, format="diffusers"), "decode_bf16"),(_model("z-image", BaseModelType.ZImage, format="diffusers"), "decode_fp16"),- (_sdnq_pipeline("klein-sdnq", BaseModelType.Flux2), "decode_fp32"),- (_sdnq_pipeline("z-image-sdnq", BaseModelType.ZImage), "decode_fp32"),- (_sdnq_pipeline("flux-sdnq", BaseModelType.Flux), "decode_fp32"),- (_sdnq_pipeline("flux-sdnq-quantized-vae", BaseModelType.Flux), "decode_bf16"),+ (_sdnq_pipeline("klein-sdnq", BaseModelType.Flux2), "decode_bf16"),+ (_sdnq_pipeline("z-image-sdnq", BaseModelType.ZImage), "decode_fp16"),+ (_sdnq_pipeline("flux-sdnq", BaseModelType.Flux), "decode_bf16"),],- ids=["flux2-diffusers", "z-image-diffusers", "flux2-sdnq", "z-image-sdnq", "flux-sdnq", "flux-sdnq-quantized-vae"],+ ids=["flux2-diffusers", "z-image-diffusers", "flux2-sdnq", "z-image-sdnq", "flux-sdnq"],)def test_a_pipeline_decodes_in_the_dtype_its_own_vae_loads_in(pipeline, line) -> None:"""With an empty `vae` slot a FLUX.2 or Z-Image Diffusers pipeline and a self-contained SDNQ pipeline decode with- their own VAE: bf16 for FLUX.2 Diffusers, the device's bf16-safe dtype for Z-Image (here fp16), fp32 for the SDNQ- pipelines, whose loaders give no dtype, and bf16 for an SDNQ-quantized FLUX.1 VAE. A CPU VAE installed beside them- is no reason to pick one: Generate fills no `vae` slot for a pipeline."""+ their own VAE: bf16 for every FLUX.1 and FLUX.2 pipeline, the device's bf16-safe dtype for Z-Image (here fp16). A CPU+ VAE installed beside them is no reason to pick one: Generate fills no `vae` slot for a pipeline."""vae_base = BaseModelType.Flux2 if pipeline.base == BaseModelType.Flux2 else BaseModelType.Fluxstandalone = [_model("a-cpu-vae", vae_base, ModelType.VAE, cpu_only=True),_model("b-gpu-vae", vae_base, ModelType.VAE, cpu_only=False),]- vaes = VaeDtypes(- standalone_flux="fp32",- z_image_pipeline="fp16",- sdnq_quantized_vae=lambda config: config.key == "flux-sdnq-quantized-vae",- )+ vaes = VaeDtypes(standalone_flux="fp32", z_image_pipeline="fp16")assert _lines_of(_plan(pipeline, standalone, vae_dtypes=vaes)) == {(line, ())}@@ -286,7 +280,7 @@ GGUF_KLEIN_9B = _model("klein-9b-gguf", BaseModelType.Flux2, format="gguf_quanti"decode_bf16",),# Without a fitting one, the first pipeline at all, which gives the VAE beside the standalone encoder.- ([_sdnq_pipeline("a-sdnq-4b", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B)], "decode_fp32"),+ ([_sdnq_pipeline("a-sdnq-4b", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B)], "decode_bf16"),# Without a pipeline, Generate fills the slot with a standalone VAE.([_model("flux2-vae", BaseModelType.Flux2, ModelType.VAE)], "decode_fp16"),],@@ -296,23 +290,32 @@ def test_a_flux2_model_without_its_own_vae_decodes_with_its_component_source_vae"""Generate gives a GGUF or checkpoint FLUX.2 model an installed FLUX.2 pipeline as its component source(`getAutoFlux2ComponentSourceModel`), and the FLUX.2 model loader node decodes with that pipeline's VAE. A standaloneQwen3 8B encoder is installed, as one that fits no pipeline needs."""- vaes = VaeDtypes(standalone_flux="fp16", z_image_pipeline="bf16", sdnq_quantized_vae=lambda config: False)+ vaes = VaeDtypes(standalone_flux="fp16", z_image_pipeline="bf16")assert _lines_of(_plan(GGUF_KLEIN_9B, [*sources, QWEN3_8B], vae_dtypes=vaes)) == {(line, ())}+def test_the_component_source_is_the_first_pipeline_whose_qwen3_encoder_fits() -> None:+ """Every FLUX.2 pipeline's own VAE decodes in bf16, so the lines above do not tell which one was picked."""+ sdnq_4b = _sdnq_pipeline("a-sdnq-4b", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B)+ diffusers_9b = _model("b-diffusers-9b", BaseModelType.Flux2, format="diffusers", variant=Flux2VariantType.Klein9B)++ assert vae_source(GGUF_KLEIN_9B, [sdnq_4b, diffusers_9b, QWEN3_8B]) is diffusers_9b+ assert vae_source(GGUF_KLEIN_9B, [sdnq_4b, QWEN3_8B]) is sdnq_4b++KLEIN_4B_SDNQ = _sdnq_pipeline("klein-4b-sdnq", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B)FLUX2_VAE = _model("flux2-vae", BaseModelType.Flux2, ModelType.VAE)GGUF_DEV = _model("dev-gguf", BaseModelType.Flux2, format="gguf_quantized", variant=Flux2VariantType.Dev)SDNQ_DEV = _sdnq_pipeline("dev-sdnq", BaseModelType.Flux2, variant=Flux2VariantType.Dev)MISTRAL = _model("mistral", BaseModelType.Any, ModelType.MistralEncoder, variant=MistralVariantType.Mistral24B)-FP16_VAES = VaeDtypes(standalone_flux="fp16", z_image_pipeline="bf16", sdnq_quantized_vae=lambda config: False)-"""A standalone FLUX.2 VAE decodes in fp16, apart from a Diffusers pipeline's bf16 and an SDNQ pipeline's fp32."""+FP16_VAES = VaeDtypes(standalone_flux="fp16", z_image_pipeline="bf16")+"""A standalone FLUX.2 VAE decodes in fp16, apart from a pipeline's own bf16."""@pytest.mark.parametrize("target, line",- [(GGUF_KLEIN_9B, f"decode_{SDNQ_PIPELINE_VAE_DTYPE}"), (GGUF_DEV, "decode_fp16")],+ [(GGUF_KLEIN_9B, f"decode_{FLUX_PIPELINE_VAE_DTYPE}"), (GGUF_DEV, "decode_fp16")],ids=["klein-takes-the-sdnq-pipelines-vae", "dev-decodes-with-the-standalone-vae"],)def test_an_sdnq_flux2_pipeline_is_a_component_source_for_klein_only(target, line) -> None:@@ -332,12 +335,15 @@ def test_a_dev_model_beside_only_an_sdnq_pipeline_and_no_vae_cannot_be_calibratedef test_a_diffusers_klein_pipeline_gives_a_dev_model_its_vae_beside_a_mistral_encoder() -> None:- """The [dev] loader takes the VAE of any Diffusers FLUX.2 pipeline, passing over an SDNQ one listed first."""+ """The [dev] loader takes the VAE of any Diffusers FLUX.2 pipeline, passing over an SDNQ one listed first: it+ decodes with the pipeline's own VAE (bf16), not the standalone one (fp16 here)."""klein = _model("klein-diffusers", BaseModelType.Flux2, format="diffusers", variant=Flux2VariantType.Klein4B)+ models = [KLEIN_4B_SDNQ, klein, FLUX2_VAE, MISTRAL]- plan = _plan(GGUF_DEV, [KLEIN_4B_SDNQ, klein, FLUX2_VAE, MISTRAL], vae_dtypes=FP16_VAES)+ plan = _plan(GGUF_DEV, models, vae_dtypes=FP16_VAES)- assert _lines_of(plan) == {(f"decode_{FLUX2_PIPELINE_VAE_DTYPE}", ())}+ assert vae_source(GGUF_DEV, models) is klein+ assert _lines_of(plan) == {(f"decode_{FLUX_PIPELINE_VAE_DTYPE}", ())}def test_an_sdnq_dev_model_decodes_with_a_standalone_vae_not_its_own() -> None:@@ -346,7 +352,7 @@ def test_an_sdnq_dev_model_decodes_with_a_standalone_vae_not_its_own() -> None:dev = _model("dev-diffusers", BaseModelType.Flux2, format="diffusers", variant=Flux2VariantType.Dev)assert _lines_of(_plan(SDNQ_DEV, [FLUX2_VAE, MISTRAL], vae_dtypes=FP16_VAES)) == {("decode_fp16", ())}- assert _lines_of(_plan(SDNQ_DEV, [dev], vae_dtypes=FP16_VAES)) == {(f"decode_{FLUX2_PIPELINE_VAE_DTYPE}", ())}+ assert _lines_of(_plan(SDNQ_DEV, [dev], vae_dtypes=FP16_VAES)) == {(f"decode_{FLUX_PIPELINE_VAE_DTYPE}", ())}@pytest.mark.parametrize(@@ -724,8 +730,8 @@ def test_a_flux_sdnq_pipeline_decodes_with_its_own_vae_whatever_its_default_vae(plan = _plan(sdnq, [cpu], vae_dtypes=FP32_VAES)- assert plan.supported and _lines_of(plan) == {(f"decode_{SDNQ_PIPELINE_VAE_DTYPE}", ())}- assert _lines_of(_plan(sdnq, [cpu])) == {(f"decode_{SDNQ_PIPELINE_VAE_DTYPE}", ())}+ assert plan.supported and _lines_of(plan) == {(f"decode_{FLUX_PIPELINE_VAE_DTYPE}", ())}+ assert _lines_of(_plan(sdnq, [cpu])) == {(f"decode_{FLUX_PIPELINE_VAE_DTYPE}", ())}@pytest.mark.parametrize(@@ -991,25 +997,37 @@ def _dtype_of(model: torch.nn.Module) -> str:return dtype_name(next(model.parameters()).dtype)[email protected]("on_disk", [torch.bfloat16, torch.float32], ids=["bf16-on-disk", "fp32-on-disk"])@pytest.mark.parametrize(- "loader_class, vae_class",- [(Flux2SDNQCheckpointModel, AutoencoderKLFlux2), (ZImageSDNQCheckpointModel, AutoencoderKL)],- ids=["flux2", "z-image"],+ "vae_class", [AutoencoderKLFlux2, AutoencoderKL], ids=["flux2-autoencoder", "generic-autoencoder-fallback"])-def test_an_sdnq_pipelines_own_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path, loader_class, vae_class):- _save_tiny_vae(tmp_path / "vae", vae_class, torch.bfloat16)- loader = loader_class.__new__(loader_class)+def test_a_flux2_sdnq_pipelines_own_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path, vae_class, on_disk):+ _save_tiny_vae(tmp_path / "vae", vae_class, on_disk)+ loader = Flux2SDNQCheckpointModel.__new__(Flux2SDNQCheckpointModel)vae = loader._load_vae(SimpleNamespace(path=str(tmp_path), submodels=None))- assert _dtype_of(vae) == SDNQ_PIPELINE_VAE_DTYPE+ assert _dtype_of(vae) == FLUX_PIPELINE_VAE_DTYPE-def test_a_flux_sdnq_pipelines_plain_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path):[email protected]("safe_dtype", [torch.bfloat16, torch.float16], ids=["bf16-safe", "no-bf16"])+def test_a_z_image_sdnq_pipelines_own_vae_loads_in_the_bf16_safe_dtype_the_plan_sizes_for(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, safe_dtype+):_save_tiny_vae(tmp_path / "vae", AutoencoderKL, torch.bfloat16)+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", classmethod(lambda cls, device=None: safe_dtype))+ loader = ZImageSDNQCheckpointModel.__new__(ZImageSDNQCheckpointModel)++ vae = loader._load_vae(SimpleNamespace(path=str(tmp_path), submodels=None))++ assert _dtype_of(vae) == _vae_dtypes(torch.device("cpu")).z_image_pipeline == dtype_name(safe_dtype)+++def test_a_flux_sdnq_pipelines_plain_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path):+ _save_tiny_vae(tmp_path / "vae", AutoencoderKL, torch.float32)loader = FluxSDNQDiffusersModel.__new__(FluxSDNQDiffusersModel)- assert _dtype_of(loader._load_vae(tmp_path / "vae")) == SDNQ_PIPELINE_VAE_DTYPE+ assert _dtype_of(loader._load_vae(tmp_path / "vae")) == FLUX_PIPELINE_VAE_DTYPEdef test_a_flux2_diffusers_pipelines_own_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path):@@ -1022,7 +1040,7 @@ def test_a_flux2_diffusers_pipelines_own_vae_loads_in_the_dtype_the_plan_sizes_fvae = loader._load_model(SimpleNamespace(path=str(tmp_path), repo_variant=None), SubModelType.VAE)- assert _dtype_of(vae) == FLUX2_PIPELINE_VAE_DTYPE+ assert _dtype_of(vae) == FLUX_PIPELINE_VAE_DTYPE@pytest.mark.parametrize("precision, expected", [("float32", "fp32"), ("bfloat16", "bf16"), ("auto", "bf16")])@@ -1037,18 +1055,7 @@ def test_the_service_reads_a_standalone_flux_vaes_dtype_from_the_precision_setti# The bf16 probe on a card that has it; no CUDA device is needed for the answer.monkeypatch.setattr(torch, "empty", lambda *args, dtype, device: empty(0, dtype=dtype))- assert _vae_dtypes(GPU, Path("models")).standalone_flux == expected---def test_the_service_tells_an_sdnq_quantized_vae_folder_where_the_loader_looks(tmp_path: Path):- quantized, plain = tmp_path / "flux-sdnq" / "vae", tmp_path / "flux-sdnq-plain" / "vae"- quantized.mkdir(parents=True)- plain.mkdir(parents=True)- (quantized / "quantization_config.json").write_text(json.dumps({"quant_method": "sdnq"}))- vaes = _vae_dtypes(torch.device("cpu"), tmp_path)-- assert vaes.sdnq_quantized_vae(SimpleNamespace(path="flux-sdnq", submodels=None))- assert not vaes.sdnq_quantized_vae(SimpleNamespace(path="flux-sdnq-plain", submodels=None))+ assert _vae_dtypes(GPU).standalone_flux == expecteddef _with_default_components(model: SimpleNamespace, **components: str) -> SimpleNamespace:@@ -1160,14 +1167,14 @@ def test_a_flux_vae_skips_a_main_model_without_its_encoders(base, encoder) -> No"pipeline, bundled_line",[(_model("z-image", BaseModelType.ZImage, format="diffusers"), "decode_bf16"),- (_sdnq_pipeline("z-image", BaseModelType.ZImage), "decode_fp32"),+ (_sdnq_pipeline("z-image", BaseModelType.ZImage), "decode_bf16"),],ids=["diffusers", "sdnq"],)def test_a_z_image_model_decodes_with_the_vae_of_its_default_component_source(pipeline, bundled_line) -> None:- """Selecting the model fills its `component_source` slot (a Z-Image pipeline), whose own VAE the model loader node- then takes where no VAE is set: under `precision: float32` the pipeline's VAE loads in bf16 where a standalone FLUX- VAE stays fp32, and the case needs no VAE pick."""+ """Selecting the model fills its `component_source` slot (a Z-Image Diffusers or SDNQ pipeline), whose own VAE the+ model loader node then takes where no VAE is set: under `precision: float32` the pipeline's VAE loads in bf16 where a+ standalone FLUX VAE stays fp32, and the case needs no VAE pick."""gguf = _model("z-image-gguf", BaseModelType.ZImage, format="gguf_quantized")flux_vae = _model("ae", BaseModelType.Flux, ModelType.VAE)with_source = _with_default_components(gguf, component_source="z-image")@@ -1183,17 +1190,6 @@ def test_a_z_image_model_decodes_with_the_vae_of_its_default_component_source(piassert _lines_of(_plan(with_vae, [pipeline, flux_vae], vae_dtypes=FP32_VAES)) == {("decode_fp32", ())}-def test_a_self_contained_z_image_pipeline_decodes_with_the_vae_of_its_default_component_source() -> None:- """The Z-Image loader takes a source's VAE over the self-contained pipeline's own, and the slot is offered for it."""- sdnq = _sdnq_pipeline("z-image-sdnq", BaseModelType.ZImage)- pipeline = _model("z-image", BaseModelType.ZImage, format="diffusers")-- assert _lines_of(_plan(sdnq, [pipeline], vae_dtypes=FP32_VAES)) == {("decode_fp32", ())}- assert _lines_of(- _plan(_with_default_components(sdnq, component_source="z-image"), [pipeline], vae_dtypes=FP32_VAES)- ) == {("decode_bf16", ())}--def test_a_z_image_default_source_whose_files_are_gone_sizes_no_case(tmp_path: Path, mock_invoker: Invoker) -> None:"""Generate skips a registered model whose files moved, so the graph decodes with the VAE it would without it."""models_dir = tmp_path / "models"diff --git a/tests/backend/flux/extensions/test_kontext_extension.py b/tests/backend/flux/extensions/test_kontext_extension.pyindex 7824468bd2..0a60be3398 100644--- a/tests/backend/flux/extensions/test_kontext_extension.py+++ b/tests/backend/flux/extensions/test_kontext_extension.py@@ -23,6 +23,8 @@ from PIL import Imageimport invokeai.backend.flux.extensions.kontext_extension as kontext_extensionfrom invokeai.backend.flux.extensions.kontext_extension import KontextExtension+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor+from invokeai.backend.quantization.sdnq.utils import SDNQQuantizationTypedef _tiny_vae() -> AutoencoderKL:@@ -85,6 +87,34 @@ def _reference_image(edge: int = 64) -> Image.Image:return Image.fromarray(pixels, mode="RGB")+class TestAnSdnqVae:+ def test_the_reference_is_encoded_in_the_dtype_the_packed_weights_compute_in(self):+ """An SDNQ VAE can lead with a packed int8 weight; the image must not be cast to that."""+ vae = _tiny_vae()+ weight = vae.encoder.conv_in.weight+ packed = SDNQTensor(+ data=torch.zeros(weight.shape[0], weight[0].numel(), dtype=torch.int8),+ quantization_type=SDNQQuantizationType.INT8_SYM,+ tensor_shape=weight.shape,+ compute_dtype=torch.bfloat16,+ scale=torch.ones(weight.shape[0], 1),+ )+ vae.encoder.conv_in.weight = torch.nn.Parameter(packed, requires_grad=False)+ seen: list[torch.dtype] = []++ def encode(x, return_dict=True):+ seen.append(x.dtype)+ distribution = MagicMock()+ distribution.mode.return_value = torch.zeros(1, 16, 8, 8)+ return MagicMock(latent_dist=distribution)++ vae.encode = encode++ _extension(vae, _reference_image())++ assert seen == [torch.bfloat16]++def test_cpu_vae_encodes_kontext_before_moving_conditioning_to_the_transformer(monkeypatch):vae = _tiny_vae()real_encode = vae.encodediff --git a/tests/backend/model_manager/load/test_sdnq_vae_dtype.py b/tests/backend/model_manager/load/test_sdnq_vae_dtype.pynew file mode 100644index 0000000000..11b9826b2b--- /dev/null+++ b/tests/backend/model_manager/load/test_sdnq_vae_dtype.py@@ -0,0 +1,113 @@+"""The dtype a SDNQ VAE loads in and computes in.++A FLUX autoencoder is broken in float16, which `precision: auto` picks on CUDA and MPS, so every FLUX.1 VAE path+avoids it, a standalone SDNQ one included. Other bases follow the configured dtype. Whatever the compute dtype, the+parameters the export leaves unpacked are cast to it: a group norm does not cast its input, so a norm in the dtype on+disk would meet an input of another one.+"""++import json+from pathlib import Path++import pytest+import torch+from diffusers import AutoencoderKL+from safetensors.torch import save_file++from invokeai.backend.model_manager.configs.vae import (+ VAE_Diffusers_FLUX_Config,+ VAE_Diffusers_SD3_Config,+ VAE_Diffusers_SDXL_Config,+)+from invokeai.backend.model_manager.load.model_loaders.flux import FluxSDNQDiffusersModel+from invokeai.backend.model_manager.load.model_loaders.vae import VAELoader+from invokeai.backend.model_manager.taxonomy import SubModelType+++def _packed_compute_dtypes(vae: torch.nn.Module) -> set[torch.dtype]:+ return {p.compute_dtype for p in vae.parameters() if hasattr(p, "compute_dtype")}+++def _unpacked_float_dtypes(vae: torch.nn.Module) -> set[torch.dtype]:+ return {p.dtype for p in vae.parameters() if not hasattr(p, "compute_dtype") and p.is_floating_point()}+++def sdnq_vae_folder(tmp_path: Path) -> Path:+ """A tiny SDNQ VAE: the mid-block attention projections are packed int8 with a scale, the rest is stored in fp16."""+ vae = AutoencoderKL(+ block_out_channels=(32,),+ down_block_types=("DownEncoderBlock2D",),+ up_block_types=("UpDecoderBlock2D",),+ norm_num_groups=8,+ latent_channels=4,+ layers_per_block=1,+ )+ vae.save_config(tmp_path)+ state_dict = {}+ for key, value in vae.state_dict().items():+ if value.ndim == 2 and key.endswith("weight"):+ state_dict[key] = torch.randint(-100, 100, value.shape, dtype=torch.int8)+ state_dict[key.removesuffix("weight") + "scale"] = torch.full((value.shape[0], 1), 0.01)+ else:+ state_dict[key] = value.to(torch.float16)+ save_file(state_dict, str(tmp_path / "diffusion_pytorch_model.safetensors"))+ (tmp_path / "quantization_config.json").write_text(json.dumps({"quant_method": "sdnq", "weights_dtype": "int8"}))+ return tmp_path+++def _load(folder: Path, config_class: type, configured: torch.dtype) -> AutoencoderKL:+ loader = VAELoader.__new__(VAELoader)+ loader._torch_dtype = configured+ loader._torch_device = torch.device("cpu")+ return loader._load_model(config_class.model_construct(path=str(folder), name="vae"), SubModelType.VAE)+++ "configured, expected",+ [+ pytest.param(torch.float16, torch.bfloat16, id="auto-on-cuda-becomes-bf16"),+ pytest.param(torch.bfloat16, torch.bfloat16, id="bf16-stays"),+ pytest.param(torch.float32, torch.float32, id="fp32-stays"),+ ],+)+def test_a_flux_sdnq_vae_never_dequantizes_to_float16(sdnq_vae_folder, configured, expected) -> None:+ vae = _load(sdnq_vae_folder, VAE_Diffusers_FLUX_Config, configured)++ assert _packed_compute_dtypes(vae) == {expected}+ assert _unpacked_float_dtypes(vae) == {expected}+++ "config_class",+ [+ pytest.param(VAE_Diffusers_SDXL_Config, id="sdxl"),+ pytest.param(VAE_Diffusers_SD3_Config, id="sd3"),+ ],+)+def test_another_bases_sdnq_vae_follows_the_configured_dtype(sdnq_vae_folder, config_class) -> None:+ vae = _load(sdnq_vae_folder, config_class, torch.float16)++ assert _packed_compute_dtypes(vae) == {torch.float16}+ assert _unpacked_float_dtypes(vae) == {torch.float16}+++def test_an_sdnq_vae_with_unpacked_tensors_stored_in_another_dtype_runs(sdnq_vae_folder) -> None:+ """Float32 compute against fp16 on disk: the group norms would otherwise get an fp32 input and fp16 parameters,+ which the CPU refuses. Float32 keeps the forward off the CPU's slow bf16 matmul."""+ vae = _load(sdnq_vae_folder, VAE_Diffusers_FLUX_Config, torch.float32)++ with torch.inference_mode():+ image = vae.decode(torch.zeros(1, 4, 8, 8), return_dict=False)[0]+ latents = vae.encode(torch.zeros(1, 3, 8, 8)).latent_dist.mode()++ assert image.dtype == latents.dtype == torch.float32+++def test_a_flux_sdnq_pipelines_sdnq_vae_dequantizes_to_bf16_and_casts_the_rest(sdnq_vae_folder) -> None:+ loader = FluxSDNQDiffusersModel.__new__(FluxSDNQDiffusersModel)++ vae = loader._load_sdnq_vae(sdnq_vae_folder)++ assert _packed_compute_dtypes(vae) == {torch.bfloat16}+ assert _unpacked_float_dtypes(vae) == {torch.bfloat16}diff --git a/tests/fixtures/working_memory_calibration.py b/tests/fixtures/working_memory_calibration.pyindex 358507ece3..585dc89290 100644--- a/tests/fixtures/working_memory_calibration.py+++ b/tests/fixtures/working_memory_calibration.py@@ -27,7 +27,7 @@ from invokeai.backend.working_memory.probe import MeasuredWindow, ReasonGPU = torch.device("cuda:0")GPU_CLASS = DeviceClass(vendor="nvidia", name="Test GPU 24GB", total_mib=24564, backend="cuda", arch="sm_89")-GPU_VAE_DTYPES = VaeDtypes(standalone_flux="bf16", z_image_pipeline="bf16", sdnq_quantized_vae=lambda config: False)+GPU_VAE_DTYPES = VaeDtypes(standalone_flux="bf16", z_image_pipeline="bf16")OTHER_CLASS = DeviceClass(vendor="amd", name="Test GPU 16GB", total_mib=16304, backend="hip", arch="gfx1200")@@ -78,7 +78,7 @@ def calibration_service(device_memory=(lambda device: DeviceMemory(device_class.total_mib * 2**20, 0))if device_memory == "whole card"else device_memory,- vae_dtypes=lambda device, models_path: vae_dtypes,+ vae_dtypes=lambda device: vae_dtypes,is_model_missing=is_model_missing,**extra,)