Skip to content

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

9.0 KB
Raw Blame
import json
from typing import Optional

from invokeai.app.invocations.baseinvocation import (
    BaseInvocation,
    BaseInvocationOutput,
    Classification,
    invocation,
    invocation_output,
)
from invokeai.app.invocations.fields import FieldDescriptions, Input, InputField, OutputField
from invokeai.app.invocations.model import (
    Mistral3EncoderField,
    ModelIdentifierField,
    PromptEnhancerField,
    TransformerField,
    VAEField,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.architectures import accepted_vae_bases
from invokeai.backend.model_manager.taxonomy import (
    BaseModelType,
    MistralVariantType,
    ModelFormat,
    ModelType,
    SubModelType,
)

# A single file -- safetensors or GGUF -- holds the transformer alone; its companions are chosen on the node.
_SINGLE_FILE_FORMATS = frozenset({ModelFormat.Checkpoint, ModelFormat.GGUFQuantized})


@invocation_output("ernie_image_model_loader_output")
class ErnieImageModelLoaderOutput(BaseInvocationOutput):
    """ERNIE-Image model loader output."""

    transformer: TransformerField = OutputField(description=FieldDescriptions.transformer, title="Transformer")
    text_encoder: Mistral3EncoderField = OutputField(description="Mistral3 text encoder", title="Text Encoder")
    vae: VAEField = OutputField(description=FieldDescriptions.vae, title="VAE")
    prompt_enhancer: PromptEnhancerField | None = OutputField(
        default=None,
        description="Optional prompt-enhancer (Ministral3ForCausalLM)",
        title="Prompt Enhancer",
    )


@invocation(
    "ernie_image_model_loader",
    title="Main Model - ERNIE-Image",
    tags=["model", "ernie-image"],
    category="model",
    version="1.0.0",
    classification=Classification.Prototype,
)
class ErnieImageModelLoaderInvocation(BaseInvocation):
    """Loads an ERNIE-Image diffusers pipeline and emits its submodels.

    The transformer, VAE, text encoder, and (optional) prompt enhancer are all expected to
    live inside the same diffusers pipeline directory under their conventional subfolders
    (`transformer/`, `vae/`, `text_encoder/`, `tokenizer/`, `pe/`, `pe_tokenizer/`).
    """

    model: ModelIdentifierField = InputField(
        description="ERNIE-Image model. A diffusers pipeline provides every submodel; a single-file "
        "transformer needs a text encoder and a VAE selected below.",
        input=Input.Direct,
        ui_model_base=BaseModelType.ErnieImage,
        ui_model_type=ModelType.Main,
        title="ERNIE-Image Model",
    )

    text_encoder_model: Optional[ModelIdentifierField] = InputField(
        default=None,
        description="Standalone Ministral 3B text encoder. Required when the model is a single-file transformer.",
        input=Input.Direct,
        ui_model_type=ModelType.MistralEncoder,
        title="Text Encoder",
    )

    vae_model: Optional[ModelIdentifierField] = InputField(
        default=None,
        description="Standalone VAE (AutoencoderKLFlux2, the one ERNIE-Image shares with FLUX.2). "
        "Required when the model is a single-file transformer.",
        input=Input.Direct,
        ui_model_base=accepted_vae_bases(BaseModelType.ErnieImage),
        ui_model_type=ModelType.VAE,
        title="VAE",
    )

    use_prompt_enhancer: bool = InputField(
        default=True,
        description="If true and the pipeline ships with a prompt-enhancer submodel, expose it on the output. "
        "Single-file transformers carry no prompt enhancer.",
        title="Use Prompt Enhancer",
    )

    def invoke(self, context: InvocationContext) -> ErnieImageModelLoaderOutput:
        config = context.models.get_config(self.model)
        is_single_file = config.format in _SINGLE_FILE_FORMATS

        if is_single_file:
            return self._load_from_single_file(context)

        transformer = self.model.model_copy(update={"submodel_type": SubModelType.Transformer})
        vae = self.model.model_copy(update={"submodel_type": SubModelType.VAE})
        tokenizer = self.model.model_copy(update={"submodel_type": SubModelType.Tokenizer})
        text_encoder = self.model.model_copy(update={"submodel_type": SubModelType.TextEncoder})

        prompt_enhancer: PromptEnhancerField | None = None
        if self.use_prompt_enhancer and self._pipeline_has_prompt_enhancer(context):
            pe_tok = self.model.model_copy(update={"submodel_type": SubModelType.PromptEnhancerTokenizer})
            pe_lm = self.model.model_copy(update={"submodel_type": SubModelType.PromptEnhancer})
            prompt_enhancer = PromptEnhancerField(tokenizer=pe_tok, text_encoder=pe_lm)

        return ErnieImageModelLoaderOutput(
            transformer=TransformerField(transformer=transformer, loras=[]),
            text_encoder=Mistral3EncoderField(tokenizer=tokenizer, text_encoder=text_encoder),
            vae=VAEField(vae=vae),
            prompt_enhancer=prompt_enhancer,
        )

    def _load_from_single_file(self, context: InvocationContext) -> ErnieImageModelLoaderOutput:
        """A single file holds the transformer alone, so its companions are chosen on this node.

        The prompt enhancer is not among them: it is a Ministral3 language model that only the
        diffusers pipeline ships, and the model manager has no standalone type for it.
        """
        missing = [
            title
            for title, field in (("Text Encoder", self.text_encoder_model), ("VAE", self.vae_model))
            if field is None
        ]
        if missing:
            raise ValueError(
                f"A single-file ERNIE-Image transformer needs {' and '.join(missing)} selected on this node. "
                "Install the standalone Ministral 3B encoder and the FLUX.2 VAE, or select an ERNIE-Image "
                "diffusers pipeline, which carries both."
            )
        assert self.text_encoder_model is not None and self.vae_model is not None

        # Every Mistral encoder is installed under the same type, but ERNIE-Image conditions on
        # Ministral 3B: half the width of the Mistral Small 3 encoders FLUX.2 uses. Selecting one of
        # those otherwise fails as a shape mismatch deep inside denoising, long after the point
        # where a user could see what they picked wrong.
        encoder_variant = getattr(context.models.get_config(self.text_encoder_model), "variant", None)
        if encoder_variant is not MistralVariantType.Ministral3B:
            raise ValueError(
                f"'{self.text_encoder_model.name}' is not the encoder ERNIE-Image conditions on. "
                "It needs Ministral 3B (hidden size 3072); the Mistral Small 3 encoders that FLUX.2 "
                "uses are 5120 wide and would fail with a shape mismatch during denoising."
            )

        return ErnieImageModelLoaderOutput(
            transformer=TransformerField(
                transformer=self.model.model_copy(update={"submodel_type": SubModelType.Transformer}), loras=[]
            ),
            text_encoder=Mistral3EncoderField(
                tokenizer=self.text_encoder_model.model_copy(update={"submodel_type": SubModelType.Tokenizer}),
                text_encoder=self.text_encoder_model.model_copy(update={"submodel_type": SubModelType.TextEncoder}),
            ),
            vae=VAEField(vae=self.vae_model.model_copy(update={"submodel_type": SubModelType.VAE})),
            prompt_enhancer=None,
        )

    def _pipeline_has_prompt_enhancer(self, context: InvocationContext) -> bool:
        """Check whether the pipeline ships a *loadable* prompt-enhancer.

        Both the LM and its tokenizer are required, and both must be declared in `model_index.json`:
        `GenericDiffusersLoader.get_hf_load_class` resolves each submodel's class from that file and
        raises "the ... submodel is not available for this model" on a missing key. Gating on the
        directory alone would let a partial install pass this check and then hard-fail the whole
        generation at load time -- and since the toggle defaults to on, that would be the default
        experience for such an install.
        """
        config = context.models.get_config(self.model)
        # Models inside the Invoke-managed models dir are recorded with paths relative to
        # `models_path`; only the loader rewrites `config.path` to an absolute path, and that
        # happens after this check. Resolve against `models_path` the same way the loader does,
        # otherwise this would silently probe the server process's CWD and never find `pe/`.
        models_path = context.config.get().models_path
        model_path = (models_path / config.path).resolve()

        required = (SubModelType.PromptEnhancer, SubModelType.PromptEnhancerTokenizer)
        if not all((model_path / submodel.value).is_dir() for submodel in required):
            return False

        try:
            index = json.loads((model_path / "model_index.json").read_text(encoding="utf-8"))
        except (OSError, ValueError):
            return False
        return all(submodel.value in index for submodel in required)