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
"""Linears that keep their weight quantized in buffers and materialize it on every forward.
Three schemes store their Linears this way, ``int8_convrot``, ``nvfp4`` and Ideogram 4's row-wise fp8
(``fp8_rowwise``); GGUF keeps a plain Linear but packs its weight in a ``GGMLTensor`` and dequantizes it
per forward just the same. The code around them
needs the same three answers about any of these: whether a LoRA has to ride along as a sidecar, how
much memory one forward needs on top of the model's resident size, and whether FP8 Storage may cast the
build's other, full-precision layers (`leaves_dense_layers_to_fp8_storage`). The first two are asked of the
loaded module tree and live here, so callers ask once for every scheme: a module-level scheme answers by
subclassing, GGUF -- whose quantization lives on the weight, not the module -- is delegated to.
"""
import abc
import sys
from typing import Any, ClassVar
import torch
import torch.nn.functional as F
from invokeai.backend.model_manager.taxonomy import ModelFormat
from invokeai.backend.quantization.gguf.ggml_tensor import peak_ggml_linear_dequant_transient_bytes
class DequantizingLinear(torch.nn.Module, abc.ABC):
"""A Linear whose weight is kept quantized as buffers and dequantized on every forward.
Subclasses register their payload as persistent buffers under the checkpoint's own key names, so
``load_state_dict`` assigns the quantized tensors straight into them and the model cache moves them
between devices like any other weight. ``bias`` is a buffer as well, or ``None``.
``forward`` takes the weight from :meth:`_dequantized_weight` on the input's device and in its dtype,
so a partial load that left the buffers on the CPU streams them per call instead of failing. The model
cache wraps these modules for sidecar patches (see ``AUTOCAST_MODULE_TYPE_MAPPING``).
Both methods are abstract so that a scheme missing one fails where its modules are built, at load,
rather than in the denoise node that sizes its working memory from them.
"""
#: Whether FP8 Storage may cast the other, full-precision layers of a build holding this scheme. By default it
#: declines the whole build: those layers keep the precision the build chose. A scheme opts in only where
#: measurement showed that casting them costs nothing material.
leaves_dense_layers_to_fp8_storage: ClassVar[bool] = False
in_features: int
out_features: int
bias: torch.Tensor | None
@abc.abstractmethod
def _dequantized_weight(self, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
"""The weight as ``[out_features, in_features]`` in ``dtype`` on ``device``, for one forward."""
@abc.abstractmethod
def dequant_transient_bytes(self, compute_dtype: torch.dtype) -> int:
"""Peak bytes one forward of this layer allocates beyond its resident buffers."""
def forward(self, x: torch.Tensor) -> torch.Tensor:
weight = self._dequantized_weight(x.device, x.dtype)
bias = self.bias.to(device=x.device, dtype=x.dtype) if self.bias is not None else None
return F.linear(x, weight, bias)
def requires_sidecar_patching(model: Any, model_format: ModelFormat) -> bool:
"""Whether LoRA has to be applied as a sidecar rather than written into the weights.
The format alone does not answer this. A plain ``checkpoint`` may still hold
:class:`DequantizingLinear` modules -- an ``int8_tensorwise`` or ``nvfp4`` build whose Linears the
loader replaced -- and those keep their weights as quantized *buffers*, which a direct patch cannot
write into. Worse, the patcher's own fallbacks iterate ``module.parameters()``, and these modules have
none, so they answer "not quantized" and direct patching is chosen. So the loaded module tree is
consulted, not just the config.
"""
if model_format in (ModelFormat.GGUFQuantized, ModelFormat.SDNQQuantized):
return True
# bitsandbytes Linears (Ideogram 4's nf4 pair is a Diffusers folder) pack their weight into a uint8
# parameter, which a direct patch reports as a shape mismatch and skips, layer by layer. Their classes
# are only looked up, never imported: bitsandbytes is optional, and a model holding such modules has
# imported them already.
quantized_types = (DequantizingLinear, *_loaded_bnb_linear_types())
return any(isinstance(module, quantized_types) for module in model.modules())
def _loaded_bnb_linear_types() -> tuple[type, ...]:
found: list[type] = []
for module_name, class_name in (
("invokeai.backend.quantization.bnb_nf4", "InvokeLinearNF4"),
("invokeai.backend.quantization.bnb_llm_int8", "InvokeLinear8bitLt"),
):
module = sys.modules.get(module_name)
if module is not None:
found.append(getattr(module, class_name))
return tuple(found)
def peak_dequant_transient_bytes(model: torch.nn.Module, compute_dtype: torch.dtype) -> int:
"""Peak bytes one forward transiently needs to dequantize this model's quantized linears.
A :class:`DequantizingLinear` materializes its weight per forward, and so does a Linear whose weight
is a GGUF ``GGMLTensor`` (see :func:`peak_ggml_linear_dequant_transient_bytes`), so that allocation is
not covered by the model's resident size and has to fit inside the calling node's working-memory
reservation. The layers run one after another and free their weight before the next one allocates, so
the peak is the largest single layer's transient. Zero when the model holds no such layer.
``compute_dtype`` applies to the module-level schemes; a GGUF weight carries its own.
Not covered: the matmul's own cuBLAS workspace, which a dense Linear of the same shape allocates too
and which a node's activation estimate already includes.
"""
dequantizing = max(
(
module.dequant_transient_bytes(compute_dtype)
for module in model.modules()
if isinstance(module, DequantizingLinear)
),
default=0,
)
return max(dequantizing, peak_ggml_linear_dequant_transient_bytes(model))