repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
InvokeAI | invokeai/app/invocations/video_frame_extract_range.py | .py | """Extract a contiguous range of frames from a video and re-encode as MP4.
Companion to ``video_frame_extract`` (single frame β image) and
``video_concat`` (many videos β one). This node takes a slice of an input
video and emits a new MP4, so the output can be fed straight into
Concatenate Videos to splice clips toget... | 245 | 10,477 |
InvokeAI | invokeai/app/invocations/ip_adapter.py | .py | from builtins import float
from typing import List, Literal, Optional, Union
from pydantic import BaseModel, Field, field_validator, model_validator
from typing_extensions import Self
from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_output
from invokeai.... | 233 | 10,807 |
InvokeAI | invokeai/app/invocations/flux2_vae_decode.py | .py | """Flux2 Klein VAE Decode Invocation.
Decodes latents to images using the FLUX.2 32-channel VAE (AutoencoderKLFlux2).
"""
import torch
from einops import rearrange
from PIL import Image
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields... | 96 | 3,794 |
InvokeAI | invokeai/app/invocations/collections.py | .py | # Copyright (c) 2023 Kyle Schouviller (https://github.com/kyle0654) and the InvokeAI Team
import numpy as np
from pydantic import ValidationInfo, field_validator
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.fields import InputField
from invokeai.app.inv... | 76 | 3,036 |
InvokeAI | invokeai/app/invocations/sd3_text_encoder.py | .py | from contextlib import ExitStack
from typing import Iterator, Tuple
import torch
from transformers import (
CLIPTextModel,
CLIPTextModelWithProjection,
CLIPTokenizer,
T5EncoderModel,
T5Tokenizer,
)
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.inv... | 208 | 9,777 |
InvokeAI | invokeai/app/invocations/wan_latents_to_image.py | .py | """Wan 2.2 latents-to-image invocation.
Decodes Wan latents using the Wan VAE (AutoencoderKLWan).
Latents from the denoise loop are in normalised space (zero-centred). Before
VAE decode they are denormalised using the VAE config's per-channel
``latents_mean`` / ``latents_std`` (matching Diffusers ``WanPipeline``).
T... | 122 | 5,323 |
InvokeAI | invokeai/app/invocations/ernie_image_prompt_enhancer.py | .py | import json
from contextlib import ExitStack
from typing import Optional
import torch
from transformers import PreTrainedModel, PreTrainedTokenizerBase, StoppingCriteria, StoppingCriteriaList
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.f... | 128 | 6,088 |
InvokeAI | invokeai/app/invocations/flux_ip_adapter.py | .py | from builtins import float
from typing import List, Literal, Union
from pydantic import field_validator, model_validator
from typing_extensions import Self
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.fields import InputField
from invokeai.app.invocation... | 90 | 3,964 |
InvokeAI | invokeai/app/invocations/z_image_image_to_latents.py | .py | from typing import Union
import einops
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import (
FieldDescriptions,
ImageField,
Input,
... | 111 | 4,959 |
InvokeAI | invokeai/app/invocations/wan_video_denoise.py | .py | """Wan 2.2 video denoise invocation (T2V / I2V).
Multi-frame counterpart to :mod:`wan_denoise`. Drives the same flow-matching
schedule + expert-swap MoE logic, but the noise tensor has a real temporal
dimension (``T_lat = (num_frames - 1) // 4 + 1``) and the I2V conditioning is
built across all latent frames (first fr... | 401 | 19,512 |
InvokeAI | invokeai/app/invocations/metadata_linked.py | .py | # Adopted from @skunworkxdark's metadata nodes (MIT License)
# https://github.com/skunkworxdark/metadata-linked-nodes
# Thanks to @skunworkxdark for the original implementation!
import copy
from typing import Any, Dict, Literal, Optional, TypeVar, Union
from pydantic import model_validator
from invokeai.app.invocati... | 1,367 | 47,413 |
InvokeAI | invokeai/app/invocations/flux2_dev_text_encoder.py | .py | """FLUX.2 [dev] text encoder invocation.
FLUX.2 [dev] uses a Mistral Small 3 (hidden_size=5120) text encoder. Two variants
are supported (see ``MistralVariantType``), both read at the same hidden-state
indices (10, 20, 30):
- **Mistral24B** β the 40-layer encoder BFL ships in the canonical
``black-forest-labs/FLUX.... | 254 | 12,879 |
InvokeAI | invokeai/app/invocations/video_concat.py | .py | """Concatenate two or more videos with an optional transition.
Pairs naturally with the I2V chaining workflow: feed several Wan-generated
clips into this node to glue them into one longer video. The transition
options hide the seam between independently-denoised clips.
Implementation uses imageio (FFMPEG plugin) for ... | 287 | 13,578 |
InvokeAI | invokeai/app/invocations/dw_openpose.py | .py | import onnxruntime as ort
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.fields import ImageField, InputField, WithBoard, WithMetadata
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import In... | 51 | 2,226 |
InvokeAI | invokeai/app/invocations/ernie_image_denoise.py | .py | from contextlib import ExitStack
from typing import Optional
import torch
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import (
ErnieImageConditioningField,
F... | 257 | 12,323 |
InvokeAI | invokeai/app/invocations/controlnet.py | .py | # Invocations for ControlNet image preprocessors
# initial implementation by Gregg Helt, 2023
from typing import List, Union
from pydantic import BaseModel, Field, field_validator, model_validator
from invokeai.app.invocations.baseinvocation import (
BaseInvocation,
BaseInvocationOutput,
Classification,
... | 137 | 5,486 |
InvokeAI | invokeai/app/invocations/qwen_image_image_to_latents.py | .py | import einops
import torch
from PIL import Image as PILImage
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import (
FieldDescriptions,
ImageField,
Input,
InputField,
WithBoard,
WithMetadata,
)
from invokeai.ap... | 110 | 4,988 |
InvokeAI | invokeai/app/invocations/cogview4_latents_to_image.py | .py | from contextlib import nullcontext
import torch
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from einops import rearrange
from PIL import Image
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import (
Fie... | 83 | 3,383 |
InvokeAI | invokeai/app/invocations/normal_bae.py | .py | from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.fields import ImageField, InputField, WithBoard, WithMetadata
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invoke... | 32 | 1,312 |
InvokeAI | invokeai/app/invocations/z_image_denoise.py | .py | import inspect
import math
from contextlib import ExitStack
from typing import Callable, Iterator, Optional
import einops
import torch
import torchvision.transforms as tv_transforms
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from PIL import Image
from torchvision.transforms.functional import resi... | 813 | 39,655 |
InvokeAI | invokeai/app/invocations/ideogram4_latents_to_image.py | .py | import torch
from einops import rearrange
from PIL import Image
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
from invokeai.app.invocations.fields import (
FieldDescriptions,
Input,
InputField,
LatentsField,
WithBoard,
WithMetadata,
)
from invoke... | 63 | 2,615 |
InvokeAI | invokeai/app/invocations/canny.py | .py | import cv2
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.fields import ImageField, InputField, WithBoard, WithMetadata
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.shared.invocation_context import InvocationContext... | 35 | 1,466 |
InvokeAI | tests/test_imports.py | .py | import importlib
import pkgutil
import subprocess
import sys
import textwrap
import invokeai
KNOWN_IMPORT_ERRORS = {
"invokeai.backend.image_util.normal_bae.nets.submodules.efficientnet_repo.setup",
"invokeai.backend.image_util.normal_bae.nets.submodules.efficientnet_repo.validate",
"invokeai.backend.imag... | 70 | 2,687 |
InvokeAI | tests/test_model_hash.py | .py | # pyright:reportPrivateUsage=false
from pathlib import Path
from typing import Iterable
import pytest
from blake3 import blake3
from invokeai.backend.model_hash.model_hash import HASHING_ALGORITHMS, MODEL_FILE_EXTENSIONS, ModelHash
test_cases: list[tuple[HASHING_ALGORITHMS, str]] = [
("md5", "md5:a0cd925fc063f9... | 134 | 4,623 |
InvokeAI | tests/test_nodes.py | .py | from typing import Any, Callable, Union
from unittest.mock import MagicMock
from invokeai.app.invocations.baseinvocation import (
BaseInvocation,
BaseInvocationOutput,
invocation,
invocation_output,
)
from invokeai.app.invocations.fields import InputField, OutputField
from invokeai.app.invocations.imag... | 196 | 7,123 |
InvokeAI | tests/test_graph_execution_state.py | .py | from collections import defaultdict, deque
from collections.abc import Iterator
from typing import Optional
from unittest.mock import Mock
import pytest
from pydantic import TypeAdapter
from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationContext
from invokeai.app.invoca... | 2,241 | 99,177 |
InvokeAI | tests/test_check_pins.py | .py | from __future__ import annotations
import importlib.util
import json
import re
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent
def _load_module(module_path: Path, module_name: str):
spec = importlib.util.spec_fr... | 538 | 22,676 |
InvokeAI | tests/test_object_serializer_disk.py | .py | import tempfile
from dataclasses import dataclass
from pathlib import Path
import pytest
import torch
from invokeai.app.services.object_serializer.object_serializer_common import ObjectNotFoundError
from invokeai.app.services.object_serializer.object_serializer_disk import ObjectSerializerDisk
from invokeai.app.servi... | 189 | 7,352 |
InvokeAI | tests/test_config.py | .py | from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any
import pytest
from pydantic import ValidationError
from invokeai.app.invocations.baseinvocation import InvocationRegistry
from invokeai.app.services.config.config_default import (
DefaultInvokeAIAppConfig,
InvokeAIAppConfi... | 396 | 14,241 |
InvokeAI | tests/test_profiler.py | .py | import re
from logging import Logger
from pathlib import Path
from tempfile import TemporaryDirectory
import pytest
from invokeai.app.util.profiler import Profiler
def test_profiler_starts():
with TemporaryDirectory() as tempdir:
profiler = Profiler(logger=Logger("test_profiler"), output_dir=Path(tempdi... | 54 | 1,750 |
InvokeAI | tests/test_docs_json_export.py | .py | from __future__ import annotations
import importlib.util
import json
from pathlib import Path
def _load_module(module_path: Path, module_name: str):
spec = importlib.util.spec_from_file_location(module_name, module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.m... | 78 | 2,767 |
InvokeAI | tests/test_asyncio_shutdown.py | .py | """
Tests that verify the fix for the two-Ctrl+C shutdown hang.
Root cause: asyncio.to_thread() (used during generation for SQLite session queue operations)
creates non-daemon threads via the event loop's default ThreadPoolExecutor. When the event
loop is interrupted by KeyboardInterrupt without calling loop.shutdown_... | 148 | 5,961 |
InvokeAI | tests/test_session_queue.py | .py | import json
import pytest
from pydantic import TypeAdapter, ValidationError
from invokeai.app.invocations.fields import VideoField
from invokeai.app.invocations.video_frame_extract import VideoFrameExtractInvocation
from invokeai.app.services.session_queue.session_queue_common import (
Batch,
BatchDataCollect... | 295 | 11,570 |
InvokeAI | tests/test_model_search.py | .py | from pathlib import Path
import pytest
from invokeai.backend.model_manager.search import ModelSearch
@pytest.fixture
def model_search(tmp_path: Path) -> tuple[ModelSearch, Path]:
search = ModelSearch()
return search, tmp_path
def test_model_search_on_search_started(model_search: tuple[ModelSearch, Path]):... | 143 | 4,656 |
InvokeAI | tests/test_dangerously_run_function_in_subprocess.py | .py | from tests.dangerously_run_function_in_subprocess import dangerously_run_function_in_subprocess
def test_simple_function():
def test_func():
print("Hello, Test!")
stdout, stderr, returncode = dangerously_run_function_in_subprocess(test_func)
assert returncode == 0
assert stdout.strip() == "H... | 58 | 1,407 |
InvokeAI | tests/test_sqlite_migrator.py | .py | import sqlite3
from contextlib import closing
from logging import Logger
from pathlib import Path
from tempfile import TemporaryDirectory
import pytest
from pydantic import ValidationError
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.shared.sqlite_migrator.... | 764 | 32,718 |
InvokeAI | tests/test_path.py | .py | """
Not really a test, but a way to verify that the paths are existing
and fail early if they are not.
"""
import pathlib
import unittest
from os import path as osp
from PIL import Image
import invokeai.app.assets.images as image_assets
import invokeai.configs as configs
class ConfigsTestCase(unittest.TestCase):
... | 41 | 1,140 |
InvokeAI | tests/dangerously_run_function_in_subprocess.py | .py | import inspect
import subprocess
import sys
import textwrap
from typing import Any, Callable
def dangerously_run_function_in_subprocess(func: Callable[[], Any]) -> tuple[str, str, int]:
"""**Use with caution! This should _only_ be used with trusted code!**
Extracts a function's source and runs it in a separa... | 47 | 1,370 |
InvokeAI | tests/test_invocation_cache_memory.py | .py | # pyright: reportPrivateUsage=false
from contextlib import suppress
from invokeai.app.invocations.fields import ImageField
from invokeai.app.invocations.primitives import ImageOutput
from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
from tests.test_nodes import PromptTest... | 208 | 7,898 |
InvokeAI | tests/test_node_graph.py | .py | import copy
import pickle
import subprocess
import sys
import textwrap
from pathlib import Path
import pytest
from pydantic import TypeAdapter, ValidationError
from pydantic.json_schema import models_json_schema
from invokeai.app.invocations.baseinvocation import (
BaseInvocation,
BaseInvocationOutput,
In... | 1,225 | 38,692 |
InvokeAI | tests/test_item_storage_memory.py | .py | import re
import pytest
from pydantic import BaseModel
from invokeai.app.services.item_storage.item_storage_common import ItemNotFoundError
from invokeai.app.services.item_storage.item_storage_memory import ItemStorageMemory
class MockItemModel(BaseModel):
id: str
value: int
@pytest.fixture
def item_stora... | 112 | 3,796 |
InvokeAI | tests/conftest.py | .py | # conftest.py is a special pytest file. Fixtures defined in this file will be accessible to all tests in this directory
# without needing to explicitly import them. (https://docs.pytest.org/en/6.2.x/fixture.html)
# We import the model_installer and torch_device fixtures here so that they can be used by all tests. Fla... | 101 | 5,268 |
InvokeAI | tests/fixtures/sqlite_database.py | .py | from logging import Logger
from unittest import mock
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.image_files.image_files_base import ImageFileStorageBase
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.sh... | 14 | 596 |
InvokeAI | tests/model_identification/test_identification.py | .py | import json
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from pprint import pformat
from typing import Any
import pytest
from invokeai.backend.model_manager.configs.controlnet import ControlAdapterDefaultSettings
from invokeai.backend.model_manager.configs.factory import (
Mode... | 110 | 3,776 |
InvokeAI | tests/model_identification/strip_model.py | .py | """
Usage:
strip_model.py <model_path> <output_dir>
Strips tensor data from model state_dict while preserving metadata.
Used to create lightweight models for testing model classification.
Parameters:
<model_path> The path to the model to be stripped.
<output_dir> Directory where stripped model... | 113 | 3,518 |
InvokeAI | tests/model_identification/stripped_model_on_disk.py | .py | import json
from pathlib import Path
from typing import Any, Optional
import gguf
import torch
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk, StateDict
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
class StrippedModelOnDisk(ModelOnDisk):
METADATA_KEY = "metadata_ke... | 84 | 3,347 |
InvokeAI | tests/backend/test_text_llm_pipeline.py | .py | """Regression test for TextLLMPipeline's system-role fallback.
Some chat templates (notably Gemma) reject a dedicated "system" role and raise
"System role not supported". The pipeline should fold the system prompt into the user
turn and retry instead of failing prompt expansion.
"""
from unittest.mock import MagicMoc... | 87 | 3,243 |
InvokeAI | tests/backend/flux2/test_regional_prompting_extension.py | .py | from unittest.mock import patch
import torch
from invokeai.backend.flux2.extensions.regional_prompting_extension import Flux2RegionalPromptingExtension
from invokeai.backend.flux2.text_conditioning import Flux2TextConditioning
from invokeai.backend.util.devices import TorchDevice
def _cpu_device():
return patch... | 120 | 5,113 |
InvokeAI | tests/backend/pid/test_pid_state_dict_utils.py | .py | """Regression tests for the PiD key-space normalisation shared by identification and loading.
Identification and the loader used to carry a copy each, and the copies had diverged: only the
loader dropped the distill-only submodules. That drift is silent in the dangerous direction β
identification accepting a checkpoin... | 98 | 5,268 |
InvokeAI | tests/backend/pid/test_pid_decode.py | .py | """Regression tests for the PiD distill schedule, decoder/base validation and checkpoint completeness."""
import math
from typing import Any
from unittest.mock import patch
import pytest
import torch
from invokeai.backend.model_manager.taxonomy import BaseModelType
from invokeai.backend.pid import decode as pid_deco... | 347 | 16,451 |
InvokeAI | tests/backend/pid/test_pid_chunked_equivalence.py | .py | """What `pid_memory_optimization` guarantees about the decoded image, at production dimensions.
`test_pixeldit_official.py` pins the chunked `PiTBlock` against the unchunked one at toy size on the
CPU. That is a real assertion about the *math* - and it holds exactly - but it cannot see the shape
of the problem the set... | 235 | 11,620 |
InvokeAI | tests/backend/pid/test_pixeldit_official.py | .py | import math
import pytest
import torch
from invokeai.backend.pid._src.networks.pixeldit_official import PiTBlock
def _build_pit_block() -> PiTBlock:
return PiTBlock(
pixel_hidden_size=4,
patch_hidden_size=8,
patch_size=2,
num_heads=2,
mlp_ratio=2.0,
attn_hidden_si... | 124 | 3,991 |
InvokeAI | tests/backend/ernie_image/test_ernie_denoise.py | .py | import pytest
import torch
from diffusers import FlowMatchEulerDiscreteScheduler, FlowMatchHeunDiscreteScheduler
from invokeai.backend.ernie_image.denoise import denoise
from invokeai.backend.ernie_image.sampling_utils import get_schedule
from invokeai.backend.flux.schedulers import ERNIE_IMAGE_SCHEDULER_MAP
from invo... | 214 | 9,134 |
InvokeAI | tests/backend/krea2/test_attention.py | .py | import pytest
import torch
from diffusers.models.transformers.transformer_krea2 import Krea2Attention, Krea2AttnProcessor
from torch.nn.attention import SDPBackend
import invokeai.backend.krea2.attention as krea2_attention
from invokeai.backend.krea2.attention import Krea2MemoryEfficientAttnProcessor, Krea2RegionalPro... | 124 | 6,538 |
InvokeAI | tests/backend/krea2/test_vae_compat.py | .py | import accelerate
import pytest
from diffusers.models.autoencoders import AutoencoderKLWan
from invokeai.backend.krea2.vae_compat import as_qwen_image_vae
def test_as_qwen_image_vae_preserves_the_cached_model_and_its_hooks() -> None:
with accelerate.init_empty_weights():
model = AutoencoderKLWan()
h... | 45 | 1,631 |
InvokeAI | tests/backend/krea2/test_regional_prompting.py | .py | import pytest
import torch
from diffusers.models.transformers.transformer_krea2 import Krea2Transformer2DModel
from invokeai.backend.krea2.attention import (
Krea2RegionalPromptingState,
build_krea2_attention_processors,
)
from invokeai.backend.krea2.regional_prompting import (
Krea2RegionalPromptingExtens... | 243 | 9,588 |
InvokeAI | tests/backend/ideogram4/test_text_encoder_loader.py | .py | """Tests for the Ideogram 4 text-encoder load-completeness guard.
The encoder is built under accelerate.init_empty_weights() and filled from the checkpoint. A missing
non-tied weight would leave a tensor on the meta device β passing the load but failing later during
device movement / encoding. _verify_encoder_fully_ma... | 58 | 2,434 |
InvokeAI | tests/backend/ideogram4/test_quantized_loading.py | .py | """Tests for the Ideogram 4 weight-only fp8 loading mechanism.
The Ideogram 4 fp8 text encoder is loaded by building the empty architecture, swapping its
quantized ``nn.Linear`` layers for ``Fp8Linear`` (gated on a saved per-row scale), then loading the
prequantized state dict with ``assign=True`` / ``strict=False`` β... | 143 | 6,185 |
InvokeAI | tests/backend/ideogram4/test_guidance_schedule.py | .py | """Tests for Ideogram 4's effective guidance schedule.
The schedule is ``(polish_gw,)*N_polish + (main_gw,)*N_main`` in loop-index order (index 0 is the
final/polish step). A guidance_scale override must replace the main weight while preserving the
polish tail, and there must always be at least one main step so the ov... | 49 | 2,369 |
InvokeAI | tests/backend/ideogram4/test_caption.py | .py | """Tests for the Ideogram 4 runtime caption assembly (Python port of buildIdeogram4Caption).
Kept behaviorally identical to the frontend assembler so that moving the work into the
ideogram4_caption_builder node (so dynamic prompts / batching vary the encoded caption) does not
change the encoded output for a given (pro... | 94 | 4,470 |
InvokeAI | tests/backend/ideogram4/test_caption_builder_node.py | .py | """Validation tests for the Ideogram4CaptionBuilderInvocation region bbox contract.
The caption builder forwards each region's bbox verbatim into the structured JSON, so a malformed box
(wrong length or out-of-range coordinate) would emit a prompt the model may misapply. The Ideogram4Region
model must reject such boxe... | 38 | 1,237 |
InvokeAI | tests/backend/stable_diffusion/test_extension_manager.py | .py | from unittest import mock
import pytest
from invokeai.backend.stable_diffusion.denoise_context import DenoiseContext
from invokeai.backend.stable_diffusion.extension_callback_type import ExtensionCallbackType
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase, callback
from invokeai.backend.s... | 113 | 3,842 |
InvokeAI | tests/backend/stable_diffusion/test_vae_tiling.py | .py | from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from invokeai.backend.stable_diffusion.vae_tiling import patch_vae_tiling_params
def test_patch_vae_tiling_params():
"""Smoke test the patch_vae_tiling_params(...) context manager. The main purpose of this unit test is to detect if
diffus... | 14 | 500 |
InvokeAI | tests/backend/stable_diffusion/test_hidiffusion_utils.py | .py | import copy
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
import torch
from invokeai.backend.hidiffusion.hidiffusion import (
_resize_controlnet_residual,
switching_threshold_ratio_dict,
text_to_img_controlnet_switching_threshold_ratio_dict,
)
from invokeai.bac... | 372 | 13,789 |
InvokeAI | tests/backend/stable_diffusion/extensions/test_base.py | .py | from unittest import mock
from invokeai.backend.stable_diffusion.denoise_context import DenoiseContext
from invokeai.backend.stable_diffusion.extension_callback_type import ExtensionCallbackType
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase, callback
class MockExtension(ExtensionBase):
... | 47 | 1,588 |
InvokeAI | tests/backend/quantization/test_sdnq_diagnostics_and_eval_mode.py | .py | """SDNQ diagnostics must not cost anything when nobody is listening.
The uint4 diagnostic ran full-tensor reductions (and a `unique()` sort) on the first dequantization
of every model, and wrote to stdout β bypassing the app's log level, format and handlers. It is now
gated on the log level before computing anything, ... | 76 | 3,219 |
InvokeAI | tests/backend/quantization/test_bnb_llm_int8.py | .py | import pytest
import torch
try:
from invokeai.backend.quantization.bnb_llm_int8 import InvokeLinear8bitLt
except ImportError:
pass
def test_invoke_linear_8bit_lt_quantization():
"""Test quantization with InvokeLinear8bitLt."""
if not torch.cuda.is_available():
pytest.skip("CUDA is not availab... | 86 | 3,254 |
InvokeAI | tests/backend/quantization/test_sdnq_detection.py | .py | """Identification and loading must reach the same verdict about an SDNQ folder.
They consult the same directory, so a disagreement is not cosmetic: when identification calls a
markerless export "plain diffusers" and hands it to a diffusers config, the loader then runs
`from_pretrained()` over packed SDNQ weights and e... | 111 | 4,867 |
InvokeAI | tests/backend/quantization/sdnq/test_sdnq_tensor.py | .py | """Unit tests for SDNQTensor class."""
import torch
from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
from invokeai.backend.quantization.sdnq.utils import SDNQQuantizationType
class TestSDNQTensor:
"""Tests for SDNQTensor dequantization and operations."""
def test_symmetric_dequantizati... | 233 | 8,747 |
InvokeAI | tests/backend/quantization/sdnq/test_sdnq_tensor_device.py | .py | """Tests that moving an SDNQTensor to a device moves all of its payloads, not just quantized_data.
The model cache moves parameters with .to(target_device). If only quantized_data moved, a
"GPU-resident" SDNQ parameter would keep its scale / zero_point / svd tensors in system RAM,
forcing a host->device copy of all of... | 45 | 2,016 |
InvokeAI | tests/backend/quantization/sdnq/test_sdnq_loader.py | .py | """Integration tests for SDNQ state dict loader."""
from pathlib import Path
import pytest
import torch
from invokeai.backend.quantization.sdnq.loaders import (
has_sdnq_keys,
raise_on_incomplete_sdnq_load,
sdnq_sd_loader,
)
from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
class Te... | 255 | 10,739 |
InvokeAI | tests/backend/quantization/sdnq/test_sdnq_dequant_broadcast.py | .py | """Tests that per-group dequantization accepts 2D scale/zero-point tensors.
SDNQ stores per-group scale/zero_point as either [out_features, num_groups, 1] or, without the
trailing singleton, [out_features, num_groups]. A 2D param must be normalized before arithmetic;
otherwise it right-aligns against the 3D grouped we... | 71 | 2,852 |
InvokeAI | tests/backend/quantization/sdnq/test_sdnq_tensor_size.py | .py | """Tests that cache byte accounting reflects an SDNQTensor's real storage.
calc_tensor_size() must count the packed uint4/int5 data plus every auxiliary payload (scale,
zero_point, svd), not the wrapper's advertised dequantized shape with a uint8 dtype (which
over-counts packed weights and omits the auxiliary tensors)... | 64 | 2,475 |
InvokeAI | tests/backend/quantization/gguf/test_ggml_tensor.py | .py | import gguf
import pytest
import torch
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.util.calc_tensor_size import calc_tensor_size
def quantize_tensor(data: torch.Tensor, ggml_quantization_type: gguf.GGMLQuantizationType) -> GGMLTensor:
"""Quantize a torch.Tensor to ... | 129 | 4,805 |
InvokeAI | tests/backend/ip_adapter/test_ip_adapter.py | .py | import pytest
import torch
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType, SubModelType
from invokeai.backend.stable_diffusion.diffusion.unet_attention_patcher import UNetAttentionPatcher
from invokeai.backend.util.test_utils import install_and_load_model
def build_dummy_sd15_unet_input... | 85 | 3,436 |
InvokeAI | tests/backend/t5/test_t5_tokenizer.py | .py | """Tests for the bundled T5-XXL tokenizer.
The T5 v1.1 XXL tokenizer is vendored in the package so features that only need to tokenize prompts
(Anima's LLM Adapter, the GGUF T5 encoder loader) don't have to install a 9GB T5-XXL encoder just to
obtain a ~2MB tokenizer.
"""
from invokeai.backend.t5.t5_tokenizer import ... | 39 | 1,323 |
InvokeAI | tests/backend/llava_onevision/test_llava_onevision_pipeline.py | .py | """Tests for the LlavaOnevisionPipeline class."""
import threading
from unittest.mock import MagicMock, patch
import torch
from PIL import Image
from invokeai.backend.llava_onevision_pipeline import LlavaOnevisionPipeline
def _make_mock_processor() -> MagicMock:
"""Create a mock LLaVA processor whose tokenizer... | 148 | 4,832 |
InvokeAI | tests/backend/z_image/test_z_image_controlnet_extension.py | .py | from types import SimpleNamespace
from unittest.mock import patch
import torch
from invokeai.backend.z_image.z_image_controlnet_extension import ZImageControlNetExtension
def test_init_logs_control_adapter_diagnostics_without_stdout(capsys):
control_adapter = SimpleNamespace(
control_layers=[
... | 25 | 784 |
InvokeAI | tests/backend/tiles/test_tiles.py | .py | import numpy as np
import pytest
from invokeai.backend.tiles.tiles import (
calc_tiles_even_split,
calc_tiles_min_overlap,
calc_tiles_with_overlap,
merge_tiles_with_linear_blending,
)
from invokeai.backend.tiles.utils import TBLR, Tile
####################################
# Test calc_tiles_with_overla... | 626 | 22,169 |
InvokeAI | tests/backend/tiles/test_utils.py | .py | import numpy as np
import pytest
from invokeai.backend.tiles.utils import TBLR, paste
def test_paste_no_mask_success():
"""Test successful paste with mask=None."""
dst_image = np.zeros((5, 5, 3), dtype=np.uint8)
# Create src_image with a pattern that can be used to validate that it was pasted correctly.... | 102 | 3,778 |
InvokeAI | tests/backend/wan/test_wan_ref_image_extension.py | .py | """Tests for the Wan 2.2 I2V reference-image VAE-latent encoder helper."""
from unittest.mock import MagicMock
import pytest
import torch
from PIL import Image
from invokeai.backend.wan.extensions.wan_ref_image_extension import (
encode_reference_image_to_condition,
encode_reference_image_to_video_condition,... | 231 | 9,632 |
InvokeAI | tests/backend/wan/test_rocm_causal_conv3d.py | .py | """Tests for the ROCm WanCausalConv3d conv2d decomposition.
The decomposition replaces MIOpen's Im3d2Col conv3d fallback (61% of Wan VAE
decode GPU time on RDNA3; ~48x slower than the decomposed path). These tests pin
that the decomposed forward is numerically equivalent to the stock diffusers
forward on CPU β includi... | 90 | 3,498 |
InvokeAI | tests/backend/wan/test_sampling_utils.py | .py | """Tests for Wan 2.2 sampling utilities."""
import torch
from invokeai.backend.model_manager.taxonomy import WanVariantType
from invokeai.backend.wan.sampling_utils import (
get_default_latent_channels,
get_spatial_scale_factor,
make_noise,
)
class TestVariantConstants:
def test_a14b_uses_8x_spatial... | 92 | 2,665 |
InvokeAI | tests/backend/model_manager/test_starter_models.py | .py | """Tests for the Krea-2 starter-model bundle and its GGUF dependency wiring.
A single-file / GGUF Krea-2 transformer ships *only* the transformer, so it is unusable without a
standalone Qwen-Image VAE and Qwen3-VL text encoder. These tests assert that the Krea-2 launchpad
bundle exists, exposes both the diffusers and ... | 81 | 3,632 |
InvokeAI | tests/backend/model_manager/test_external_api_config.py | .py | import pytest
from pydantic import ValidationError
from invokeai.backend.model_manager.configs.external_api import (
ExternalApiModelConfig,
ExternalApiModelDefaultSettings,
ExternalImageSize,
ExternalModelCapabilities,
)
def test_external_api_model_config_defaults() -> None:
capabilities = Exter... | 55 | 1,882 |
InvokeAI | tests/backend/model_manager/test_model_load_optimization.py | .py | import pytest
import torch
from invokeai.backend.model_manager.load.optimizations import _no_op, skip_torch_weight_init
@pytest.mark.parametrize(
["torch_module", "layer_args"],
[
(torch.nn.Linear, {"in_features": 10, "out_features": 20}),
(torch.nn.Conv1d, {"in_channels": 10, "out_channels":... | 74 | 3,296 |
InvokeAI | tests/backend/model_manager/test_libc_util.py | .py | import pytest
from invokeai.backend.model_manager.util.libc_util import LibcUtil, Struct_mallinfo2
def test_libc_util_mallinfo2():
"""Smoke test of LibcUtil().mallinfo2()."""
try:
libc = LibcUtil()
except OSError:
# TODO: Set the expected result preemptively based on the system properties... | 28 | 767 |
InvokeAI | tests/backend/model_manager/model_manager_fixtures.py | .py | # Fixtures to support testing of the model_manager v2 installer, metadata and record store
import os
import shutil
from pathlib import Path
import pytest
from requests.sessions import Session
from requests_testadapter import TestAdapter, TestSession
from invokeai.app.services.config import InvokeAIAppConfig
from inv... | 360 | 12,481 |
InvokeAI | tests/backend/model_manager/test_ernie_image_default_settings.py | .py | from invokeai.backend.model_manager.configs.main import MainModelDefaultSettings
from invokeai.backend.model_manager.taxonomy import BaseModelType
class TestErnieImageDefaultSettings:
def test_base_defaults(self) -> None:
s = MainModelDefaultSettings.from_base(BaseModelType.ErnieImage, None, "ERNIE-Image"... | 47 | 2,304 |
InvokeAI | tests/backend/model_manager/test_wan_default_settings.py | .py | """Tests for Wan 2.2 default settings."""
from invokeai.backend.model_manager.configs.main import MainModelDefaultSettings
from invokeai.backend.model_manager.taxonomy import BaseModelType, WanVariantType
class TestWanDefaultSettings:
def test_a14b_defaults(self) -> None:
s = MainModelDefaultSettings.fro... | 26 | 946 |
InvokeAI | tests/backend/model_manager/test_memory_snapshot.py | .py | import pytest
from invokeai.backend.model_manager.load.memory_snapshot import MemorySnapshot, get_pretty_snapshot_diff
from invokeai.backend.model_manager.util.libc_util import Struct_mallinfo2
def test_memory_snapshot_capture():
"""Smoke test of MemorySnapshot.capture()."""
snapshot = MemorySnapshot.capture... | 40 | 1,503 |
InvokeAI | tests/backend/model_manager/model_metadata/metadata_examples.py | .py | # from stabilityai/sdxl-turbo, via the HF API
# This was derived by examination of the outgoing and incoming request.Session
RepoHFMetadata1 = b"""
{"_id":"6564b36f4eb2f55240230f48","id":"stabilityai/sdxl-turbo","modelId":"stabilityai/sdxl-turbo","author":"test_author","sha":"f4b0486b498f84668e828044de1d0c8ba486e05b","... | 33 | 48,910 |
InvokeAI | tests/backend/model_manager/load/test_krea2_loader_boundaries.py | .py | from types import SimpleNamespace
from unittest.mock import MagicMock
import torch
from invokeai.backend.model_manager.configs.main import (
Main_Checkpoint_Krea2_Config,
Main_Diffusers_Krea2_Config,
Main_GGUF_Krea2_Config,
)
from invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncod... | 161 | 6,476 |
InvokeAI | tests/backend/model_manager/load/test_t5_gguf_loader.py | .py | """Unit tests for the GGUF-quantized T5 encoder loader helpers.
These cover the pure, high-risk parts of ``T5EncoderGGUFModel`` in isolation:
- ``_convert_t5_gguf_to_transformers`` (llama.cpp -> HF transformers key remapping)
- ``_infer_t5_config_from_state_dict`` (tensor-shape -> ``T5Config`` inference)
- ``_make_fee... | 209 | 8,739 |
InvokeAI | tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py | .py | """Unit tests for the pure state-dict helpers in the Qwen-Image / Qwen-VL loader.
These freeze the checkpoint key-surgery that the loaders perform before instantiating a model,
so a regression like the transformers-5.x one (where `_checkpoint_conversion_mapping` became
`{}` and the `visual.* -> model.visual.*` remap w... | 170 | 7,222 |
InvokeAI | tests/backend/model_manager/load/test_diffusers_039_compatibility.py | .py | from inspect import signature
from types import SimpleNamespace
import accelerate
import diffusers
import pytest
import torch
from packaging.version import Version
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
def test_pinned_diffusers_exposes_existing_and_kr... | 201 | 6,264 |
InvokeAI | tests/backend/model_manager/load/test_loaded_model_compute_device.py | .py | """Regression tests for issue #9373.
When partial loading is active and VRAM pressure has temporarily offloaded *all* of a model's weights back to
RAM, `get_effective_device(model)` reports CPU (it only inspects current parameter residency). The VAE decode
invocations used to move the latents to that inferred device, ... | 134 | 6,746 |
InvokeAI | tests/backend/model_manager/load/test_loaded_model.py | .py | import pytest
import torch
from invokeai.backend.model_manager.load.load_base import LoadedModelWithoutConfig
from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecord
from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_only_full_load import (
CachedModelOnlyFu... | 83 | 3,153 |
InvokeAI | tests/backend/model_manager/load/test_load_default_fp8.py | .py | """Tests for `ModelLoader` FP8 helpers.
Covers:
- `_should_use_fp8` excludes ControlLoRA (the LoRA loader never runs the layerwise
casting helper, and a LoRA isn't a standalone forward module β so a persisted
`fp8_storage=true` must be a no-op).
- `_wrap_forward_with_fp8_cast` uses pre/post hooks with `always_call... | 517 | 21,578 |
InvokeAI | tests/backend/model_manager/load/test_sdnq_vae_shard_detection.py | .py | """Tests that SDNQ VAE detection handles sharded / arbitrarily named safetensors folders.
The shared sdnq_sd_loader supports sharded directories, so a VAE whose SDNQ weight and its scale are
split across standard shard files must still be detected as SDNQ (and routed to _load_sdnq_vae),
not fall through to the generic... | 50 | 2,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.