Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(mm): identify Qwen2.5/Qwen3 causal LMs as Text LLM, not Qwen3 encoder (#9097)
Alexander Eichhornd50c898a7c1d
diff --git a/invokeai/app/services/model_records/model_records_sql.py b/invokeai/app/services/model_records/model_records_sql.pyindex f104c3855e..3452ba4431 100644--- a/invokeai/app/services/model_records/model_records_sql.py+++ b/invokeai/app/services/model_records/model_records_sql.py@@ -47,6 +47,7 @@ from pathlib import Pathfrom typing import List, Optional, Unionimport pydantic+from pydantic import ValidationErrorfrom invokeai.app.services.model_records.model_records_base import (DuplicateModelException,@@ -59,10 +60,35 @@ from invokeai.app.services.model_records.model_records_base import (from invokeai.app.services.shared.pagination import PaginatedResultsfrom invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirectionfrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.backend.model_manager.configs.base import Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactoryfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType+def _construct_config_for_type(fields: dict, target_type: ModelType) -> AnyModelConfig:+ """Try every config class whose `type` default matches `target_type` and return the first that validates.++ Used when changing a model's type via the update endpoint: the existing record's `format`/`variant`+ fields belong to the old class and may not have a discriminator match in the new type space, so we+ fall back to constructing each candidate class directly with whatever fields it accepts.+ """+ last_error: Exception | None = None+ for candidate_class in Config_Base.CONFIG_CLASSES:+ type_field = candidate_class.model_fields.get("type")+ if type_field is None or type_field.default != target_type:+ continue+ try:+ return candidate_class(**fields) # type: ignore[return-value]+ except ValidationError as e:+ last_error = e+ if last_error is not None:+ raise last_error+ raise ValidationError.from_exception_data(+ f"No model config class found for type={target_type!r}",+ line_errors=[],+ )++class ModelRecordServiceSQL(ModelRecordServiceBase):"""Implementation of the ModelConfigStore ABC using a SQL database."""@@ -154,8 +180,24 @@ class ModelRecordServiceSQL(ModelRecordServiceBase):for field_name in changes.model_fields_set:record_as_dict[field_name] = getattr(changes, field_name)- # 3. Attempt to create a new model config from the updated dict- record = ModelConfigFactory.from_dict(record_as_dict)+ # 3. Attempt to create a new model config from the updated dict.+ #+ # When the model type is being changed, the previous record's `format` and `variant` likely+ # belong to the old config class and won't validate against the new one (e.g. switching a+ # Qwen3 encoder to a Text LLM keeps format=qwen3_encoder, which has no matching discriminator+ # under text_llm). If the initial validation fails and the type changed, retry with stale+ # format/variant fields stripped so the new class can apply its own defaults.+ type_changed = "type" in changes.model_fields_set and changes.type != record.type+ try:+ record = ModelConfigFactory.from_dict(record_as_dict)+ except ValidationError:+ if not type_changed:+ raise+ fallback_dict = dict(record_as_dict)+ for stale_field in ("format", "variant"):+ if stale_field not in changes.model_fields_set:+ fallback_dict.pop(stale_field, None)+ record = _construct_config_for_type(fallback_dict, changes.type)# If we get this far, the updated model config is valid, so we can save it to the database.json_serialized = record.model_dump_json()diff --git a/invokeai/backend/model_manager/configs/qwen3_encoder.py b/invokeai/backend/model_manager/configs/qwen3_encoder.pyindex 82cf3b62c8..308539aa35 100644--- a/invokeai/backend/model_manager/configs/qwen3_encoder.py+++ b/invokeai/backend/model_manager/configs/qwen3_encoder.py@@ -186,6 +186,14 @@ class Qwen3Encoder_Qwen3Encoder_Config(Config_Base):if config_path_nested.exists():expected_config_path = config_path_nestedelif config_path_direct.exists():+ # Standalone text_encoder downloads do not bundle tokenizer files. If we see tokenizer files at the+ # root next to config.json, this is a complete causal LM (TextLLM), not a Qwen3 encoder subfolder.+ tokenizer_files = ("tokenizer.json", "tokenizer.model", "tokenizer_config.json")+ if any((mod.path / f).exists() for f in tokenizer_files):+ raise NotAMatchError(+ "directory looks like a complete causal LM (config.json and tokenizer files at root), "+ "not a standalone Qwen3 encoder"+ )expected_config_path = config_path_directelse:raise NotAMatchError(diff --git a/invokeai/backend/model_manager/starter_models.py b/invokeai/backend/model_manager/starter_models.pyindex be8b9f7399..289d72e4a3 100644--- a/invokeai/backend/model_manager/starter_models.py+++ b/invokeai/backend/model_manager/starter_models.py@@ -819,14 +819,48 @@ flux_redux = StarterModel()# endregion-# region LlavaOnevisionModel+# region LlavaOnevisionModel (vision-language models for Image-to-Prompt)llava_onevision = StarterModel(name="LLaVA Onevision Qwen2 0.5B",base=BaseModelType.Any,source="llava-hf/llava-onevision-qwen2-0.5b-ov-hf",- description="LLaVA Onevision VLLM model",+ description="LLaVA Onevision vision-language model (~1 GB). Lightweight default for the Image-to-Prompt feature.",type=ModelType.LlavaOnevision,)++llava_onevision_7b = StarterModel(+ name="LLaVA Onevision Qwen2 7B",+ base=BaseModelType.Any,+ source="llava-hf/llava-onevision-qwen2-7b-ov-hf",+ description="LLaVA Onevision 7B vision-language model. Larger, higher-quality alternative for Image-to-Prompt. (~16 GB)",+ type=ModelType.LlavaOnevision,+)+# endregion++# region TextLLM (causal language models for Prompt Expansion)+qwen2_5_1_5b_instruct = StarterModel(+ name="Qwen2.5-1.5B-Instruct",+ base=BaseModelType.Any,+ source="Qwen/Qwen2.5-1.5B-Instruct",+ description="Qwen2.5 1.5B instruction-tuned LLM. Recommended default for the Prompt Expansion feature — small and fast. (~3 GB)",+ type=ModelType.TextLLM,+)++qwen2_5_3b_instruct = StarterModel(+ name="Qwen2.5-3B-Instruct",+ base=BaseModelType.Any,+ source="Qwen/Qwen2.5-3B-Instruct",+ description="Qwen2.5 3B instruction-tuned LLM. Better prompt expansion quality at the cost of more VRAM. (~6 GB)",+ type=ModelType.TextLLM,+)++smollm2_1_7b_instruct = StarterModel(+ name="SmolLM2-1.7B-Instruct",+ base=BaseModelType.Any,+ source="HuggingFaceTB/SmolLM2-1.7B-Instruct",+ description="SmolLM2 1.7B instruction-tuned LLM (Apache-2.0). Alternative to Qwen for prompt expansion. (~3 GB)",+ type=ModelType.TextLLM,+)# endregion# region FLUX Fill@@ -1333,6 +1367,10 @@ STARTER_MODELS: list[StarterModel] = [siglip,flux_redux,llava_onevision,+ llava_onevision_7b,+ qwen2_5_1_5b_instruct,+ qwen2_5_3b_instruct,+ smollm2_1_7b_instruct,flux_fill,flux2_vae,flux2_klein_4b,diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex 035b1ddd89..243c5de32c 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -387,7 +387,12 @@"expandPromptWithLLM": "Expand Prompt with LLM","expandPrompt": "Expand Prompt","selectTextLLM": "Select Text LLM...",- "expand": "Expand"+ "expand": "Expand",+ "noTextLLMInstalledTitle": "No Text LLM installed",+ "noTextLLMInstalledDescription": "Prompt expansion needs a Text LLM (causal language model). We recommend Qwen2.5-1.5B-Instruct (~3 GB) — small, fast, and available as a starter model.",+ "noVisionModelInstalledTitle": "No vision model installed",+ "noVisionModelInstalledDescription": "Image-to-prompt needs a vision-language model (e.g. LLaVA Onevision). The 0.5B starter (~1 GB) is the lightweight default.",+ "openModelManager": "Open Model Manager"},"queue": {"queue": "Queue",diff --git a/invokeai/frontend/web/src/features/prompt/ExpandPromptButton.tsx b/invokeai/frontend/web/src/features/prompt/ExpandPromptButton.tsxindex a5cf73cd56..e0f035963a 100644--- a/invokeai/frontend/web/src/features/prompt/ExpandPromptButton.tsx+++ b/invokeai/frontend/web/src/features/prompt/ExpandPromptButton.tsx@@ -16,8 +16,10 @@ import {import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';import { useDisclosure } from 'common/hooks/useBoolean';import { positivePromptChanged, selectPositivePrompt } from 'features/controlLayers/store/paramsSlice';+import { setInstallModelsTabByName } from 'features/modelManagerV2/store/installModelsStore';import { ModelPicker } from 'features/parameters/components/ModelPicker';import { setPromptUndo } from 'features/prompt/promptUndo';+import { navigationApi } from 'features/ui/layouts/navigation-api';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { PiSparkleBold } from 'react-icons/pi';@@ -38,6 +40,8 @@ export const ExpandPromptButton = memo(() => {const [selectedModel, setSelectedModel] = useState<AnyModelConfig | undefined>(undefined);const [expandPrompt, { isLoading }] = useExpandPromptMutation();+ const hasModels = modelConfigs.length > 0;+const handleModelChange = useCallback((model: AnyModelConfig) => {setSelectedModel(model);}, []);@@ -61,10 +65,11 @@ export const ExpandPromptButton = memo(() => {}}, [selectedModel, prompt, expandPrompt, dispatch, popover]);- // Don't render if no TextLLM models are installed- if (modelConfigs.length === 0) {- return null;- }+ const handleOpenModelManager = useCallback(() => {+ popover.close();+ navigationApi.switchToTab('models');+ setInstallModelsTabByName('starterModels');+ }, [popover]);return (<Popover@@ -77,14 +82,14 @@ export const ExpandPromptButton = memo(() => {><PopoverTrigger><span>- <Tooltip label={t('prompt.expandPromptWithLLM')}>+ <Tooltip label={hasModels ? t('prompt.expandPromptWithLLM') : t('prompt.noTextLLMInstalledTitle')}><IconButtonsize="sm"variant="promptOverlay"aria-label={t('prompt.expandPromptWithLLM')}icon={<PiSparkleBold />}sx={isLoading ? loadingStyles : undefined}- isDisabled={isLoading || !prompt.trim()}+ isDisabled={isLoading || (hasModels && !prompt.trim())}/></Tooltip></span>@@ -93,27 +98,41 @@ export const ExpandPromptButton = memo(() => {<PopoverContent p={3} w={350}><PopoverArrow /><PopoverBody p={0}>- <Flex flexDir="column" gap={3}>- <Text fontWeight="semibold" fontSize="sm">- {t('prompt.expandPrompt')}- </Text>- <ModelPicker- pickerId="expand-prompt-model"- modelConfigs={modelConfigs}- selectedModelConfig={selectedModel}- onChange={handleModelChange}- placeholder={t('prompt.selectTextLLM')}- />- <Button- size="sm"- colorScheme="invokeBlue"- onClick={handleExpand}- isLoading={isLoading}- isDisabled={!selectedModel || !prompt.trim()}- >- {t('prompt.expand')}- </Button>- </Flex>+ {hasModels ? (+ <Flex flexDir="column" gap={3}>+ <Text fontWeight="semibold" fontSize="sm">+ {t('prompt.expandPrompt')}+ </Text>+ <ModelPicker+ pickerId="expand-prompt-model"+ modelConfigs={modelConfigs}+ selectedModelConfig={selectedModel}+ onChange={handleModelChange}+ placeholder={t('prompt.selectTextLLM')}+ />+ <Button+ size="sm"+ colorScheme="invokeBlue"+ onClick={handleExpand}+ isLoading={isLoading}+ isDisabled={!selectedModel || !prompt.trim()}+ >+ {t('prompt.expand')}+ </Button>+ </Flex>+ ) : (+ <Flex flexDir="column" gap={3}>+ <Text fontWeight="semibold" fontSize="sm">+ {t('prompt.noTextLLMInstalledTitle')}+ </Text>+ <Text fontSize="sm" color="base.300">+ {t('prompt.noTextLLMInstalledDescription')}+ </Text>+ <Button size="sm" colorScheme="invokeBlue" onClick={handleOpenModelManager}>+ {t('prompt.openModelManager')}+ </Button>+ </Flex>+ )}</PopoverBody></PopoverContent></Portal>diff --git a/invokeai/frontend/web/src/features/prompt/ImageToPromptButton.tsx b/invokeai/frontend/web/src/features/prompt/ImageToPromptButton.tsxindex a56665bf62..fb4dbb668c 100644--- a/invokeai/frontend/web/src/features/prompt/ImageToPromptButton.tsx+++ b/invokeai/frontend/web/src/features/prompt/ImageToPromptButton.tsx@@ -18,8 +18,10 @@ import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';import { useDisclosure } from 'common/hooks/useBoolean';import { useImageUploadButton } from 'common/hooks/useImageUploadButton';import { positivePromptChanged, selectPositivePrompt } from 'features/controlLayers/store/paramsSlice';+import { setInstallModelsTabByName } from 'features/modelManagerV2/store/installModelsStore';import { ModelPicker } from 'features/parameters/components/ModelPicker';import { setPromptUndo } from 'features/prompt/promptUndo';+import { navigationApi } from 'features/ui/layouts/navigation-api';import { memo, useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { PiImageBold } from 'react-icons/pi';@@ -46,6 +48,8 @@ export const ImageToPromptButton = memo(({ droppedImage, onClearDroppedImage }:const [uploadedImage, setUploadedImage] = useState<ImageDTO | undefined>(undefined);const [imageToPrompt, { isLoading }] = useImageToPromptMutation();+ const hasModels = modelConfigs.length > 0;+const handleModelChange = useCallback((model: AnyModelConfig) => {setSelectedModel(model);}, []);@@ -93,10 +97,11 @@ export const ImageToPromptButton = memo(({ droppedImage, onClearDroppedImage }:setUploadedImage(undefined);}, [popover]);- // Don't render if no LLaVA models are installed- if (modelConfigs.length === 0) {- return null;- }+ const handleOpenModelManager = useCallback(() => {+ handleClose();+ navigationApi.switchToTab('models');+ setInstallModelsTabByName('starterModels');+ }, [handleClose]);return (<Popover@@ -109,7 +114,7 @@ export const ImageToPromptButton = memo(({ droppedImage, onClearDroppedImage }:><PopoverTrigger><span>- <Tooltip label={t('prompt.imageToPrompt')}>+ <Tooltip label={hasModels ? t('prompt.imageToPrompt') : t('prompt.noVisionModelInstalledTitle')}><IconButtonsize="sm"variant="promptOverlay"@@ -125,42 +130,56 @@ export const ImageToPromptButton = memo(({ droppedImage, onClearDroppedImage }:<PopoverContent p={3} w={350}><PopoverArrow /><PopoverBody p={0}>- <Flex flexDir="column" gap={3}>- <Text fontWeight="semibold" fontSize="sm">- {t('prompt.imageToPrompt')}- </Text>- <ModelPicker- pickerId="image-to-prompt-model"- modelConfigs={modelConfigs}- selectedModelConfig={selectedModel}- onChange={handleModelChange}- placeholder={t('prompt.selectVisionModel')}- />- <Flex gap={2} alignItems="center">- <Button size="sm" variant="outline" flexGrow={1} {...getUploadButtonProps()}>- {uploadedImage ? t('prompt.changeImage') : t('prompt.uploadImage')}+ {hasModels ? (+ <Flex flexDir="column" gap={3}>+ <Text fontWeight="semibold" fontSize="sm">+ {t('prompt.imageToPrompt')}+ </Text>+ <ModelPicker+ pickerId="image-to-prompt-model"+ modelConfigs={modelConfigs}+ selectedModelConfig={selectedModel}+ onChange={handleModelChange}+ placeholder={t('prompt.selectVisionModel')}+ />+ <Flex gap={2} alignItems="center">+ <Button size="sm" variant="outline" flexGrow={1} {...getUploadButtonProps()}>+ {uploadedImage ? t('prompt.changeImage') : t('prompt.uploadImage')}+ </Button>+ <input {...getUploadInputProps()} />+ {uploadedImage && (+ <Image+ src={uploadedImage.image_url}+ alt="Uploaded"+ boxSize={10}+ objectFit="cover"+ borderRadius="base"+ />+ )}+ </Flex>+ <Button+ size="sm"+ colorScheme="invokeBlue"+ onClick={handleGenerate}+ isLoading={isLoading}+ isDisabled={!selectedModel || !uploadedImage}+ >+ {t('prompt.generatePrompt')}+ </Button>+ </Flex>+ ) : (+ <Flex flexDir="column" gap={3}>+ <Text fontWeight="semibold" fontSize="sm">+ {t('prompt.noVisionModelInstalledTitle')}+ </Text>+ <Text fontSize="sm" color="base.300">+ {t('prompt.noVisionModelInstalledDescription')}+ </Text>+ <Button size="sm" colorScheme="invokeBlue" onClick={handleOpenModelManager}>+ {t('prompt.openModelManager')}</Button>- <input {...getUploadInputProps()} />- {uploadedImage && (- <Image- src={uploadedImage.image_url}- alt="Uploaded"- boxSize={10}- objectFit="cover"- borderRadius="base"- />- )}</Flex>- <Button- size="sm"- colorScheme="invokeBlue"- onClick={handleGenerate}- isLoading={isLoading}- isDisabled={!selectedModel || !uploadedImage}- >- {t('prompt.generatePrompt')}- </Button>- </Flex>+ )}</PopoverBody></PopoverContent></Portal>diff --git a/tests/app/services/model_records/test_model_records_sql.py b/tests/app/services/model_records/test_model_records_sql.pyindex 19a1b74e73..9307e35e0c 100644--- a/tests/app/services/model_records/test_model_records_sql.py+++ b/tests/app/services/model_records/test_model_records_sql.py@@ -26,6 +26,8 @@ from invokeai.backend.model_manager.configs.main import (Main_Diffusers_SDXL_Config,MainModelDefaultSettings,)+from invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_Qwen3Encoder_Config+from invokeai.backend.model_manager.configs.text_llm import TextLLM_Diffusers_Configfrom invokeai.backend.model_manager.configs.textual_inversion import TI_File_SD1_Configfrom invokeai.backend.model_manager.configs.vae import VAE_Diffusers_SD1_Configfrom invokeai.backend.model_manager.taxonomy import (@@ -35,6 +37,7 @@ from invokeai.backend.model_manager.taxonomy import (ModelSourceType,ModelType,ModelVariantType,+ Qwen3VariantType,SchedulerPredictionType,)from invokeai.backend.util.logging import InvokeAILogger@@ -112,6 +115,30 @@ def test_model_records_updates_model_class(store: ModelRecordServiceBase):assert isinstance(new_config, LoRA_LyCORIS_SDXL_Config)+def test_update_changing_type_drops_stale_format_and_variant(store: ModelRecordServiceBase):+ """When the type changes, format/variant from the old class must not block validation of the new class.++ Regression test for https://github.com/invoke-ai/InvokeAI/issues/9090: switching a misidentified+ Qwen3 encoder to TextLLM previously failed because the old `format=qwen3_encoder` and `variant`+ fields were carried over and no discriminator under `type=text_llm` matched.+ """+ config = Qwen3Encoder_Qwen3Encoder_Config(+ source="test/source/",+ source_type=ModelSourceType.Path,+ path="/tmp/Qwen2.5-1.5B-Instruct",+ file_size=1024,+ name="Qwen2.5-1.5B-Instruct",+ hash="ABC123",+ variant=Qwen3VariantType.Qwen3_4B,+ )+ config.key = "key1"+ store.add_model(config)++ changes = ModelRecordChanges(type=ModelType.TextLLM)+ new_config = store.update_model(config.key, changes, allow_class_change=True)+ assert isinstance(new_config, TextLLM_Diffusers_Config)++def test_model_records_rejects_invalid_attr_changes(store: ModelRecordServiceBase):config = example_ti_config("key1")store.add_model(config)diff --git a/tests/backend/model_manager/configs/test_qwen3_encoder_config.py b/tests/backend/model_manager/configs/test_qwen3_encoder_config.pynew file mode 100644index 0000000000..2574b7433a--- /dev/null+++ b/tests/backend/model_manager/configs/test_qwen3_encoder_config.py@@ -0,0 +1,81 @@+"""Regression tests for Qwen3 Encoder config probing.++See https://github.com/invoke-ai/InvokeAI/issues/9090++`Qwen2.5-1.5B-Instruct` (a standalone causal LM) was being misidentified as a+`Qwen3Encoder` because the diffusers-style config check matched any directory with+`config.json` at the root and a Qwen* class name. A complete causal LM also bundles+tokenizer files at the root, while standalone text_encoder downloads do not — we+use that to disambiguate.+"""++import json+from pathlib import Path+from tempfile import TemporaryDirectory+from unittest.mock import MagicMock++import pytest++from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError+from invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_Qwen3Encoder_Config++_OVERRIDE_FIELDS: dict[str, object] = {+ "hash": "blake3:fakehash",+ "path": "/fake/models/test-model",+ "file_size": 1000,+ "name": "test-model",+ "description": "test",+ "source": "test",+ "source_type": "path",+ "key": "test-key",+}+++def _write_config(path: Path, hidden_size: int = 2560, architecture: str = "Qwen2ForCausalLM") -> None:+ path.write_text(json.dumps({"architectures": [architecture], "hidden_size": hidden_size}))++[email protected]("tokenizer_file", ["tokenizer.json", "tokenizer.model", "tokenizer_config.json"])+def test_complete_causal_lm_is_rejected(tokenizer_file: str) -> None:+ """A directory with config.json + tokenizer files at root is a TextLLM, not a Qwen3 encoder."""+ with TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ _write_config(root / "config.json")+ (root / tokenizer_file).write_text("{}")++ mod = MagicMock()+ mod.path = root++ with pytest.raises(NotAMatchError, match="complete causal LM"):+ Qwen3Encoder_Qwen3Encoder_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))+++def test_standalone_text_encoder_subfolder_still_matches() -> None:+ """A standalone text_encoder download (config.json at root, no tokenizer files) should still match."""+ with TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ _write_config(root / "config.json")++ mod = MagicMock()+ mod.path = root++ config = Qwen3Encoder_Qwen3Encoder_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))+ assert config.type.value == "qwen3_encoder"+++def test_nested_text_encoder_with_root_tokenizer_still_matches() -> None:+ """A model with text_encoder/config.json should match even if tokenizer files exist at root.++ The tokenizer-at-root heuristic only applies to the standalone (root-level config.json) case.+ """+ with TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ (root / "text_encoder").mkdir()+ _write_config(root / "text_encoder" / "config.json")+ (root / "tokenizer.json").write_text("{}")++ mod = MagicMock()+ mod.path = root++ config = Qwen3Encoder_Qwen3Encoder_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))+ assert config.type.value == "qwen3_encoder"