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/backend/pid/_ext/imaginaire/lazy_config/instantiate.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Stdlib-only `instantiate()`. The upstream module also handled
# omegaconf.DictConfig / ListConfig structured configs and OmegaConf.to_object
# round-trips. In the vendored decoder... | 73 | 2,708 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/utils/device.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | 126 | 3,922 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/utils/misc.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Minimal stand-in for the upstream misc module. The full module pulled in
# wandb / straggler / termcolor / easy_io / DTensor helpers that the decoder
# inference subset does not u... | 49 | 1,332 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/utils/count_params.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | 30 | 1,141 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/utils/distributed.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | 445 | 17,623 |
InvokeAI | invokeai/backend/pid/_ext/imaginaire/utils/log.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# stdlib-based replacement for the upstream loguru-based logger.
# Provides a drop-in `logger` plus `info/warning/error/...` module-level
# functions so vendored call sites do not n... | 55 | 1,297 |
InvokeAI | invokeai/backend/sig_lip/sig_lip_pipeline.py | .py | import torch
from PIL import Image
from transformers import SiglipImageProcessor, SiglipVisionModel
class SigLipPipeline:
"""A wrapper for a SigLIP model + processor."""
def __init__(
self,
siglip_processor: SiglipImageProcessor,
siglip_model: SiglipVisionModel,
):
self._s... | 21 | 740 |
InvokeAI | invokeai/backend/ernie_image/denoise.py | .py | """ERNIE-Image denoising loop.
A direct re-implementation of the denoise loop in
`diffusers.pipelines.ernie_image.ErnieImagePipeline.__call__`, factored out so
InvokeAI can drive the transformer with its own scheduling, CFG, and inpainting
machinery instead of going through the upstream pipeline as a black box.
"""
i... | 219 | 11,059 |
InvokeAI | invokeai/backend/ernie_image/sampling_utils.py | .py | """Sampling utilities for ERNIE-Image.
Mirrors the static helpers in `diffusers.pipelines.ernie_image.pipeline_ernie_image.ErnieImagePipeline`
so we can drive the transformer ourselves while remaining wire-compatible with upstream weights.
"""
from typing import List
import torch
# Latent channels of the ERNIE-Imag... | 99 | 4,418 |
InvokeAI | invokeai/backend/krea2/vae_compat.py | .py | """Compatibility helpers for the Qwen-Image VAE used by Krea-2.
Krea-2 (and Qwen-Image) decode/encode with ``AutoencoderKLQwenImage``. A standalone single-file
``qwen_image_vae.safetensors`` in the native (ComfyUI/Wan) layout is byte-identical to the Anima VAE
and therefore classified with the Anima base, which loads ... | 58 | 3,254 |
InvokeAI | invokeai/backend/krea2/attention.py | .py | """Memory-efficient attention processor for the Krea-2 transformer.
The stock ``Krea2AttnProcessor`` calls ``scaled_dot_product_attention`` with ``enable_gqa=True`` (Krea-2 uses
grouped-query attention: 48 query heads, 12 key/value heads). PyTorch's fused flash / memory-efficient SDPA
kernels do **not** support ``enab... | 113 | 5,487 |
InvokeAI | invokeai/backend/krea2/regional_prompting.py | .py | from dataclasses import dataclass
import torch
import torchvision
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Range
from invokeai.backend.util.mask import to_standard_float_mask
@dataclass
class Krea2TextConditioning:
prompt_embeds: torch.Tensor
mask: torch.Tensor | None
@dat... | 133 | 5,794 |
InvokeAI | invokeai/backend/krea2/sampling_utils.py | .py | """Sampling/packing utilities for Krea-2 (Krea2Pipeline) inference.
InvokeAI hand-writes its own denoise loop for Qwen-family models rather than calling the
diffusers pipeline ``__call__``. These helpers replicate the Krea-2 sampling math so the
``Krea2Transformer2DModel`` (loaded from diffusers) can be driven directl... | 98 | 4,013 |
InvokeAI | invokeai/backend/ideogram4/autoencoder.py | .py | """Flux2 KL autoencoder."""
from __future__ import annotations
import math
import re
from dataclasses import dataclass, field
import torch
from einops import rearrange
from torch import Tensor, nn
@dataclass
class AutoEncoderParams:
resolution: int = 256
in_channels: int = 3
ch: int = 128
out_ch: i... | 385 | 13,762 |
InvokeAI | invokeai/backend/ideogram4/modeling_ideogram4.py | .py | """Ideogram4 transformer backbone.
The transformer consumes Qwen3-VL embeddings and flow-matching noise tokens to
produce velocity predictions on image latents.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
fr... | 368 | 13,054 |
InvokeAI | invokeai/backend/ideogram4/quantized_loading.py | .py | from __future__ import annotations
import warnings
from typing import TYPE_CHECKING
import torch
import torch.nn as nn
import torch.nn.functional as F
if TYPE_CHECKING:
pass
_BNB_SIBLING_SUFFIXES = (
".absmax",
".quant_map",
".nested_absmax",
".nested_quant_map",
)
# Largest magnitude represent... | 283 | 10,690 |
InvokeAI | invokeai/backend/ideogram4/scheduler.py | .py | """Logit-normal schedule and Euler flow-matching sampler."""
from __future__ import annotations
import math
from dataclasses import dataclass
import torch
@dataclass(frozen=True)
class LogitNormalSchedule:
mean: float
std: float = 1.0
logsnr_min: float = -15.0
logsnr_max: float = 18.0
def __ca... | 70 | 2,293 |
InvokeAI | invokeai/backend/ideogram4/sampler_configs.py | .py | """Named sampler configurations for Ideogram 4 inference."""
from __future__ import annotations
from invokeai.backend.ideogram4.scheduler import SamplerParameters
# guidance_schedule is in loop-INDEX order: index 0 is the LAST (polish) step.
# Each preset does the first N_main sampling steps at gw=7, then N_cleanup
... | 30 | 850 |
InvokeAI | invokeai/backend/ideogram4/transformer_pair.py | .py | """Container holding Ideogram 4's two transformer branches as a single submodel.
Ideogram 4 uses dual-branch asymmetric CFG with two *separate* weight sets
(``transformer/`` and ``unconditional_transformer/`` on disk). InvokeAI's model
cache keys a cached entity by (model, submodel_type) and there is no
"unconditional... | 26 | 1,090 |
InvokeAI | invokeai/backend/ideogram4/denoise.py | .py | """Ideogram 4 denoising loop.
Ports ``Ideogram4Pipeline.__call__``'s sampling loop, decoupled from model loading
and text encoding. Runs the Euler flow-matching loop with dual-branch asymmetric
CFG: the conditional transformer over the packed ``[text][image]`` sequence and the
unconditional transformer over image-only... | 127 | 5,212 |
InvokeAI | invokeai/backend/ideogram4/__init__.py | .py | """Ideogram 4 backend.
The model modules (``modeling_ideogram4``, ``autoencoder``, ``latent_norm``,
``scheduler``, ``sampler_configs``, ``constants``, ``quantized_loading``) are
adapted from the Apache-2.0 Ideogram 4 reference implementation
(https://github.com/ideogram-oss/ideogram4). See ``NOTICE.md``. The remaining... | 44 | 1,479 |
InvokeAI | invokeai/backend/ideogram4/constants.py | .py | SEQUENCE_PADDING_INDICATOR = -1
OUTPUT_IMAGE_INDICATOR = 2
LLM_TOKEN_INDICATOR = 3
# Image grid coordinates start at this offset so they never collide with text token indices
# (text positions start at 0 and never exceed max_text_tokens, which is well below this).
IMAGE_POSITION_OFFSET = 65536
# Layers of Qwen3-VL w... | 12 | 462 |
InvokeAI | invokeai/backend/ideogram4/latent_norm.py | .py | from __future__ import annotations
import torch
LATENT_SHIFT: tuple[float, ...] = (
0.01984364,
0.10149707,
0.29689495,
0.27188619,
-0.21445648,
-0.15979549,
0.05021099,
-0.15083604,
-0.15360136,
-0.20131799,
0.01922352,
0.0622626,
0.10140969,
-0.06739428,
0... | 273 | 4,530 |
InvokeAI | invokeai/backend/ideogram4/caption.py | .py | """Runtime assembly of Ideogram 4's structured JSON caption.
This is the Python port of the frontend ``buildIdeogram4Caption`` (buildIdeogram4Prompt.ts). It runs
at generation time (inside the ``ideogram4_caption_builder`` node) rather than at graph-build time, so
that dynamic-prompt expansions and prompt batching — w... | 93 | 4,889 |
InvokeAI | invokeai/backend/ideogram4/sampling_utils.py | .py | """Sampling helpers for Ideogram 4: packed-sequence construction and latent unpacking.
These wrap the vendored reference model (``modeling_ideogram4`` etc.) for use in
InvokeAI invocations. They mirror the logic of ``Ideogram4Pipeline._build_inputs``
and ``Ideogram4Pipeline._decode`` from the reference implementation,... | 131 | 5,291 |
InvokeAI | invokeai/backend/ideogram4/text_encoding.py | .py | """Qwen3-VL text encoding for Ideogram 4.
Ideogram 4 conditions on a concatenation of hidden states taken from 13 specific
layers of the Qwen3-VL language model (see ``QWEN3_VL_ACTIVATION_LAYERS``), giving
a ``(seq_len, 4096 * 13) == (seq_len, 53248)`` feature tensor.
The reference pipeline runs the encoder over the ... | 88 | 3,625 |
InvokeAI | invokeai/backend/stable_diffusion/vae_tiling.py | .py | from contextlib import contextmanager
from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTiny
@contextmanager
def patch_vae_tiling_params(
vae: AutoencoderKL | AutoencoderTiny,
tile_sample_min_size: int,
tile_latent... | 36 | 1,353 |
InvokeAI | invokeai/backend/stable_diffusion/extension_callback_type.py | .py | from enum import Enum
class ExtensionCallbackType(Enum):
SETUP = "setup"
PRE_DENOISE_LOOP = "pre_denoise_loop"
POST_DENOISE_LOOP = "post_denoise_loop"
PRE_STEP = "pre_step"
POST_STEP = "post_step"
PRE_UNET = "pre_unet"
POST_UNET = "post_unet"
POST_COMBINE_NOISE_PREDS = "post_combine_no... | 13 | 331 |
InvokeAI | invokeai/backend/stable_diffusion/__init__.py | .py | """
Initialization file for the invokeai.backend.stable_diffusion package
"""
from invokeai.backend.stable_diffusion.diffusers_pipeline import ( # noqa: F401
PipelineIntermediateState,
StableDiffusionGeneratorPipeline,
)
from invokeai.backend.stable_diffusion.diffusion import InvokeAIDiffuserComponent # noqa... | 16 | 448 |
InvokeAI | invokeai/backend/stable_diffusion/diffusers_pipeline.py | .py | from __future__ import annotations
import math
from contextlib import nullcontext
from dataclasses import dataclass
from typing import Any, Callable, List, Optional, Union
import einops
import PIL.Image
import psutil
import torch
import torchvision.transforms as T
from diffusers.models.autoencoders.autoencoder_kl imp... | 618 | 30,692 |
InvokeAI | invokeai/backend/stable_diffusion/denoise_context.py | .py | from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Type, Union
import torch
from diffusers import UNet2DConditionModel
from diffusers.schedulers.scheduling_utils import SchedulerMixin, SchedulerOutput
if TYPE_CHECKING:
from in... | 132 | 5,425 |
InvokeAI | invokeai/backend/stable_diffusion/hidiffusion_utils.py | .py | from __future__ import annotations
import copy
import sys
from contextlib import contextmanager
from typing import Any, Optional
import torch
from invokeai.backend.hidiffusion.hidiffusion import (
switching_threshold_ratio_dict as _switching_threshold_ratio_dict,
)
from invokeai.backend.hidiffusion.hidiffusion i... | 170 | 6,215 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion_backend.py | .py | from __future__ import annotations
import torch
from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
from diffusers.schedulers.scheduling_utils import SchedulerMixin, SchedulerOutput
from tqdm.auto import tqdm
from invokeai.app.services.config.config_default import get_config
from invokeai.backen... | 146 | 6,390 |
InvokeAI | invokeai/backend/stable_diffusion/extensions_manager.py | .py | from __future__ import annotations
from contextlib import ExitStack, contextmanager
from typing import TYPE_CHECKING, Callable, Dict, List, Optional
import torch
from diffusers import UNet2DConditionModel
from invokeai.app.services.session_processor.session_processor_common import CanceledException
from invokeai.bac... | 83 | 3,502 |
InvokeAI | invokeai/backend/stable_diffusion/multi_diffusion_pipeline.py | .py | from __future__ import annotations
import copy
from dataclasses import dataclass
from typing import Any, Callable, Optional
import torch
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from invokeai.backend.stable_diffusion.diffusers_pipeline import (
ControlNetData,
PipelineIntermediateStat... | 195 | 9,588 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/freeu.py | .py | from __future__ import annotations
from contextlib import contextmanager
from typing import TYPE_CHECKING
from diffusers import UNet2DConditionModel
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase
if TYPE_CHECKING:
from invokeai.app.shared.models import FreeUConfig
from invokeai.... | 36 | 952 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/preview.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Optional
import torch
from invokeai.backend.stable_diffusion.extension_callback_type import ExtensionCallbackType
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase, callback
if ... | 64 | 2,301 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/seamless.py | .py | from __future__ import annotations
from contextlib import contextmanager
from typing import Callable, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
from diffusers import UNet2DConditionModel
from diffusers.models.lora import LoRACompatibleConv
from invokeai.backend.stable_diffusion.extensions.base i... | 72 | 2,640 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/lora.py | .py | from __future__ import annotations
from contextlib import contextmanager
from typing import TYPE_CHECKING
from diffusers import UNet2DConditionModel
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.stable_diffusio... | 58 | 2,459 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/inpaint.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import einops
import torch
from diffusers import UNet2DConditionModel
from invokeai.backend.stable_diffusion.extension_callback_type import ExtensionCallbackType
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase, ... | 121 | 5,940 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/hidiffusion.py | .py | from __future__ import annotations
from contextlib import contextmanager
from typing import Optional
import torch
from diffusers import UNet2DConditionModel
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase
from invokeai.backend.stable_diffusion.hidiffusion_utils import hidiffusion_patch
fr... | 50 | 1,781 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/t2i_adapter.py | .py | from __future__ import annotations
import math
from typing import TYPE_CHECKING, List, Optional, Union
import torch
from diffusers import T2IAdapter
from PIL.Image import Image
from invokeai.app.util.controlnet_utils import prepare_control_image
from invokeai.backend.model_manager.taxonomy import BaseModelType
from ... | 123 | 5,263 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/rescale_cfg.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from invokeai.backend.stable_diffusion.extension_callback_type import ExtensionCallbackType
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase, callback
if TYPE_CHECKING:
from invokeai.backend.stable_diffus... | 37 | 1,393 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/inpaint_model.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from diffusers import UNet2DConditionModel
from invokeai.backend.stable_diffusion.extension_callback_type import ExtensionCallbackType
from invokeai.backend.stable_diffusion.extensions.base import ExtensionBase, callback
if T... | 89 | 3,899 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/base.py | .py | from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Dict, List
from diffusers import UNet2DConditionModel
if TYPE_CHECKING:
from invokeai.backend.stable_diffusion.denoise_context import DenoiseContext
from invo... | 73 | 2,840 |
InvokeAI | invokeai/backend/stable_diffusion/extensions/controlnet.py | .py | from __future__ import annotations
import math
from contextlib import contextmanager
from typing import TYPE_CHECKING, List, Optional, Union
import torch
from PIL.Image import Image
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.app.util.controlnet_utils import CONTROLNET_MODE_VALUE... | 159 | 6,406 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion/unet_attention_patcher.py | .py | from contextlib import contextmanager
from typing import List, Optional, TypedDict
from diffusers.models import UNet2DConditionModel
from invokeai.backend.ip_adapter.ip_adapter import IPAdapter
from invokeai.backend.stable_diffusion.diffusion.custom_atttention import (
CustomAttnProcessor2_0,
IPAdapterAttenti... | 76 | 3,653 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion/regional_prompt_data.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
import torch
import torch.nn.functional as F
if TYPE_CHECKING:
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
TextConditioningRegions,
)
class RegionalPromptData:
"""A class to manage the prompt dat... | 111 | 5,463 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion/__init__.py | .py | """
Initialization file for invokeai.models.diffusion
"""
from invokeai.backend.stable_diffusion.diffusion.shared_invokeai_diffusion import (
InvokeAIDiffuserComponent, # noqa: F401
)
| 8 | 190 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion/regional_ip_data.py | .py | import torch
class RegionalIPData:
"""A class to manage the data for regional IP-Adapter conditioning."""
def __init__(
self,
image_prompt_embeds: list[torch.Tensor],
scales: list[float],
masks: list[torch.Tensor],
dtype: torch.dtype,
device: torch.device,
... | 73 | 3,299 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion/custom_atttention.py | .py | from dataclasses import dataclass
from typing import List, Optional, cast
import torch
import torch.nn.functional as F
from diffusers.models.attention_processor import Attention, AttnProcessor2_0
from invokeai.backend.ip_adapter.ip_attention_weights import IPAttentionProcessorWeights
from invokeai.backend.stable_diff... | 220 | 9,995 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion/conditioning_data.py | .py | from __future__ import annotations
import math
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
import torch
from invokeai.backend.stable_diffusion.diffusion.regional_prompt_data import RegionalPromptData
if TYPE_CHECKING:
from invokea... | 443 | 17,651 |
InvokeAI | invokeai/backend/stable_diffusion/diffusion/shared_invokeai_diffusion.py | .py | from __future__ import annotations
import math
from typing import Any, Callable, Optional, Union
import torch
from typing_extensions import TypeAlias
from invokeai.app.services.config.config_default import get_config
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
IPAdapterData,
R... | 497 | 23,923 |
InvokeAI | invokeai/backend/stable_diffusion/schedulers/__init__.py | .py | from invokeai.backend.stable_diffusion.schedulers.schedulers import SCHEDULER_MAP # noqa: F401
__all__ = ["SCHEDULER_MAP"]
| 4 | 125 |
InvokeAI | invokeai/backend/stable_diffusion/schedulers/schedulers.py | .py | from typing import Any, Literal, Type
from diffusers import (
DDIMScheduler,
DDPMScheduler,
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSDEScheduler,
DPMSolverSinglestepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
HeunDiscreteScheduler,
K... | 104 | 3,791 |
InvokeAI | invokeai/backend/quantization/bnb_nf4.py | .py | import bitsandbytes as bnb
import torch
# This file contains utils for working with models that use bitsandbytes NF4 quantization.
# The utils in this file are partially inspired by:
# https://github.com/Lightning-AI/pytorch-lightning/blob/1551a16b94f5234a4a78801098f64d0732ef5cb5/src/lightning/fabric/plugins/precision... | 157 | 7,486 |
InvokeAI | invokeai/backend/quantization/bnb_llm_int8.py | .py | import warnings
import bitsandbytes as bnb
import torch
# This file contains utils for working with models that use bitsandbytes LLM.int8() quantization.
# The utils in this file are partially inspired by:
# https://github.com/Lightning-AI/pytorch-lightning/blob/1551a16b94f5234a4a78801098f64d0732ef5cb5/src/lightning/... | 167 | 7,599 |
InvokeAI | invokeai/backend/quantization/sdnq/loaders.py | .py | """SDNQ State Dict Loader - loads SDNQ quantized safetensors files."""
import gc
import json
import logging
from collections.abc import Iterable
from pathlib import Path
from typing import Any, Union
import torch
from safetensors.torch import load_file
from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQT... | 399 | 18,012 |
InvokeAI | invokeai/backend/quantization/sdnq/utils.py | .py | """SDNQ (SD.Next Quantization) utility functions and enums."""
import logging
from enum import Enum
from typing import Optional
import torch
from invokeai.backend.util.logging import InvokeAILogger
logger = InvokeAILogger.get_logger(__name__)
# How many elements the one-shot uint4 diagnostic may look at. Every fig... | 364 | 14,277 |
InvokeAI | invokeai/backend/quantization/sdnq/__init__.py | .py | """SDNQ (SD.Next Quantization) support for InvokeAI.
This module provides support for loading SDNQ quantized models with on-the-fly
CPU dequantization, similar to GGUF support.
"""
from invokeai.backend.quantization.sdnq.loaders import has_sdnq_keys, has_sdnq_tensors, sdnq_sd_loader
from invokeai.backend.quantization... | 18 | 558 |
InvokeAI | invokeai/backend/quantization/sdnq/detection.py | .py | """Deciding whether a folder holds SDNQ-quantized weights.
This is one question with one answer, but it used to have four near-identical implementations — in
`configs/main.py`, the FLUX and Z-Image loaders, and `vae.py` — and only the last of them looked past
the `quantization_config.json` marker. That divergence is a... | 63 | 2,730 |
InvokeAI | invokeai/backend/quantization/sdnq/sdnq_tensor.py | .py | """SDNQTensor - A torch.Tensor subclass for SDNQ quantized weights with on-the-fly dequantization."""
import logging
from typing import Optional, overload
import torch
from invokeai.backend.quantization.sdnq.utils import (
SDNQQuantizationType,
apply_svd_correction,
dequantize_asymmetric,
dequantize_... | 421 | 18,686 |
InvokeAI | invokeai/backend/quantization/scripts/quantize_t5_xxl_bnb_llm_int8.py | .py | from pathlib import Path
import accelerate
from safetensors.torch import load_file, save_file
from transformers import AutoConfig, AutoModelForTextEncoding, T5EncoderModel
from invokeai.backend.quantization.bnb_llm_int8 import quantize_model_llm_int8
from invokeai.backend.quantization.scripts.load_flux_model_bnb_nf4 ... | 96 | 4,514 |
InvokeAI | invokeai/backend/quantization/scripts/load_flux_model_bnb_nf4.py | .py | import time
from contextlib import contextmanager
from pathlib import Path
import accelerate
import torch
from safetensors.torch import load_file, save_file
from invokeai.backend.flux.model import Flux
from invokeai.backend.flux.util import get_flux_transformers_params
from invokeai.backend.model_manager.taxonomy imp... | 98 | 3,957 |
InvokeAI | invokeai/backend/quantization/scripts/load_flux_model_bnb_llm_int8.py | .py | from pathlib import Path
import accelerate
from safetensors.torch import load_file, save_file
from invokeai.backend.flux.model import Flux
from invokeai.backend.flux.util import get_flux_transformers_params
from invokeai.backend.model_manager.taxonomy import ModelVariantType
from invokeai.backend.quantization.bnb_llm... | 81 | 3,660 |
InvokeAI | invokeai/backend/quantization/gguf/loaders.py | .py | import gc
from pathlib import Path
import gguf
import torch
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES
from invokeai.backend.util.logging import InvokeAILogger
logger = InvokeAILogger.get_logger()
class WrappedG... | 58 | 1,969 |
InvokeAI | invokeai/backend/quantization/gguf/utils.py | .py | # Largely based on https://github.com/city96/ComfyUI-GGUF
from typing import Callable, Optional, Union
import gguf
import torch
# should not be a Set until this is resolved: https://github.com/pytorch/pytorch/issues/145761
TORCH_COMPATIBLE_QTYPES = [None, gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16]... | 310 | 10,472 |
InvokeAI | invokeai/backend/quantization/gguf/ggml_tensor.py | .py | from typing import overload
import gguf
import torch
from invokeai.backend.quantization.gguf.utils import (
DEQUANTIZE_FUNCTIONS,
TORCH_COMPATIBLE_QTYPES,
dequantize,
)
def dequantize_and_run(func, args, kwargs):
"""A helper function for running math ops on GGMLTensor inputs.
Dequantizes the in... | 197 | 8,266 |
InvokeAI | invokeai/backend/ip_adapter/resampler.py | .py | # copied from https://github.com/tencent-ailab/IP-Adapter (Apache License 2.0)
# tencent ailab comment: modified from
# https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
import math
import torch
import torch.nn as nn
# FFN
def FeedForward(dim: int, mult: int = 4):
inner_dim =... | 167 | 5,158 |
InvokeAI | invokeai/backend/ip_adapter/ip_attention_weights.py | .py | import torch
class IPAttentionProcessorWeights(torch.nn.Module):
"""The IP-Adapter weights for a single attention processor.
This class is a torch.nn.Module sub-class to facilitate loading from a state_dict. It does not have a forward(...)
method.
"""
def __init__(self, in_dim: int, out_dim: int... | 47 | 1,879 |
InvokeAI | invokeai/backend/ip_adapter/ip_adapter.py | .py | # copied from https://github.com/tencent-ailab/IP-Adapter (Apache License 2.0)
# and modified as needed
import pathlib
from typing import List, Optional, TypedDict, Union
import safetensors
import safetensors.torch
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionModelWithPr... | 263 | 10,660 |
InvokeAI | invokeai/backend/t5/t5_tokenizer.py | .py | """Bundled T5-XXL tokenizer.
Several features need to tokenize prompts with the T5 v1.1 XXL tokenizer without ever loading the
~9GB T5-XXL weights:
- Anima tokenizes prompts to index the LLM Adapter's learned embedding table.
- The GGUF T5 encoder loader needs a tokenizer since single-file GGUFs don't ship one that
... | 28 | 1,044 |
InvokeAI | invokeai/backend/z_image/z_image_controlnet_extension.py | .py | # Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""Z-Image ControlNet Extension for spatial conditioning.
This module provides an extension-based approach to Z-Image ControlNet,
similar to how FLUX ControlNet works. Instead of duplicating the entire
transformer, we compute control hints separa... | 529 | 21,955 |
InvokeAI | invokeai/backend/z_image/z_image_patchify_utils.py | .py | # Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""Utility functions for Z-Image patchify operations."""
from typing import List, Tuple
import torch
# Sequence must be multiple of this value (from diffusers transformer_z_image)
SEQ_MULTI_OF = 32
def create_coordinate_grid(
size: Tuple[... | 136 | 4,810 |
InvokeAI | invokeai/backend/z_image/z_image_transformer_patch.py | .py | """Utilities for patching the ZImageTransformer2DModel to support regional attention masks."""
from contextlib import contextmanager
from typing import Callable, List, Optional, Tuple
import torch
def create_regional_forward(
original_forward: Callable,
regional_attn_mask: torch.Tensor,
img_seq_len: int... | 241 | 10,762 |
InvokeAI | invokeai/backend/z_image/__init__.py | .py | # Z-Image backend utilities
from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
from invokeai.backend.z_image.z_image_control_transformer import ZImageControlTransformer2DModel
from invokeai.backend.z_image.z_image_controlnet_extension import (
ZImageControlNetExtension,
z_image_fo... | 17 | 610 |
InvokeAI | invokeai/backend/z_image/z_image_control_adapter.py | .py | # Adapted from https://github.com/aigc-apps/VideoX-Fun/blob/main/videox_fun/models/z_image_transformer2d_control.py
# Copyright (c) Alibaba, Inc. and its affiliates.
# Apache License 2.0
"""
Z-Image Control Adapter for InvokeAI.
This module provides a standalone control adapter that can be combined with
a base ZImage... | 239 | 8,519 |
InvokeAI | invokeai/backend/z_image/z_image_control_transformer.py | .py | # Adapted from https://github.com/aigc-apps/VideoX-Fun/blob/main/videox_fun/models/z_image_transformer2d_control.py
# Copyright (c) Alibaba, Inc. and its affiliates.
# Apache License 2.0
"""
Z-Image Control Transformer for InvokeAI.
This module provides the ZImageControlTransformer2DModel which extends the base
ZImag... | 644 | 24,207 |
InvokeAI | invokeai/backend/z_image/text_conditioning.py | .py | from dataclasses import dataclass
import torch
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Range
@dataclass
class ZImageTextConditioning:
"""Z-Image text conditioning with optional regional mask.
Attributes:
prompt_embeds: Text embeddings from Qwen3 encoder. Shape: (se... | 75 | 2,749 |
InvokeAI | invokeai/backend/z_image/extensions/regional_prompting_extension.py | .py | from typing import Optional
import torch
import torchvision
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.mask import to_standard_float_mask
from invokeai.backend.z_image.text_conditioning import ZImageRegionalTextConditioning, ZImageTextConditioning
class ZImageRegionalPromptingE... | 206 | 8,762 |
InvokeAI | invokeai/backend/tiles/utils.py | .py | import math
from typing import Optional
import cv2
import numpy as np
from pydantic import BaseModel, Field
class TBLR(BaseModel):
top: int
bottom: int
left: int
right: int
def __eq__(self, other):
return (
self.top == other.top
and self.bottom == other.bottom
... | 153 | 5,643 |
InvokeAI | invokeai/backend/tiles/tiles.py | .py | import math
from typing import Union
import numpy as np
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.backend.tiles.utils import TBLR, Tile, paste, seam_blend
def calc_overlap(tiles: list[Tile], num_tiles_x: int, num_tiles_y: int) -> list[Tile]:
"""Calculate and update the ove... | 427 | 20,459 |
InvokeAI | invokeai/backend/wan/rocm_causal_conv3d.py | .py | """ROCm workaround: decompose WanCausalConv3d into per-temporal-tap conv2d calls.
MIOpen (ROCm's cuDNN equivalent) has no implicit-GEMM 3D-convolution kernels for
the shapes used by the Wan VAE on RDNA3 — it falls back to ``Im3d2Col``, which
materializes every 3x3x3 patch into a matrix before a GEMM. Profiling a Wan 2... | 82 | 3,796 |
InvokeAI | invokeai/backend/wan/sampling_utils.py | .py | """Sampling utilities for Wan 2.2 image generation.
Single-frame inference uses 5D ``[B, C, T=1, H, W]`` latent tensors. The
scale factors are dictated by the model variant:
* A14B — standard Wan VAE: spatial 8x, latent channels 16
* TI2V-5B — Wan2.2-VAE: spatial 16x, latent channels 48
"""
from __future__ import a... | 83 | 2,848 |
InvokeAI | invokeai/backend/wan/extensions/wan_ref_image_extension.py | .py | """Wan 2.2 I2V reference-image conditioning.
Wan 2.2 I2V-A14B conditions on a reference image by **VAE-encoding** it and
concatenating the resulting latents to the noise latents along the channel
dim — its transformer has ``in_channels=36`` (16 noise + 16 ref-image latents
+ 4 first-frame mask) rather than 16.
This m... | 220 | 10,442 |
InvokeAI | invokeai/backend/model_manager/model_on_disk.py | .py | from pathlib import Path
from typing import Any, Optional, TypeAlias
import safetensors.torch
import torch
from gguf import GGUFValueType
from picklescan.scanner import scan_file_path
from safetensors import safe_open
from invokeai.app.services.config.config_default import get_config
from invokeai.backend.model_hash.... | 175 | 7,351 |
InvokeAI | invokeai/backend/model_manager/starter_models.py | .py | from typing import Optional
from pydantic import BaseModel
from invokeai.backend.model_manager.configs.external_api import (
ExternalApiModelDefaultSettings,
ExternalImageSize,
ExternalModelCapabilities,
ExternalModelPanelSchema,
ExternalResolutionPreset,
)
from invokeai.backend.model_manager.taxo... | 2,632 | 110,010 |
InvokeAI | invokeai/backend/model_manager/single_file_config_files.py | .py | from dataclasses import dataclass
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
ModelType,
ModelVariantType,
SchedulerPredictionType,
)
@dataclass(frozen=True)
class LegacyConfigKey:
type: ModelType
... | 94 | 3,406 |
InvokeAI | invokeai/backend/model_manager/search.py | .py | # Copyright 2023, Lincoln D. Stein and the InvokeAI Team
"""
Abstract base class and implementation for recursive directory search for models.
Example usage:
```
from invokeai.backend.model_manager import ModelSearch, ModelProbe
def find_main_models(model: Path) -> bool:
info = ModelProbe.probe(model)... | 143 | 4,902 |
InvokeAI | invokeai/backend/model_manager/taxonomy.py | .py | from enum import Enum
from typing import Dict, TypeAlias, Union
import onnxruntime as ort
import torch
from diffusers.models.modeling_utils import ModelMixin
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from pydantic import TypeAdapter
from invokeai.backend.raw_model import RawModel
# ModelMixin ... | 401 | 13,893 |
InvokeAI | invokeai/backend/model_manager/omi/__init__.py | .py | from invokeai.backend.model_manager.omi.omi import convert_from_omi
from invokeai.backend.model_manager.omi.vendor.model_spec.architecture import (
flux_dev_1_lora,
stable_diffusion_xl_1_lora,
)
__all__ = ["flux_dev_1_lora", "stable_diffusion_xl_1_lora", "convert_from_omi"]
| 8 | 284 |
InvokeAI | invokeai/backend/model_manager/omi/omi.py | .py | from invokeai.backend.model_manager.model_on_disk import StateDict
from invokeai.backend.model_manager.omi.vendor.convert.lora import (
convert_flux_lora as omi_flux,
)
from invokeai.backend.model_manager.omi.vendor.convert.lora import (
convert_lora_util as lora_util,
)
from invokeai.backend.model_manager.omi.... | 22 | 828 |
InvokeAI | invokeai/backend/model_manager/load/load_base.py | .py | # Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""
Base class for model loading in InvokeAI.
"""
from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Tuple
from weakref ... | 194 | 8,297 |
InvokeAI | invokeai/backend/model_manager/load/optimizations.py | .py | from contextlib import contextmanager
from typing import Any, Generator
import torch
def _no_op(*args: Any, **kwargs: Any) -> None:
pass
@contextmanager
def skip_torch_weight_init() -> Generator[None, None, None]:
"""Monkey patch several of the common torch layers (torch.nn.Linear, torch.nn.Conv1d, etc.) t... | 32 | 1,392 |
InvokeAI | invokeai/backend/model_manager/load/model_loader_registry.py | .py | # Copyright (c) 2024 Lincoln D. Stein and the InvokeAI Development team
"""
This module implements a system in which model loaders register the
type, base and format of models that they know how to load.
Use like this:
cls, model_config, submodel_type = ModelLoaderRegistry.get_implementation(model_config, submodel_... | 100 | 4,088 |
InvokeAI | invokeai/backend/model_manager/load/__init__.py | .py | # Copyright (c) 2024 Lincoln D. Stein and the InvokeAI Development Team
"""
Init file for the model loader.
"""
from importlib import import_module
from pathlib import Path
from invokeai.backend.model_manager.load.load_base import LoadedModel, LoadedModelWithoutConfig, ModelLoaderBase
from invokeai.backend.model_mana... | 28 | 1,015 |
InvokeAI | invokeai/backend/model_manager/load/load_default.py | .py | # Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""Default implementation of model loading in InvokeAI."""
import copy
import itertools
import re
from logging import Logger
from pathlib import Path
from typing import Optional
import torch
from invokeai.app.services.config import InvokeAIAppC... | 621 | 33,633 |
InvokeAI | invokeai/backend/model_manager/load/memory_snapshot.py | .py | import gc
from typing import Optional
import psutil
import torch
from typing_extensions import Self
from invokeai.backend.model_manager.util.libc_util import LibcUtil, Struct_mallinfo2
from invokeai.backend.util.devices import TorchDevice
GB = 2**30 # 1 GB
class MemorySnapshot:
"""A snapshot of RAM and VRAM u... | 107 | 4,561 |
InvokeAI | invokeai/backend/model_manager/load/model_util.py | .py | # Copyright (c) 2024 The InvokeAI Development Team
"""Various utility functions needed by the loader and caching system."""
import json
import logging
from pathlib import Path
from typing import Optional
import onnxruntime as ort
import torch
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffu... | 189 | 7,929 |
InvokeAI | invokeai/backend/model_manager/load/model_cache/dev_utils.py | .py | from contextlib import contextmanager
import torch
from invokeai.backend.util.logging import InvokeAILogger
@contextmanager
def log_operation_vram_usage(operation_name: str):
"""A helper function for tuning working memory requirements for memory-intensive ops.
Sample usage:
```python
with log_oper... | 34 | 1,065 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.