Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

Merge branch 'main' into refactor/invocations-by-architecture

Alexander Eichhorna2ef52662a35
diff --cc invokeai/backend/model_manager/starter_models/__init__.py
index f494cb6995,0000000000..3f6990e7f7
mode 100644,000000..100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@@ -1,1071 -1,0 +1,1071 @@@
+"""The starter model catalogue.
+
+`STARTER_MODELS` is a curated order, not a derived one: it is what the install dialog shows, in
+the sequence someone decided on. It stays written out here rather than assembled from the
+per-architecture modules, because assembling it would lose that sequence and nothing could
+reconstruct it.
+
+Every name is re-exported, so `from ...starter_models import <anything>` keeps working.
+"""
+
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_base as anima_base,
+)
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_lllite_depth_preview3 as anima_lllite_depth_preview3,
+)
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_lllite_inpainting as anima_lllite_inpainting,
+)
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_lllite_lineart_preview3 as anima_lllite_lineart_preview3,
+)
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_lllite_pose_preview3 as anima_lllite_pose_preview3,
+)
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_lllite_scribble_preview3 as anima_lllite_scribble_preview3,
+)
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_lllite_sketch as anima_lllite_sketch,
+)
+from invokeai.backend.model_manager.starter_models.anima import (
+ anima_vae as anima_vae,
+)
+from invokeai.backend.model_manager.starter_models.cogview4 import (
+ cogview4 as cogview4,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ anima_qwen3_encoder as anima_qwen3_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ animesharp_v4_rcan as animesharp_v4_rcan,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ clip_l_encoder as clip_l_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ clip_vit_l_image_encoder as clip_vit_l_image_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ dfn2b_clip_vit_l_image_encoder as dfn2b_clip_vit_l_image_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ esrgan_srx4 as esrgan_srx4,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_dev_comfy_mistral_bf16 as flux2_dev_comfy_mistral_bf16,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_dev_comfy_mistral_fp4 as flux2_dev_comfy_mistral_fp4,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_dev_comfy_mistral_fp8 as flux2_dev_comfy_mistral_fp8,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_dev_cow_mistral_iq4_xs as flux2_dev_cow_mistral_iq4_xs,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_dev_cow_mistral_q4 as flux2_dev_cow_mistral_q4,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_dev_cow_mistral_q8 as flux2_dev_cow_mistral_q8,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_klein_qwen3_4b_encoder as flux2_klein_qwen3_4b_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ flux2_klein_qwen3_8b_encoder as flux2_klein_qwen3_8b_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ gemma2_2b_encoder as gemma2_2b_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ ip_adapter_sd_image_encoder as ip_adapter_sd_image_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ ip_adapter_sdxl_image_encoder as ip_adapter_sdxl_image_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ llava_onevision as llava_onevision,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ llava_onevision_7b as llava_onevision_7b,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ qwen2_5_1_5b_instruct as qwen2_5_1_5b_instruct,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ qwen2_5_3b_instruct as qwen2_5_3b_instruct,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ qwen3_vl_encoder_4b as qwen3_vl_encoder_4b,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ qwen_vl_encoder_diffusers as qwen_vl_encoder_diffusers,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ qwen_vl_encoder_fp8 as qwen_vl_encoder_fp8,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ realesrgan_x2 as realesrgan_x2,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ realesrgan_x4 as realesrgan_x4,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ siglip as siglip,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ smollm2_1_7b_instruct as smollm2_1_7b_instruct,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ swinir as swinir,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ t5_8b_quantized_encoder as t5_8b_quantized_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ t5_base_encoder as t5_base_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ t5_gguf_q3_k_s_encoder as t5_gguf_q3_k_s_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ t5_gguf_q6_k_encoder as t5_gguf_q6_k_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ wan_22_t5_encoder as wan_22_t5_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ z_image_qwen3_encoder as z_image_qwen3_encoder,
+)
+from invokeai.backend.model_manager.starter_models.common import (
+ z_image_qwen3_encoder_quantized as z_image_qwen3_encoder_quantized,
+)
+from invokeai.backend.model_manager.starter_models.ernie_image import (
+ ernie_image as ernie_image,
+)
+from invokeai.backend.model_manager.starter_models.ernie_image import (
+ ernie_image_turbo as ernie_image_turbo,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ GEMINI_3_1_FLASH_RESOLUTION_PRESETS as GEMINI_3_1_FLASH_RESOLUTION_PRESETS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ GEMINI_3_IMAGE_ALLOWED_ASPECT_RATIOS as GEMINI_3_IMAGE_ALLOWED_ASPECT_RATIOS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ GEMINI_3_IMAGE_MAX_SIZE as GEMINI_3_IMAGE_MAX_SIZE,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ GEMINI_3_PRO_RESOLUTION_PRESETS as GEMINI_3_PRO_RESOLUTION_PRESETS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ OPENAI_GPT_IMAGE_ASPECT_RATIO_SIZES as OPENAI_GPT_IMAGE_ASPECT_RATIO_SIZES,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ OPENAI_GPT_IMAGE_ASPECT_RATIOS as OPENAI_GPT_IMAGE_ASPECT_RATIOS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ OPENAI_GPT_IMAGE_PANEL_SCHEMA as OPENAI_GPT_IMAGE_PANEL_SCHEMA,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ QWEN_IMAGE_2_ALLOWED_ASPECT_RATIOS as QWEN_IMAGE_2_ALLOWED_ASPECT_RATIOS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ QWEN_IMAGE_MAX_ALLOWED_ASPECT_RATIOS as QWEN_IMAGE_MAX_ALLOWED_ASPECT_RATIOS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ SEEDREAM_1K_SIZES as SEEDREAM_1K_SIZES,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ SEEDREAM_2K_SIZES as SEEDREAM_2K_SIZES,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ SEEDREAM_ASPECT_RATIOS as SEEDREAM_ASPECT_RATIOS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ SEEDREAM_PANEL_SCHEMA as SEEDREAM_PANEL_SCHEMA,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ WAN_V2_ALLOWED_ASPECT_RATIOS as WAN_V2_ALLOWED_ASPECT_RATIOS,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ _gemini_3_resolution_presets as _gemini_3_resolution_presets,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ alibabacloud_qwen_image_2 as alibabacloud_qwen_image_2,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ alibabacloud_qwen_image_2_pro as alibabacloud_qwen_image_2_pro,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ alibabacloud_qwen_image_edit_max as alibabacloud_qwen_image_edit_max,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ alibabacloud_qwen_image_max as alibabacloud_qwen_image_max,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ alibabacloud_wan26_t2i as alibabacloud_wan26_t2i,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ gemini_3_1_flash_image_preview as gemini_3_1_flash_image_preview,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ gemini_flash_image as gemini_flash_image,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ gemini_pro_image_preview as gemini_pro_image_preview,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ openai_dall_e_3 as openai_dall_e_3,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ openai_gpt_image_1 as openai_gpt_image_1,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ openai_gpt_image_1_5 as openai_gpt_image_1_5,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ openai_gpt_image_1_mini as openai_gpt_image_1_mini,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ openai_gpt_image_2 as openai_gpt_image_2,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ seedream_4_0 as seedream_4_0,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ seedream_4_5 as seedream_4_5,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ seedream_5_0 as seedream_5_0,
+)
+from invokeai.backend.model_manager.starter_models.external import (
+ seedream_5_0_lite as seedream_5_0_lite,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_canny_control_lora as flux_canny_control_lora,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_depth_control_lora as flux_depth_control_lora,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_dev as flux_dev,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_dev_quantized as flux_dev_quantized,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_fill as flux_fill,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_kontext as flux_kontext,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_kontext_quantized as flux_kontext_quantized,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_krea as flux_krea,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_krea_quantized as flux_krea_quantized,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_redux as flux_redux,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_schnell as flux_schnell,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_schnell_quantized as flux_schnell_quantized,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_schnell_sdnq as flux_schnell_sdnq,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_vae as flux_vae,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ ip_adapter_flux as ip_adapter_flux,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ pid_decoder_flux_2k as pid_decoder_flux_2k,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ pid_decoder_flux_2kto4k as pid_decoder_flux_2kto4k,
+)
+from invokeai.backend.model_manager.starter_models.flux import (
+ union_cnet_flux as union_cnet_flux,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_diffusers as flux2_dev_diffusers,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_diffusers_nf4 as flux2_dev_diffusers_nf4,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_gguf_q3_k_m as flux2_dev_gguf_q3_k_m,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_gguf_q4_k_m as flux2_dev_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_gguf_q5_k_m as flux2_dev_gguf_q5_k_m,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_gguf_q6_k as flux2_dev_gguf_q6_k,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_gguf_q8_0 as flux2_dev_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_4b as flux2_klein_4b,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_4b_fp8 as flux2_klein_4b_fp8,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_4b_gguf_q4 as flux2_klein_4b_gguf_q4,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_4b_gguf_q8 as flux2_klein_4b_gguf_q8,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_4b_sdnq as flux2_klein_4b_sdnq,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_4b_single as flux2_klein_4b_single,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_9b as flux2_klein_9b,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_9b_fp8 as flux2_klein_9b_fp8,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_9b_gguf_q4 as flux2_klein_9b_gguf_q4,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_9b_gguf_q8 as flux2_klein_9b_gguf_q8,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_klein_9b_sdnq as flux2_klein_9b_sdnq,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_vae as flux2_vae,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ pid_decoder_flux2_2k as pid_decoder_flux2_2k,
+)
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ pid_decoder_flux2_2kto4k as pid_decoder_flux2_2kto4k,
+)
+from invokeai.backend.model_manager.starter_models.ideogram_4 import (
+ ideogram_4_fp8 as ideogram_4_fp8,
+)
+from invokeai.backend.model_manager.starter_models.ideogram_4 import (
+ ideogram_4_nf4 as ideogram_4_nf4,
+)
+from invokeai.backend.model_manager.starter_models.krea_2 import (
+ krea2_raw as krea2_raw,
+)
+from invokeai.backend.model_manager.starter_models.krea_2 import (
+ krea2_turbo as krea2_turbo,
+)
+from invokeai.backend.model_manager.starter_models.krea_2 import (
+ krea2_turbo_gguf_q4_k_m as krea2_turbo_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.krea_2 import (
+ krea2_turbo_gguf_q8_0 as krea2_turbo_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
+ minimax_h3_components as minimax_h3_components,
+)
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
+ minimax_h3_int8_text_encoder as minimax_h3_int8_text_encoder,
+)
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
+ minimax_h3_int8_transformer as minimax_h3_int8_transformer,
+)
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_lightx2v_turbo_lora as minimax_h3_lightx2v_turbo_lora,
++ minimax_h3_lightx2v_ref2v_turbo_lora as minimax_h3_lightx2v_ref2v_turbo_lora,
+)
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_ref2v_turbo_lora as minimax_h3_ref2v_turbo_lora,
++ minimax_h3_lightx2v_turbo_lora as minimax_h3_lightx2v_turbo_lora,
+)
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
+ minimax_h3_ref2va_int8_transformer as minimax_h3_ref2va_int8_transformer,
+)
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
+ minimax_h3_turbo_lora as minimax_h3_turbo_lora,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ pid_decoder_qwenimage_2kto4k as pid_decoder_qwenimage_2kto4k,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image as qwen_image,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_edit as qwen_image_edit,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_edit_gguf_q2_k as qwen_image_edit_gguf_q2_k,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_edit_gguf_q4_k_m as qwen_image_edit_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_edit_gguf_q6_k as qwen_image_edit_gguf_q6_k,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_edit_gguf_q8_0 as qwen_image_edit_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_edit_lightning_4step as qwen_image_edit_lightning_4step,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_edit_lightning_8step as qwen_image_edit_lightning_8step,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_gguf_q2_k as qwen_image_gguf_q2_k,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_gguf_q4_k_m as qwen_image_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_gguf_q6_k as qwen_image_gguf_q6_k,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_gguf_q8_0 as qwen_image_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_lightning_4step as qwen_image_lightning_4step,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_lightning_8step as qwen_image_lightning_8step,
+)
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ qwen_image_vae as qwen_image_vae,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ canny_sd1 as canny_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ cyberrealistic_negative as cyberrealistic_negative,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ cyberrealistic_sd1 as cyberrealistic_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ deliberate_inpainting_sd1 as deliberate_inpainting_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ deliberate_sd1 as deliberate_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ depth_sd1 as depth_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ dreamshaper_8_inpainting_sd1 as dreamshaper_8_inpainting_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ dreamshaper_8_sd1 as dreamshaper_8_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ easy_neg_sd1 as easy_neg_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ inpaint_cnet_sd1 as inpaint_cnet_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ ip_adapter_plus_face_sd1 as ip_adapter_plus_face_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ ip_adapter_plus_sd1 as ip_adapter_plus_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ ip_adapter_sd1 as ip_adapter_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ lineart_anime_sd1 as lineart_anime_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ lineart_sd1 as lineart_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ mlsd_sd1 as mlsd_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ normal_bae_sd1 as normal_bae_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ openpose_sd1 as openpose_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ qr_code_cnet_sd1 as qr_code_cnet_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ rev_animated_sd1 as rev_animated_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ scribble_sd1 as scribble_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ seg_sd1 as seg_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ shuffle_sd1 as shuffle_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ softedge_sd1 as softedge_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ t2i_canny_sd1 as t2i_canny_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ t2i_depth_sd1 as t2i_depth_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ t2i_sketch_sd1 as t2i_sketch_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ tile_sd1 as tile_sd1,
+)
+from invokeai.backend.model_manager.starter_models.sd_3 import (
+ pid_decoder_sd3_2k as pid_decoder_sd3_2k,
+)
+from invokeai.backend.model_manager.starter_models.sd_3 import (
+ pid_decoder_sd3_2kto4k as pid_decoder_sd3_2kto4k,
+)
+from invokeai.backend.model_manager.starter_models.sd_3 import (
+ sd35_large as sd35_large,
+)
+from invokeai.backend.model_manager.starter_models.sd_3 import (
+ sd35_medium as sd35_medium,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ alien_lora_sdxl as alien_lora_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ archvis_sdxl as archvis_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ canny_sdxl as canny_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ depth_sdxl as depth_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ dreamshaper_sdxl as dreamshaper_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ ip_adapter_plus_sdxl as ip_adapter_plus_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ ip_adapter_sdxl as ip_adapter_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ juggernaut_sdxl as juggernaut_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ noodle_lora_sdxl as noodle_lora_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ openpose_sdxl as openpose_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ pid_decoder_sdxl_2kto4k as pid_decoder_sdxl_2kto4k,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ qr_code_cnet_sdxl as qr_code_cnet_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ scribble_sdxl as scribble_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ sdxl_fp16_vae_fix as sdxl_fp16_vae_fix,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ softedge_sdxl as softedge_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ t2i_canny_sdxl as t2i_canny_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ t2i_lineart_sdxl as t2i_lineart_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ t2i_sketch_sdxl as t2i_sketch_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ tile_sdxl as tile_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl import (
+ union_cnet_sdxl as union_cnet_sdxl,
+)
+from invokeai.backend.model_manager.starter_models.sdxl_refiner import (
+ sdxl_refiner as sdxl_refiner,
+)
+from invokeai.backend.model_manager.starter_models.types import (
+ StarterModel as StarterModel,
+)
+from invokeai.backend.model_manager.starter_models.types import (
+ StarterModelBundle as StarterModelBundle,
+)
+from invokeai.backend.model_manager.starter_models.types import (
+ StarterModelWithoutDependencies as StarterModelWithoutDependencies,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_5b_vae as wan_22_5b_vae,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_a14b_vae as wan_22_a14b_vae,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_i2v_a14b_diffusers as wan_22_i2v_a14b_diffusers,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_i2v_a14b_gguf_q4_k_m as wan_22_i2v_a14b_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_i2v_a14b_gguf_q8_0 as wan_22_i2v_a14b_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_i2v_a14b_low_gguf_q4_k_m as wan_22_i2v_a14b_low_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_i2v_a14b_low_gguf_q8_0 as wan_22_i2v_a14b_low_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_i2v_lightning_high as wan_22_i2v_lightning_high,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_i2v_lightning_low as wan_22_i2v_lightning_low,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_t2v_a14b_diffusers as wan_22_t2v_a14b_diffusers,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_t2v_a14b_gguf_q4_k_m as wan_22_t2v_a14b_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_t2v_a14b_gguf_q8_0 as wan_22_t2v_a14b_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_t2v_a14b_low_gguf_q4_k_m as wan_22_t2v_a14b_low_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_t2v_a14b_low_gguf_q8_0 as wan_22_t2v_a14b_low_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_t2v_lightning_high as wan_22_t2v_lightning_high,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_t2v_lightning_low as wan_22_t2v_lightning_low,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_ti2v_5b_diffusers as wan_22_ti2v_5b_diffusers,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_ti2v_5b_gguf_q4_k_m as wan_22_ti2v_5b_gguf_q4_k_m,
+)
+from invokeai.backend.model_manager.starter_models.wan import (
+ wan_22_ti2v_5b_gguf_q8_0 as wan_22_ti2v_5b_gguf_q8_0,
+)
+from invokeai.backend.model_manager.starter_models.z_image import (
+ z_image_controlnet_tile as z_image_controlnet_tile,
+)
+from invokeai.backend.model_manager.starter_models.z_image import (
+ z_image_controlnet_union as z_image_controlnet_union,
+)
+from invokeai.backend.model_manager.starter_models.z_image import (
+ z_image_turbo as z_image_turbo,
+)
+from invokeai.backend.model_manager.starter_models.z_image import (
+ z_image_turbo_q8 as z_image_turbo_q8,
+)
+from invokeai.backend.model_manager.starter_models.z_image import (
+ z_image_turbo_quantized as z_image_turbo_quantized,
+)
+from invokeai.backend.model_manager.starter_models.z_image import (
+ z_image_turbo_sdnq as z_image_turbo_sdnq,
+)
+from invokeai.backend.model_manager.taxonomy import BaseModelType
+
+# List of starter models, displayed on the frontend.
+# The order/sort of this list is not changed by the frontend - set it how you want it here.
+STARTER_MODELS: list[StarterModel] = [
+ flux_kontext_quantized,
+ flux_schnell_quantized,
+ flux_dev_quantized,
+ flux_schnell,
+ flux_dev,
+ flux_schnell_sdnq,
+ sd35_medium,
+ sd35_large,
+ ideogram_4_nf4,
+ ideogram_4_fp8,
+ cyberrealistic_sd1,
+ rev_animated_sd1,
+ dreamshaper_8_sd1,
+ dreamshaper_8_inpainting_sd1,
+ deliberate_sd1,
+ deliberate_inpainting_sd1,
+ juggernaut_sdxl,
+ dreamshaper_sdxl,
+ archvis_sdxl,
+ sdxl_refiner,
+ sdxl_fp16_vae_fix,
+ flux_vae,
+ alien_lora_sdxl,
+ noodle_lora_sdxl,
+ easy_neg_sd1,
+ ip_adapter_sd1,
+ ip_adapter_plus_sd1,
+ ip_adapter_plus_face_sd1,
+ ip_adapter_sdxl,
+ ip_adapter_plus_sdxl,
+ ip_adapter_flux,
+ qr_code_cnet_sd1,
+ qr_code_cnet_sdxl,
+ canny_sd1,
+ inpaint_cnet_sd1,
+ mlsd_sd1,
+ depth_sd1,
+ normal_bae_sd1,
+ seg_sd1,
+ lineart_sd1,
+ lineart_anime_sd1,
+ openpose_sd1,
+ scribble_sd1,
+ softedge_sd1,
+ shuffle_sd1,
+ tile_sd1,
+ canny_sdxl,
+ depth_sdxl,
+ softedge_sdxl,
+ openpose_sdxl,
+ scribble_sdxl,
+ tile_sdxl,
+ union_cnet_sdxl,
+ union_cnet_flux,
+ flux_canny_control_lora,
+ flux_depth_control_lora,
+ t2i_canny_sd1,
+ t2i_sketch_sd1,
+ t2i_depth_sd1,
+ t2i_canny_sdxl,
+ t2i_lineart_sdxl,
+ t2i_sketch_sdxl,
+ realesrgan_x4,
+ animesharp_v4_rcan,
+ realesrgan_x2,
+ swinir,
+ t5_base_encoder,
+ t5_8b_quantized_encoder,
+ t5_gguf_q3_k_s_encoder,
+ t5_gguf_q6_k_encoder,
+ clip_l_encoder,
+ dfn2b_clip_vit_l_image_encoder,
+ siglip,
+ flux_redux,
+ llava_onevision,
+ llava_onevision_7b,
+ qwen2_5_1_5b_instruct,
+ qwen2_5_3b_instruct,
+ smollm2_1_7b_instruct,
+ flux_fill,
+ flux2_vae,
+ flux2_klein_4b,
+ flux2_klein_4b_single,
+ flux2_klein_4b_fp8,
+ flux2_klein_9b,
+ flux2_klein_9b_fp8,
+ flux2_klein_4b_sdnq,
+ flux2_klein_9b_sdnq,
+ flux2_klein_4b_gguf_q4,
+ flux2_klein_4b_gguf_q8,
+ flux2_klein_9b_gguf_q4,
+ flux2_klein_9b_gguf_q8,
+ flux2_klein_qwen3_4b_encoder,
+ flux2_klein_qwen3_8b_encoder,
+ flux2_dev_comfy_mistral_bf16,
+ flux2_dev_comfy_mistral_fp4,
+ flux2_dev_comfy_mistral_fp8,
+ flux2_dev_cow_mistral_iq4_xs,
+ flux2_dev_cow_mistral_q4,
+ flux2_dev_cow_mistral_q8,
+ flux2_dev_diffusers,
+ flux2_dev_diffusers_nf4,
+ flux2_dev_gguf_q3_k_m,
+ flux2_dev_gguf_q4_k_m,
+ flux2_dev_gguf_q5_k_m,
+ flux2_dev_gguf_q6_k,
+ flux2_dev_gguf_q8_0,
+ cogview4,
+ qwen_image_vae,
+ qwen_vl_encoder_fp8,
+ qwen_vl_encoder_diffusers,
+ qwen_image_edit,
+ qwen_image_edit_gguf_q2_k,
+ qwen_image_edit_gguf_q4_k_m,
+ qwen_image_edit_gguf_q6_k,
+ qwen_image_edit_gguf_q8_0,
+ qwen_image_edit_lightning_4step,
+ qwen_image_edit_lightning_8step,
+ qwen_image,
+ qwen_image_gguf_q2_k,
+ qwen_image_gguf_q4_k_m,
+ qwen_image_gguf_q6_k,
+ qwen_image_gguf_q8_0,
+ qwen_image_lightning_4step,
+ qwen_image_lightning_8step,
+ flux_krea,
+ flux_krea_quantized,
+ z_image_turbo,
+ z_image_turbo_quantized,
+ z_image_turbo_q8,
+ z_image_turbo_sdnq,
+ z_image_qwen3_encoder,
+ z_image_qwen3_encoder_quantized,
+ z_image_controlnet_union,
+ z_image_controlnet_tile,
+ ernie_image,
+ ernie_image_turbo,
+ krea2_turbo,
+ krea2_raw,
+ krea2_turbo_gguf_q4_k_m,
+ krea2_turbo_gguf_q8_0,
+ qwen3_vl_encoder_4b,
+ wan_22_t5_encoder,
+ wan_22_a14b_vae,
+ wan_22_5b_vae,
+ wan_22_t2v_a14b_diffusers,
+ wan_22_t2v_a14b_low_gguf_q4_k_m,
+ wan_22_t2v_a14b_gguf_q4_k_m,
+ wan_22_t2v_a14b_low_gguf_q8_0,
+ wan_22_t2v_a14b_gguf_q8_0,
+ wan_22_t2v_lightning_high,
+ wan_22_t2v_lightning_low,
+ wan_22_i2v_a14b_diffusers,
+ wan_22_i2v_a14b_low_gguf_q4_k_m,
+ wan_22_i2v_a14b_gguf_q4_k_m,
+ wan_22_i2v_a14b_low_gguf_q8_0,
+ wan_22_i2v_a14b_gguf_q8_0,
+ wan_22_i2v_lightning_high,
+ wan_22_i2v_lightning_low,
+ wan_22_ti2v_5b_diffusers,
+ wan_22_ti2v_5b_gguf_q4_k_m,
+ wan_22_ti2v_5b_gguf_q8_0,
+ minimax_h3_int8_transformer,
+ minimax_h3_ref2va_int8_transformer,
+ minimax_h3_int8_text_encoder,
+ minimax_h3_components,
+ minimax_h3_turbo_lora,
+ minimax_h3_lightx2v_turbo_lora,
- minimax_h3_ref2v_turbo_lora,
++ minimax_h3_lightx2v_ref2v_turbo_lora,
+ gemini_flash_image,
+ gemini_pro_image_preview,
+ gemini_3_1_flash_image_preview,
+ openai_gpt_image_2,
+ openai_gpt_image_1_5,
+ openai_gpt_image_1,
+ openai_gpt_image_1_mini,
+ openai_dall_e_3,
+ seedream_5_0,
+ seedream_5_0_lite,
+ seedream_4_5,
+ seedream_4_0,
+ alibabacloud_qwen_image_2_pro,
+ alibabacloud_qwen_image_2,
+ alibabacloud_qwen_image_max,
+ alibabacloud_wan26_t2i,
+ alibabacloud_qwen_image_edit_max,
+ anima_base,
+ anima_qwen3_encoder,
+ anima_vae,
+ anima_lllite_inpainting,
+ anima_lllite_sketch,
+ anima_lllite_depth_preview3,
+ anima_lllite_scribble_preview3,
+ anima_lllite_lineart_preview3,
+ anima_lllite_pose_preview3,
+ gemma2_2b_encoder,
+ pid_decoder_flux_2k,
+ pid_decoder_flux_2kto4k,
+ pid_decoder_flux2_2k,
+ pid_decoder_flux2_2kto4k,
+ pid_decoder_sd3_2k,
+ pid_decoder_sd3_2kto4k,
+ pid_decoder_sdxl_2kto4k,
+ pid_decoder_qwenimage_2kto4k,
+]
+
+sd1_bundle: list[StarterModel] = [
+ dreamshaper_8_sd1,
+ easy_neg_sd1,
+ ip_adapter_sd1,
+ ip_adapter_plus_sd1,
+ ip_adapter_plus_face_sd1,
+ canny_sd1,
+ inpaint_cnet_sd1,
+ mlsd_sd1,
+ depth_sd1,
+ normal_bae_sd1,
+ seg_sd1,
+ lineart_sd1,
+ lineart_anime_sd1,
+ openpose_sd1,
+ scribble_sd1,
+ softedge_sd1,
+ shuffle_sd1,
+ tile_sd1,
+ swinir,
+]
+
+sdxl_bundle: list[StarterModel] = [
+ juggernaut_sdxl,
+ sdxl_fp16_vae_fix,
+ ip_adapter_sdxl,
+ ip_adapter_plus_sdxl,
+ canny_sdxl,
+ depth_sdxl,
+ softedge_sdxl,
+ openpose_sdxl,
+ scribble_sdxl,
+ tile_sdxl,
+ swinir,
+]
+
+flux_bundle: list[StarterModel] = [
+ flux_schnell_quantized,
+ flux_dev_quantized,
+ flux_vae,
+ t5_8b_quantized_encoder,
+ clip_l_encoder,
+ union_cnet_flux,
+ ip_adapter_flux,
+ flux_canny_control_lora,
+ flux_depth_control_lora,
+ flux_redux,
+ flux_fill,
+ flux_kontext_quantized,
+ flux_krea_quantized,
+]
+
+zimage_bundle: list[StarterModel] = [
+ z_image_turbo_quantized,
+ z_image_qwen3_encoder_quantized,
+ z_image_controlnet_union,
+ z_image_controlnet_tile,
+ flux_vae,
+]
+
+flux2_klein_bundle: list[StarterModel] = [
+ flux2_klein_4b_gguf_q4,
+ flux2_vae,
+ flux2_klein_qwen3_4b_encoder,
+]
+
+# Turbo only: both checkpoints are 8B and the full pipeline is a large download, so the bundle
+# ships the fast default. The undistilled `ernie_image` is still installable individually.
+ernie_image_bundle: list[StarterModel] = [
+ ernie_image_turbo,
+]
+
+qwen_image_bundle: list[StarterModel] = [
+ qwen_image_vae,
+ qwen_vl_encoder_fp8,
+ qwen_image_edit,
+ qwen_image_edit_gguf_q4_k_m,
+ qwen_image_edit_gguf_q8_0,
+ qwen_image_edit_lightning_4step,
+ qwen_image_edit_lightning_8step,
+ qwen_image,
+ qwen_image_gguf_q4_k_m,
+ qwen_image_gguf_q8_0,
+ qwen_image_lightning_4step,
+ qwen_image_lightning_8step,
+]
+
+anima_bundle: list[StarterModel] = [
+ anima_base,
+ anima_qwen3_encoder,
+ anima_vae,
+ anima_lllite_inpainting,
+ anima_lllite_sketch,
+]
+
+krea2_bundle: list[StarterModel] = [
+ qwen_image_vae,
+ qwen3_vl_encoder_4b,
+ krea2_turbo,
+ krea2_raw,
+ krea2_turbo_gguf_q4_k_m,
+ krea2_turbo_gguf_q8_0,
+]
+
+# Wan 2.2 starter bundles. Split into T2V and I2V so users only pay for the
+# capability they need: a 12 GB card can install just the T2V bundle and have
+# both text-to-video (T2V-A14B) and a low-VRAM image-to-video option (via
+# TI2V-5B, which handles both modes in one ~3.4 GB model). The I2V bundle adds
+# the heavier I2V-A14B path for users with more headroom. Q8 variants and full
+# Diffusers builds stay available as a-la-carte starters.
+wan_t2v_bundle: list[StarterModel] = [
+ wan_22_t5_encoder,
+ wan_22_a14b_vae,
+ wan_22_5b_vae,
+ wan_22_ti2v_5b_gguf_q4_k_m,
+ wan_22_t2v_a14b_gguf_q4_k_m,
+ wan_22_t2v_a14b_low_gguf_q4_k_m,
+ wan_22_t2v_lightning_high,
+ wan_22_t2v_lightning_low,
+]
+
+wan_i2v_bundle: list[StarterModel] = [
+ wan_22_t5_encoder,
+ wan_22_a14b_vae,
+ wan_22_i2v_a14b_gguf_q4_k_m,
+ wan_22_i2v_a14b_low_gguf_q4_k_m,
+ wan_22_i2v_lightning_high,
+ wan_22_i2v_lightning_low,
+]
+
+# nf4 is the recommended 24GB CUDA path; the fp8 build is offered separately for non-CUDA / more VRAM.
+ideogram_bundle: list[StarterModel] = [
+ ideogram_4_nf4,
+]
+
+# The working set for MiniMax H3 video+audio generation (~85 GB): shared components from
+# the official repo plus Comfy-Org's int8 single-file FL2VA and Ref2VA transformers and the
+# text encoder, and the three turbo (step-distillation) LoRAs for fast low-step rendering.
+# See the license note in the MiniMax H3 region above.
+minimax_h3_bundle: list[StarterModel] = [
+ minimax_h3_components,
+ minimax_h3_int8_text_encoder,
+ minimax_h3_int8_transformer,
+ minimax_h3_ref2va_int8_transformer,
+ minimax_h3_turbo_lora,
+ minimax_h3_lightx2v_turbo_lora,
- minimax_h3_ref2v_turbo_lora,
++ minimax_h3_lightx2v_ref2v_turbo_lora,
+]
+
+STARTER_BUNDLES: dict[str, StarterModelBundle] = {
+ BaseModelType.StableDiffusion1: StarterModelBundle(name="Stable Diffusion 1.5", models=sd1_bundle),
+ BaseModelType.StableDiffusionXL: StarterModelBundle(name="SDXL", models=sdxl_bundle),
+ BaseModelType.Flux: StarterModelBundle(name="FLUX.1 dev", models=flux_bundle),
+ BaseModelType.Flux2: StarterModelBundle(name="FLUX.2 Klein", models=flux2_klein_bundle),
+ BaseModelType.ZImage: StarterModelBundle(name="Z-Image Turbo", models=zimage_bundle),
+ BaseModelType.ErnieImage: StarterModelBundle(name="ERNIE-Image", models=ernie_image_bundle),
+ BaseModelType.QwenImage: StarterModelBundle(name="Qwen Image", models=qwen_image_bundle),
+ BaseModelType.Anima: StarterModelBundle(name="Anima", models=anima_bundle),
+ BaseModelType.Krea2: StarterModelBundle(name="Krea-2", models=krea2_bundle),
+ "wan_t2v": StarterModelBundle(name="Wan 2.2 Text-to-Video", models=wan_t2v_bundle),
+ "wan_i2v": StarterModelBundle(name="Wan 2.2 Image-to-Video", models=wan_i2v_bundle),
+ BaseModelType.MiniMaxH3: StarterModelBundle(name="MiniMax H3", models=minimax_h3_bundle),
+ BaseModelType.Ideogram4: StarterModelBundle(name="Ideogram 4", models=ideogram_bundle),
+}
+
+assert len(STARTER_MODELS) == len({m.source for m in STARTER_MODELS}), "Duplicate starter models"
diff --cc invokeai/backend/model_manager/starter_models/minimax_h3.py
index aae46425b4,0000000000..15992f8b20
mode 100644,000000..100644
--- a/invokeai/backend/model_manager/starter_models/minimax_h3.py
+++ b/invokeai/backend/model_manager/starter_models/minimax_h3.py
@@@ -1,96 -1,0 +1,103 @@@
+"""MiniMax H3 starter models."""
+
+from invokeai.backend.model_manager.starter_models.types import StarterModel
+from invokeai.backend.model_manager.taxonomy import (
+ BaseModelType,
+ ModelFormat,
+ ModelType,
+)
+
+minimax_h3_components = StarterModel(
+ name="MiniMax H3 Components",
+ base=BaseModelType.MiniMaxH3,
+ source="MiniMaxAI/MiniMax-H3::modular_model_index.json+transformer/config.json+tokenizer+processor+vae+audio_vae",
+ description="MiniMax H3 shared components: tokenizer, processor and video/audio VAEs, without "
+ "transformer or text-encoder weights (~11 GB). Pair with the MiniMax H3 single-file transformer "
+ "and text encoder. NOTE: This model is distributed under a restrictive license that forbids its "
+ "use in certain territories. Please see https://huggingface.co/MiniMaxAI/MiniMax-H3 for details.",
+ type=ModelType.Main,
+ format=ModelFormat.Diffusers,
+)
+
+minimax_h3_int8_text_encoder = StarterModel(
+ name="MiniMax H3 Text Encoder (int8)",
+ base=BaseModelType.MiniMaxH3,
+ source="Comfy-Org/MiniMax-H3::text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors",
+ description="Truncated Qwen3-VL-32B conditioning encoder for MiniMax H3, int8 quantized (~27 GB). "
+ "Select it in the MiniMax H3 Model Loader's text encoder field. NOTE: This model is distributed "
+ "under a restrictive license that forbids its use in certain territories. Please see "
+ "https://huggingface.co/MiniMaxAI/MiniMax-H3 for details.",
+ type=ModelType.Qwen3VLEncoder,
+ format=ModelFormat.Checkpoint,
+)
+
+minimax_h3_int8_transformer = StarterModel(
+ name="MiniMax H3 FL2VA Transformer (int8, pruned)",
+ base=BaseModelType.MiniMaxH3,
+ source="Comfy-Org/MiniMax-H3::diffusion_models/minimax_h3_fl2va_pruned_int8_convrot.safetensors",
+ description="MiniMax H3 video+audio generation. AdaLN-pruned int8 single-file transformer (~21 GB); "
+ "select it in the MiniMax H3 Model Loader's transformer field. Total size with dependencies: ~59 GB. "
+ "NOTE: This model is distributed under a restrictive license that forbids its use in certain "
+ "territories. Please see https://huggingface.co/MiniMaxAI/MiniMax-H3 for details.",
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ dependencies=[minimax_h3_components, minimax_h3_int8_text_encoder],
+)
+
+minimax_h3_ref2va_int8_transformer = StarterModel(
+ name="MiniMax H3 Ref2VA Transformer (int8, pruned)",
+ base=BaseModelType.MiniMaxH3,
+ source="Comfy-Org/MiniMax-H3::diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ description="MiniMax H3 reference-conditioned video+audio generation: up to 3 video and 9 image "
+ "references. AdaLN-pruned int8 single-file transformer (~21 GB); select it in the MiniMax H3 "
+ "Model Loader's transformer field. Total size with dependencies: ~59 GB. NOTE: This model is "
+ "distributed under a restrictive license that forbids its use in certain territories. Please "
+ "see https://huggingface.co/MiniMaxAI/MiniMax-H3 for details.",
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ dependencies=[minimax_h3_components, minimax_h3_int8_text_encoder],
+)
+
+minimax_h3_turbo_lora = StarterModel(
+ name="MiniMax H3 Turbo LoRA",
+ base=BaseModelType.MiniMaxH3,
+ source="larryvrh/MiniMax-H3-Turbo-Lora::minimax_h3_turbo_v4_step600_ema.safetensors",
+ description="Step-distillation LoRA for MiniMax H3 (Apache 2.0): renders video+audio in 4-8 "
+ "denoising steps instead of ~50. Apply at strength 1.0 and lower Steps to 6-8. Works with the "
+ "full and the pruned int8 transformers.",
+ type=ModelType.LoRA,
+ format=ModelFormat.LyCORIS,
+)
+
+# Only the *_comfyui_* files in the LightX2V repo are installable: they carry the native
+# fused-key layout (diffusion_model.blocks.N.attn.qkv_proj) that the H3 LoRA probe accepts.
+# The non-comfyui files use already-diffusers keys (transformer_blocks.N.attn.to_q with
+# PEFT ".default" adapter names), which the probe rejects as a different architecture.
+minimax_h3_lightx2v_turbo_lora = StarterModel(
+ name="MiniMax H3 LightX2V Turbo LoRA",
+ base=BaseModelType.MiniMaxH3,
+ source="lightx2v/Minimax-h3-Turbo::minimax_h3_fl2v_turbo_8step_v1.0_comfyui_bf16.safetensors",
+ description="LightX2V step-distillation LoRA for MiniMax H3 (Apache 2.0), 8-step v1.0 (~2 GB): "
+ "renders video+audio in ~8 denoising steps instead of ~50. Apply at strength 1.0 and lower "
+ "Steps to 8. Works with the full and the pruned int8 transformers.",
+ type=ModelType.LoRA,
+ format=ModelFormat.LyCORIS,
+)
+
- minimax_h3_ref2v_turbo_lora = StarterModel(
- name="MiniMax H3 Ref2V Turbo LoRA",
++# The LightX2V 8-step v1.0 (768p) Ref2V distillation replaces the earlier 4-step v0.1 repack
++# (Comfy-Org/MiniMax-H3::loras/minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors):
++# v0.1 carries a strong rightward camera-pan bias whenever a VIDEO reference is conditioned
++# on, which neither the undistilled 30-step base nor this v1.0 release shows (verified
++# 2026-09-07). Same fused-key comfyui layout as the FL2VA LightX2V file above.
++minimax_h3_lightx2v_ref2v_turbo_lora = StarterModel(
++ name="MiniMax H3 LightX2V Ref2V Turbo LoRA",
+ base=BaseModelType.MiniMaxH3,
- source="Comfy-Org/MiniMax-H3::loras/minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors",
- description="Step-distillation LoRA for the MiniMax H3 Ref2VA transformer (~2 GB): renders "
- "reference-conditioned video+audio in ~4 denoising steps instead of ~50. Apply at strength 1.0 "
- "and lower Steps to 4. Trained against the Ref2VA transformer; not intended for FL2VA.",
++ source="lightx2v/Minimax-h3-Turbo::minimax_h3_ref2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
++ description="LightX2V step-distillation LoRA for the MiniMax H3 Ref2VA transformer (Apache 2.0), "
++ "8-step v1.0 768p (~2 GB): renders reference-conditioned video+audio in ~8 denoising steps "
++ "instead of ~50. Apply at strength 1.0 and lower Steps to 8. Trained against the Ref2VA "
++ "transformer; not intended for FL2VA. Supersedes the 4-step v0.1 Ref2V Turbo repack, which "
++ "pans the camera rightward whenever a video reference is used.",
+ type=ModelType.LoRA,
+ format=ModelFormat.LyCORIS,
+)
diff --cc invokeai/frontend/web/openapi.json
index a16ec7dc20,6e31935c11..2fa89f5b6d
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@@ -542,11 -514,76 +542,82 @@@
]
}
},
+ "/api/v1/utilities/fonts": {
+ "get": {
- "tags": ["utilities"],
++ "tags": [
++ "utilities"
++ ],
+ "summary": "List User Fonts",
+ "operationId": "list_user_fonts",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserFontsResponse"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/utilities/fonts/{font_path}": {
+ "get": {
- "tags": ["utilities"],
++ "tags": [
++ "utilities"
++ ],
+ "summary": "Get User Font File",
+ "operationId": "get_user_font_file",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "font_path",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "title": "Font Path"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v1/utilities/expand-prompt": {
"post": {
- "tags": ["utilities"],
+ "tags": [
+ "utilities"
+ ],
"summary": "Expand Prompt",
"description": "Expand a brief prompt into a detailed image generation prompt using a text LLM.",
"operationId": "expand_prompt",
@@@ -636,42 -671,423 +707,472 @@@
]
}
},
+ "/api/v1/fonts": {
+ "get": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "List Fonts",
+ "operationId": "list_fonts",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "offset",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "minimum": 0,
+ "default": 0,
+ "title": "Offset"
+ }
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 1000,
+ "minimum": 0,
+ "default": 100,
+ "title": "Limit"
+ }
+ },
+ {
+ "name": "search",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 200
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Search"
+ }
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/FontScope",
+ "default": "all"
+ }
+ },
+ {
+ "name": "content_hash",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "pattern": "^[a-f0-9]{64}$"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Content Hash"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FontListResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "Upload Font",
+ "operationId": "upload_font",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "multipart/form-data": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_upload_font"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FontUploadResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/fonts/validate": {
+ "post": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "Validate Font",
+ "operationId": "validate_font",
+ "requestBody": {
+ "content": {
+ "multipart/form-data": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_validate_font"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FontValidationResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/fonts/rescan": {
+ "post": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "Rescan Fonts",
+ "operationId": "rescan_fonts",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FontRescanResponse"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/fonts/{font_id}/file": {
+ "get": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "Get Font File",
+ "operationId": "get_font_file",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "font_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "title": "Font Id"
+ }
+ },
+ {
+ "name": "expected_hash",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "pattern": "^[a-f0-9]{64}$"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Expected Hash"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/fonts/{font_id}": {
+ "get": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "Get Font",
+ "operationId": "get_font",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "font_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "title": "Font Id"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FontDTO"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "Delete Font",
+ "operationId": "delete_font",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "font_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "title": "Font Id"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "Successful Response"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/fonts/{font_id}/instance": {
+ "post": {
- "tags": ["fonts"],
++ "tags": [
++ "fonts"
++ ],
+ "summary": "Create Font Instance",
+ "operationId": "create_font_instance",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "font_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "title": "Font Id"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/FontInstanceRequest"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/v2/models/capabilities": {
+ "get": {
+ "tags": [
+ "model_manager"
+ ],
+ "summary": "List Architecture Capabilities",
+ "description": "What each model architecture can generate, and which generation features it supports.\n\nA static table, the same for every install and every user, derived from what the architectures\ndeclare under `invokeai/backend/architectures/defs/`. Fetch it once and join it against model\nrecords locally: look up `(base, variant)`, fall back to `(base, null)`.\n\nDeliberately not a field on the model records themselves \u2014 it is the same for every model of an\narchitecture, and putting it there would add these fields to all 115 config schemas.\n\nAuthenticated like every other route here even though the response holds nothing user-specific:\nthe allowlist for public routes is short and deliberate, and this is not a reason to lengthen it.\n\nDeclared `def`, not `async def`: it awaits nothing, so FastAPI runs it in a threadpool instead of\non the event loop. See docs/contributing/blocking-work-in-api-routes.",
+ "operationId": "list_architecture_capabilities",
+ "responses": {
+ "200": {
+ "description": "What each model architecture supports",
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": {
+ "$ref": "#/components/schemas/ArchitectureCapabilities"
+ },
+ "type": "array",
+ "title": "Response List Architecture Capabilities"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
"/api/v2/models/": {
"get": {
- "tags": ["model_manager"],
+ "tags": [
+ "model_manager"
+ ],
"summary": "List Model Records",
"description": "Get a list of models.",
"operationId": "list_model_records",
@@@ -7068,6 -7334,37 +7559,39 @@@
}
}
}
+ },
+ "requestBody": {
+ "required": true,
+ "content": {
+ "multipart/form-data": {
+ "schema": {
+ "properties": {
+ "file": {
+ "type": "string",
+ "contentMediaType": "application/octet-stream",
+ "title": "File"
+ },
+ "metadata": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Metadata",
+ "description": "The metadata to associate with the video, must be a stringified JSON dict"
+ }
+ },
+ "type": "object",
- "required": ["file"],
++ "required": [
++ "file"
++ ],
+ "title": "Body_upload_video"
+ }
+ }
+ }
}
}
},
@@@ -19487,11 -19017,27 +20011,31 @@@
}
},
"type": "object",
- "required": ["is_public"],
+ "required": [
+ "is_public"
+ ],
"title": "Body_update_workflow_is_public"
},
+ "Body_upload_font": {
+ "properties": {
+ "file": {
+ "type": "string",
+ "contentMediaType": "application/octet-stream",
+ "title": "File",
+ "description": "The font file to upload"
+ },
+ "scope": {
+ "type": "string",
+ "title": "Scope",
+ "default": "private"
+ }
+ },
+ "type": "object",
- "required": ["file"],
++ "required": [
++ "file"
++ ],
+ "title": "Body_upload_font"
+ },
"Body_upload_image": {
"properties": {
"file": {
@@@ -19528,12 -19072,10 +20072,12 @@@
}
},
"type": "object",
- "required": ["file"],
+ "required": [
+ "file"
+ ],
"title": "Body_upload_image"
},
- "Body_upload_video": {
+ "Body_validate_font": {
"properties": {
"file": {
"type": "string",
@@@ -19554,10 -19085,8 +20087,10 @@@
}
},
"type": "object",
- "required": ["file"],
+ "required": [
+ "file"
+ ],
- "title": "Body_upload_video"
+ "title": "Body_validate_font"
},
"BooleanCollectionInvocation": {
"category": "primitives",
@@@ -38668,6 -36850,277 +39201,310 @@@
"title": "FluxVariantType",
"description": "FLUX.1 model variants."
},
+ "FontAxisDTO": {
+ "properties": {
+ "tag": {
+ "type": "string",
+ "title": "Tag"
+ },
+ "label": {
+ "type": "string",
+ "title": "Label"
+ },
+ "minimum": {
+ "type": "number",
+ "title": "Minimum"
+ },
+ "default": {
+ "type": "number",
+ "title": "Default"
+ },
+ "maximum": {
+ "type": "number",
+ "title": "Maximum"
+ },
+ "hidden": {
+ "type": "boolean",
+ "title": "Hidden"
+ }
+ },
+ "type": "object",
- "required": ["tag", "label", "minimum", "default", "maximum", "hidden"],
++ "required": [
++ "tag",
++ "label",
++ "minimum",
++ "default",
++ "maximum",
++ "hidden"
++ ],
+ "title": "FontAxisDTO"
+ },
+ "FontDTO": {
+ "properties": {
+ "id": {
+ "type": "string",
+ "title": "Id"
+ },
+ "family": {
+ "type": "string",
+ "title": "Family"
+ },
+ "label": {
+ "type": "string",
+ "title": "Label"
+ },
+ "style": {
+ "type": "string",
+ "title": "Style"
+ },
+ "weight": {
+ "type": "integer",
+ "title": "Weight"
+ },
+ "content_hash": {
+ "type": "string",
+ "title": "Content Hash"
+ },
+ "scope": {
+ "type": "string",
- "enum": ["private", "shared"],
++ "enum": [
++ "private",
++ "shared"
++ ],
+ "title": "Scope"
+ },
+ "source": {
+ "type": "string",
- "enum": ["uploaded", "directory"],
++ "enum": [
++ "uploaded",
++ "directory"
++ ],
+ "title": "Source"
+ },
+ "filename": {
+ "type": "string",
+ "title": "Filename"
+ },
+ "byte_size": {
+ "type": "integer",
+ "title": "Byte Size"
+ },
+ "url": {
+ "type": "string",
+ "title": "Url"
+ },
+ "axes": {
+ "items": {
+ "$ref": "#/components/schemas/FontAxisDTO"
+ },
+ "type": "array",
+ "title": "Axes"
+ },
+ "instances": {
+ "items": {
+ "$ref": "#/components/schemas/FontInstanceDTO"
+ },
+ "type": "array",
+ "title": "Instances"
+ }
+ },
+ "type": "object",
+ "required": [
+ "id",
+ "family",
+ "label",
+ "style",
+ "weight",
+ "content_hash",
+ "scope",
+ "source",
+ "filename",
+ "byte_size",
+ "url",
+ "axes",
+ "instances"
+ ],
+ "title": "FontDTO"
+ },
+ "FontInstanceDTO": {
+ "properties": {
+ "name": {
+ "type": "string",
+ "title": "Name"
+ },
+ "coordinates": {
+ "additionalProperties": {
+ "type": "number"
+ },
+ "type": "object",
+ "title": "Coordinates"
+ }
+ },
+ "type": "object",
- "required": ["name", "coordinates"],
++ "required": [
++ "name",
++ "coordinates"
++ ],
+ "title": "FontInstanceDTO"
+ },
+ "FontInstanceRequest": {
+ "properties": {
+ "content_hash": {
+ "type": "string",
+ "maxLength": 64,
+ "minLength": 64,
+ "pattern": "^[a-f0-9]{64}$",
+ "title": "Content Hash"
+ },
+ "coordinates": {
+ "additionalProperties": {
+ "type": "number"
+ },
+ "type": "object",
+ "title": "Coordinates"
+ }
+ },
+ "type": "object",
- "required": ["content_hash"],
++ "required": [
++ "content_hash"
++ ],
+ "title": "FontInstanceRequest"
+ },
+ "FontListResponse": {
+ "properties": {
+ "offset": {
+ "type": "integer",
+ "title": "Offset"
+ },
+ "limit": {
+ "type": "integer",
+ "title": "Limit"
+ },
+ "total": {
+ "type": "integer",
+ "title": "Total"
+ },
+ "items": {
+ "items": {
+ "$ref": "#/components/schemas/FontDTO"
+ },
+ "type": "array",
+ "title": "Items"
+ }
+ },
+ "type": "object",
- "required": ["offset", "limit", "total", "items"],
++ "required": [
++ "offset",
++ "limit",
++ "total",
++ "items"
++ ],
+ "title": "FontListResponse"
+ },
+ "FontRescanResponse": {
+ "properties": {
+ "indexed": {
+ "type": "integer",
+ "title": "Indexed"
+ },
+ "revision": {
+ "type": "integer",
+ "title": "Revision"
+ }
+ },
+ "type": "object",
- "required": ["indexed", "revision"],
++ "required": [
++ "indexed",
++ "revision"
++ ],
+ "title": "FontRescanResponse"
+ },
+ "FontScope": {
+ "type": "string",
- "enum": ["private", "shared", "all"],
++ "enum": [
++ "private",
++ "shared",
++ "all"
++ ],
+ "title": "FontScope",
+ "description": "The account scope of an uploaded font."
+ },
+ "FontUploadResponse": {
+ "properties": {
+ "font": {
+ "$ref": "#/components/schemas/FontDTO"
+ },
+ "created": {
+ "type": "boolean",
+ "title": "Created"
+ }
+ },
+ "type": "object",
- "required": ["font", "created"],
++ "required": [
++ "font",
++ "created"
++ ],
+ "title": "FontUploadResponse"
+ },
+ "FontValidationResponse": {
+ "properties": {
+ "filename": {
+ "type": "string",
+ "title": "Filename"
+ },
+ "family": {
+ "type": "string",
+ "title": "Family"
+ },
+ "label": {
+ "type": "string",
+ "title": "Label"
+ },
+ "style": {
+ "type": "string",
+ "title": "Style"
+ },
+ "weight": {
+ "type": "integer",
+ "title": "Weight"
+ },
+ "content_hash": {
+ "type": "string",
+ "title": "Content Hash"
+ },
+ "byte_size": {
+ "type": "integer",
+ "title": "Byte Size"
+ },
+ "axes": {
+ "items": {
+ "$ref": "#/components/schemas/FontAxisDTO"
+ },
+ "type": "array",
+ "title": "Axes"
+ },
+ "instances": {
+ "items": {
+ "$ref": "#/components/schemas/FontInstanceDTO"
+ },
+ "type": "array",
+ "title": "Instances"
+ }
+ },
+ "type": "object",
+ "required": [
+ "filename",
+ "family",
+ "label",
+ "style",
+ "weight",
+ "content_hash",
+ "byte_size",
+ "axes",
+ "instances"
+ ],
+ "title": "FontValidationResponse"
+ },
"ForInvocation": {
"class": "invocation",
"classification": "stable",
@@@ -56237,14 -53974,39 +57074,44 @@@
"description": "Path to directory for outputs.",
"default": "outputs"
},
+ "fonts_dir": {
+ "type": "string",
+ "format": "path",
+ "title": "Fonts Dir",
+ "description": "Path to directory for custom fonts.",
+ "default": "fonts"
+ },
+ "fonts_storage_dir": {
+ "type": "string",
+ "format": "path",
+ "title": "Fonts Storage Dir",
+ "description": "Path to application-managed uploaded fonts.",
+ "default": "fonts-uploaded"
+ },
+ "max_font_upload_bytes": {
+ "type": "integer",
+ "maximum": 134217728.0,
+ "exclusiveMinimum": 0.0,
+ "title": "Max Font Upload Bytes",
+ "description": "Maximum size of one uploaded custom font in bytes.",
+ "default": 33554432
+ },
+ "max_font_library_bytes": {
+ "type": "integer",
+ "maximum": 17179869184.0,
+ "exclusiveMinimum": 0.0,
+ "title": "Max Font Library Bytes",
+ "description": "Maximum total size of uploaded custom fonts in bytes per account or shared library.",
+ "default": 1073741824
+ },
"image_subfolder_strategy": {
"type": "string",
- "enum": ["flat", "date", "type", "hash"],
+ "enum": [
+ "flat",
+ "date",
+ "type",
+ "hash"
+ ],
"title": "Image Subfolder Strategy",
"description": "Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.",
"default": "flat"
@@@ -99772,6 -95368,77 +100639,91 @@@
"title": "UserDTO",
"description": "User data transfer object."
},
+ "UserFont": {
+ "properties": {
+ "id": {
+ "type": "string",
+ "title": "Id"
+ },
+ "family": {
+ "type": "string",
+ "title": "Family"
+ },
+ "label": {
+ "type": "string",
+ "title": "Label"
+ },
+ "path": {
+ "type": "string",
+ "title": "Path"
+ },
+ "url": {
+ "type": "string",
+ "title": "Url"
+ },
+ "faces": {
+ "items": {
+ "$ref": "#/components/schemas/UserFontFace"
+ },
+ "type": "array",
+ "title": "Faces"
+ }
+ },
+ "type": "object",
- "required": ["id", "family", "label", "path", "url", "faces"],
++ "required": [
++ "id",
++ "family",
++ "label",
++ "path",
++ "url",
++ "faces"
++ ],
+ "title": "UserFont"
+ },
+ "UserFontFace": {
+ "properties": {
+ "path": {
+ "type": "string",
+ "title": "Path"
+ },
+ "url": {
+ "type": "string",
+ "title": "Url"
+ },
+ "weight": {
+ "type": "integer",
+ "title": "Weight"
+ },
+ "style": {
+ "type": "string",
+ "title": "Style"
+ }
+ },
+ "type": "object",
- "required": ["path", "url", "weight", "style"],
++ "required": [
++ "path",
++ "url",
++ "weight",
++ "style"
++ ],
+ "title": "UserFontFace"
+ },
+ "UserFontsResponse": {
+ "properties": {
+ "fonts": {
+ "items": {
+ "$ref": "#/components/schemas/UserFont"
+ },
+ "type": "array",
+ "title": "Fonts"
+ }
+ },
+ "type": "object",
- "required": ["fonts"],
++ "required": [
++ "fonts"
++ ],
+ "title": "UserFontsResponse"
+ },
"UserProfileUpdateRequest": {
"properties": {
"display_name": {
diff --cc invokeai/frontend/web/src/services/api/schema.ts
index 211ca87a88,74cbd59c8b..056c78404d
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@@ -396,39 -430,110 +430,143 @@@ export type paths =
patch?: never;
trace?: never;
};
+ "/api/v1/fonts": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /** List Fonts */
+ get: operations["list_fonts"];
+ put?: never;
+ /** Upload Font */
+ post: operations["upload_font"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/fonts/validate": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Validate Font */
+ post: operations["validate_font"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/fonts/rescan": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Rescan Fonts */
+ post: operations["rescan_fonts"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/fonts/{font_id}/file": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /** Get Font File */
+ get: operations["get_font_file"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/fonts/{font_id}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /** Get Font */
+ get: operations["get_font"];
+ put?: never;
+ post?: never;
+ /** Delete Font */
+ delete: operations["delete_font"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/fonts/{font_id}/instance": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Create Font Instance */
+ post: operations["create_font_instance"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v2/models/capabilities": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * List Architecture Capabilities
+ * @description What each model architecture can generate, and which generation features it supports.
+ *
+ * A static table, the same for every install and every user, derived from what the architectures
+ * declare under `invokeai/backend/architectures/defs/`. Fetch it once and join it against model
+ * records locally: look up `(base, variant)`, fall back to `(base, null)`.
+ *
+ * Deliberately not a field on the model records themselves — it is the same for every model of an
+ * architecture, and putting it there would add these fields to all 115 config schemas.
+ *
+ * Authenticated like every other route here even though the response holds nothing user-specific:
+ * the allowlist for public routes is short and deliberate, and this is not a reason to lengthen it.
+ *
+ * Declared `def`, not `async def`: it awaits nothing, so FastAPI runs it in a threadpool instead of
+ * on the event loop. See docs/contributing/blocking-work-in-api-routes.
+ */
+ get: operations["list_architecture_capabilities"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v2/models/": {
parameters: {
query?: never;
@@@ -46869,26 -47082,255 +47245,275 @@@ export interface operations
};
};
};
+ list_fonts: {
+ parameters: {
+ query?: {
+ offset?: number;
+ limit?: number;
+ search?: string | null;
+ scope?: components["schemas"]["FontScope"];
+ content_hash?: string | null;
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FontListResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ upload_font: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "multipart/form-data": components["schemas"]["Body_upload_font"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FontUploadResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ validate_font: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "multipart/form-data": components["schemas"]["Body_validate_font"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FontValidationResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ rescan_fonts: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FontRescanResponse"];
+ };
+ };
+ };
+ };
+ get_font_file: {
+ parameters: {
+ query?: {
+ expected_hash?: string | null;
+ };
+ header?: never;
+ path: {
+ font_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": unknown;
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ get_font: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ font_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FontDTO"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ delete_font: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ font_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 204: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ create_font_instance: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ font_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["FontInstanceRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": unknown;
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ list_architecture_capabilities: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description What each model architecture supports */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ArchitectureCapabilities"][];
+ };
+ };
+ };
+ };
list_model_records: {
parameters: {
query?: {
diff --cc tests/app/invocations/test_flux2_working_memory.py
index 0000000000,9cdbc695c2..4739ac51b6
mode 000000,100644..100644
--- a/tests/app/invocations/test_flux2_working_memory.py
+++ b/tests/app/invocations/test_flux2_working_memory.py
@@@ -1,0 -1,1224 +1,1224 @@@
+ """FLUX.2 working-memory estimates: the transformer denoise and both VAE directions.
+
+ The FLUX.2 path originally called `model_on_device()` with no `working_mem_bytes` anywhere, so the
+ model cache reserved only the small default `device_working_mem_gb` and filled the rest of the card
+ with the model. Reference images make that fatal rather than merely tight: their latents are
+ concatenated onto the image stream, so three 1024x1024 references quadruple the attended sequence of
+ a 1024x1024 generation. See https://github.com/invoke-ai/InvokeAI/issues/9500.
+
+ The `MEASURED_*` tables below are peak *reserved* memory measured on CUDA in bf16 (the conservative
+ quantity, including allocator overhead). Every estimate must stay an upper bound on them.
+ """
+
+ from unittest.mock import MagicMock, patch
+
+ import pytest
+ import torch
+ import torch.nn.functional as F
+ from diffusers.models.autoencoders.autoencoder_kl_flux2 import AutoencoderKLFlux2
+
-from invokeai.app.invocations.flux2_denoise import (
++from invokeai.app.invocations.flux2.flux2_denoise import (
+ FLUX2_ATTENTION_HEAD_DIM,
+ FLUX2_BYTES_PER_TOKEN_AT_REFERENCE_WIDTH,
+ FLUX2_MAX_HIDDEN_SIZE,
+ FLUX2_REFERENCE_HIDDEN_SIZE,
+ Flux2DenoiseInvocation,
+ )
-from invokeai.app.invocations.flux2_vae_decode import Flux2VaeDecodeInvocation
-from invokeai.app.invocations.flux2_vae_encode import Flux2VaeEncodeInvocation
++from invokeai.app.invocations.vae.flux2_vae_decode import Flux2VaeDecodeInvocation
++from invokeai.app.invocations.vae.flux2_vae_encode import Flux2VaeEncodeInvocation
+ from invokeai.backend.util.attention import (
+ SDPA_MATH_BYTES_PER_SCORE_ELEMENT,
+ _diffusers_attention_dispatch,
+ _torch_sdpa_materializes_score_matrix,
+ sdpa_score_matrix_bytes,
+ )
+ from invokeai.backend.util.vae_working_memory import (
+ _FLUX2_VAE_SCALING_CONSTANTS,
+ estimate_vae_working_memory_flux2,
+ )
+
+ MB = 1024**2
+ GB = 1024**3
+
+ # The estimator's default width, and the head count that follows from it. The suite's pinned
+ # `MEASURED_DENOISE` table was taken on Klein 9B, which is that default, so those rows are unmoved
+ # by the width scaling.
+ KLEIN_9B_HEADS = FLUX2_REFERENCE_HIDDEN_SIZE // FLUX2_ATTENTION_HEAD_DIM
+ PER_TOKEN = FLUX2_BYTES_PER_TOKEN_AT_REFERENCE_WIDTH
+
+
+ def _per_token(hidden):
+ """The estimator's per-token cost at a given width, as it computes it."""
+ return int(FLUX2_BYTES_PER_TOKEN_AT_REFERENCE_WIDTH * hidden / FLUX2_REFERENCE_HIDDEN_SIZE)
+
+
+ # The measured tables in this module were all taken on CUDA, where SDPA runs a fused kernel and no
+ # score matrix is materialized. torch reports its CPU flash kernel as eligible for every shape used
+ # here, so passing a CPU device reproduces that regime without needing a GPU on the test runner. The
+ # materializing regime gets its own class below.
+ FUSED = torch.device("cpu")
+
+
+ def _estimate(
+ image_seq_len,
+ ref_image_seq_len=0,
+ text_seq_len=512,
+ num_loras=0,
+ batch_size=1,
+ hidden_size=FLUX2_REFERENCE_HIDDEN_SIZE,
+ regional_bias=0,
+ has_regional_mask=False,
+ device=FUSED,
+ ):
+ return Flux2DenoiseInvocation._estimate_working_memory(
+ MagicMock(spec=Flux2DenoiseInvocation),
+ image_seq_len=image_seq_len,
+ ref_image_seq_len=ref_image_seq_len,
+ text_seq_len=text_seq_len,
+ num_loras=num_loras,
+ batch_size=batch_size,
+ hidden_size=hidden_size,
+ regional_attention_bias_bytes=regional_bias,
+ has_regional_attention_mask=has_regional_mask,
+ device=device,
+ )
+
+
+ class TestFlux2DenoiseWorkingMemoryEstimate:
+ # (image tokens, reference tokens, measured peak reserved MB) on the Klein 9B geometry.
+ # Token grids are pixels/16, so a 1024px square is 4096 tokens.
+ MEASURED_DENOISE = [
+ (1024, 0, 448), # 512px
+ (4096, 0, 1702), # 1024px
+ (4096, 4096, 3324), # 1024px + one 1024px reference
+ (4096, 8192, 4840), # + two references
+ (4096, 12288, 6538), # + three references (the tiled-refiner case from #9500)
+ (6889, 12288, 7528), # 1328px tile + three 1024px references
+ (6889, 20667, 10954), # 1328px tile + three 1328px references
+ (16384, 0, 6538), # 2048px, no references
+ ]
+
+ @pytest.mark.parametrize("image_seq_len, ref_image_seq_len, measured_mb", MEASURED_DENOISE)
+ def test_estimate_is_an_upper_bound_on_measured_peak(self, image_seq_len, ref_image_seq_len, measured_mb):
+ """The cache treats the estimate as the amount it must keep free, so under-estimating OOMs."""
+ assert _estimate(image_seq_len, ref_image_seq_len) >= measured_mb * MB
+
+ @pytest.mark.parametrize("image_seq_len, ref_image_seq_len, measured_mb", MEASURED_DENOISE)
+ def test_estimate_does_not_wildly_over_reserve(self, image_seq_len, ref_image_seq_len, measured_mb):
+ """Over-estimating is not free: the cache offloads the transformer to RAM to honor the
+ reservation, and a model running over PCIe is indistinguishable from a hang."""
+ assert _estimate(image_seq_len, ref_image_seq_len) <= measured_mb * MB + 2 * GB
+
+ def test_reference_image_tokens_are_counted(self):
+ """The regression this whole module exists for: reference tokens are attended like image
+ tokens and cost the same per token, so they must enter the estimate."""
+ without_refs = _estimate(image_seq_len=4096)
+ with_refs = _estimate(image_seq_len=4096, ref_image_seq_len=12288)
+ assert with_refs - without_refs == 12288 * PER_TOKEN
+
+ def test_estimate_is_linear_in_total_sequence(self):
+ """Attention runs through SDPA, so there is no O(seq^2) term to model -- image, reference and
+ text tokens are interchangeable at the same per-token cost."""
+ assert _estimate(image_seq_len=8192) == _estimate(image_seq_len=4096, ref_image_seq_len=4096)
+ assert _estimate(image_seq_len=4096, text_seq_len=1024) - _estimate(image_seq_len=4096, text_seq_len=512) == (
+ 512 * PER_TOKEN
+ )
+
+ def test_lora_margin_is_added_per_lora(self):
+ """Sidecar-patched LoRAs add an activation branch per patched layer."""
+ base = _estimate(image_seq_len=4096)
+ assert _estimate(image_seq_len=4096, num_loras=1) - base == int(0.5 * GB)
+ assert _estimate(image_seq_len=4096, num_loras=3) - base == int(1.5 * GB)
+
+ def test_regional_attention_bias_is_added(self):
+ base = _estimate(image_seq_len=4096)
+ assert _estimate(image_seq_len=4096, regional_bias=123 * MB) - base == 123 * MB
+
+
+ class TestTransformerWidthIsBudgeted:
+ """Per-token activation cost is linear in the transformer's hidden width, not only in the token
+ count. Measured slope between 4608 and 9216 tokens on CUDA/bf16, block count and everything else
+ held fixed, each point in a fresh process:
+
+ 3072 (Klein 4B) 0.2912 MB/tok 4096 (Klein 9B) 0.3859 6144 ([dev]) 0.5547
+
+ which is 0.755 / 1.000 / 1.438 of the Klein 9B slope against width ratios of 0.75 / 1.00 / 1.50.
+ Linear, and sub-linear at the top, so scaling the constant by width stays an upper bound.
+
+ The same holds on ROCm/gfx1201, measured independently: 0.3147 / 0.4067 / 0.5890, i.e. ratios of
+ 0.774 / 1.000 / 1.448. The absolute constant is per-build (which is why it is 0.42, not CUDA's
+ 0.386); the width ratio is architectural and is the same on both.
+
+ Calibrating on Klein 9B alone -- which this did -- silently under-reserved FLUX.2 [dev] by a
+ third, and [dev] reaches the denoise node as a first-class path with its own loader and starter
+ models. The head count follows the same width, so the score-matrix term gets the variant's real
+ count rather than the widest.
+ """
+
+ # (platform, hidden size, measured MB per token). Reproduce with
+ # `scripts/calibrate_flux2_working_memory.py --only denoise`.
+ MEASURED_WIDTH_SLOPE = [
+ ("cuda-4090", 3072, 0.2912),
+ ("cuda-4090", 4096, 0.3859),
+ ("cuda-4090", 6144, 0.5547),
+ ("rocm-gfx1201", 3072, 0.3147),
+ ("rocm-gfx1201", 4096, 0.4067),
+ ("rocm-gfx1201", 6144, 0.5890),
+ ]
+
+ def _slope_per_token(self, hidden):
+ short = _estimate(image_seq_len=4096, text_seq_len=512, hidden_size=hidden)
+ long = _estimate(image_seq_len=8704, text_seq_len=512, hidden_size=hidden)
+ return (long - short) / (9216 - 4608)
+
+ @pytest.mark.parametrize("platform, hidden, measured_mb", MEASURED_WIDTH_SLOPE)
+ def test_the_estimate_upper_bounds_the_measured_slope(self, platform, hidden, measured_mb):
+ """The constant has to bound the worst build measured, not the one it was written on. It was
+ 0.4, which is under the 0.4067 gfx1201 costs at the reference width; it is 0.42. The upper
+ guard keeps that from drifting into over-reservation, since this is the dominant term."""
+ slope = self._slope_per_token(hidden)
+ assert slope >= measured_mb * MB
+ assert slope <= 1.25 * measured_mb * MB
+
+ def test_the_slope_is_linear_in_width(self):
+ klein_9b = self._slope_per_token(4096)
+ assert self._slope_per_token(3072) == pytest.approx(0.75 * klein_9b, rel=0.01)
+ assert self._slope_per_token(6144) == pytest.approx(1.50 * klein_9b, rel=0.01)
+
+ @pytest.mark.parametrize("hidden, heads", [(3072, 24), (4096, 32), (6144, 48)])
+ def test_the_score_matrix_uses_the_variants_real_head_count(self, hidden, heads):
+ """It used to charge 48 heads for every variant. On a materializing backend that is a third
+ too much on Klein 9B and double on Klein 4B -- and on MPS, where the probe always takes the
+ materializing branch, that term lands on every single estimate."""
+ seq_len = 4096 + 512
+ fused = _estimate(image_seq_len=4096, has_regional_mask=True, hidden_size=hidden)
+ with _materializing():
+ materializing = _estimate(
+ image_seq_len=4096, has_regional_mask=True, hidden_size=hidden, device=MATERIALIZING
+ )
+ assert materializing - fused == heads * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+
+
+ class TestFlux2DenoiseBatchIsBudgeted:
+ """A batch of B is B independent sequences, so it enters the linear term exactly as extra
+ sequence does. Measured on the Klein geometry (48 heads x 128, mlp 3.0) with a reduced block
+ count -- the constant is block-count independent -- peak reserved, each point in a fresh process:
+
+ B=1, 4608 tokens -> 2570MB B=2, 4608 each (9216 total) -> 5126MB
+ B=1, 9728 tokens -> 5584MB B=2, 9728 each (19456 total) -> 11120MB
+ B=1, 14336 tokens -> 8284MB B=3, 4608 each (13824 total) -> 7656MB
+
+ Per *total* token that is 0.554-0.578MB across every row: batch and sequence are interchangeable.
+ (The absolute figure is not comparable to the Klein table elsewhere in this module -- a 3-block
+ stand-in amortizes per-forward overhead differently. Only the equivalence is being tested.)
+
+ Batched latents reach this node through the API and custom graphs, not the stock UI.
+ """
+
+ def test_batch_and_sequence_are_interchangeable(self):
+ """Two samples of 4608 tokens must cost what one sample of 9216 costs -- the measurement
+ above says 5126MB against 5584MB, equal to within the allocator's noise."""
+ assert _estimate(image_seq_len=4096, text_seq_len=512, batch_size=2) == _estimate(
+ image_seq_len=8704, text_seq_len=512, batch_size=1
+ )
+
+ @pytest.mark.parametrize("batch", [2, 3, 4])
+ def test_each_extra_sample_adds_exactly_its_own_tokens(self, batch):
+ single = _estimate(image_seq_len=4096)
+ assert _estimate(image_seq_len=4096, batch_size=batch) - single == (batch - 1) * (4096 + 512) * PER_TOKEN
+
+ def test_reference_tokens_scale_with_the_batch(self):
+ """`ensure_batch_size` repeats the reference latents across the batch."""
+ single = _estimate(image_seq_len=4096, ref_image_seq_len=12288)
+ assert _estimate(image_seq_len=4096, ref_image_seq_len=12288, batch_size=2) - single == (
+ (4096 + 12288 + 512) * PER_TOKEN
+ )
+
+ def test_the_fixed_base_does_not_scale_with_the_batch(self):
+ """It covers transient weight casts and allocator slack -- properties of the weights, not of
+ how many samples run through them. Scaling it would add a GB per sample for nothing."""
+ deltas = {
+ _estimate(image_seq_len=4096, batch_size=b + 1) - _estimate(image_seq_len=4096, batch_size=b)
+ for b in (1, 2, 3)
+ }
+ assert deltas == {(4096 + 512) * PER_TOKEN}
+
+ def test_the_regional_bias_does_not_scale_with_the_batch(self):
+ """`get_joint_attention_kwargs` builds it as (1, 1, S, S) and lets SDPA broadcast it, so
+ there is exactly one of them however many samples are in flight."""
+ bias = (4096 + 512) ** 2 * 2
+ single = _estimate(image_seq_len=4096, regional_bias=bias, has_regional_mask=True)
+ double = _estimate(image_seq_len=4096, regional_bias=bias, has_regional_mask=True, batch_size=2)
+ assert double - single == (4096 + 512) * PER_TOKEN
+
+ def test_the_score_matrix_scales_with_the_batch(self):
+ """Where it is materialized at all it is shaped (batch, heads, S, S)."""
+ seq_len = 4096 + 512
+ with _materializing():
+ single = _estimate(image_seq_len=4096, has_regional_mask=True, device=MATERIALIZING)
+ double = _estimate(image_seq_len=4096, has_regional_mask=True, batch_size=2, device=MATERIALIZING)
+ assert double - single == (
+ seq_len * PER_TOKEN + KLEIN_9B_HEADS * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ )
+
+ def test_the_lora_margin_scales_with_the_batch(self):
+ """A sidecar patch adds an activation branch, and activations are per sample."""
+ assert _estimate(image_seq_len=4096, num_loras=2, batch_size=3) - _estimate(
+ image_seq_len=4096, num_loras=0, batch_size=3
+ ) == 3 * int(1.0 * GB)
+
+
+ class TestFlux2VaeWorkingMemoryEstimate:
+ # (operation, pixel size, measured peak reserved MB), bf16, untiled.
+ MEASURED_VAE = [
+ ("decode", 512, 1086),
+ ("decode", 768, 2414),
+ ("decode", 1024, 4260),
+ ("decode", 1328, 7146),
+ ("decode", 1536, 9578),
+ ("encode", 512, 536),
+ ("encode", 1024, 2122),
+ ("encode", 1328, 3022),
+ ]
+
+ def _mock_bf16_vae(self):
+ vae = MagicMock(spec=AutoencoderKLFlux2)
+ vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)]) # element_size == 2
+ return vae
+
+ def _tensor_for(self, operation, px):
+ # decode receives 32-channel latents at pixels/8; encode receives a pixel image.
+ return torch.zeros(1, 32, px // 8, px // 8) if operation == "decode" else torch.zeros(1, 3, px, px)
+
+ @pytest.mark.parametrize("operation, px, measured_mb", MEASURED_VAE)
+ def test_estimate_is_an_upper_bound_on_measured_peak(self, operation, px, measured_mb):
+ estimate = estimate_vae_working_memory_flux2(
+ operation=operation, image_tensor=self._tensor_for(operation, px), vae=self._mock_bf16_vae(), device=FUSED
+ )
+ assert estimate >= measured_mb * MB
+
+ @pytest.mark.parametrize("operation, expected_constant", [("decode", 2200), ("encode", 1100)])
+ def test_constant_scales_pixel_area_and_element_size(self, operation, expected_constant):
+ estimate = estimate_vae_working_memory_flux2(
+ operation=operation, image_tensor=self._tensor_for(operation, 1024), vae=self._mock_bf16_vae(), device=FUSED
+ )
+ assert estimate == 1024 * 1024 * 2 * expected_constant
+
+ def test_tiled_estimate_is_bounded_by_the_tile_not_the_image(self):
+ """Reference-image encoding forces 512px tiling precisely so the peak stops following the
+ reference resolution -- measured flat at ~0.55GB from 1024px up to the 2024px reference cap."""
+ estimates = [
+ estimate_vae_working_memory_flux2(
+ operation="encode",
+ image_tensor=torch.zeros(1, 3, px, px),
+ vae=self._mock_bf16_vae(),
+ tile_size=512,
+ device=FUSED,
+ )
+ for px in (1024, 1328, 2024)
+ ]
+ assert len(set(estimates)) == 1
+ assert estimates[0] == int(512 * 512 * 2 * 1100 * 1.25)
+ assert estimates[0] >= 558 * MB # measured tiled peak at 2024px
+ # The whole point of tiling: it must shrink the reservation, not just bound the VAE.
+ untiled = estimate_vae_working_memory_flux2(
+ operation="encode", image_tensor=torch.zeros(1, 3, 2024, 2024), vae=self._mock_bf16_vae(), device=FUSED
+ )
+ assert estimates[0] < untiled / 4
+
+
+ class TestVaeConstantsFollowTheConvBackend:
+ """The pixel-area constant is not one number. MIOpen's convolution workspaces cost far more than
+ cuDNN's for the same decode, and the gap is not the attention term -- it is identical on the
+ fused path. Fitted with `scripts/calibrate_flux2_working_memory.py --only vae`, peak reserved,
+ each point in a fresh process:
+
+ decode encode
+ cuDNN RTX 4090 2180 2185 2165 1072 1063 1061
+ MIOpen RX 9070 XT 3453 3369 3368 2687 2688 2688
+
+ Flat across 512/768/1024px on both, so the linear model holds; only the coefficient moves. Note
+ the encode column: cuDNN's is half its decode, MIOpen's is four fifths, so "encoding costs half
+ of decoding" -- the ratio the other estimators in the module use -- is a cuDNN property, not an
+ architectural one.
+ """
+
+ # (backend, operation, px, measured GiB)
+ MEASURED = [
+ ("cudnn", "decode", 512, 1.064),
+ ("cudnn", "decode", 768, 2.400),
+ ("cudnn", "decode", 1024, 4.229),
+ ("cudnn", "encode", 512, 0.523),
+ ("cudnn", "encode", 768, 1.168),
+ ("cudnn", "encode", 1024, 2.072),
+ ("miopen", "decode", 512, 1.686),
+ ("miopen", "decode", 768, 3.701),
+ ("miopen", "decode", 1024, 6.578),
+ # PRO W7900 (gfx1100). Costs slightly more per pixel than gfx1201 and sets the column.
+ ("miopen", "decode", 512, 1.721),
+ ("miopen", "decode", 768, 3.781),
+ ("miopen", "decode", 1024, 6.703),
+ ("miopen", "encode", 512, 1.312),
+ ("miopen", "encode", 768, 2.953),
+ ("miopen", "encode", 1024, 5.250),
+ ]
+
+ @pytest.mark.parametrize("backend, operation, px, measured_gib", MEASURED)
+ def test_the_constant_upper_bounds_its_own_backend(self, backend, operation, px, measured_gib):
+ """Each column has to bound the hardware it was fitted on. Before this the cuDNN column was
+ used everywhere, leaving a 2.3 GiB shortfall on a 1024px MIOpen decode."""
+ constant = _FLUX2_VAE_SCALING_CONSTANTS[backend][operation]
+ estimate = px * px * 2 * constant # bf16 element size
+ assert estimate >= measured_gib * GB
+ assert estimate <= 1.3 * measured_gib * GB
+
+ def test_the_cudnn_constant_would_not_cover_miopen(self):
+ """The regression this guards: a 1024px MIOpen decode needs 6.58 GiB and the cuDNN constant
+ reserves 4.30. That is the same class of shortfall #9500 reports, one backend over."""
+ cudnn = _FLUX2_VAE_SCALING_CONSTANTS["cudnn"]["decode"]
+ assert 1024 * 1024 * 2 * cudnn < 6.578 * GB
+
+ def test_the_encode_ratio_is_not_architectural(self):
+ """cuDNN's encode is half its decode; MIOpen's is four fifths. A shared ratio cannot express
+ both, which is why the table carries the two operations separately."""
+ ratios = {
+ backend: consts["encode"] / consts["decode"] for backend, consts in _FLUX2_VAE_SCALING_CONSTANTS.items()
+ }
+ assert ratios["cudnn"] == pytest.approx(0.50, abs=0.02)
+ assert ratios["miopen"] == pytest.approx(0.76, abs=0.03)
+
+ def test_a_rocm_build_selects_the_miopen_column(self):
+ """A HIP build reports `device.type == "cuda"`, so the torch build is the discriminator."""
+ vae = MagicMock(spec=AutoencoderKLFlux2)
+ vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+ latents = torch.zeros(1, 32, 128, 128)
+
+ def estimate():
+ v = MagicMock(spec=AutoencoderKLFlux2)
+ v.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+ return estimate_vae_working_memory_flux2(
+ operation="decode", image_tensor=latents, vae=v, device=torch.device("cuda")
+ )
+
+ with (
+ patch("torch.version.hip", "7.1.25424"),
+ patch("invokeai.backend.util.attention._torch_sdpa_materializes_score_matrix", return_value=False),
+ ):
+ rocm = estimate()
+ with (
+ patch("torch.version.hip", None),
+ patch("invokeai.backend.util.attention._torch_sdpa_materializes_score_matrix", return_value=False),
+ ):
+ cuda = estimate()
+
+ assert rocm > cuda
+ assert rocm / cuda == pytest.approx(3600 / 2200, rel=1e-3)
+
+
+ class TestFlux2VaeBatchIsBudgeted:
+ """`vae.decode` is handed whatever batch the latents carry, and a `LatentsField` is not pinned to
+ one. An estimate built from H and W alone gives a two-sample decode the same reservation as a
+ single one, so the cache admits it to a card that cannot run it -- the reservation is there, and
+ the OOM happens anyway.
+
+ Measured at 1024px on CUDA/bf16, peak reserved, each point in a fresh process: 4.23GB at batch 1,
+ 7.96GB at batch 2, 11.89GB at batch 3. Linear, and slightly sub-linear per sample, so scaling the
+ single-sample estimate is an upper bound rather than a fit.
+ """
+
+ # (batch, measured peak reserved MB) for a 1024px decode.
+ MEASURED_DECODE_BATCH = [(1, 4229), (2, 7955), (3, 11889)]
+
+ def _decode_estimate(self, batch, px=1024, tile_size=None, device=FUSED):
+ vae = MagicMock(spec=AutoencoderKLFlux2)
+ vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+ return estimate_vae_working_memory_flux2(
+ operation="decode",
+ image_tensor=torch.zeros(batch, 32, px // 8, px // 8),
+ vae=vae,
+ tile_size=tile_size,
+ device=device,
+ )
+
+ @pytest.mark.parametrize("batch, measured_mb", MEASURED_DECODE_BATCH)
+ def test_estimate_is_an_upper_bound_on_the_measured_batch_peak(self, batch, measured_mb):
+ estimate = self._decode_estimate(batch)
+ assert estimate >= measured_mb * MB
+ assert estimate <= 2 * measured_mb * MB
+
+ def test_estimate_scales_with_the_batch(self):
+ """The regression in one assertion: before this, all three of these were equal."""
+ single = self._decode_estimate(1)
+ assert self._decode_estimate(2) == 2 * single
+ assert self._decode_estimate(3) == 3 * single
+
+ def test_a_three_dimensional_tensor_is_one_sample(self):
+ """A bare `(C, H, W)` latent has no batch axis; `shape[0]` would read the channel count."""
+ vae = MagicMock(spec=AutoencoderKLFlux2)
+ vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+ unbatched = estimate_vae_working_memory_flux2(
+ operation="decode", image_tensor=torch.zeros(32, 128, 128), vae=vae, device=FUSED
+ )
+ assert unbatched == self._decode_estimate(1)
+
+ def test_tiling_bounds_the_tile_not_the_batch(self):
+ """Tiling caps the spatial term at one tile, but every sample still runs through it."""
+ single = self._decode_estimate(1, px=1024, tile_size=512)
+ assert self._decode_estimate(3, px=1024, tile_size=512) == 3 * single
+
+ def test_the_score_matrix_scales_with_the_batch(self):
+ """It is shaped (batch, heads, S, S), so where it is materialized at all it scales with the
+ batch just as the linear term does -- and since both scale together, the larger of the two
+ stays the larger at every batch size."""
+ tokens = 128 * 128
+ score = tokens * tokens * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ linear = self._decode_estimate(1) # fused: the spatial term on its own
+ with _materializing():
+ assert self._decode_estimate(1, device=MATERIALIZING) == max(linear, score)
+ assert self._decode_estimate(3, device=MATERIALIZING) == 3 * max(linear, score)
+
+
+ class TestFlux2VaeInvocationsRequestWorkingMemory:
+ """The estimate is worthless unless it reaches `model_on_device()`."""
+
+ def _mock_vae_info(self):
+ vae = MagicMock(spec=AutoencoderKLFlux2)
+ vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+
+ vae_info = MagicMock()
+ vae_info.model = vae
+ vae_info.compute_device = torch.device("cpu")
+ cm = MagicMock()
+ cm.__enter__ = MagicMock(return_value=(None, vae))
+ cm.__exit__ = MagicMock(return_value=None)
+ vae_info.model_on_device = MagicMock(return_value=cm)
+ return vae_info
+
+ def test_decode_requests_working_memory(self):
+ vae_info = self._mock_vae_info()
+ context = MagicMock()
+ context.models.load.return_value = vae_info
+ context.tensors.load.return_value = torch.zeros(1, 32, 128, 128)
+
+ expected = 10 * GB
+ with patch(
- "invokeai.app.invocations.flux2_vae_decode.estimate_vae_working_memory_flux2", return_value=expected
++ "invokeai.app.invocations.vae.flux2_vae_decode.estimate_vae_working_memory_flux2", return_value=expected
+ ) as estimate:
+ invocation = Flux2VaeDecodeInvocation.model_construct(
+ latents=MagicMock(latents_name="latents"), vae=MagicMock(vae=MagicMock())
+ )
+ try:
+ invocation.invoke(context)
+ except Exception:
+ # The mocked decode math fails downstream; we only care that the cache was asked to
+ # reserve the estimate before the device context was entered.
+ pass
+
+ estimate.assert_called_once()
+ assert estimate.call_args.kwargs["operation"] == "decode"
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected)
+
+ def test_encode_requests_working_memory(self):
+ vae_info = self._mock_vae_info()
+ context = MagicMock()
+ context.models.load.return_value = vae_info
+
+ expected = 4 * GB
+ with (
+ patch(
- "invokeai.app.invocations.flux2_vae_encode.estimate_vae_working_memory_flux2", return_value=expected
++ "invokeai.app.invocations.vae.flux2_vae_encode.estimate_vae_working_memory_flux2", return_value=expected
+ ) as estimate,
+ patch(
- "invokeai.app.invocations.flux2_vae_encode.image_resized_to_grid_as_tensor",
++ "invokeai.app.invocations.vae.flux2_vae_encode.image_resized_to_grid_as_tensor",
+ return_value=torch.zeros(3, 1024, 1024),
+ ),
+ ):
+ invocation = Flux2VaeEncodeInvocation.model_construct(
+ image=MagicMock(image_name="image"), vae=MagicMock(vae=MagicMock())
+ )
+ try:
+ invocation.invoke(context)
+ except Exception:
+ pass
+
+ estimate.assert_called_once()
+ assert estimate.call_args.kwargs["operation"] == "encode"
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected)
+
+
+ class _StopBeforeLoad(Exception):
+ """Raised in place of entering the transformer's device context, to end _run_diffusion early."""
+
+
+ class TestFlux2DenoiseRequestsWorkingMemory:
+ """The denoise node must hand its estimate to the cache, and that estimate must grow with the
+ attached reference images -- the combination that #9500 was missing."""
+
+ def _run(self, num_ref_tokens: int, batch: int = 1, init_batch: int | None = None, variant="klein_9b"):
+ """Drive `_run_diffusion` up to the transformer load and return the requested working memory."""
+ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
+ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
+ ConditioningFieldData,
+ FLUXConditioningInfo,
+ )
+
+ transformer_info = MagicMock()
+ transformer_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
+
+ context = MagicMock()
+ context.models.load.return_value = transformer_info
+ from invokeai.backend.model_manager.taxonomy import Flux2VariantType
+
+ context.models.get_config.return_value = MagicMock(
+ base=BaseModelType.Flux2,
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant=Flux2VariantType(variant) if variant is not None else None,
+ )
+ context.conditioning.load.return_value = ConditioningFieldData(
+ conditionings=[FLUXConditioningInfo(clip_embeds=torch.zeros(1, 768), t5_embeds=torch.zeros(1, 512, 12288))]
+ )
+
+ ref_extension = MagicMock()
+ ref_extension.ref_image_latents = torch.zeros(1, num_ref_tokens, 128)
+
+ if init_batch is not None:
+ # img2img: the node loads these, then preblends them with its own batch-1 noise.
+ context.tensors.load.return_value = torch.zeros(init_batch, 32, 128, 128)
+
+ invocation = Flux2DenoiseInvocation.model_construct(
+ latents=MagicMock(latents_name="init") if init_batch is not None else None,
+ noise=None,
+ denoise_mask=None,
+ denoising_start=0.0,
+ denoising_end=1.0,
+ add_noise=True,
+ transformer=MagicMock(transformer=MagicMock(), loras=[]),
+ positive_text_conditioning=MagicMock(conditioning_name="pos", mask=None),
+ negative_text_conditioning=None,
+ guidance=4.0,
+ cfg_scale=1.0,
+ width=1024,
+ height=1024,
+ num_steps=4,
+ scheduler="euler",
+ seed=0,
+ vae=MagicMock(vae=MagicMock()),
+ kontext_conditioning=MagicMock() if num_ref_tokens else None,
+ )
+
+ with (
+ patch.object(Flux2DenoiseInvocation, "_get_bn_stats", return_value=None),
+ patch("invokeai.backend.util.devices.TorchDevice.choose_torch_device", return_value=torch.device("cpu")),
- patch("invokeai.app.invocations.flux2_denoise.Flux2RefImageExtension", return_value=ref_extension),
++ patch("invokeai.app.invocations.flux2.flux2_denoise.Flux2RefImageExtension", return_value=ref_extension),
+ patch.object(
+ Flux2DenoiseInvocation, "_prepare_noise_tensor", return_value=torch.zeros(batch, 32, 128, 128)
+ ),
+ pytest.raises(_StopBeforeLoad),
+ ):
+ invocation._run_diffusion(context)
+
+ transformer_info.model_on_device.assert_called_once()
+ return transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"]
+
+ def test_estimate_reaches_the_model_cache(self):
+ """Without this the cache reserves only the default `device_working_mem_gb`."""
+ assert self._run(num_ref_tokens=0) == _estimate(image_seq_len=64 * 64, text_seq_len=512)
+
+ def test_reference_images_raise_the_reservation(self):
+ """Three 1024x1024 references add 12288 tokens to a 1024x1024 generation's 4096."""
+ without_refs = self._run(num_ref_tokens=0)
+ with_refs = self._run(num_ref_tokens=12288)
+ assert with_refs - without_refs == 12288 * PER_TOKEN
+
+ def test_the_real_batch_reaches_the_reservation(self):
+ """A batched latent tensor is reachable through the API and custom graphs. The node has `b`
+ in hand at the estimate; before this it simply did not pass it, so a two-sample run reserved
+ one sample's worth and the cache admitted it to a card that could not run it."""
+ assert self._run(num_ref_tokens=0, batch=2) == _estimate(image_seq_len=64 * 64, text_seq_len=512, batch_size=2)
+
+ def test_a_batched_run_reserves_more_than_a_single_one(self):
+ single = self._run(num_ref_tokens=0, batch=1)
+ assert self._run(num_ref_tokens=0, batch=2) - single == (64 * 64 + 512) * PER_TOKEN
+
+ @pytest.mark.parametrize(
+ "variant, hidden",
+ [("klein_4b", 3072), ("klein_4b_base", 3072), ("klein_9b", 4096), ("klein_9b_base", 4096), ("dev", 6144)],
+ )
+ def test_the_variants_width_reaches_the_reservation(self, variant, hidden):
+ """Per-token cost is linear in the transformer's width, so the reservation has to know which
+ variant it is loading. Calibrating on Klein 9B alone under-reserved [dev] by a third. Base
+ variants share their distilled twin's geometry."""
+ assert self._run(num_ref_tokens=0, variant=variant) == _estimate(
+ image_seq_len=64 * 64, text_seq_len=512, hidden_size=hidden
+ )
+
+ def test_dev_reserves_half_again_what_klein_9b_does(self):
+ """The blocker in one assertion: 1024x1024 with three 1024x1024 references is 16896 tokens,
+ where the difference is ~3GB."""
+ tokens = 64 * 64 + 12288 + 512
+ klein = self._run(num_ref_tokens=12288, variant="klein_9b")
+ dev = self._run(num_ref_tokens=12288, variant="dev")
+ assert dev - klein == tokens * (_per_token(6144) - _per_token(4096))
+ assert dev - klein > 2 * GB
+
+ def test_an_unreadable_variant_falls_back_to_the_widest(self):
+ """Over-reserving on a model we cannot identify beats under-reserving on the largest one."""
+ assert self._run(num_ref_tokens=0, variant=None) == _estimate(
+ image_seq_len=64 * 64, text_seq_len=512, hidden_size=FLUX2_MAX_HIDDEN_SIZE
+ )
+
+ def test_a_batched_init_latent_beats_the_batch_1_noise_it_is_blended_with(self):
+ """img2img takes `x = t_0 * noise + (1 - t_0) * init_latents`, and this node builds its noise
+ at batch 1 from width/height/seed. Two batched init latents therefore broadcast up to a
+ two-sample `x` while the noise tensor -- the thing the batch used to be read from -- still
+ says 1. The reservation has to follow `x`."""
+ assert self._run(num_ref_tokens=0, init_batch=2) == _estimate(
+ image_seq_len=64 * 64, text_seq_len=512, batch_size=2
+ )
+
+ def test_the_blended_batch_is_read_after_the_broadcast(self):
+ single = self._run(num_ref_tokens=0, init_batch=1)
+ assert self._run(num_ref_tokens=0, init_batch=3) - single == 2 * (64 * 64 + 512) * PER_TOKEN
+
+ def test_repeated_reference_latents_are_counted_per_sample(self):
+ """`ensure_batch_size` repeats the reference latents across the batch, so their tokens scale
+ with it as well -- the worst case in #9500, doubled."""
+ single = self._run(num_ref_tokens=12288, batch=1)
+ double = self._run(num_ref_tokens=12288, batch=2)
+ assert double - single == (64 * 64 + 12288 + 512) * PER_TOKEN
+
+
+ def _materializing_probe(device_type, device_index, dtype, head_dim, has_attn_mask):
+ """A synthetic stand-in for the torch probe, so both regimes can be exercised without hardware.
+
+ It reports `math` for a head dim above 128 -- which is what ROCm really does, gfx1100 answers
+ MATH for the VAE's 512-wide head -- and also for an additive mask, which is *not* a hardware
+ claim: gfx1100 reports the memory-efficient kernel for a masked 128-wide head, same as CUDA.
+ The mask leg is here only to drive the masked branch of the estimator; which builds take it is
+ the probe's business, not this module's.
+ """
+ return head_dim > 128 or has_attn_mask
+
+
+ class _null:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+
+ def _materializing():
+ return patch(
+ "invokeai.backend.util.attention._torch_sdpa_materializes_score_matrix", side_effect=_materializing_probe
+ )
+
+
+ # Any CUDA device object works here: the probe is patched out, so nothing is allocated on it.
+ MATERIALIZING = torch.device("cuda")
+
+
+ class TestMaterializedScoreMatrixIsBudgeted:
+ """The linear estimates above assume SDPA never builds the O(S^2) score matrix. That is a
+ property of the *build*, not of FLUX.2: some builds have no fused kernel for the VAE's 512-wide
+ head, or for the dense additive mask regional prompting attaches, and fall through to `math`.
+ Where that happens the score matrix eventually dominates, so the estimate has to account for it
+ -- otherwise the fix works on CUDA and still OOMs elsewhere.
+
+ How it accounts for it differs between the two estimators, and the difference is measured rather
+ than assumed. In the transformer the score matrix is live alongside the block activations, so it
+ adds. In the VAE the mid-block sits alone at the 8x-downsampled bottleneck, so the two peak in
+ different phases and the estimate takes the larger -- see `TestVaeTermsDoNotAdd`.
+ """
+
+ def _mock_bf16_vae(self):
+ vae = MagicMock(spec=AutoencoderKLFlux2)
+ vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+ return vae
+
+ def _vae_estimate(self, operation, px, device, tile_size=None):
+ tensor = torch.zeros(1, 32, px // 8, px // 8) if operation == "decode" else torch.zeros(1, 3, px, px)
+ return estimate_vae_working_memory_flux2(
+ operation=operation,
+ image_tensor=tensor,
+ vae=self._mock_bf16_vae(),
+ tile_size=tile_size,
+ device=device,
+ )
+
+ # (operation, pixel size, mid-block tokens). The VAE attends on the 8x-downsampled grid.
+ @pytest.mark.parametrize(
+ "operation, px, tokens",
+ [
+ ("decode", 1536, 192 * 192),
+ ("encode", 1024, 128 * 128),
+ ("encode", 1328, 166 * 166),
+ ],
+ )
+ def test_the_score_matrix_takes_over_where_it_is_the_larger_term(self, operation, px, tokens):
+ """Quadratic beats linear eventually. At these sizes it already has, so the estimate is the
+ score matrix exactly -- not the linear term, and not the two added together."""
+ with _materializing():
+ materializing = self._vae_estimate(operation, px, device=MATERIALIZING)
+ assert materializing == tokens * tokens * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert materializing > self._vae_estimate(operation, px, device=FUSED)
+
+ def test_mps_style_dispatch_failure_reserves_the_vae_score_matrix(self):
+ """The MPS case end to end, through the real probe rather than a stand-in: on a device torch
+ cannot answer a dispatch query for, the score matrix has to be priced. Reporting those
+ devices as fused -- as this PR first did -- is what let the decode be admitted to a card that
+ could not run it."""
+ with patch("torch.ops.aten._fused_sdp_choice", side_effect=NotImplementedError("no MPS kernel")):
+ materializing = self._vae_estimate("decode", 1536, device=FUSED)
+ fused = self._vae_estimate("decode", 1536, device=FUSED)
+
+ tokens = 192 * 192
+ assert materializing == tokens * tokens * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert materializing > fused + 10 * GB
+
+ def test_vae_score_matrix_dominates_at_high_resolution(self):
+ """A 1536px decode is ~9.7GB of convolution activations on cuDNN, and more than twice that
+ again in scores where SDPA has to materialize them. An estimate that omits the term is not
+ merely tight, it is wrong by a factor of two."""
+ with _materializing():
+ materializing = self._vae_estimate("decode", 1536, device=MATERIALIZING)
+ assert materializing > 20 * GB
+ assert materializing > 2 * self._vae_estimate("decode", 1536, device=FUSED)
+
+ def test_tiling_makes_the_score_matrix_irrelevant(self):
+ """Tiling caps the mid-block sequence at (tile/8)^2, which drops the quadratic term far below
+ the tile's own linear cost -- so a tiled estimate is the linear term whether the build
+ materializes or not, and is flat across input sizes."""
+ with _materializing():
+ estimates = [
+ self._vae_estimate("encode", px, device=MATERIALIZING, tile_size=512) for px in (1024, 1328, 2024)
+ ]
+ untiled = self._vae_estimate("encode", 2024, device=MATERIALIZING)
+ assert len(set(estimates)) == 1
+ assert estimates[0] == self._vae_estimate("encode", 1024, device=FUSED, tile_size=512)
+ # Tiling turns a 100GB+ reservation at the 2024px reference cap into under 2GB.
+ assert estimates[0] < untiled / 50
+
+
+ class TestVaeTermsDoNotAdd:
+ """The two VAE terms peak in different phases of the same forward, so the estimate takes the
+ larger rather than the sum. The mid-block sits at the 8x-downsampled bottleneck -- first in the
+ decoder, last in the encoder -- so the full-resolution convolution feature maps that drive the
+ linear term are not live while the score matrix is, and peak *reserved* is a high-water mark.
+
+ Measured, decode, peak reserved, fresh process per point:
+
+ px cuDNN fused cuDNN forced-math linear(2200) score(17)
+ 1024 4.229 3.527 4.30 4.25
+ 1280 6.590 5.924 6.71 10.38
+ 1536 9.353 11.965 9.67 21.52
+
+ Forcing math measures *below* the fused path until 1536px, and even there it exceeds it by
+ 2.6GB against the 21.5GB the score term prices standalone -- the attention phase reuses blocks
+ the allocator is already holding. On gfx1100 and gfx1201, forcing math moves the measured peak
+ by nothing at all up to 1024px, and the totals stay flat-linear in area either way.
+
+ Summing the terms reserved 11.1GB for a 1024px gfx1100 decode that measures 6.7GB. Taking the
+ max reserves 6.8GB.
+ """
+
+ def _estimate(self, px, device, materializing):
+ vae = MagicMock(spec=AutoencoderKLFlux2)
+ vae.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+ with _materializing() if materializing else _null():
+ return estimate_vae_working_memory_flux2(
+ operation="decode", image_tensor=torch.zeros(1, 32, px // 8, px // 8), vae=vae, device=device
+ )
+
+ # (pixel size, measured GiB) for a decode on the PRO W7900. Its 512px point is what sets the
+ # MIOpen decode constant: implied 3525, where gfx1201 asks for only 3453.
+ MEASURED_W7900_DECODE = [(1024, 6.703), (768, 3.781), (512, 1.721)]
+
+ @pytest.mark.parametrize("px, measured_gib", MEASURED_W7900_DECODE)
+ def test_the_max_model_bounds_the_measured_miopen_peak(self, px, measured_gib):
+ linear = px * px * 2 * _FLUX2_VAE_SCALING_CONSTANTS["miopen"]["decode"]
+ score = (px // 8) ** 4 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert max(linear, score) >= measured_gib * GB
+ assert max(linear, score) <= 1.15 * measured_gib * GB
+
+ def test_the_sum_model_would_have_over_reserved_by_two_thirds(self):
+ """At 1024px the sum reserves 11.1GiB for a decode that measures 6.7 -- on a 16GB card that
+ is the difference between the transformer staying resident and being evicted."""
+ linear = 1024 * 1024 * 2 * _FLUX2_VAE_SCALING_CONSTANTS["miopen"]["decode"]
+ score = 16384 * 16384 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert (linear + score) / (6.703 * GB) > 1.6
+ assert max(linear, score) / (6.703 * GB) < 1.15
+
+ def test_the_estimate_is_the_larger_term_not_the_sum(self):
+ """At 1024px the two are within 2% of each other on the cuDNN column, which makes this the
+ sharpest place to tell the models apart."""
+ linear = 1024 * 1024 * 2 * _FLUX2_VAE_SCALING_CONSTANTS["cudnn"]["decode"]
+ score = 16384 * 16384 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert self._estimate(1024, MATERIALIZING, materializing=True) == max(linear, score)
+ assert self._estimate(1024, MATERIALIZING, materializing=True) < linear + score
+
+ # (operation, px, measured GiB) with cuDNN's linear constant and a materializing kernel -- the
+ # combination MPS lands in, and the only place the max model is not an upper bound on its own.
+ MEASURED_CUDNN_FORCED_MATH = [
+ ("encode", 512, 0.523),
+ ("encode", 768, 1.801),
+ ("encode", 1024, 4.072),
+ ("decode", 1024, 3.527),
+ ("decode", 1280, 5.924),
+ ("decode", 1536, 11.965),
+ ]
+
+ @pytest.mark.parametrize("operation, px, measured_gib", MEASURED_CUDNN_FORCED_MATH)
+ def test_the_working_memory_floor_covers_the_crossover(self, operation, px, measured_gib):
+ """A max model is weakest where the two terms are near-equal, and one measured point shows
+ it: a 768px encode wants 1.80GiB against a 1.35GiB max. It is not reachable as a shortfall,
+ because the cache floors every reservation at `device_working_mem_gb` and the whole crossover
+ region sits below that floor. Reproducible to three decimals across runs, so this is the
+ model's real shape, not noise -- which is why it is pinned rather than rounded away."""
+ constant = _FLUX2_VAE_SCALING_CONSTANTS["cudnn"][operation]
+ area = px * px if operation == "decode" else px * px
+ linear = area * 2 * constant
+ score = (px // 8) ** 4 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ floored = max(max(linear, score), 3 * GB) # what ModelCache._get_vram_available reserves
+ assert floored >= measured_gib * GB
+
+ def test_a_fused_build_is_unaffected(self):
+ """The max only ever removes reservation, never adds it: with no score matrix the estimate is
+ the linear term, exactly as before."""
+ linear = 1024 * 1024 * 2 * _FLUX2_VAE_SCALING_CONSTANTS["cudnn"]["decode"]
+ assert self._estimate(1024, FUSED, materializing=False) == linear
+
+ def test_regional_prompting_adds_the_score_matrix(self):
+ """The dense `S x S` additive bias is what pushes SDPA off its fused kernel. Budgeting only
+ the bias tensor -- as this PR first did -- under-reserves by the score matrix, which is two
+ orders of magnitude larger."""
+ seq_len = 4096 + 512
+ bias_bytes = seq_len * seq_len * 2
+ fused = _estimate(
+ image_seq_len=4096, text_seq_len=512, regional_bias=bias_bytes, has_regional_mask=True, device=FUSED
+ )
+ with _materializing():
+ materializing = _estimate(
+ image_seq_len=4096,
+ text_seq_len=512,
+ regional_bias=bias_bytes,
+ has_regional_mask=True,
+ device=MATERIALIZING,
+ )
+ assert materializing - fused == (KLEIN_9B_HEADS * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT)
+ assert materializing - fused > 50 * bias_bytes
+
+ def test_denoise_without_a_regional_mask_is_unaffected(self):
+ """FLUX.2's 128-wide attention head is inside every backend's fused limit, so an ordinary
+ generation -- reference images included -- keeps the plain linear estimate. This term exists
+ for the masked case; it must not tax the common one."""
+ with _materializing():
+ assert _estimate(image_seq_len=4096, ref_image_seq_len=12288, device=MATERIALIZING) == _estimate(
+ image_seq_len=4096, ref_image_seq_len=12288, device=FUSED
+ )
+
+
+ class TestSdpaBackendProbe:
+ """`sdpa_score_matrix_bytes` decides the term above, so its defaults are load-bearing."""
+
+ def test_cpu_reports_its_fused_flash_kernel(self):
+ """torch ships a fused flash-attention CPU kernel that takes the VAE's 512-wide head and an
+ additive mask, so the CPU estimate stays linear -- and the rest of this module can use a CPU
+ device to stand in for the CUDA regime the constants were measured on."""
+ assert (
+ sdpa_score_matrix_bytes(
+ device=torch.device("cpu"),
+ dtype=torch.bfloat16,
+ num_heads=1,
+ head_dim=512,
+ seq_len=16384,
+ has_attn_mask=True,
+ )
+ == 0
+ )
+
+ def test_a_device_torch_cannot_answer_for_is_budgeted_as_math(self):
+ """MPS is the case that matters: torch registers `_fused_sdp_choice` for CPU, CUDA/ROCm and
+ XPU only, and it is exactly the devices it cannot answer for that have no fused SDPA kernel
+ either. A 1024px FLUX.2 VAE decode there materializes 16384^2 scores, ~3.5GB the estimate
+ used to omit entirely."""
+ with patch("torch.ops.aten._fused_sdp_choice", side_effect=NotImplementedError("no MPS kernel")):
+ estimated = sdpa_score_matrix_bytes(
+ device=torch.device("cpu"), dtype=torch.bfloat16, num_heads=1, head_dim=512, seq_len=16384
+ )
+ assert estimated == 16384 * 16384 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert estimated > 3 * GB
+
+ def test_a_failed_probe_is_budgeted_as_math(self):
+ """A probe that cannot allocate, or a torch without the op, leaves us knowing nothing. The
+ old code read that as "fused" and reserved zero; the shortfall it hides is an OOM, so the
+ unknown answer has to be the expensive one."""
+ with patch("torch.empty", side_effect=torch.cuda.OutOfMemoryError("probe could not allocate")):
+ estimated = sdpa_score_matrix_bytes(
+ device=torch.device("cpu"), dtype=torch.bfloat16, num_heads=1, head_dim=512, seq_len=16384
+ )
+ assert estimated == 16384 * 16384 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+
+ def _cpu_estimate(self):
+ return sdpa_score_matrix_bytes(
+ device=torch.device("cpu"), dtype=torch.bfloat16, num_heads=1, head_dim=128, seq_len=4096
+ )
+
+ def test_disabling_the_fused_kernels_at_runtime_changes_the_answer(self):
+ """The probe is not cached, so an estimate priced after a runtime switch does not inherit the
+ answer from before it. Nothing is cleared between these calls on purpose."""
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ assert self._cpu_estimate() == 0
+ with sdpa_kernel([SDPBackend.MATH]):
+ assert self._cpu_estimate() == 4096 * 4096 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert self._cpu_estimate() == 0
+
+ def test_a_priority_reorder_changes_the_answer_with_every_flag_unchanged(self):
+ """`sdpa_kernel(..., set_priority=True)` puts `MATH` first while leaving all four enable
+ flags True, and torch takes the first eligible backend in that order. A cache keyed on the
+ flags -- which is what this probe used to have -- could not see the switch and would keep
+ reserving zero. Not caching at all is what makes that unrepresentable."""
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ math_first = [
+ SDPBackend.MATH,
+ SDPBackend.FLASH_ATTENTION,
+ SDPBackend.EFFICIENT_ATTENTION,
+ SDPBackend.CUDNN_ATTENTION,
+ ]
+ flags = ("flash_sdp_enabled", "mem_efficient_sdp_enabled", "math_sdp_enabled", "cudnn_sdp_enabled")
+
+ assert self._cpu_estimate() == 0
+ with sdpa_kernel(math_first, set_priority=True):
+ # The finding in one line: every flag a key could hold is still True in here.
+ assert all(getattr(torch.backends.cuda, name)() for name in flags if hasattr(torch.backends.cuda, name))
+ # CPU's chooser ignores the priority order, so stand in for the answer CUDA gives.
+ with patch("torch.ops.aten._fused_sdp_choice", return_value=int(SDPBackend.MATH)):
+ assert self._cpu_estimate() == 4096 * 4096 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert self._cpu_estimate() == 0
+
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="only CUDA's chooser honours the priority order")
+ def test_this_build_reports_a_real_priority_reorder(self):
+ """The same case against the real dispatcher rather than a stand-in. Verified on torch
+ 2.7.1+cu128: `_fused_sdp_choice` answers EFFICIENT outside and MATH inside."""
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ def estimate():
+ return sdpa_score_matrix_bytes(
+ device=torch.device("cuda"), dtype=torch.bfloat16, num_heads=1, head_dim=128, seq_len=4096
+ )
+
+ assert estimate() == 0
+ with sdpa_kernel(
+ [
+ SDPBackend.MATH,
+ SDPBackend.FLASH_ATTENTION,
+ SDPBackend.EFFICIENT_ATTENTION,
+ SDPBackend.CUDNN_ATTENTION,
+ ],
+ set_priority=True,
+ ):
+ assert estimate() == 4096 * 4096 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert estimate() == 0
+
+ def test_the_probe_asks_torch_the_same_question_sdpa_does(self):
+ """`_fused_sdp_choice` is the dispatch query `F.scaled_dot_product_attention` itself runs, so
+ a `MATH` answer means the real forward materializes. Reimplementing the eligibility rules
+ instead would go stale with every torch release."""
+ from torch.nn.attention import SDPBackend
+
+ with patch("torch.ops.aten._fused_sdp_choice", return_value=int(SDPBackend.MATH)):
+ assert _torch_sdpa_materializes_score_matrix("cpu", None, torch.bfloat16, 128, False)
+ with patch("torch.ops.aten._fused_sdp_choice", return_value=int(SDPBackend.EFFICIENT_ATTENTION)):
+ assert not _torch_sdpa_materializes_score_matrix("cpu", None, torch.bfloat16, 128, False)
+
+ def test_empty_sequences_cost_nothing(self):
+ with _materializing():
+ assert (
+ sdpa_score_matrix_bytes(
+ device=MATERIALIZING, dtype=torch.bfloat16, num_heads=48, head_dim=128, seq_len=0
+ )
+ == 0
+ )
+
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="asks the real CUDA/ROCm dispatcher")
+ def test_this_build_reports_its_own_dispatch(self):
+ """The head dim is the discriminator that actually holds: CUDA's memory-efficient kernel
+ takes the VAE's 512-wide head, ROCm caps at 128 and reports `math` for it. Masks are not a
+ discriminator -- gfx1100 reports the memory-efficient kernel for a masked 128-wide head just
+ as CUDA does -- so the masked case only has to agree with whatever torch says, which is the
+ whole point of asking it."""
+ vae_bytes = sdpa_score_matrix_bytes(
+ device=torch.device("cuda"), dtype=torch.bfloat16, num_heads=1, head_dim=512, seq_len=16384
+ )
+ masked_bytes = sdpa_score_matrix_bytes(
+ device=torch.device("cuda"),
+ dtype=torch.bfloat16,
+ num_heads=48,
+ head_dim=128,
+ seq_len=4608,
+ has_attn_mask=True,
+ )
+ assert vae_bytes == (0 if torch.version.hip is None else 16384 * 16384 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT)
+ materializes = _torch_sdpa_materializes_score_matrix(
+ "cuda", torch.device("cuda").index, torch.bfloat16, 128, True
+ )
+ assert masked_bytes == (48 * 4608 * 4608 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT if materializes else 0)
+
+ # (platform, heads, seq, head_dim, bytes per score element), SDPBackend.MATH forced, each point
+ # in a fresh process. Reproduce with `scripts/calibrate_flux2_working_memory.py --only sdpa`.
+ MEASURED_BYTES_PER_ELEMENT = [
+ ("cuda-4090", 1, 4096, 512, 12.88),
+ ("cuda-4090", 1, 8192, 512, 10.28),
+ ("cuda-4090", 1, 16384, 512, 9.71),
+ ("cuda-4090", 4, 4096, 128, 9.97),
+ ("cuda-4090", 48, 4608, 128, 9.58),
+ ("rocm-gfx1100", 1, 4096, 512, 13.62),
+ ("rocm-gfx1100", 1, 8192, 512, 10.78),
+ ("rocm-gfx1100", 1, 16384, 512, 9.76),
+ ("rocm-gfx1100", 4, 4096, 128, 10.16),
+ ("rocm-gfx1100", 48, 4608, 128, 9.59),
+ ("rocm-gfx1201", 1, 4096, 512, 16.38),
+ ("rocm-gfx1201", 1, 8192, 512, 13.47),
+ ("rocm-gfx1201", 1, 16384, 512, 11.99),
+ ("rocm-gfx1201", 4, 4096, 128, 12.84),
+ ("rocm-gfx1201", 48, 4608, 128, 11.69),
+ ]
+
+ @pytest.mark.parametrize("platform, num_heads, seq_len, head_dim, measured", MEASURED_BYTES_PER_ELEMENT)
+ def test_the_constant_upper_bounds_every_measured_platform(self, platform, num_heads, seq_len, head_dim, measured):
+ """The constant has to bound the worst build anyone has measured, not the one it was written
+ on. It was 13 (CUDA's worst point rounded up), then 14 when gfx1100 came in at 13.62, and is
+ 17 because gfx1201 costs 16.38 for the same shape. The spread between the two AMD cards is
+ wider than the gap between CUDA and either of them, so there is no "the ROCm number"."""
+ assert SDPA_MATH_BYTES_PER_SCORE_ELEMENT >= measured
+
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="measures real peak reserved memory")
+ @pytest.mark.parametrize("num_heads, seq_len, head_dim", [(1, 4096, 512), (4, 4096, 128)])
+ def test_constant_upper_bounds_a_forced_math_forward(self, num_heads, seq_len, head_dim):
+ """Pin the bytes-per-score-element calibration against a real `math` forward, so a future
+ edit to the constant cannot silently reintroduce the shortfall it exists to cover."""
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ device = torch.device("cuda")
+ q = torch.randn(1, num_heads, seq_len, head_dim, device=device, dtype=torch.bfloat16)
+ k = torch.randn_like(q)
+ v = torch.randn_like(q)
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ before = torch.cuda.memory_reserved()
+ with sdpa_kernel([SDPBackend.MATH]), torch.no_grad():
+ F.scaled_dot_product_attention(q, k, v)
+ torch.cuda.synchronize()
+ measured = torch.cuda.max_memory_reserved() - before
+
+ estimate = num_heads * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ assert estimate >= measured, (
+ f"{estimate / num_heads / seq_len / seq_len:.2f} bytes/element measured here; "
+ f"SDPA_MATH_BYTES_PER_SCORE_ELEMENT={SDPA_MATH_BYTES_PER_SCORE_ELEMENT} must be an upper bound"
+ )
+ # Loose on purpose. The constant is the worst of three measured platforms (CUDA ~10
+ # bytes/element, gfx1100 ~10-14, gfx1201 ~12-16), so on any one of them it over-shoots by
+ # design; and this runs in-process, where the allocator may satisfy the forward from blocks
+ # it already holds and report a smaller delta than a fresh process would. The guard is here
+ # to catch an order-of-magnitude blunder, not to pin the calibration -- that is what
+ # `test_the_constant_upper_bounds_every_measured_platform` and the calibration script do.
+ assert estimate <= 3 * measured
+
+
+ def _diffusers_backend(name):
+ """Force the process-wide diffusers attention backend, as `DIFFUSERS_ATTN_BACKEND` would."""
+ from diffusers.models.attention_dispatch import AttentionBackendName
+
+ return patch(
+ "diffusers.models.attention_dispatch._AttentionBackendRegistry.get_active_backend",
+ return_value=(AttentionBackendName(name), None),
+ )
+
+
+ class TestDiffusersAttentionDispatchIsConsulted:
+ """The FLUX.2 transformer does not call `F.scaled_dot_product_attention` -- it calls diffusers'
+ `dispatch_attention_fn`, which honours `DIFFUSERS_ATTN_BACKEND` and the `attention_backend()`
+ context manager. A user on `_native_math` materializes the score matrix on hardware where the
+ torch probe reports a fused kernel, so asking torch alone is not enough for the transformer.
+
+ The VAE is the other half of the same point: its mid-block attention goes through
+ `AttnProcessor2_0`, which calls `F.scaled_dot_product_attention` itself, so the diffusers
+ backend must *not* move its estimate.
+ """
+
+ def test_forced_math_backend_reaches_the_denoise_estimate(self):
+ with _diffusers_backend("_native_math"):
+ forced_math = _estimate(image_seq_len=4096, device=FUSED)
+ native = _estimate(image_seq_len=4096, device=FUSED)
+ seq_len = 4096 + 512
+ assert forced_math - native == (KLEIN_9B_HEADS * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT)
+
+ def test_a_fused_backend_leaves_the_denoise_estimate_linear(self):
+ """`flash`, `sage`, `xformers` and friends exist precisely to avoid the score matrix; they
+ must not be taxed for it, on any device."""
+ with _diffusers_backend("flash"), _materializing():
+ forced_flash = _estimate(image_seq_len=4096, has_regional_mask=True, device=MATERIALIZING)
+ assert forced_flash == _estimate(image_seq_len=4096, has_regional_mask=True, device=FUSED)
+
+ def test_the_vae_estimate_ignores_the_diffusers_backend(self):
+ """`AttnProcessor2_0` bypasses the dispatcher, so the VAE's answer comes from torch alone."""
+
+ def estimate():
+ v = MagicMock(spec=AutoencoderKLFlux2)
+ v.parameters.return_value = iter([torch.zeros(1, dtype=torch.bfloat16)])
+ return estimate_vae_working_memory_flux2(
+ operation="decode", image_tensor=torch.zeros(1, 32, 128, 128), vae=v, device=FUSED
+ )
+
+ with _diffusers_backend("_native_math"):
+ forced_math = estimate()
+ assert forced_math == estimate()
+
+ def test_a_backend_switch_is_not_masked_by_an_earlier_estimate(self):
+ """The active backend is mutable process state. Caching the first answer would keep
+ reserving zero for every later estimate in a long-lived process that has since switched to
+ `_native_math` -- the exact case this lookup exists to catch. Deliberately no cache is
+ cleared between the two calls here; the production code must not be holding one."""
+ native = _estimate(image_seq_len=4096, device=FUSED)
+ with _diffusers_backend("_native_math"):
+ after_switch = _estimate(image_seq_len=4096, device=FUSED)
+ back_to_native = _estimate(image_seq_len=4096, device=FUSED)
+
+ seq_len = 4096 + 512
+ assert after_switch - native == (KLEIN_9B_HEADS * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT)
+ assert back_to_native == native
+
+ def test_a_model_level_override_reaches_the_registry(self):
+ """Why the estimator does not need the model in hand: it is priced before the transformer is
+ loaded, and `set_attention_backend()` stamps its choice onto the process-wide registry as
+ well as onto the model's attention processors -- deliberately, "so that it propagates
+ gracefully throughout". If diffusers ever stops doing that, a per-model override could
+ disagree with the estimate, and this test is where that shows up."""
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
+ from diffusers.models.attention_dispatch import _AttentionBackendRegistry
+ from diffusers.models.modeling_utils import ModelMixin
+
+ class _Tiny(ModelMixin, ConfigMixin):
+ @register_to_config
+ def __init__(self):
+ super().__init__()
+ self.lin = torch.nn.Linear(2, 2)
+
+ previous = _AttentionBackendRegistry._active_backend
+ try:
+ _Tiny().set_attention_backend("_native_math")
+ assert _diffusers_attention_dispatch() == "math"
+ finally:
+ _AttentionBackendRegistry._active_backend = previous
+
+ def test_an_unreadable_dispatcher_is_budgeted_as_math(self):
+ """`_AttentionBackendRegistry` is private; if diffusers moves it we lose the answer. The
+ conservative reading is the materializing one, and it is logged rather than silent."""
+ with patch(
+ "diffusers.models.attention_dispatch._AttentionBackendRegistry.get_active_backend",
+ side_effect=AttributeError("moved"),
+ ):
+ assert _diffusers_attention_dispatch() == "math"
diff --cc tests/app/invocations/test_minimax_h3_reference_nodes.py
index 3ae7001d67,99c2ea8e1b..57cb05e627
--- a/tests/app/invocations/test_minimax_h3_reference_nodes.py
+++ b/tests/app/invocations/test_minimax_h3_reference_nodes.py
@@@ -19,8 -19,9 +19,9 @@@ from invokeai.app.invocations.fields im
MiniMaxH3ReferenceMediaField,
VideoField,
)
-from invokeai.app.invocations.minimax_h3_denoise import MiniMaxH3DenoiseInvocation
-from invokeai.app.invocations.minimax_h3_reference import (
+from invokeai.app.invocations.minimax_h3.minimax_h3_denoise import MiniMaxH3DenoiseInvocation
+from invokeai.app.invocations.minimax_h3.minimax_h3_reference import (
+ _ResolvedVideoRange,
load_reference_audio,
normalize_reference_list,
reference_has_audio,
@@@ -88,6 -89,48 +89,50 @@@ class TestMediaField
assert reference_signature_entry(_image_ref(), (1024, 1024), 124) != image
+ class TestResolvedVideoRange:
+ """The reference range's start/length enforcement. No decoding: the probe is stubbed."""
+
+ @staticmethod
+ def _resolve(start: int, end: int, n_frames: int = 300) -> _ResolvedVideoRange:
+ context = MagicMock()
+ context.videos.get_path.return_value = "clip.mp4"
+ reference = _video_ref()
+ reference.start_frame = start
+ reference.end_frame = end
+ with (
+ patch(
- "invokeai.app.invocations.minimax_h3_reference.probe_video",
++ "invokeai.app.invocations.minimax_h3.minimax_h3_reference.probe_video",
+ return_value=(640, 480, n_frames / 24.0, 24.0),
+ ),
- patch("invokeai.app.invocations.minimax_h3_reference.decoder_frame_count", return_value=n_frames),
++ patch(
++ "invokeai.app.invocations.minimax_h3.minimax_h3_reference.decoder_frame_count", return_value=n_frames
++ ),
+ ):
+ return _ResolvedVideoRange(context, reference)
+
+ def test_resolves_positive_and_negative_bounds(self):
+ span = self._resolve(10, 49)
+ assert (span.start, span.end) == (10, 49)
+ tail = self._resolve(-24, -1)
+ assert (tail.start, tail.end) == (276, 299)
+
+ def test_pins_the_length_to_the_last_frame(self):
+ # A start frame plus a length that runs past the end takes the rest of the clip
+ # rather than failing the generation.
+ span = self._resolve(250, 449)
+ assert (span.start, span.end) == (250, 299)
+
+ def test_rejects_a_start_frame_past_the_end(self):
+ with pytest.raises(ValueError, match="start_frame=300 is out of range"):
+ self._resolve(300, 400)
+ with pytest.raises(ValueError, match="start_frame=-301 is out of range"):
+ self._resolve(-301, -1)
+
+ def test_rejects_an_inverted_range(self):
+ with pytest.raises(ValueError, match="must not be before start_frame"):
+ self._resolve(100, 50)
+
+
def _transformer_field(variant: str | None) -> MiniMaxH3TransformerField:
return MiniMaxH3TransformerField(
transformer=ModelIdentifierField(