Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(models): bundle encoder tokenizers and configs instead of fetching them
Alexander Eichhorn6f8cb3a53ba1
diff --git a/docs/src/content/docs/features/krea-2.mdx b/docs/src/content/docs/features/krea-2.mdxindex 4346c93514..26112c0781 100644--- a/docs/src/content/docs/features/krea-2.mdx+++ b/docs/src/content/docs/features/krea-2.mdx@@ -47,10 +47,10 @@ encoder if you have them. If none are installed, you'll be prompted to pick thembefore you can generate. Selecting a Diffusers Krea-2 model clears those standalone selections and usesthe bundled components.-:::note[Qwen3-VL encoder download]-Single-file Qwen3-VL encoders bundle only the weights. The tokenizer/config are fetched once from-HuggingFace (`Qwen/Qwen3-VL-4B-Instruct`) on first use, then cached for offline use. A single-file fp8-encoder is kept resident in fp8 (roughly half the VRAM of the bf16 encoder).+:::note[Qwen3-VL encoder]+Single-file Qwen3-VL encoders bundle only the weights. Their tokenizer and architecture config ship+with InvokeAI, so these encoders load without network access. A single-file fp8 encoder is kept+resident in fp8 (roughly half the VRAM of the bf16 encoder).:::## Conditioning enhancersdiff --git a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.pyindex b7013fbede..768f413e0e 100644--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py@@ -22,6 +22,10 @@ from invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.model_manager.load.model_cache.model_cache import MB, MODEL_LOAD_LOCKfrom invokeai.backend.model_manager.load.model_util import calc_model_size_by_fsfrom invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes+from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (+ load_bundled_qwen2_5_vl_preprocessor_config_dict,+ tokenizer_can_encode,+)from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,QwenImageConditioningInfo,@@ -180,18 +184,31 @@ class QwenImageTextEncoderInvocation(BaseInvocation):conditioning_name = context.conditioning.save(conditioning_data)return QwenImageConditioningOutput.build(conditioning_name)- def _encode(- self, context: InvocationContext, images: list[PILImage.Image]- ) -> tuple[torch.Tensor, torch.Tensor | None]:- """Encode text prompt and reference images using Qwen2.5-VL.+ @staticmethod+ def _build_processor(tokenizer: Any, model_root: Path) -> Any:+ """Wrap an already-loaded tokenizer in the Qwen2.5-VL processor for this install.- Matches the diffusers QwenImagePipeline._get_qwen_prompt_embeds logic:- 1. Format prompt with the edit-specific system template- 2. Run through Qwen2.5-VL to get hidden states- 3. Extract valid (non-padding) tokens and drop the system prefix- 4. Return padded embeddings + attention mask+ The tokenizer is passed in rather than built here: every encoder loader already serves it as+ a submodel, so the model cache owns exactly one copy. Re-deriving it from `model_root` cost+ a ~7MB vocabulary parse on every generation and produced a second copy the cache knew+ nothing about.++ What is left to decide is the image preprocessor, and that genuinely depends on the layout:+ a folder install may carry its own, a single-file checkpoint carries nothing."""- from transformers import AutoTokenizer, Qwen2_5_VLProcessor+ from transformers import Qwen2_5_VLProcessor++ # Every tokenizer source converges here -- the standalone encoder loaders and the diffusers+ # main-model loader alike -- which is why the check belongs at this point rather than in any+ # one of them. A `tokenizer/` that lost its vocabulary does not make `from_pretrained` raise:+ # it yields a one-token vocabulary that encodes every prompt to an empty sequence, so the+ # image comes out of no prompt conditioning at all with nothing in the log.+ if not tokenizer_can_encode(tokenizer):+ raise RuntimeError(+ f"The Qwen2.5-VL tokenizer loaded for this encoder ({model_root}) cannot encode "+ "anything, which means its vocabulary files are missing. Reinstall the model: "+ "generating with it would silently produce images from no prompt conditioning at all."+ )try:from transformers import Qwen2_5_VLImageProcessor as _ImageProcessorCls@@ -207,48 +224,54 @@ class QwenImageTextEncoderInvocation(BaseInvocation):Qwen2VLVideoProcessor as _VideoProcessorCls,)- # Format the prompt with one vision placeholder per reference image- text = _build_prompt(self.prompt, len(images))-- # Build the processor- tokenizer_config = context.models.get_config(self.qwen_vl_encoder.tokenizer)- model_root = context.models.get_absolute_path(tokenizer_config)-- # Single-file checkpoints (e.g. ComfyUI fp8_scaled): model_root is the- # safetensors file itself, so there's no tokenizer/processor folder- # alongside it. Fall back to the canonical Qwen2.5-VL repo on HF (small- # ~10 MB download for tokenizer+processor configs, cached for offline use).- if model_root.is_file():- HF_REPO = "Qwen/Qwen2.5-VL-7B-Instruct"- try:- tokenizer = AutoTokenizer.from_pretrained(HF_REPO, local_files_only=True)- except OSError:- tokenizer = AutoTokenizer.from_pretrained(HF_REPO)- try:- image_processor = _ImageProcessorCls.from_pretrained(HF_REPO, local_files_only=True)- except OSError:- try:- image_processor = _ImageProcessorCls.from_pretrained(HF_REPO)- except Exception:- image_processor = _ImageProcessorCls()- else:+ image_processor = None+ if not model_root.is_file():+ # A folder install may ship its own; a single-file checkpoint has no folder to search.tokenizer_dir = model_root / "tokenizer"- tokenizer = AutoTokenizer.from_pretrained(str(tokenizer_dir), local_files_only=True)-- image_processor = Nonefor search_dir in [model_root / "processor", tokenizer_dir, model_root, model_root / "image_processor"]:if (search_dir / "preprocessor_config.json").exists():image_processor = _ImageProcessorCls.from_pretrained(str(search_dir), local_files_only=True)break- if image_processor is None:- image_processor = _ImageProcessorCls()-- processor = Qwen2_5_VLProcessor(+ if image_processor is None:+ # The vendored config, never a bare constructor: transformers' class defaults cap a+ # reference image at 1,003,520 pixels against the release's 12,845,056, so a bare one+ # silently downscales by ~3.6x per side. `from_dict` also rewrites that class-level+ # default in place, so a bare constructor would return whichever budget the previously+ # loaded encoder happened to leave behind.+ image_processor = _ImageProcessorCls.from_dict(load_bundled_qwen2_5_vl_preprocessor_config_dict())++ return Qwen2_5_VLProcessor(tokenizer=tokenizer,image_processor=image_processor,video_processor=_VideoProcessorCls(),)+ def _encode(+ self, context: InvocationContext, images: list[PILImage.Image]+ ) -> tuple[torch.Tensor, torch.Tensor | None]:+ """Encode text prompt and reference images using Qwen2.5-VL.++ Matches the diffusers QwenImagePipeline._get_qwen_prompt_embeds logic:+ 1. Format prompt with the edit-specific system template+ 2. Run through Qwen2.5-VL to get hidden states+ 3. Extract valid (non-padding) tokens and drop the system prefix+ 4. Return padded embeddings + attention mask+ """+ # Format the prompt with one vision placeholder per reference image+ text = _build_prompt(self.prompt, len(images))++ tokenizer_config = context.models.get_config(self.qwen_vl_encoder.tokenizer)+ # Through the model cache: both encoder loaders serve this tokenizer as a submodel, so+ # taking it from there keeps one copy per process instead of parsing a 7MB vocabulary on+ # every generation into a second copy the cache knew nothing about.+ #+ # `.model` rather than `model_on_device()`: a tokenizer has no device residency to lock or+ # move, and it has to outlive this statement anyway -- the processor holds it until the+ # encode below. Holding the reference is what keeps it alive; eviction only drops the cache+ # record.+ tokenizer = context.models.load(self.qwen_vl_encoder.tokenizer).model+ processor = self._build_processor(tokenizer, context.models.get_absolute_path(tokenizer_config))+context.util.signal_progress("Running Qwen2.5-VL text/vision encoder")if self.quantization != "none":diff --git a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.pyindex dd5d57acbb..8d44eb46eb 100644--- a/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py+++ b/invokeai/backend/model_manager/configs/qwen3_vl_encoder.py@@ -185,8 +185,8 @@ class Qwen3VLEncoder_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):Distinguished from the text-only ``Qwen3Encoder`` checkpoint (Z-Image) by the presence of theQwen3-VL visual tower. Neither the config nor the tokenizer is bundled in a single-file- checkpoint; both are pulled from HuggingFace by the loader, from the repo the recorded variant- names.+ checkpoint; the loader supplies both from the copies vendored in ``invokeai.backend.qwen3_vl``,+ selecting the config by the recorded variant."""base: Literal[BaseModelType.Any] = Field(default=BaseModelType.Any)diff --git a/invokeai/backend/model_manager/configs/qwen_vl_encoder.py b/invokeai/backend/model_manager/configs/qwen_vl_encoder.pyindex 27abf935d0..a3454f375c 100644--- a/invokeai/backend/model_manager/configs/qwen_vl_encoder.py+++ b/invokeai/backend/model_manager/configs/qwen_vl_encoder.py@@ -122,8 +122,9 @@ class QwenVLEncoder_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):and the visual tower into one file (typically with FP8 + per-tensor`weight_scale` ComfyUI quantization).- The matching tokenizer + processor are pulled from HuggingFace- (`Qwen/Qwen2.5-VL-7B-Instruct`) on first use and cached for offline use.+ The tokenizer, architecture config and image preprocessor config all ship with InvokeAI+ (vendored from the Apache-2.0 `Qwen/Qwen2.5-VL-7B-Instruct` release), so this encoder loads+ without network access."""base: Literal[BaseModelType.Any] = Field(default=BaseModelType.Any)diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 81eec2f3e0..c17b78d903 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -2,8 +2,6 @@"""Class for Krea-2 model loading in InvokeAI."""from abc import abstractmethod-from collections.abc import Iterator-from contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any, Generic, Optional, TypeVar@@ -31,7 +29,6 @@ from invokeai.backend.model_manager.taxonomy import (BaseModelType,ModelFormat,ModelType,- Qwen3VLVariantType,SubModelType,)from invokeai.backend.model_manager.util.qwen3_gguf import convert_qwen3_llamacpp_keys@@ -68,6 +65,10 @@ from invokeai.backend.quantization.nvfp4 import (pop_nvfp4_layers,predict_nvfp4_install_size,)+from invokeai.backend.qwen3_vl.qwen3_vl_assets import (+ load_bundled_qwen3_vl_config_dict,+ load_bundled_qwen3_vl_tokenizer,+)from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, reject_incomplete_load@@ -777,22 +778,6 @@ def _reject_incomplete_load(model: Any, *, what: str) -> None:reject_incomplete_load(model, what=what)-def _tokenizer_can_encode(tokenizer: Any) -> bool:- """Whether a tokenizer loaded from the HuggingFace cache is actually usable.-- Not paranoia: when the cache holds the repo's `config.json` but none of its tokenizer files --- which is exactly the state `_load_text_encoder` leaves behind on a first run, because it fetches- the config first -- `AutoTokenizer.from_pretrained(..., local_files_only=True)` does not raise.- It returns a `Qwen2Tokenizer` with a one-token vocabulary and no chat template, which encodes- every prompt to an empty sequence. The generation then runs on no conditioning at all, and- nothing in the log says so. Probing the round trip is what tells the two apart.- """- try:- return bool(tokenizer("probe", add_special_tokens=False)["input_ids"])- except Exception:- return False--_Qwen3VLSingleFileConfig = TypeVar("_Qwen3VLSingleFileConfig", Qwen3VLEncoder_Checkpoint_Config, Qwen3VLEncoder_GGUF_Config)@@ -801,21 +786,16 @@ _Qwen3VLSingleFileConfig = TypeVar(class _Qwen3VLEncoderSingleFileLoader(ModelLoader, Generic[_Qwen3VLSingleFileConfig]):"""Shared plumbing for the two single-file Qwen3-VL encoder loaders (safetensors and GGUF).- Neither container ships a config or tokenizer, so both take them from HuggingFace with- offline-cache fallback, from the repo the config's recorded variant names -- the file itself says- nothing about which Qwen3-VL it is beyond its shapes. Only the weight decoding differs, which is- what the subclasses supply.+ Neither container ships a config or tokenizer, so both take them from the assets vendored in+ `invokeai.backend.qwen3_vl` -- the file itself says nothing about which Qwen3-VL it is beyond+ its shapes, so the config's recorded variant selects the config. Only the weight decoding+ differs, which is what the subclasses supply."""# Not a ClassVar: it is parameterized per subclass, which is what lets `_load_text_encoder`# narrow its argument to that subclass's config without violating the base's signature.CONFIG_CLASS: type[_Qwen3VLSingleFileConfig]- HF_REPO_BY_VARIANT = {- Qwen3VLVariantType.Qwen3VL_4B: "Qwen/Qwen3-VL-4B-Instruct",- Qwen3VLVariantType.Qwen3VL_8B: "Qwen/Qwen3-VL-8B-Instruct",- }-def _load_model(self,config: AnyModelConfig,@@ -826,7 +806,7 @@ class _Qwen3VLEncoderSingleFileLoader(ModelLoader, Generic[_Qwen3VLSingleFileConmatch submodel_type:case SubModelType.Tokenizer:- return self._load_tokenizer(config)+ return load_bundled_qwen3_vl_tokenizer()case SubModelType.TextEncoder:return self._load_text_encoder(config)@@ -839,48 +819,18 @@ class _Qwen3VLEncoderSingleFileLoader(ModelLoader, Generic[_Qwen3VLSingleFileCondef _load_text_encoder(self, config: _Qwen3VLSingleFileConfig) -> AnyModel:"""Decode this container's weights into the Qwen3-VL module tree."""- def _hf_repo(self, config: _Qwen3VLSingleFileConfig) -> str:- return self.HF_REPO_BY_VARIANT[config.variant]+ def _load_te_config(self, config: _Qwen3VLSingleFileConfig) -> Any:+ """Build the architecture config for this variant from the vendored copy.- def _load_tokenizer(self, config: _Qwen3VLSingleFileConfig) -> AnyModel:- repo = self._hf_repo(config)- # A partial offline cache (e.g. config present but vocab/merges missing) raises something other- # than OSError (e.g. TypeError) deep in the slow-tokenizer path, so catch broadly and re-fetch.- try:- tokenizer = AutoTokenizer.from_pretrained(repo, local_files_only=True, extra_special_tokens={})- except Exception:- tokenizer = None- if tokenizer is not None and _tokenizer_can_encode(tokenizer):- return tokenizer- with self._explaining_hf_failure(repo, "tokenizer"):- return AutoTokenizer.from_pretrained(repo, extra_special_tokens={})-- def _load_hf_config(self, config: _Qwen3VLSingleFileConfig) -> Any:- repo = self._hf_repo(config)- try:- te_config = AutoConfig.from_pretrained(repo, local_files_only=True)- except Exception:- with self._explaining_hf_failure(repo, "config"):- te_config = AutoConfig.from_pretrained(repo)- return _normalize_qwen3vl_rope_config(te_config)-- @contextmanager- def _explaining_hf_failure(self, repo: str, what: str) -> Iterator[None]:- """Say why a local single-file encoder is reaching for a HuggingFace repo it never installed.-- Raw, the failure is a transformers ``OSError`` naming a repo the user did not choose, with- nothing connecting it to the encoder they did. Identification needs no network, so this is- also the first point at which an offline user learns the requirement exists.+ Normalization stays here rather than being frozen into the vendored file: whether+ `rope_parameters` has to be mirrored onto `rope_scaling` is a property of the installed+ transformers, not of the release. It is a no-op on transformers 5.5.4, which already+ populates both; `TestNormalizeQwen3vlRopeConfig` covers the versions where it is not."""- try:- yield- except Exception as e:- raise RuntimeError(- f"Could not load the Qwen3-VL {what} from '{repo}'. A single-file Qwen3-VL encoder ships "- f"weights only, so its {what} is taken from that repository and cached on first use. "- "Connect once to populate the cache, or install the encoder in its directory form, which "- f"carries its own {what}."- ) from e+ from transformers import Qwen3VLConfig++ config_dict = load_bundled_qwen3_vl_config_dict(config.variant)+ return _normalize_qwen3vl_rope_config(Qwen3VLConfig.from_dict(config_dict))@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.Qwen3VLEncoder, format=ModelFormat.Checkpoint)@@ -962,7 +912,7 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncodequantize_fp8_scaled(sd, fp8_layers, model_dtype)fp8_layers = {}- te_config = self._load_hf_config(config)+ te_config = self._load_te_config(config)with accelerate.init_empty_weights():model = Qwen3VLModel._from_config(te_config)@@ -1102,7 +1052,7 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GG# Before the file is read, not after. This is the one step that can need the network, and# `gguf_sd_loader` copies every tensor into RAM -- so resolving the config first turns a# cold-offline failure from "read 2.5 GB, then raise" into an immediate one.- te_config = self._load_hf_config(config)+ te_config = self._load_te_config(config)sd = gguf_sd_loader(Path(config.path), compute_dtype=model_dtype)# Unconditional: identification requires the llama.cpp `token_embd.weight`, so this file isdiff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex 28710a272a..7e98f930ec 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -48,6 +48,10 @@ from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plain_fold_cannot_decodefrom invokeai.backend.quantization.nvfp4 import install_nvfp4_layers, pop_nvfp4_layers, predict_nvfp4_install_size+from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (+ load_bundled_qwen2_5_vl_config_dict,+ load_bundled_qwen2_5_vl_tokenizer,+)from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, log_unexpected_keys@@ -402,13 +406,11 @@ class QwenVLEncoderLoader(ModelLoader):class QwenVLEncoderCheckpointLoader(ModelLoader):"""Loads a single-file Qwen2.5-VL encoder checkpoint (e.g. ComfyUI fp8_scaled).- The checkpoint bundles the language model and the visual tower into one- safetensors file. Tokenizer + processor are pulled from HuggingFace- (`Qwen/Qwen2.5-VL-7B-Instruct`) on first use, with offline cache fallback.+ The checkpoint bundles the language model and the visual tower into one safetensors file, so+ it carries neither the architecture config nor the tokenizer. Both are vendored in+ `invokeai.backend.qwen2_5_vl`, so this encoder loads with no network access."""- DEFAULT_HF_REPO = "Qwen/Qwen2.5-VL-7B-Instruct"-def _load_model(self,config: AnyModelConfig,@@ -419,7 +421,7 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):match submodel_type:case SubModelType.Tokenizer:- return self._load_tokenizer_with_offline_fallback()+ return load_bundled_qwen2_5_vl_tokenizer()case SubModelType.TextEncoder:return self._load_text_encoder_from_singlefile(config)@@ -428,33 +430,9 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):f"Received: {submodel_type.value if submodel_type else 'None'}")- def _load_tokenizer_with_offline_fallback(self) -> AnyModel:- from transformers import AutoTokenizer-- from invokeai.backend.util.logging import InvokeAILogger-- logger = InvokeAILogger.get_logger(self.__class__.__name__)-- try:- return AutoTokenizer.from_pretrained(self.DEFAULT_HF_REPO, local_files_only=True)- except OSError:- logger.info(- f"Tokenizer for single-file Qwen VL encoder not found in HuggingFace cache; "- f"downloading from {self.DEFAULT_HF_REPO} (one-time, requires network access)."- )- try:- return AutoTokenizer.from_pretrained(self.DEFAULT_HF_REPO)- except OSError as e:- raise RuntimeError(- f"Failed to load Qwen VL tokenizer. Single-file Qwen VL encoder checkpoints do not "- f"include the tokenizer; it must be downloaded from HuggingFace ({self.DEFAULT_HF_REPO}) "- f"on first use. Either restore network access, or install the encoder in the "- f"diffusers folder layout (text_encoder/ + tokenizer/) instead. Original error: {e}"- ) from e-def _load_text_encoder_from_singlefile(self, config: QwenVLEncoder_Checkpoint_Config) -> AnyModel:from safetensors.torch import load_file- from transformers import AutoConfig, Qwen2_5_VLForConditionalGeneration+ from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGenerationfrom invokeai.backend.util.logging import InvokeAILogger@@ -479,25 +457,10 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):# it will never use.reject_int8_layers_a_plain_fold_cannot_decode(sd, "Qwen2.5-VL encoder checkpoint")- # Fetch the architecture config from HuggingFace (small, ~5KB).- # Offline fallback: tries cache first, downloads only if missing.- try:- qwen_config = AutoConfig.from_pretrained(self.DEFAULT_HF_REPO, local_files_only=True)- except OSError:- logger.info(- f"Architecture config for single-file Qwen VL encoder not found in HuggingFace cache; "- f"downloading from {self.DEFAULT_HF_REPO} (one-time, ~5KB, requires network access)."- )- try:- qwen_config = AutoConfig.from_pretrained(self.DEFAULT_HF_REPO)- except OSError as e:- raise RuntimeError(- f"Failed to load Qwen VL architecture config. Single-file Qwen VL encoder checkpoints "- f"do not include the model config; it must be downloaded from HuggingFace "- f"({self.DEFAULT_HF_REPO}) on first use. Either restore network access, or install the "- f"encoder in the diffusers folder layout (text_encoder/config.json + tokenizer/) "- f"instead. Original error: {e}"- ) from e+ # The architecture config is vendored rather than fetched: these constants decide the+ # module tree that the weights below are folded into, and a re-upload changing one of them+ # would silently change conditioning against unchanged weights.+ qwen_config = Qwen2_5_VLConfig.from_dict(load_bundled_qwen2_5_vl_config_dict())qwen_config.torch_dtype = model_dtype# Built before the reservation, which depends on its modules: they decide which nvfp4 layers stay packed.diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 607ae4bef5..366972b0bb 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -1672,10 +1672,11 @@ class Qwen3EncoderGGUFLoader(ModelLoader):@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.Qwen3Encoder, format=ModelFormat.SDNQQuantized)class Qwen3EncoderSDNQLoader(ModelLoader):- """Class to load SDNQ-quantized Qwen3 Encoder models for Z-Image."""+ """Class to load SDNQ-quantized Qwen3 Encoder models for Z-Image.- # Default HuggingFace model to load tokenizer from when using SDNQ Qwen3 encoder- DEFAULT_TOKENIZER_SOURCE = "Qwen/Qwen3-4B"+ SDNQ exports carry packed weights only, so the tokenizer comes from the copy vendored in+ `invokeai.backend.qwen3` -- the same one the single-file and GGUF Qwen3 encoders already use.+ """def _load_model(self,@@ -1691,18 +1692,11 @@ class Qwen3EncoderSDNQLoader(ModelLoader):case SubModelType.TextEncoder:return self._load_from_sdnq(config)case SubModelType.Tokenizer:- return self._load_tokenizer_with_offline_fallback()+ return load_bundled_qwen3_tokenizer()submodel_str = submodel_type.value if submodel_type else "None"raise ValueError(f"Only TextEncoder and Tokenizer submodels are supported. Received: {submodel_str}")- def _load_tokenizer_with_offline_fallback(self) -> AnyModel:- """Load tokenizer with local_files_only fallback for offline support."""- try:- return AutoTokenizer.from_pretrained(self.DEFAULT_TOKENIZER_SOURCE, local_files_only=True)- except OSError:- return AutoTokenizer.from_pretrained(self.DEFAULT_TOKENIZER_SOURCE)-def _load_from_sdnq(self,config: AnyModelConfig,diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.pyindex 0a20b1e258..e71c789e1f 100644--- a/invokeai/backend/model_manager/starter_models/common.py+++ b/invokeai/backend/model_manager/starter_models/common.py@@ -159,7 +159,7 @@ qwen_vl_encoder_fp8 = StarterModel(base=BaseModelType.Any,source="https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors",description="ComfyUI's single-file FP8-scaled Qwen2.5-VL 7B encoder. Bundles the language model and "- "visual tower; tokenizer/processor are fetched from HuggingFace on first use. (~7GB)",+ "visual tower; its tokenizer and config ship with InvokeAI. (~7GB)",type=ModelType.QwenVLEncoder,format=ModelFormat.Checkpoint,)@@ -169,7 +169,7 @@ qwen_vl_encoder_nvfp4 = StarterModel(base=BaseModelType.Any,source="https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_nvfp4.safetensors",description="ComfyUI's single-file nvfp4/fp8-mixed Qwen2.5-VL 7B encoder. Bundles the language model and visual "- "tower; tokenizer/processor are fetched from HuggingFace on first use. Its nvfp4 layers stay packed, about 6.7GB "+ "tower; its tokenizer and config ship with InvokeAI. Its nvfp4 layers stay packed, about 6.7GB ""once loaded. ~5.7GB download",type=ModelType.QwenVLEncoder,format=ModelFormat.Checkpoint,diff --git a/invokeai/backend/qwen2_5_vl/__init__.py b/invokeai/backend/qwen2_5_vl/__init__.pynew file mode 100644index 0000000000..56e58d5521--- /dev/null+++ b/invokeai/backend/qwen2_5_vl/__init__.py@@ -0,0 +1,5 @@+"""Qwen2.5-VL encoder backend module.++Holds the vendored architecture config for the single-file Qwen2.5-VL encoders used by+Qwen-Image. See `qwen2_5_vl_assets` for what is bundled and what deliberately is not.+"""diff --git a/invokeai/backend/qwen2_5_vl/qwen2_5_vl_7b_instruct_config.json b/invokeai/backend/qwen2_5_vl/qwen2_5_vl_7b_instruct_config.jsonnew file mode 100644index 0000000000..58ee12a9fb--- /dev/null+++ b/invokeai/backend/qwen2_5_vl/qwen2_5_vl_7b_instruct_config.json@@ -0,0 +1,61 @@+{+ "architectures": [+ "Qwen2_5_VLForConditionalGeneration"+ ],+ "attention_dropout": 0.0,+ "bos_token_id": 151643,+ "eos_token_id": 151645,+ "vision_start_token_id": 151652,+ "vision_end_token_id": 151653,+ "vision_token_id": 151654,+ "image_token_id": 151655,+ "video_token_id": 151656,+ "hidden_act": "silu",+ "hidden_size": 3584,+ "initializer_range": 0.02,+ "intermediate_size": 18944,+ "max_position_embeddings": 128000,+ "max_window_layers": 28,+ "model_type": "qwen2_5_vl",+ "num_attention_heads": 28,+ "num_hidden_layers": 28,+ "num_key_value_heads": 4,+ "rms_norm_eps": 1e-06,+ "rope_theta": 1000000.0,+ "sliding_window": 32768,+ "tie_word_embeddings": false,+ "torch_dtype": "bfloat16",+ "transformers_version": "4.41.2",+ "use_cache": true,+ "use_sliding_window": false,+ "vision_config": {+ "depth": 32,+ "hidden_act": "silu",+ "hidden_size": 1280,+ "intermediate_size": 3420,+ "num_heads": 16,+ "in_chans": 3,+ "out_hidden_size": 3584,+ "patch_size": 14,+ "spatial_merge_size": 2,+ "spatial_patch_size": 14,+ "window_size": 112,+ "fullatt_block_indexes": [+ 7,+ 15,+ 23,+ 31+ ],+ "tokens_per_second": 2,+ "temporal_patch_size": 2+ },+ "rope_scaling": {+ "type": "mrope",+ "mrope_section": [+ 16,+ 24,+ 24+ ]+ },+ "vocab_size": 152064+}\ No newline at end of filediff --git a/invokeai/backend/qwen2_5_vl/qwen2_5_vl_7b_instruct_preprocessor_config.json b/invokeai/backend/qwen2_5_vl/qwen2_5_vl_7b_instruct_preprocessor_config.jsonnew file mode 100644index 0000000000..7f3b746825--- /dev/null+++ b/invokeai/backend/qwen2_5_vl/qwen2_5_vl_7b_instruct_preprocessor_config.json@@ -0,0 +1,19 @@+{+ "min_pixels": 3136,+ "max_pixels": 12845056,+ "patch_size": 14,+ "temporal_patch_size": 2,+ "merge_size": 2,+ "image_mean": [+ 0.48145466,+ 0.4578275,+ 0.40821073+ ],+ "image_std": [+ 0.26862954,+ 0.26130258,+ 0.27577711+ ],+ "image_processor_type": "Qwen2VLImageProcessor",+ "processor_class": "Qwen2_5_VLProcessor"+}\ No newline at end of filediff --git a/invokeai/backend/qwen2_5_vl/qwen2_5_vl_assets.py b/invokeai/backend/qwen2_5_vl/qwen2_5_vl_assets.pynew file mode 100644index 0000000000..32a100917e--- /dev/null+++ b/invokeai/backend/qwen2_5_vl/qwen2_5_vl_assets.py@@ -0,0 +1,78 @@+"""Vendored tokenizer, architecture config and image preprocessor config for Qwen2.5-VL.++Single-file Qwen2.5-VL encoder checkpoints (e.g. ComfyUI's fp8_scaled build) carry weights only,+so all three of these used to be fetched from ``Qwen/Qwen2.5-VL-7B-Instruct`` at load time. Each+had its own reason to stop:++- The config's constants decide the module tree the weights are folded into, and a re-upload+ changing one of them would change conditioning against unchanged weights, silently.+- The preprocessor config decides the reference-image pixel budget. The fallback when the hub was+ unreachable was a bare ``Qwen2VLImageProcessor()``, whose class defaults cap an image at+ 1,003,520 pixels against the release's 12,845,056 — a ~3.6x downscale per side, unlogged.+- The tokenizer is the one whose absence was worst. A hub cache holding the repo's ``config.json``+ but none of its tokenizer files does not raise: ``AutoTokenizer`` returns a one-token vocabulary+ that encodes every prompt to an empty sequence, so the image is generated from no conditioning+ at all. InvokeAI itself used to create that cache state by fetching the config first.++Everything here is vendored verbatim from the Apache-2.0 release, so single-file Qwen-Image now+loads with no network access at all.++``tokenizer_can_encode`` remains because the same silent failure is reachable from a *local*+directory: a folder-layout install whose ``tokenizer/`` lost its vocabulary loads just as+successfully, and just as uselessly. Vendoring cannot fix somebody else's incomplete install, so+the loader probes what it reads from disk.+"""++import json+from functools import lru_cache+from pathlib import Path+from typing import Any++from transformers import PreTrainedTokenizerBase++from invokeai.backend.util.bundled_tokenizer import load_gzipped_tokenizer_dir++_ASSET_DIR = Path(__file__).parent+_TOKENIZER_DIR = _ASSET_DIR / "tokenizer"+_CONFIG_PATH = _ASSET_DIR / "qwen2_5_vl_7b_instruct_config.json"+_PREPROCESSOR_CONFIG_PATH = _ASSET_DIR / "qwen2_5_vl_7b_instruct_preprocessor_config.json"+++@lru_cache(maxsize=1)+def load_bundled_qwen2_5_vl_tokenizer() -> PreTrainedTokenizerBase:+ """Load the vendored Qwen2.5-VL fast tokenizer. Result is cached for the process."""+ return load_gzipped_tokenizer_dir(_TOKENIZER_DIR)+++def load_bundled_qwen2_5_vl_config_dict() -> dict[str, Any]:+ """The vendored ``Qwen/Qwen2.5-VL-7B-Instruct`` ``config.json``, as published.++ Returns a fresh dict per call: the loader sets ``torch_dtype`` on the config it builds from it.+ """+ config_dict: dict[str, Any] = json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))+ return config_dict+++def load_bundled_qwen2_5_vl_preprocessor_config_dict() -> dict[str, Any]:+ """The vendored ``preprocessor_config.json``, as published.++ Handed to ``Qwen2VLImageProcessor.from_dict`` rather than a directory: it is the only asset+ the image processor needs, so staging a directory for it would buy nothing.+ """+ config_dict: dict[str, Any] = json.loads(_PREPROCESSOR_CONFIG_PATH.read_text(encoding="utf-8"))+ return config_dict+++def tokenizer_can_encode(tokenizer: Any) -> bool:+ """Whether a tokenizer that loaded successfully is actually usable.++ Not paranoia, and not only about the hub: a directory holding ``tokenizer_config.json`` but no+ vocabulary — an interrupted model install, or a wheel with a bad data glob — does not make+ ``from_pretrained`` raise. It returns a ``Qwen2Tokenizer`` with a one-token vocabulary and no+ chat template, which encodes every prompt to an empty sequence. The generation then runs on no+ conditioning at all, and nothing in the log says so. Probing the round trip tells the two apart.+ """+ try:+ return bool(tokenizer("probe", add_special_tokens=False)["input_ids"])+ except Exception:+ return Falsediff --git a/invokeai/backend/qwen2_5_vl/tokenizer/tokenizer.json.gz b/invokeai/backend/qwen2_5_vl/tokenizer/tokenizer.json.gznew file mode 100644index 0000000000..c5644b4edbBinary files /dev/null and b/invokeai/backend/qwen2_5_vl/tokenizer/tokenizer.json.gz differdiff --git a/invokeai/backend/qwen2_5_vl/tokenizer/tokenizer_config.json b/invokeai/backend/qwen2_5_vl/tokenizer/tokenizer_config.jsonnew file mode 100644index 0000000000..91684ea3dc--- /dev/null+++ b/invokeai/backend/qwen2_5_vl/tokenizer/tokenizer_config.json@@ -0,0 +1,207 @@+{+ "add_prefix_space": false,+ "added_tokens_decoder": {+ "151643": {+ "content": "<|endoftext|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151644": {+ "content": "<|im_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151645": {+ "content": "<|im_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151646": {+ "content": "<|object_ref_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151647": {+ "content": "<|object_ref_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151648": {+ "content": "<|box_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151649": {+ "content": "<|box_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151650": {+ "content": "<|quad_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151651": {+ "content": "<|quad_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151652": {+ "content": "<|vision_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151653": {+ "content": "<|vision_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151654": {+ "content": "<|vision_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151655": {+ "content": "<|image_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151656": {+ "content": "<|video_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151657": {+ "content": "<tool_call>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151658": {+ "content": "</tool_call>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151659": {+ "content": "<|fim_prefix|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151660": {+ "content": "<|fim_middle|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151661": {+ "content": "<|fim_suffix|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151662": {+ "content": "<|fim_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151663": {+ "content": "<|repo_name|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151664": {+ "content": "<|file_sep|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ }+ },+ "additional_special_tokens": [+ "<|im_start|>",+ "<|im_end|>",+ "<|object_ref_start|>",+ "<|object_ref_end|>",+ "<|box_start|>",+ "<|box_end|>",+ "<|quad_start|>",+ "<|quad_end|>",+ "<|vision_start|>",+ "<|vision_end|>",+ "<|vision_pad|>",+ "<|image_pad|>",+ "<|video_pad|>"+ ],+ "bos_token": null,+ "chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}",+ "clean_up_tokenization_spaces": false,+ "eos_token": "<|im_end|>",+ "errors": "replace",+ "model_max_length": 131072,+ "pad_token": "<|endoftext|>",+ "split_special_tokens": false,+ "tokenizer_class": "Qwen2Tokenizer",+ "unk_token": null,+ "add_bos_token": false+}diff --git a/invokeai/backend/qwen3/qwen3_tokenizer.py b/invokeai/backend/qwen3/qwen3_tokenizer.pyindex 7ed651057a..da1001d361 100644--- a/invokeai/backend/qwen3/qwen3_tokenizer.py+++ b/invokeai/backend/qwen3/qwen3_tokenizer.py@@ -8,30 +8,17 @@ across the 0.6B / 4B / 8B variants, so a single self-contained copy (Apache-2.0,vendored from ``Qwen/Qwen3-4B``) serves every Qwen3 encoder, fully offline."""-import gzip-import shutil-import tempfilefrom functools import lru_cachefrom pathlib import Path-from transformers import AutoTokenizer, PreTrainedTokenizerBase+from transformers import PreTrainedTokenizerBase-_TOKENIZER_DIR = Path(__file__).parent / "tokenizer"+from invokeai.backend.util.bundled_tokenizer import load_gzipped_tokenizer_dir-# tokenizer.json is ~11MB uncompressed, over the repo's 10MB LFS threshold, so it is-# vendored gzip-compressed and expanded into a temp dir at load time.-_TOKENIZER_JSON_GZ = _TOKENIZER_DIR / "tokenizer.json.gz"+_TOKENIZER_DIR = Path(__file__).parent / "tokenizer"@lru_cache(maxsize=1)def load_bundled_qwen3_tokenizer() -> PreTrainedTokenizerBase:"""Load the vendored Qwen3 fast tokenizer. Result is cached for the process."""- # The fast tokenizer reads the vocab fully into memory at construction, so the- # decompressed files only need to exist for the duration of from_pretrained().- with tempfile.TemporaryDirectory() as tmp:- tmp_dir = Path(tmp)- with gzip.open(_TOKENIZER_JSON_GZ, "rb") as src, open(tmp_dir / "tokenizer.json", "wb") as dst:- shutil.copyfileobj(src, dst)- for name in ("tokenizer_config.json", "special_tokens_map.json"):- shutil.copyfile(_TOKENIZER_DIR / name, tmp_dir / name)- return AutoTokenizer.from_pretrained(tmp_dir, local_files_only=True)+ return load_gzipped_tokenizer_dir(_TOKENIZER_DIR)diff --git a/invokeai/backend/qwen3/tokenizer/tokenizer_config.json b/invokeai/backend/qwen3/tokenizer/tokenizer_config.jsonindex f17e6b5d5a..f9e98c8990 100644--- a/invokeai/backend/qwen3/tokenizer/tokenizer_config.json+++ b/invokeai/backend/qwen3/tokenizer/tokenizer_config.json@@ -230,7 +230,6 @@"clean_up_tokenization_spaces": false,"eos_token": "<|im_end|>","errors": "replace",- "extra_special_tokens": {},"model_max_length": 131072,"pad_token": "<|endoftext|>","split_special_tokens": false,diff --git a/invokeai/backend/qwen3_vl/__init__.py b/invokeai/backend/qwen3_vl/__init__.pynew file mode 100644index 0000000000..1db4b12100--- /dev/null+++ b/invokeai/backend/qwen3_vl/__init__.py@@ -0,0 +1,5 @@+"""Qwen3-VL encoder backend module.++Vendored assets for the Qwen3-VL text encoders that arrive as single-file safetensors or GGUF+containers, which carry weights only. See `qwen3_vl_assets` for what is bundled and why.+"""diff --git a/invokeai/backend/qwen3_vl/config/qwen3_vl_4b_instruct.json b/invokeai/backend/qwen3_vl/config/qwen3_vl_4b_instruct.jsonnew file mode 100644index 0000000000..22be8bb790--- /dev/null+++ b/invokeai/backend/qwen3_vl/config/qwen3_vl_4b_instruct.json@@ -0,0 +1,63 @@+{+ "architectures": [+ "Qwen3VLForConditionalGeneration"+ ],+ "image_token_id": 151655,+ "model_type": "qwen3_vl",+ "text_config": {+ "attention_bias": false,+ "attention_dropout": 0.0,+ "bos_token_id": 151643,+ "dtype": "bfloat16",+ "eos_token_id": 151645,+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 2560,+ "initializer_range": 0.02,+ "intermediate_size": 9728,+ "max_position_embeddings": 262144,+ "model_type": "qwen3_vl_text",+ "num_attention_heads": 32,+ "num_hidden_layers": 36,+ "num_key_value_heads": 8,+ "rms_norm_eps": 1e-06,+ "rope_scaling": {+ "mrope_interleaved": true,+ "mrope_section": [+ 24,+ 20,+ 20+ ],+ "rope_type": "default"+ },+ "rope_theta": 5000000,+ "tie_word_embeddings": true,+ "use_cache": true,+ "vocab_size": 151936+ },+ "tie_word_embeddings": true,+ "transformers_version": "4.57.0.dev0",+ "video_token_id": 151656,+ "vision_config": {+ "deepstack_visual_indexes": [+ 5,+ 11,+ 17+ ],+ "depth": 24,+ "hidden_act": "gelu_pytorch_tanh",+ "hidden_size": 1024,+ "in_channels": 3,+ "initializer_range": 0.02,+ "intermediate_size": 4096,+ "model_type": "qwen3_vl",+ "num_heads": 16,+ "num_position_embeddings": 2304,+ "out_hidden_size": 2560,+ "patch_size": 16,+ "spatial_merge_size": 2,+ "temporal_patch_size": 2+ },+ "vision_end_token_id": 151653,+ "vision_start_token_id": 151652+}diff --git a/invokeai/backend/qwen3_vl/config/qwen3_vl_8b_instruct.json b/invokeai/backend/qwen3_vl/config/qwen3_vl_8b_instruct.jsonnew file mode 100644index 0000000000..0e2df614c5--- /dev/null+++ b/invokeai/backend/qwen3_vl/config/qwen3_vl_8b_instruct.json@@ -0,0 +1,62 @@+{+ "architectures": [+ "Qwen3VLForConditionalGeneration"+ ],+ "image_token_id": 151655,+ "model_type": "qwen3_vl",+ "text_config": {+ "attention_bias": false,+ "attention_dropout": 0.0,+ "bos_token_id": 151643,+ "dtype": "bfloat16",+ "eos_token_id": 151645,+ "head_dim": 128,+ "hidden_act": "silu",+ "hidden_size": 4096,+ "initializer_range": 0.02,+ "intermediate_size": 12288,+ "max_position_embeddings": 262144,+ "model_type": "qwen3_vl_text",+ "num_attention_heads": 32,+ "num_hidden_layers": 36,+ "num_key_value_heads": 8,+ "rms_norm_eps": 1e-06,+ "rope_scaling": {+ "mrope_interleaved": true,+ "mrope_section": [+ 24,+ 20,+ 20+ ],+ "rope_type": "default"+ },+ "rope_theta": 5000000,+ "use_cache": true,+ "vocab_size": 151936+ },+ "tie_word_embeddings": false,+ "transformers_version": "4.57.0.dev0",+ "video_token_id": 151656,+ "vision_config": {+ "deepstack_visual_indexes": [+ 8,+ 16,+ 24+ ],+ "depth": 27,+ "hidden_act": "gelu_pytorch_tanh",+ "hidden_size": 1152,+ "in_channels": 3,+ "initializer_range": 0.02,+ "intermediate_size": 4304,+ "model_type": "qwen3_vl",+ "num_heads": 16,+ "num_position_embeddings": 2304,+ "out_hidden_size": 4096,+ "patch_size": 16,+ "spatial_merge_size": 2,+ "temporal_patch_size": 2+ },+ "vision_end_token_id": 151653,+ "vision_start_token_id": 151652+}diff --git a/invokeai/backend/qwen3_vl/qwen3_vl_assets.py b/invokeai/backend/qwen3_vl/qwen3_vl_assets.pynew file mode 100644index 0000000000..7f0b0fbe85--- /dev/null+++ b/invokeai/backend/qwen3_vl/qwen3_vl_assets.py@@ -0,0 +1,74 @@+"""Vendored tokenizer and architecture configs for the single-file Qwen3-VL encoders.++Single-file safetensors and GGUF Qwen3-VL encoders ship weights only, so the tokenizer and the+architecture config used to be fetched from ``Qwen/Qwen3-VL-{4B,8B}-Instruct`` at load time. Three+things make that the wrong source of truth:++- A partially populated HF cache — the repo's ``config.json`` present, its tokenizer files not —+ does not raise. ``AutoTokenizer`` returns a ``Qwen2Tokenizer`` with a one-token vocabulary that+ encodes every prompt to an empty sequence, and the generation then runs on no conditioning at+ all with nothing in the log to say so. Fetching the config first is exactly what left the cache+ in that state, so the failure was reachable on an ordinary first run.+- Architecture constants can change under a re-upload. A wrong ``rope_theta`` (1e6 rather than+ Qwen3-VL's 5e6) costs relative L2 0.1008 against otherwise identical weights — as much as a full+ Q4 quantization, and just as silent.+- Offline, air-gapped and proxied installs have no route to the hub at all.++The tokenizer is byte-identical across the 4B and 8B releases — verified by md5 against both+snapshots when it was vendored, which is why one copy serves both, in both container formats. That+identity cannot be re-checked here without the hub, so what the tests pin instead is the behaviour+that depends on it: the exact token ids and the single-id vision markers. Configs differ per+variant and are vendored per variant.++Everything here is vendored verbatim from the Apache-2.0 ``Qwen/Qwen3-VL-{4B,8B}-Instruct``+releases. The configs are deliberately *not* normalized on the way in: whether ``rope_parameters``+has to be mirrored onto ``rope_scaling`` depends on the installed transformers version, not on the+file, so that stays in the load path (`normalize_qwen3vl_rope_config`) where it can keep tracking+transformers. Freezing a normalized config here would bake in today's transformers instead.+"""++import json+from functools import lru_cache+from pathlib import Path+from typing import Any++from transformers import PreTrainedTokenizerBase++from invokeai.backend.model_manager.taxonomy import Qwen3VLVariantType+from invokeai.backend.util.bundled_tokenizer import load_gzipped_tokenizer_dir++_ASSET_DIR = Path(__file__).parent+_TOKENIZER_DIR = _ASSET_DIR / "tokenizer"+_CONFIG_DIR = _ASSET_DIR / "config"++_CONFIG_BY_VARIANT: dict[Qwen3VLVariantType, str] = {+ Qwen3VLVariantType.Qwen3VL_4B: "qwen3_vl_4b_instruct.json",+ Qwen3VLVariantType.Qwen3VL_8B: "qwen3_vl_8b_instruct.json",+}+++@lru_cache(maxsize=1)+def load_bundled_qwen3_vl_tokenizer() -> PreTrainedTokenizerBase:+ """Load the vendored Qwen3-VL fast tokenizer. Result is cached for the process.++ ``extra_special_tokens={}`` matches what the loaders passed when they fetched this tokenizer+ from the hub, so the returned object is configured exactly as before.+ """+ return load_gzipped_tokenizer_dir(_TOKENIZER_DIR, extra_special_tokens={})+++def load_bundled_qwen3_vl_config_dict(variant: Qwen3VLVariantType) -> dict[str, Any]:+ """The vendored ``config.json`` for a Qwen3-VL variant, as published.++ Returns a fresh dict per call so that a caller mutating it — as `minimax_h3` does with its own+ bundled config, to truncate the layer count — cannot corrupt the copy the next load sees.+ """+ filename = _CONFIG_BY_VARIANT.get(variant)+ if filename is None:+ raise NotImplementedError(+ f"No vendored Qwen3-VL config for variant '{variant.value}'. Add one to "+ f"{_CONFIG_DIR} and register it in _CONFIG_BY_VARIANT: a single-file encoder of this "+ "variant carries no config of its own, so there is nothing to fall back to."+ )+ config_dict: dict[str, Any] = json.loads((_CONFIG_DIR / filename).read_text(encoding="utf-8"))+ return config_dictdiff --git a/invokeai/backend/qwen3_vl/tokenizer/tokenizer.json.gz b/invokeai/backend/qwen3_vl/tokenizer/tokenizer.json.gznew file mode 100644index 0000000000..957d283dcaBinary files /dev/null and b/invokeai/backend/qwen3_vl/tokenizer/tokenizer.json.gz differdiff --git a/invokeai/backend/qwen3_vl/tokenizer/tokenizer_config.json b/invokeai/backend/qwen3_vl/tokenizer/tokenizer_config.jsonnew file mode 100644index 0000000000..d3d3763207--- /dev/null+++ b/invokeai/backend/qwen3_vl/tokenizer/tokenizer_config.json@@ -0,0 +1,239 @@+{+ "add_bos_token": false,+ "add_prefix_space": false,+ "added_tokens_decoder": {+ "151643": {+ "content": "<|endoftext|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151644": {+ "content": "<|im_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151645": {+ "content": "<|im_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151646": {+ "content": "<|object_ref_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151647": {+ "content": "<|object_ref_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151648": {+ "content": "<|box_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151649": {+ "content": "<|box_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151650": {+ "content": "<|quad_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151651": {+ "content": "<|quad_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151652": {+ "content": "<|vision_start|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151653": {+ "content": "<|vision_end|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151654": {+ "content": "<|vision_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151655": {+ "content": "<|image_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151656": {+ "content": "<|video_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": true+ },+ "151657": {+ "content": "<tool_call>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151658": {+ "content": "</tool_call>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151659": {+ "content": "<|fim_prefix|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151660": {+ "content": "<|fim_middle|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151661": {+ "content": "<|fim_suffix|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151662": {+ "content": "<|fim_pad|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151663": {+ "content": "<|repo_name|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151664": {+ "content": "<|file_sep|>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151665": {+ "content": "<tool_response>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151666": {+ "content": "</tool_response>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151667": {+ "content": "<think>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ },+ "151668": {+ "content": "</think>",+ "lstrip": false,+ "normalized": false,+ "rstrip": false,+ "single_word": false,+ "special": false+ }+ },+ "additional_special_tokens": [+ "<|im_start|>",+ "<|im_end|>",+ "<|object_ref_start|>",+ "<|object_ref_end|>",+ "<|box_start|>",+ "<|box_end|>",+ "<|quad_start|>",+ "<|quad_end|>",+ "<|vision_start|>",+ "<|vision_end|>",+ "<|vision_pad|>",+ "<|image_pad|>",+ "<|video_pad|>"+ ],+ "bos_token": null,+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {%- if messages[0].content is string %}\n {{- messages[0].content }}\n {%- else %}\n {%- for content in messages[0].content %}\n {%- if 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].content is string %}\n {{- messages[0].content }}\n {%- else %}\n {%- for content in messages[0].content %}\n {%- if 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- for message in messages %}\n {%- if message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content in message.content %}\n {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}\n <|vision_start|><|image_pad|><|vision_end|>\n {%- elif content.type == 'video' or 'video' in content %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}\n <|vision_start|><|video_pad|><|vision_end|>\n {%- elif 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content_item in message.content %}\n {%- if 'text' in content_item %}\n {{- content_item.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and message.content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {%- if message.content is string %}\n {{- message.content }}\n {%- else %}\n {%- for content in message.content %}\n {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}\n <|vision_start|><|image_pad|><|vision_end|>\n {%- elif content.type == 'video' or 'video' in content %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}\n <|vision_start|><|video_pad|><|vision_end|>\n {%- elif 'text' in content %}\n {{- content.text }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",+ "clean_up_tokenization_spaces": false,+ "eos_token": "<|im_end|>",+ "errors": "replace",+ "model_max_length": 262144,+ "pad_token": "<|endoftext|>",+ "split_special_tokens": false,+ "tokenizer_class": "Qwen2Tokenizer",+ "unk_token": null+}\ No newline at end of filediff --git a/invokeai/backend/util/bundled_tokenizer.py b/invokeai/backend/util/bundled_tokenizer.pynew file mode 100644index 0000000000..94b5e9635c--- /dev/null+++ b/invokeai/backend/util/bundled_tokenizer.py@@ -0,0 +1,57 @@+"""Load a tokenizer from a vendored directory whose large files are stored gzip-compressed.++Two things make this indirection necessary rather than a wrapper around ``from_pretrained``:++- ``.gitattributes`` sets ``* text=auto``, so a raw ``tokenizer.json`` checked into the repository+ is line-ending normalized per platform and no longer matches the bytes upstream published. A+ gzip member is binary and survives that untouched, which is the whole point of vendoring: the+ vocabulary must be exactly the one the weights were trained against.+- ``tokenizer.json`` is the bulk of every vendored tokenizer (7-11MB raw, and the repository keeps+ files at or above 10MB in LFS). Compressed they are ~2MB each.++``from_pretrained`` only reads directories, so the compressed members are expanded into a+temporary directory for the duration of the call. The fast tokenizer parses the vocabulary fully+into memory during construction, so nothing reads those files afterwards.+"""++import gzip+import shutil+import tempfile+from pathlib import Path++from transformers import AutoTokenizer, PreTrainedTokenizerBase++GZIP_SUFFIX = ".gz"++# A tokenizer is only usable if one of these is staged; see `load_gzipped_tokenizer_dir`.+VOCABULARY_MEMBERS = frozenset({"tokenizer.json", "vocab.json", "spiece.model"})+++def load_gzipped_tokenizer_dir(tokenizer_dir: Path, **kwargs: object) -> PreTrainedTokenizerBase:+ """Load the vendored tokenizer in ``tokenizer_dir``, expanding any ``*.gz`` members first.++ Files are staged rather than loaded in place, so the vendored directory is never written to.++ The vocabulary is checked for explicitly rather than left to ``from_pretrained``. A directory+ holding ``tokenizer_config.json`` but no vocabulary is not an error there: it yields a+ tokenizer with a one-token vocabulary that encodes every prompt to an empty sequence, so the+ generation runs on no conditioning with nothing in the log. A wheel whose package-data globs+ missed ``*.json.gz`` produces exactly that directory, and this is where that has to be caught.+ """+ members = sorted(p for p in tokenizer_dir.iterdir() if p.is_file()) if tokenizer_dir.is_dir() else []+ staged_names = {p.stem if p.suffix == GZIP_SUFFIX else p.name for p in members}+ if not VOCABULARY_MEMBERS & staged_names:+ raise FileNotFoundError(+ f"The vendored tokenizer in {tokenizer_dir} is missing its vocabulary "+ f"(expected one of {sorted(VOCABULARY_MEMBERS)}, found {sorted(staged_names) or 'nothing'}). "+ "This InvokeAI installation is incomplete -- reinstall the package."+ )+ with tempfile.TemporaryDirectory() as tmp:+ staged = Path(tmp)+ for member in members:+ if member.suffix == GZIP_SUFFIX:+ with gzip.open(member, "rb") as src, open(staged / member.stem, "wb") as dst:+ shutil.copyfileobj(src, dst)+ else:+ shutil.copyfile(member, staged / member.name)+ return AutoTokenizer.from_pretrained(staged, local_files_only=True, **kwargs)diff --git a/pyproject.toml b/pyproject.tomlindex 7fa4e1aeaa..f47cf69ca3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -310,8 +310,12 @@ version = { attr = "invokeai.version.__version__" }[tool.setuptools.package-data]"invokeai.app.assets" = ["**/*.png"]-"invokeai.backend.anima" = ["tokenizer/*.json"]"invokeai.backend.qwen3" = ["tokenizer/*.json", "tokenizer/*.json.gz"]+"invokeai.backend.qwen3_vl" = ["tokenizer/*.json", "tokenizer/*.json.gz", "config/*.json"]+"invokeai.backend.qwen2_5_vl" = ["*.json", "tokenizer/*.json", "tokenizer/*.json.gz"]+# Read at load time by the MiniMax H3 single-file encoder loader. Without this the file is+# absent from a wheel install and that loader raises FileNotFoundError.+"invokeai.backend.minimax_h3" = ["*.json"]"invokeai.backend.t5" = ["tokenizer/*.json"]"invokeai.app.services.image_index" = ["*.txt"]"invokeai.app.services.workflow_records.default_workflows" = ["*.json"]diff --git a/tests/app/invocations/test_qwen_image_processor_assembly.py b/tests/app/invocations/test_qwen_image_processor_assembly.pynew file mode 100644index 0000000000..030364109c--- /dev/null+++ b/tests/app/invocations/test_qwen_image_processor_assembly.py@@ -0,0 +1,187 @@+"""How the Qwen-Image conditioning node assembles its Qwen2.5-VL processor.++Two things are pinned here: the tokenizer comes from the caller (the model cache) rather than+being re-derived per generation, and every layout ends up with the release's image preprocessor+rather than transformers' class defaults — those cap a reference image at 1,003,520 pixels against+the release's 12,845,056.+"""++import json+from pathlib import Path+from unittest.mock import MagicMock++import pytest++from invokeai.app.invocations.text_encoder.qwen_image_text_encoder import QwenImageTextEncoderInvocation+from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import load_bundled_qwen2_5_vl_preprocessor_config_dict++RELEASE_MAX_PIXELS = 12845056+CLASS_DEFAULT_MAX_PIXELS = 1003520+++def tokenizer(tmp_path_factory):+ """A real (tiny) fast tokenizer: `Qwen2_5_VLProcessor` type-checks what it is handed and reads+ special-token ids off it, so a double would only test the double.+ """+ from transformers import PreTrainedTokenizerFast++ spec = tmp_path_factory.mktemp("tok") / "tokenizer.json"+ spec.write_text(+ json.dumps(+ {+ "version": "1.0",+ "added_tokens": [],+ "normalizer": None,+ "pre_tokenizer": None,+ "post_processor": None,+ "decoder": None,+ "model": {+ "type": "WordLevel",+ "vocab": {"<|image_pad|>": 0, "<|video_pad|>": 1, "a": 2},+ "unk_token": "a",+ },+ }+ ),+ encoding="utf-8",+ )+ return PreTrainedTokenizerFast(tokenizer_file=str(spec))+++def test_the_callers_tokenizer_is_used_rather_than_one_built_here(tmp_path: Path, tokenizer) -> None:+ """The cache bypass this replaced: the node used to re-derive the tokenizer from `model_root`,+ parsing a ~7MB vocabulary per generation into a copy the model cache knew nothing about.+ """+ checkpoint = tmp_path / "qwen_2.5_vl_7b_fp8_scaled.safetensors"+ checkpoint.write_bytes(b"not read here")++ assert QwenImageTextEncoderInvocation._build_processor(tokenizer, checkpoint).tokenizer is tokenizer+++def test_a_single_file_checkpoint_uses_the_bundled_preprocessor(tmp_path: Path, tokenizer) -> None:+ """model_root is the safetensors file itself: no folder beside it to read a config from."""+ checkpoint = tmp_path / "encoder.safetensors"+ checkpoint.write_bytes(b"")++ processor = QwenImageTextEncoderInvocation._build_processor(tokenizer, checkpoint)++ assert processor.image_processor.size.longest_edge == RELEASE_MAX_PIXELS+++def test_a_folder_install_without_a_preprocessor_config_still_gets_the_release_budget(+ tmp_path: Path, tokenizer+) -> None:+ """The last rung used to be a bare constructor, which silently downscaled reference images.++ Reachable for anyone who installed only text_encoder + tokenizer, with no processor folder.+ """+ model_root = tmp_path / "qwen-vl"+ (model_root / "tokenizer").mkdir(parents=True)++ processor = QwenImageTextEncoderInvocation._build_processor(tokenizer, model_root)++ assert processor.image_processor.size.longest_edge == RELEASE_MAX_PIXELS+ assert processor.image_processor.size.longest_edge != CLASS_DEFAULT_MAX_PIXELS+++def test_a_folder_install_prefers_its_own_preprocessor_config(tmp_path: Path, tokenizer) -> None:+ """A complete install keeps deciding for itself; the bundle is a fallback, not an override."""+ model_root = tmp_path / "qwen-vl"+ (model_root / "tokenizer").mkdir(parents=True)+ installed = dict(load_bundled_qwen2_5_vl_preprocessor_config_dict())+ installed["max_pixels"] = 4096 * 4096+ (model_root / "processor").mkdir()+ (model_root / "processor" / "preprocessor_config.json").write_text(json.dumps(installed), encoding="utf-8")++ processor = QwenImageTextEncoderInvocation._build_processor(tokenizer, model_root)++ assert processor.image_processor.size.longest_edge == 4096 * 4096++[email protected]("search_dir", ["processor", "tokenizer", "", "image_processor"])+def test_an_installed_preprocessor_config_is_found_in_every_searched_location(+ tmp_path: Path, tokenizer, search_dir: str+) -> None:+ """Pins the search order's membership: a dropped entry would silently fall back to the bundle+ for installs that do carry their own config.+ """+ model_root = tmp_path / "qwen-vl"+ (model_root / "tokenizer").mkdir(parents=True)+ installed = dict(load_bundled_qwen2_5_vl_preprocessor_config_dict())+ installed["max_pixels"] = 2048 * 2048+ target = model_root / search_dir if search_dir else model_root+ target.mkdir(parents=True, exist_ok=True)+ (target / "preprocessor_config.json").write_text(json.dumps(installed), encoding="utf-8")++ processor = QwenImageTextEncoderInvocation._build_processor(tokenizer, model_root)++ assert processor.image_processor.size.longest_edge == 2048 * 2048+++def test_a_tokenizer_that_cannot_encode_is_refused_whatever_produced_it(tmp_path: Path) -> None:+ """Every tokenizer source converges on `_build_processor`, which is why the probe sits there.++ A `tokenizer/` that lost its vocabulary does not make `from_pretrained` raise; it yields a+ one-token vocabulary that encodes every prompt to an empty sequence. Guarding one loader would+ have left the diffusers main-model route — the one most installs use — silently unprotected.+ """++ class _Degenerate:+ def __call__(self, *_a, **_k):+ return {"input_ids": []}++ checkpoint = tmp_path / "encoder.safetensors"+ checkpoint.write_bytes(b"")++ with pytest.raises(RuntimeError, match="cannot encode anything"):+ QwenImageTextEncoderInvocation._build_processor(_Degenerate(), checkpoint)+++def test_the_node_takes_its_tokenizer_from_the_model_cache(tmp_path: Path, tokenizer, monkeypatch) -> None:+ """The cache bypass this replaced: re-deriving the tokenizer from disk per generation cost a+ ~7MB vocabulary parse and produced a second copy the model cache knew nothing about.++ Asserted on `context.models.load` rather than on timing, so reverting that one line fails here+ instead of quietly restoring the cost.+ """+ import torch++ from invokeai.app.invocations.model import ModelIdentifierField, QwenVLEncoderField+ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType++ encoder = ModelIdentifierField(+ key="enc", hash="h", name="qwen-vl", base=BaseModelType.QwenImage, type=ModelType.QwenVLEncoder+ )+ invocation = QwenImageTextEncoderInvocation(+ prompt="a cat",+ qwen_vl_encoder=QwenVLEncoderField(tokenizer=encoder, text_encoder=encoder),+ quantization="none",+ )++ model_root = tmp_path / "qwen-vl"+ (model_root / "tokenizer").mkdir(parents=True)+ context = MagicMock()+ context.models.get_absolute_path.return_value = model_root+ context.models.load.return_value.model = tokenizer++ seen: dict[str, object] = {}+ monkeypatch.setattr(+ QwenImageTextEncoderInvocation,+ "_build_processor",+ staticmethod(lambda tok, root: seen.update(tokenizer=tok, root=root) or MagicMock()),+ )+ monkeypatch.setattr(+ QwenImageTextEncoderInvocation,+ "_load_cached_encoder",+ lambda _self, _ctx: (torch.nn.Identity(), torch.device("cpu"), lambda: None),+ )+ monkeypatch.setattr(+ QwenImageTextEncoderInvocation,+ "_run_encoder",+ staticmethod(lambda *_a, **_k: (torch.zeros(1, 2, 4), torch.ones(1, 2, dtype=torch.long))),+ )++ invocation._encode(context, images=[])++ context.models.load.assert_called_once_with(invocation.qwen_vl_encoder.tokenizer)+ assert seen["tokenizer"] is tokenizer, "the node built its own tokenizer instead of using the cached one"diff --git a/tests/app/invocations/test_qwen_image_text_encoder.py b/tests/app/invocations/test_qwen_image_text_encoder.pyindex a2791f631f..e9914eea79 100644--- a/tests/app/invocations/test_qwen_image_text_encoder.py+++ b/tests/app/invocations/test_qwen_image_text_encoder.py@@ -639,7 +639,8 @@ class TestQuantizedEncoderRelease:loader,side_effect=lambda _ctx: (handoff.pop(), torch.device("cpu"), cleanup),),- patch("transformers.AutoTokenizer.from_pretrained", return_value=MagicMock()),+ # The node takes its tokenizer from the model cache now, so `context` (a MagicMock)+ # supplies it; nothing here reads one off disk.patch("transformers.Qwen2_5_VLProcessor", return_value=processor),):return invocation._encode(context, images=[])diff --git a/tests/backend/model_manager/load/qwen3vl_gguf_fixture.py b/tests/backend/model_manager/load/qwen3vl_gguf_fixture.pyindex e5c43fd5df..9a978acf0e 100644--- a/tests/backend/model_manager/load/qwen3vl_gguf_fixture.py+++ b/tests/backend/model_manager/load/qwen3vl_gguf_fixture.py@@ -136,7 +136,7 @@ def load_tiny_gguf_encoder(monkeypatch, tmp_path: Path, *, num_hidden_layers: inloader._logger = MagicMock()loader._ram_cache = MagicMock() if ram_cache is None else ram_cache- monkeypatch.setattr(Qwen3VLEncoderGGUFLoader, "_load_hf_config", lambda _self, _config: te_config)+ monkeypatch.setattr(Qwen3VLEncoderGGUFLoader, "_load_te_config", lambda _self, _config: te_config)monkeypatch.setattr("invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",lambda: torch.device("cpu"),diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex 19aff41fba..2c8b894c16 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -262,7 +262,7 @@ def test_checkpoint_encoder_loader_decodes_int8_and_does_not_call_it_fp8(monkeyploader._ram_cache = SimpleNamespace(make_room=MagicMock())loader._torch_device = torch.device("cpu")loader._logger = MagicMock()- loader._load_hf_config = lambda _config: SimpleNamespace()+ loader._load_te_config = lambda _config: SimpleNamespace()loader._apply_fp8_to_nn_module = lambda *a, **k: fp8_calls.append(a)monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)@@ -532,7 +532,7 @@ def test_the_encoder_names_itself_when_refusing_an_unmarked_int8_weight(monkeypaloader._ram_cache = SimpleNamespace(make_room=MagicMock())loader._torch_device = torch.device("cpu")loader._logger = MagicMock()- loader._load_hf_config = lambda _config: SimpleNamespace()+ loader._load_te_config = lambda _config: SimpleNamespace()monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)@@ -605,7 +605,7 @@ def test_a_merged_encoder_checkpoint_is_not_mistaken_for_a_mixed_format_one(loader._ram_cache = SimpleNamespace(make_room=MagicMock())loader._torch_device = torch.device("cpu")loader._logger = MagicMock()- loader._load_hf_config = lambda _config: SimpleNamespace()+ loader._load_te_config = lambda _config: SimpleNamespace()loader._apply_fp8_to_nn_module = lambda *a, **k: Nonemonkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)@@ -624,78 +624,52 @@ def test_a_merged_encoder_checkpoint_is_not_mistaken_for_a_mixed_format_one(assert isinstance(model.language_model.proj, Int8ConvrotLinear)-class _FakeTokenizer:- """Enough of a tokenizer to answer the loader's probe."""+def test_the_tokenizer_comes_from_the_bundle_and_never_the_network(monkeypatch) -> None:+ """The failure this replaces was silent, not loud.- def __init__(self, vocab: dict[str, int]) -> None:- self._vocab = vocab-- def __call__(self, text: str, **_kwargs) -> dict[str, list[int]]:- return {"input_ids": [self._vocab[token] for token in text.split() if token in self._vocab]}---def _tokenizer_loader(monkeypatch, cached: _FakeTokenizer | Exception):- """Stand in for the HuggingFace hub: `cached` is what the local-only attempt produces."""- import invokeai.backend.model_manager.load.model_loaders.krea2 as module-- downloaded = _FakeTokenizer({"probe": 7})- calls: list[bool] = []-- def from_pretrained(_repo: str, *, local_files_only: bool = False, **_kwargs):- calls.append(local_files_only)- if not local_files_only:- return downloaded- if isinstance(cached, Exception):- raise cached- return cached-- monkeypatch.setattr(module, "AutoTokenizer", SimpleNamespace(from_pretrained=from_pretrained))- loader = object.__new__(Qwen3VLEncoderCheckpointLoader)- config = SimpleNamespace(variant=Qwen3VLVariantType.Qwen3VL_4B)- return loader, config, downloaded, calls---def test_a_cached_tokenizer_that_cannot_encode_is_replaced(monkeypatch) -> None:- """The failure this guards is silent, not loud.-- `_load_text_encoder` fetches the repo's `config.json` first, so on a first run the cache holds+ The loader used to fetch the repo's `config.json` first, so on a first run the HF cache heldthe config and none of the tokenizer files. `from_pretrained(..., local_files_only=True)` then- returns a tokenizer with a one-token vocabulary instead of raising, every prompt encodes to an- empty sequence, and the image is generated from no conditioning at all.+ returned a tokenizer with a one-token vocabulary instead of raising, every prompt encoded to an+ empty sequence, and the image was generated from no conditioning at all. Serving the vendored+ copy removes the half-populated state that made it reachable — so the guarantee worth pinning+ is that nothing here consults the hub. What the vendored tokenizer actually encodes is covered+ in `tests/backend/qwen3_vl/test_qwen3_vl_assets.py`."""- empty = _FakeTokenizer({})- loader, config, downloaded, calls = _tokenizer_loader(monkeypatch, empty)-- assert loader._load_tokenizer(config) is downloaded- assert calls == [True, False]---def test_a_usable_cached_tokenizer_is_not_downloaded_again(monkeypatch) -> None:- cached = _FakeTokenizer({"probe": 3})- loader, config, _downloaded, calls = _tokenizer_loader(monkeypatch, cached)-- assert loader._load_tokenizer(config) is cached- assert calls == [True]+ import invokeai.backend.model_manager.load.model_loaders.krea2 as module+ sentinel = object()+ monkeypatch.setattr(module, "load_bundled_qwen3_vl_tokenizer", lambda: sentinel)+ monkeypatch.setattr(+ module,+ "AutoTokenizer",+ SimpleNamespace(+ from_pretrained=lambda *a, **k: pytest.fail("the loader reached HuggingFace for a bundled tokenizer")+ ),+ )-def test_a_missing_cache_falls_back_to_the_download(monkeypatch) -> None:- loader, config, downloaded, calls = _tokenizer_loader(monkeypatch, OSError("not cached"))+ loader = object.__new__(Qwen3VLEncoderCheckpointLoader)+ config = Qwen3VLEncoder_Checkpoint_Config.model_construct(+ path="unused.safetensors", variant=Qwen3VLVariantType.Qwen3VL_4B, name="tiny"+ )- assert loader._load_tokenizer(config) is downloaded- assert calls == [True, False]+ assert loader._load_model(config, SubModelType.Tokenizer) is sentinel-def test_each_qwen3_vl_variant_names_its_own_hugging_face_repo() -> None:+def test_each_qwen3_vl_variant_loads_its_own_bundled_config() -> None:"""The variant's whole purpose: nothing in a single file says which Qwen3-VL it is.- Every other test here stubs `_load_hf_config` out, so a table that mapped both variants to the- 4B repo would leave them all green while Ideogram 4 built a 4B architecture from an 8B+ Every other test here stubs `_load_te_config` out, so a table that mapped both variants to the+ 4B config would leave them all green while the loader built a 4B architecture from an 8Bcheckpoint — the mismatch `_variant_from_hidden_size` exists to prevent, one layer further on."""loader = object.__new__(Qwen3VLEncoderCheckpointLoader)- assert loader._hf_repo(SimpleNamespace(variant=Qwen3VLVariantType.Qwen3VL_4B)) == "Qwen/Qwen3-VL-4B-Instruct"- assert loader._hf_repo(SimpleNamespace(variant=Qwen3VLVariantType.Qwen3VL_8B)) == "Qwen/Qwen3-VL-8B-Instruct"+ widths = {+ variant: loader._load_te_config(SimpleNamespace(variant=variant)).text_config.hidden_size+ for variant in (Qwen3VLVariantType.Qwen3VL_4B, Qwen3VLVariantType.Qwen3VL_8B)+ }++ assert widths == {Qwen3VLVariantType.Qwen3VL_4B: 2560, Qwen3VLVariantType.Qwen3VL_8B: 4096}class _TinyNativeKrea2Block(torch.nn.Module):diff --git a/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py b/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.pyindex eb7b95ec57..c869bd877a 100644--- a/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py+++ b/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py@@ -9,6 +9,7 @@ from unittest.mock import MagicMock, callimport pytestimport torch+import transformers.configuration_utilsimport invokeai.backend.model_manager.load.model_loaders.krea2 as krea2_loadersfrom invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncoder_GGUF_Config@@ -23,7 +24,6 @@ from tests.backend.model_manager.load.qwen3vl_gguf_fixture import (HIDDEN_SIZE,QUANT_TOLERANCE,load_tiny_gguf_encoder,- tiny_qwen3vl_config,)@@ -137,40 +137,35 @@ def test_the_embedding_materialization_is_reserved(monkeypatch, tmp_path) -> Nonassert ram_cache.make_room.call_args_list == [call(expected)]-def test_a_missing_huggingface_config_says_why_a_local_file_needs_one(monkeypatch, tmp_path) -> None:- """A single-file encoder carries no config, so the loader fetches one — and on a cold, offline- machine transformers raises about a repo the user never chose to install. The wrapper has to- name the encoder's own requirement, and must not swallow the offline-cache attempt that makes- the fetch unnecessary in the first place.+def test_the_architecture_config_comes_from_the_bundle_and_never_the_network(monkeypatch, tmp_path) -> None:+ """A single-file encoder carries no config, so the loader supplies one from the vendored copy.++ Asserted through `AutoConfig.from_pretrained`, which used to serve this call: reaching the hub+ here is what an offline or proxied install cannot do, and what a re-upload could change under+ otherwise identical weights."""- te_config = tiny_qwen3vl_config()loader = object.__new__(Qwen3VLEncoderGGUFLoader)config = Qwen3VLEncoder_GGUF_Config.model_construct(path=str(tmp_path / "unused.gguf"), variant=Qwen3VLVariantType.Qwen3VL_4B, name="tiny")- calls: list[bool] = []-- def from_pretrained(repo: str, local_files_only: bool = False):- calls.append(local_files_only)- if local_files_only:- raise OSError("nothing cached")- raise OSError("offline")+ def refuse(*args, **kwargs):+ raise AssertionError("the loader reached HuggingFace for a config it bundles")- monkeypatch.setattr(krea2_loaders.AutoConfig, "from_pretrained", from_pretrained)+ # Patched where a config actually resolves a repo file, not at AutoConfig: the loader builds+ # the config with Qwen3VLConfig.from_dict now, so trapping AutoConfig alone would stay green if+ # someone reintroduced Qwen3VLConfig.from_pretrained (verified by mutating the loader to do+ # exactly that). `cached_file` is the single door every from_pretrained goes through, cache hit+ # included, so this catches a reintroduced fetch even on a machine that has the repo cached.+ monkeypatch.setattr(transformers.configuration_utils, "cached_file", refuse)+ monkeypatch.setattr(krea2_loaders.AutoConfig, "from_pretrained", refuse)- with pytest.raises(RuntimeError, match="Qwen/Qwen3-VL-4B-Instruct"):- loader._load_hf_config(config)+ text_config = loader._load_te_config(config).text_config- # The offline attempt comes first; only the network one is wrapped.- assert calls == [True, False]-- calls.clear()- monkeypatch.setattr(- krea2_loaders.AutoConfig,- "from_pretrained",- lambda repo, local_files_only=False: calls.append(local_files_only) or te_config,- )+ # The constants that decide the module tree the weights are folded into. rope_theta in+ # particular: 1e6 instead of Qwen3-VL's 5e6 costs relative L2 0.1008 against identical weights.+ # Read through both spellings because transformers 5.x folds the scalar into rope_parameters.+ rope_theta = getattr(text_config, "rope_theta", None) or text_config.rope_parameters["rope_theta"]- assert loader._load_hf_config(config) is te_config- assert calls == [True]+ assert rope_theta == 5000000+ assert text_config.hidden_size == 2560diff --git a/tests/backend/qwen2_5_vl/test_qwen2_5_vl_assets.py b/tests/backend/qwen2_5_vl/test_qwen2_5_vl_assets.pynew file mode 100644index 0000000000..bb88e73689--- /dev/null+++ b/tests/backend/qwen2_5_vl/test_qwen2_5_vl_assets.py@@ -0,0 +1,59 @@+"""Tests for the vendored Qwen2.5-VL architecture and preprocessor configs.++Single-file Qwen2.5-VL encoder checkpoints carry weights only. These two files are what the+loader and the conditioning node used to fetch from the hub at run time.+"""++from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (+ load_bundled_qwen2_5_vl_config_dict,+ load_bundled_qwen2_5_vl_preprocessor_config_dict,+)+++def test_bundled_config_carries_the_released_architecture() -> None:+ """The constants that decide the module tree the single-file weights are folded into."""+ config = load_bundled_qwen2_5_vl_config_dict()++ assert config["hidden_size"] == 3584+ assert config["num_hidden_layers"] == 28+ assert config["rope_theta"] == 1000000.0+ assert config["vision_config"]["out_hidden_size"] == 3584+++def test_bundled_preprocessor_config_carries_the_released_pixel_budget() -> None:+ """The previous last-resort rung built a bare ``Qwen2VLImageProcessor()``, whose class defaults+ omit these, so an offline run resized reference images differently with nothing in the log.+ """+ preprocessor = load_bundled_qwen2_5_vl_preprocessor_config_dict()++ assert preprocessor["min_pixels"] == 3136+ assert preprocessor["max_pixels"] == 12845056+ assert preprocessor["patch_size"] == 14+ assert preprocessor["merge_size"] == 2+++def test_building_an_image_processor_from_the_bundle_keeps_the_release_pixel_budget() -> None:+ """What the conditioning node now builds, in the units that actually bite.++ transformers' own class default caps a reference image at 1,003,520 pixels, so the node's old+ last-resort rung — a bare ``Qwen2VLImageProcessor()`` when the hub was unreachable — downscaled+ every reference image by ~3.6x per side before the visual tower saw it, with nothing in the log+ to say so. Not asserted against a freshly constructed processor on purpose: ``from_dict``+ rewrites that class-level default in place, so such a comparison would pass or fail on test+ ordering rather than on this bundle.+ """+ from transformers.models.qwen2_vl.image_processing_qwen2_vl import Qwen2VLImageProcessor++ processor = Qwen2VLImageProcessor.from_dict(load_bundled_qwen2_5_vl_preprocessor_config_dict())++ assert processor.size.longest_edge == 12845056+ assert processor.size.shortest_edge == 3136+ assert processor.patch_size == 14+ assert processor.merge_size == 2+++def test_config_dicts_are_not_shared_between_callers() -> None:+ """The loader sets ``torch_dtype`` on what it builds from this dict."""+ load_bundled_qwen2_5_vl_config_dict()["hidden_size"] = 1++ assert load_bundled_qwen2_5_vl_config_dict()["hidden_size"] == 3584diff --git a/tests/backend/qwen2_5_vl/test_qwen2_5_vl_tokenizer.py b/tests/backend/qwen2_5_vl/test_qwen2_5_vl_tokenizer.pynew file mode 100644index 0000000000..a719f9f9b3--- /dev/null+++ b/tests/backend/qwen2_5_vl/test_qwen2_5_vl_tokenizer.py@@ -0,0 +1,132 @@+"""Tests for the vendored Qwen2.5-VL tokenizer and the probe that guards local installs.++Single-file Qwen2.5-VL encoders ship weights only, so the tokenizer is vendored and no longer+fetched. The probe stays because the same silent failure is reachable from a folder-layout install+whose ``tokenizer/`` lost its vocabulary — vendoring cannot repair somebody else's install.+"""++import json+from pathlib import Path++from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (+ load_bundled_qwen2_5_vl_tokenizer,+ tokenizer_can_encode,+)++# Qwen2.5-VL's vocabulary. Token ids stay below this.+QWEN2_5_VL_VOCAB_SIZE = 152064+++def test_bundled_tokenizer_known_ids() -> None:+ """Pinned ids, not just "non-empty": a wrong-but-working vocabulary encodes fine and conditions+ off-distribution. These are what ``Qwen/Qwen2.5-VL-7B-Instruct`` produces for this prompt.+ """+ tokenizer = load_bundled_qwen2_5_vl_tokenizer()++ assert tokenizer("A cinematic photo of a cat").input_ids == [32, 64665, 6548, 315, 264, 8251]+++def test_bundled_tokenizer_roundtrip() -> None:+ tokenizer = load_bundled_qwen2_5_vl_tokenizer()+ prompt = "A cinematic photo of a cat"++ assert tokenizer.decode(tokenizer(prompt).input_ids) == prompt+++def test_bundled_tokenizer_encodes_a_rare_prompt_within_the_vocabulary() -> None:+ ids = load_bundled_qwen2_5_vl_tokenizer()("a rare one: zxqwv 12345").input_ids++ assert ids+ assert all(0 <= i < QWEN2_5_VL_VOCAB_SIZE for i in ids)+++def test_bundled_tokenizer_carries_the_vision_special_tokens() -> None:+ """The conditioning splices one vision placeholder per reference image. A tokenizer that+ shattered those markers into ordinary BPE pieces would still encode, just wrongly.+ """+ tokenizer = load_bundled_qwen2_5_vl_tokenizer()++ for marker in ("<|vision_start|>", "<|vision_end|>", "<|image_pad|>"):+ assert len(tokenizer(marker, add_special_tokens=False).input_ids) == 1+++def test_bundled_tokenizer_is_cached() -> None:+ """Rebuilt per call this would parse a ~7MB vocabulary on every generation."""+ assert load_bundled_qwen2_5_vl_tokenizer() is load_bundled_qwen2_5_vl_tokenizer()+++def test_the_probe_rejects_a_one_token_vocabulary() -> None:+ """The exact shape a vocabulary-less directory produces: it encodes, but to nothing."""++ class _Degenerate:+ def __call__(self, *_a, **_k):+ return {"input_ids": []}++ assert not tokenizer_can_encode(_Degenerate())+++def test_the_probe_accepts_the_bundled_tokenizer() -> None:+ assert tokenizer_can_encode(load_bundled_qwen2_5_vl_tokenizer())+++def test_the_probe_treats_a_raising_tokenizer_as_unusable() -> None:+ class _Broken:+ def __call__(self, *_a, **_k):+ raise TypeError("slow tokenizer path with no vocab files")++ assert not tokenizer_can_encode(_Broken())+++def test_the_probe_rejects_what_transformers_returns_for_a_vocabulary_less_directory(tmp_path: Path) -> None:+ """Not a hypothetical: an interrupted model install leaves exactly this on disk, and+ ``from_pretrained`` loads it without complaint.+ """+ from transformers import AutoTokenizer++ (tmp_path / "tokenizer_config.json").write_text(json.dumps({"tokenizer_class": "Qwen2Tokenizer"}), encoding="utf-8")++ degenerate = AutoTokenizer.from_pretrained(str(tmp_path), local_files_only=True)++ assert degenerate("a photo of a cat").input_ids == []+ assert not tokenizer_can_encode(degenerate)+++def test_the_diffusers_main_loader_serves_a_usable_tokenizer(tmp_path: Path) -> None:+ """A path this change made live.++ The conditioning node used to build the tokenizer itself, so for a Diffusers Qwen-Image main+ model the ``Tokenizer`` submodel had never actually been loaded through the cache. Now it is,+ via ``get_hf_load_class`` with ``dtype``/``variant`` kwargs that a tokenizer does not expect —+ harmless on the pinned transformers, and this is what says so out loud.+ """+ import gzip+ import shutil++ from invokeai.backend.model_manager.configs.main import Main_Diffusers_QwenImage_Config+ from invokeai.backend.model_manager.load.model_loaders.qwen_image import QwenImageDiffusersModel+ from invokeai.backend.model_manager.taxonomy import SubModelType+ from invokeai.backend.qwen2_5_vl import qwen2_5_vl_assets++ # Stage the vendored tokenizer as a diffusers folder install would carry it.+ vendored = Path(qwen2_5_vl_assets.__file__).parent / "tokenizer"+ tokenizer_dir = tmp_path / "tokenizer"+ tokenizer_dir.mkdir()+ with gzip.open(vendored / "tokenizer.json.gz", "rb") as src, open(tokenizer_dir / "tokenizer.json", "wb") as dst:+ shutil.copyfileobj(src, dst)+ shutil.copyfile(vendored / "tokenizer_config.json", tokenizer_dir / "tokenizer_config.json")++ # What `get_hf_load_class` reads to decide which class serves this submodel, as a real+ # diffusers Qwen-Image install carries it.+ (tmp_path / "model_index.json").write_text(+ json.dumps({"_class_name": "QwenImagePipeline", "tokenizer": ["transformers", "Qwen2Tokenizer"]}),+ encoding="utf-8",+ )++ loader = object.__new__(QwenImageDiffusersModel)+ config = Main_Diffusers_QwenImage_Config.model_construct(path=str(tmp_path), name="qwen-image", repo_variant=None)++ tokenizer = loader._load_model(config, SubModelType.Tokenizer)++ assert tokenizer.is_fast+ assert tokenizer("A cinematic photo of a cat").input_ids == [32, 64665, 6548, 315, 264, 8251]+ assert tokenizer_can_encode(tokenizer)diff --git a/tests/backend/qwen3/test_qwen3_tokenizer.py b/tests/backend/qwen3/test_qwen3_tokenizer.pyindex e24c7282cb..a128676fdf 100644--- a/tests/backend/qwen3/test_qwen3_tokenizer.py+++ b/tests/backend/qwen3/test_qwen3_tokenizer.py@@ -53,3 +53,15 @@ def test_bundled_tokenizer_has_chat_template() -> None:enable_thinking=True,)assert "<|im_start|>" in formatted+++def test_bundled_tokenizer_exposes_the_full_special_token_set() -> None:+ """The vendored tokenizer_config once carried an `extra_special_tokens: {}` that upstream does+ not have -- an artefact of the save_pretrained round trip that produced the bundle. It left+ only <|im_end|> and <|endoftext|> marked special where Qwen/Qwen3-4B marks fourteen. Prompt ids+ were unaffected, but the bundle is only worth having if it matches what it claims to mirror.+ """+ special = set(load_bundled_qwen3_tokenizer().all_special_tokens)++ assert {"<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>"} <= special+ assert len(special) == 14diff --git a/tests/backend/qwen3_vl/test_qwen3_vl_assets.py b/tests/backend/qwen3_vl/test_qwen3_vl_assets.pynew file mode 100644index 0000000000..26ba611d0b--- /dev/null+++ b/tests/backend/qwen3_vl/test_qwen3_vl_assets.py@@ -0,0 +1,122 @@+"""Tests for the vendored Qwen3-VL tokenizer and architecture configs.++Single-file and GGUF Qwen3-VL encoders ship weights only. The tokenizer and config are vendored in+the package so those encoders work offline, and so a hub re-upload cannot change the architecture+constants the weights are folded into.+"""++import json++import pytest++from invokeai.backend.model_manager.taxonomy import Qwen3VLVariantType+from invokeai.backend.qwen3_vl.qwen3_vl_assets import (+ _CONFIG_BY_VARIANT,+ load_bundled_qwen3_vl_config_dict,+ load_bundled_qwen3_vl_tokenizer,+)++# Qwen3-VL's text vocabulary. Token ids stay below this; the visual tower's special tokens are+# inside it, not beyond it.+QWEN3_VL_VOCAB_SIZE = 151936+++def test_bundled_tokenizer_known_ids() -> None:+ """Pinned ids, not just "non-empty": a wrong-but-working vocabulary encodes fine and conditions+ off-distribution. These are what ``Qwen/Qwen3-VL-8B-Instruct`` produces for this prompt.+ """+ tokenizer = load_bundled_qwen3_vl_tokenizer()++ assert tokenizer("A cinematic photo of a cat").input_ids == [32, 64665, 6548, 315, 264, 8251]+++def test_bundled_tokenizer_roundtrip() -> None:+ tokenizer = load_bundled_qwen3_vl_tokenizer()+ prompt = "A cinematic photo of a cat"++ assert tokenizer.decode(tokenizer(prompt).input_ids) == prompt+++def test_bundled_tokenizer_encodes_a_rare_prompt_within_the_vocabulary() -> None:+ ids = load_bundled_qwen3_vl_tokenizer()("a rare one: zxqwv 12345 <|vision_start|>").input_ids++ assert ids+ assert all(0 <= i < QWEN3_VL_VOCAB_SIZE for i in ids)+++def test_bundled_tokenizer_carries_the_vision_special_tokens() -> None:+ """Krea-2's conditioning splices the vision markers as single ids. A tokenizer that shattered+ them into ordinary BPE pieces would still encode every prompt, just wrongly.+ """+ tokenizer = load_bundled_qwen3_vl_tokenizer()++ for marker in ("<|vision_start|>", "<|vision_end|>", "<|image_pad|>"):+ assert len(tokenizer(marker, add_special_tokens=False).input_ids) == 1+++def test_bundled_tokenizer_has_chat_template() -> None:+ assert load_bundled_qwen3_vl_tokenizer().chat_template+++def test_bundled_tokenizer_is_cached() -> None:+ assert load_bundled_qwen3_vl_tokenizer() is load_bundled_qwen3_vl_tokenizer()+++ ("variant", "hidden_size", "num_hidden_layers"),+ [+ (Qwen3VLVariantType.Qwen3VL_4B, 2560, 36),+ (Qwen3VLVariantType.Qwen3VL_8B, 4096, 36),+ ],+)+def test_bundled_config_carries_the_released_architecture(+ variant: Qwen3VLVariantType, hidden_size: int, num_hidden_layers: int+) -> None:+ """The constants a single-file checkpoint cannot supply.++ ``rope_theta`` is the sharpest of them: 1e6 rather than Qwen3-VL's 5e6 costs relative L2 0.1008+ against otherwise identical weights — as much as a full Q4 quantization, and just as silent.+ """+ text_config = load_bundled_qwen3_vl_config_dict(variant)["text_config"]++ assert text_config["hidden_size"] == hidden_size+ assert text_config["num_hidden_layers"] == num_hidden_layers+ assert text_config["rope_theta"] == 5000000+++def test_every_variant_has_a_bundled_config() -> None:+ """A new variant must arrive with its config, not discover at load time that it has none."""+ assert set(_CONFIG_BY_VARIANT) == set(Qwen3VLVariantType)+++def test_bundled_configs_are_distinct_per_variant() -> None:+ """Guards the mapping itself: pointing both variants at one file would build a 4B architecture+ from an 8B checkpoint, which only fails much later as a shape mismatch.+ """+ configs = [json.dumps(load_bundled_qwen3_vl_config_dict(v), sort_keys=True) for v in Qwen3VLVariantType]++ assert len(set(configs)) == len(configs)+++def test_bundled_config_is_not_pre_normalized() -> None:+ """Normalization belongs in the load path, which tracks the installed transformers; freezing+ the mirrored ``rope_scaling`` into the vendored file would pin today's transformers instead.+ """+ for variant in Qwen3VLVariantType:+ assert "rope_parameters" not in load_bundled_qwen3_vl_config_dict(variant)["text_config"]+++def test_config_dicts_are_not_shared_between_callers() -> None:+ """Callers mutate what they get (layer counts, dtype, tied embeddings) before building a config."""+ first = load_bundled_qwen3_vl_config_dict(Qwen3VLVariantType.Qwen3VL_4B)+ first["text_config"]["num_hidden_layers"] = 1++ assert load_bundled_qwen3_vl_config_dict(Qwen3VLVariantType.Qwen3VL_4B)["text_config"]["num_hidden_layers"] == 36+++def test_an_unregistered_variant_is_refused_by_name() -> None:+ class _Unknown:+ value = "qwen3vl_99b"++ with pytest.raises(NotImplementedError, match="qwen3vl_99b"):+ load_bundled_qwen3_vl_config_dict(_Unknown()) # type: ignore[arg-type]diff --git a/tests/backend/util/test_bundled_tokenizer.py b/tests/backend/util/test_bundled_tokenizer.pynew file mode 100644index 0000000000..e41d93c081--- /dev/null+++ b/tests/backend/util/test_bundled_tokenizer.py@@ -0,0 +1,96 @@+"""Tests for the shared loader behind every vendored tokenizer in the package."""++import gzip+import json+from pathlib import Path++import pytest++from invokeai.backend.util.bundled_tokenizer import load_gzipped_tokenizer_dir+++def _vendor(directory: Path, *, gzipped: bool = True, with_vocabulary: bool = True) -> Path:+ """Stage a minimal but real fast-tokenizer directory, the way the package ships one."""+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "tokenizer_config.json").write_text(+ json.dumps({"tokenizer_class": "PreTrainedTokenizerFast", "model_max_length": 8}),+ encoding="utf-8",+ )+ if not with_vocabulary:+ return directory++ vocabulary = {"a": 0, "b": 1, "ab": 2}+ payload = json.dumps(+ {+ "version": "1.0",+ "added_tokens": [],+ "normalizer": None,+ "pre_tokenizer": None,+ "post_processor": None,+ "decoder": None,+ "model": {"type": "WordLevel", "vocab": vocabulary, "unk_token": "a"},+ }+ ).encode("utf-8")++ if gzipped:+ with gzip.open(directory / "tokenizer.json.gz", "wb") as fh:+ fh.write(payload)+ else:+ (directory / "tokenizer.json").write_bytes(payload)+ return directory+++def test_a_gzipped_vocabulary_is_expanded_and_loaded(tmp_path: Path) -> None:+ tokenizer = load_gzipped_tokenizer_dir(_vendor(tmp_path / "gz"))++ assert tokenizer("ab").input_ids == [2]+++def test_plain_and_gzipped_members_are_staged_together(tmp_path: Path) -> None:+ """tokenizer_config.json ships uncompressed beside a gzipped vocabulary; both must arrive."""+ tokenizer = load_gzipped_tokenizer_dir(_vendor(tmp_path / "mixed"))++ assert tokenizer.model_max_length == 8+++def test_an_uncompressed_vocabulary_is_also_accepted(tmp_path: Path) -> None:+ """The t5 bundle ships its vocabulary uncompressed; the helper must not require gzip."""+ tokenizer = load_gzipped_tokenizer_dir(_vendor(tmp_path / "plain", gzipped=False))++ assert tokenizer("ab").input_ids == [2]+++def test_kwargs_reach_from_pretrained(tmp_path: Path) -> None:+ """The Qwen3-VL bundle passes extra_special_tokens={} to keep parity with its old hub call."""+ tokenizer = load_gzipped_tokenizer_dir(_vendor(tmp_path / "kw"), model_max_length=3)++ assert tokenizer.model_max_length == 3+++def test_a_vendored_directory_without_its_vocabulary_is_refused_by_name(tmp_path: Path) -> None:+ """The silent failure this guard exists for.++ A wheel whose package-data globs matched ``tokenizer/*.json`` but not ``*.json.gz`` ships+ exactly this directory. transformers does not treat it as an error: it hands back a tokenizer+ with a one-token vocabulary that encodes every prompt to an empty sequence, so generation runs+ on no conditioning with nothing in the log. The load has to stop here instead.+ """+ incomplete = _vendor(tmp_path / "incomplete", with_vocabulary=False)++ with pytest.raises(FileNotFoundError, match="missing its vocabulary"):+ load_gzipped_tokenizer_dir(incomplete)+++def test_a_missing_directory_is_refused_rather_than_raising_from_iterdir(tmp_path: Path) -> None:+ with pytest.raises(FileNotFoundError, match="missing its vocabulary"):+ load_gzipped_tokenizer_dir(tmp_path / "absent")+++def test_the_vendored_directory_is_not_written_to(tmp_path: Path) -> None:+ """Staging, not expanding in place: the package directory is read-only in most installs."""+ vendored = _vendor(tmp_path / "readonly")+ before = sorted(p.name for p in vendored.iterdir())++ load_gzipped_tokenizer_dir(vendored)++ assert sorted(p.name for p in vendored.iterdir()) == beforediff --git a/tests/backend/z_image/test_qwen3_sdnq_loader.py b/tests/backend/z_image/test_qwen3_sdnq_loader.pynew file mode 100644index 0000000000..635801c1ea--- /dev/null+++ b/tests/backend/z_image/test_qwen3_sdnq_loader.py@@ -0,0 +1,51 @@+"""The SDNQ Qwen3 encoder's tokenizer wiring.++SDNQ exports carry packed weights only. This loader used to fetch ``Qwen/Qwen3-4B`` at load time+while the two sibling Qwen3 encoder loaders in the same module already served the vendored copy —+the drift this test exists to stop recurring.+"""++from types import SimpleNamespace++import pytest++import invokeai.backend.model_manager.load.model_loaders.z_image as z_image_loaders+from invokeai.backend.model_manager.load.model_loaders.z_image import Qwen3EncoderSDNQLoader+from invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizer+++def _config():+ from invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_SDNQ_Config++ return Qwen3Encoder_SDNQ_Config.model_construct(path="unused.safetensors", name="sdnq")+++def test_the_tokenizer_comes_from_the_bundle_and_never_the_network(monkeypatch) -> None:+ loader = object.__new__(Qwen3EncoderSDNQLoader)+ monkeypatch.setattr(+ z_image_loaders,+ "AutoTokenizer",+ SimpleNamespace(+ from_pretrained=lambda *a, **k: pytest.fail("the SDNQ loader reached HuggingFace for a bundled tokenizer")+ ),+ raising=False,+ )++ assert loader._load_model(_config(), SubModelType.Tokenizer) is load_bundled_qwen3_tokenizer()+++def test_the_served_tokenizer_encodes_a_prompt() -> None:+ """Guards the wiring end to end: a tokenizer that returns an empty sequence would otherwise+ produce an image generated from no conditioning, with nothing in the log.+ """+ loader = object.__new__(Qwen3EncoderSDNQLoader)++ assert loader._load_model(_config(), SubModelType.Tokenizer)("A cinematic photo of a cat").input_ids+++def test_an_unsupported_submodel_is_refused_by_name() -> None:+ loader = object.__new__(Qwen3EncoderSDNQLoader)++ with pytest.raises(ValueError, match="Only TextEncoder and Tokenizer"):+ loader._load_model(_config(), SubModelType.VAE)