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
import math
from typing import overload
import gguf
import torch
from invokeai.backend.quantization.gguf.utils import (
DEQUANTIZE_FUNCTIONS,
TORCH_COMPATIBLE_QTYPES,
dequantize,
)
from invokeai.backend.util.devices import TorchDevice, device_has_dedicated_vram
def dequantize_and_run(func, args, kwargs):
"""A helper function for running math ops on GGMLTensor inputs.
Dequantizes the inputs, and runs the function.
Also casts other floating point tensors to match the compute_dtype of GGMLTensors
to avoid dtype mismatches in matrix operations.
"""
# Find the compute_dtype and target_device from any GGMLTensor in the args
compute_dtype = None
target_device = None
for a in args:
if hasattr(a, "compute_dtype"):
compute_dtype = a.compute_dtype
if isinstance(a, torch.Tensor) and target_device is None:
target_device = a.device
if compute_dtype is not None and target_device is not None:
break
if compute_dtype is None or target_device is None:
for v in kwargs.values():
if hasattr(v, "compute_dtype") and compute_dtype is None:
compute_dtype = v.compute_dtype
if isinstance(v, torch.Tensor) and target_device is None:
target_device = v.device
if compute_dtype is not None and target_device is not None:
break
def process_tensor(t):
if hasattr(t, "get_dequantized_tensor"):
result = t.get_dequantized_tensor()
# Ensure the dequantized tensor is on the target device
if target_device is not None and result.device != target_device:
result = result.to(target_device)
return result
elif isinstance(t, torch.Tensor) and compute_dtype is not None and t.is_floating_point():
# Cast other floating point tensors to match the GGUF compute_dtype
return t.to(compute_dtype)
return t
dequantized_args = [process_tensor(a) for a in args]
dequantized_kwargs = {k: process_tensor(v) for k, v in kwargs.items()}
return func(*dequantized_args, **dequantized_kwargs)
def apply_to_quantized_tensor(func, args, kwargs):
"""A helper function to apply a function to a quantized GGML tensor, and re-wrap the result in a GGMLTensor.
Assumes that the first argument is a GGMLTensor.
"""
# We expect the first argument to be a GGMLTensor, and all other arguments to be non-GGMLTensors.
ggml_tensor = args[0]
assert isinstance(ggml_tensor, GGMLTensor)
assert all(not isinstance(a, GGMLTensor) for a in args[1:])
assert all(not isinstance(v, GGMLTensor) for v in kwargs.values())
new_data = func(ggml_tensor.quantized_data, *args[1:], **kwargs)
if new_data.dtype != ggml_tensor.quantized_data.dtype:
# This is intended to catch calls such as `.to(dtype-torch.float32)`, which are not supported on GGMLTensors.
raise ValueError("Operation changed the dtype of GGMLTensor unexpectedly.")
return GGMLTensor(
new_data, ggml_tensor._ggml_quantization_type, ggml_tensor.tensor_shape, ggml_tensor.compute_dtype
)
GGML_TENSOR_OP_TABLE = {
# Ops to run on the quantized tensor.
torch.ops.aten.detach.default: apply_to_quantized_tensor, # pyright: ignore
torch.ops.aten._to_copy.default: apply_to_quantized_tensor, # pyright: ignore
torch.ops.aten.clone.default: apply_to_quantized_tensor, # pyright: ignore
# Ops to run on dequantized tensors.
torch.ops.aten.t.default: dequantize_and_run, # pyright: ignore
torch.ops.aten.addmm.default: dequantize_and_run, # pyright: ignore
torch.ops.aten.mul.Tensor: dequantize_and_run, # pyright: ignore
torch.ops.aten.add.Tensor: dequantize_and_run, # pyright: ignore
torch.ops.aten.sub.Tensor: dequantize_and_run, # pyright: ignore
torch.ops.aten.allclose.default: dequantize_and_run, # pyright: ignore
torch.ops.aten.slice.Tensor: dequantize_and_run, # pyright: ignore
torch.ops.aten.view.default: dequantize_and_run, # pyright: ignore
torch.ops.aten.expand.default: dequantize_and_run, # pyright: ignore
torch.ops.aten.index_put_.default: dequantize_and_run, # pyright: ignore
}
if torch.backends.mps.is_available():
GGML_TENSOR_OP_TABLE.update(
{torch.ops.aten.linear.default: dequantize_and_run} # pyright: ignore
)
class GGMLTensor(torch.Tensor):
"""A torch.Tensor sub-class holding a quantized GGML tensor.
The underlying tensor is quantized, but the GGMLTensor class provides a dequantized view of the tensor on-the-fly
when it is used in operations.
"""
@staticmethod
def __new__(
cls,
data: torch.Tensor,
ggml_quantization_type: gguf.GGMLQuantizationType,
tensor_shape: torch.Size,
compute_dtype: torch.dtype,
):
# Type hinting is not supported for torch.Tensor._make_wrapper_subclass, so we ignore the errors.
return torch.Tensor._make_wrapper_subclass( # pyright: ignore
cls,
data.shape,
dtype=data.dtype,
layout=data.layout,
device=data.device,
strides=data.stride(),
storage_offset=data.storage_offset(),
)
def __init__(
self,
data: torch.Tensor,
ggml_quantization_type: gguf.GGMLQuantizationType,
tensor_shape: torch.Size,
compute_dtype: torch.dtype,
):
self.quantized_data = data
self._ggml_quantization_type = ggml_quantization_type
# The dequantized shape of the tensor.
self.tensor_shape = tensor_shape
self.compute_dtype = compute_dtype
def __repr__(self, *, tensor_contents=None):
return f"GGMLTensor(type={self._ggml_quantization_type.name}, dequantized_shape=({self.tensor_shape})"
@overload
def size(self, dim: None = None) -> torch.Size: ...
@overload
def size(self, dim: int) -> int: ...
def size(self, dim: int | None = None):
"""Return the size of the tensor after dequantization. I.e. the shape that will be used in any math ops."""
if dim is not None:
return self.tensor_shape[dim]
return self.tensor_shape
@property
def shape(self) -> torch.Size: # pyright: ignore[reportIncompatibleVariableOverride] pyright doesn't understand this for some reason.
"""The shape of the tensor after dequantization. I.e. the shape that will be used in any math ops."""
return self.size()
@property
def quantized_shape(self) -> torch.Size:
"""The shape of the quantized tensor."""
return self.quantized_data.shape
def requires_grad_(self, mode: bool = True) -> torch.Tensor:
"""The GGMLTensor class is currently only designed for inference (not training). Setting requires_grad to True
is not supported. This method is a no-op.
"""
return self
def get_dequantized_tensor(self):
"""Return the dequantized tensor.
Args:
dtype: The dtype of the dequantized tensor.
"""
if self._ggml_quantization_type in TORCH_COMPATIBLE_QTYPES:
return self.quantized_data.to(self.compute_dtype)
elif self._ggml_quantization_type in DEQUANTIZE_FUNCTIONS:
# TODO(ryand): Look into how the dtype param is intended to be used.
return dequantize(
data=self.quantized_data, qtype=self._ggml_quantization_type, oshape=self.tensor_shape, dtype=None
).to(self.compute_dtype)
else:
# There is no GPU implementation for this quantization type, so fallback to the numpy implementation.
# The numpy implementation infers the output shape from the stored (possibly reshaped) data, so reshape
# to the logical shape here - see GGMLTensor.tensor_shape.
new = gguf.quants.dequantize(self.quantized_data.cpu().numpy(), self._ggml_quantization_type)
return (
torch.from_numpy(new)
.reshape(self.tensor_shape)
.to(self.quantized_data.device, dtype=self.compute_dtype)
)
@classmethod
def __torch_dispatch__(cls, func, types, args, kwargs):
# We will likely hit cases here in the future where a new op is encountered that is not yet supported.
# The new op simply needs to be added to the GGML_TENSOR_OP_TABLE.
if func in GGML_TENSOR_OP_TABLE:
return GGML_TENSOR_OP_TABLE[func](func, args, kwargs)
return NotImplemented
# What one dequantization allocates beyond its result, per weight element: the block kernels in
# `utils.py` widen codes and scales through integer and float16 intermediates before the final cast.
# Measured on CUDA (torch 2.13) for a 4608x53248 weight and rounded up; F32/F16 are a plain cast. Types
# not listed get the worst measured value when they have a device kernel; types without one (the IQ
# family) decode through the numpy fallback and get `_HOST_DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT`.
# These feed the per-forward working-memory reservation. The load-time counterpart, host RAM for
# decoding a whole tensor at load, is `HOST_DEQUANT_PEAK_COPIES` below.
_GGMLQ = gguf.GGMLQuantizationType
_DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT: dict[gguf.GGMLQuantizationType, float] = {
_GGMLQ.F32: 0.05,
_GGMLQ.F16: 0.0,
_GGMLQ.Q8_0: 2.0,
_GGMLQ.Q4_0: 2.0,
_GGMLQ.Q4_1: 3.0,
_GGMLQ.Q6_K: 3.25,
_GGMLQ.Q4_K: 3.25,
_GGMLQ.Q2_K: 3.25,
_GGMLQ.Q3_K: 3.5,
_GGMLQ.Q5_K: 5.25,
_GGMLQ.BF16: 6.0,
_GGMLQ.Q5_0: 8.0,
_GGMLQ.Q5_1: 8.0,
}
_DEQUANT_INTERMEDIATE_BYTES_WORST = 8.0
# Per-forward intermediates, in bytes per weight element beyond the result, of a type with no device
# kernel: NumPy decoding can retain float32 chunks alongside its full float32 output. They live in host
# RAM, so they count only when the execution device shares it (CPU, MPS, integrated XPU) and are 0 on
# dedicated VRAM. Keep the existing conservative shared-memory allowance separate from the device-kernel
# fallback.
_HOST_DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT = 8.0
# Load time, not per forward: host RAM one dequantization of a whole tensor takes, in multiples of its result,
# reserved in the RAM cache before decoding (SDNQ's included, for `model_manager/load/quantized_embedding.py`; per
# row slice in `loaders.py`). Measured, not derived: reading the dequantizers suggests 2 (an
# intermediate plus the result), and for the 8-bit formats that is what happens -- but the k-quant, 5-bit and 4-bit
# kernels unpack through full-size temporaries that coexist with both, and BF16 is not torch-compatible here
# (`TORCH_COMPATIBLE_QTYPES` is F32/F16 only) so it shuffles rather than passing through. Peak host RSS over one 256
# MB bf16 dequantization, sampled during the call, one format per fresh process:
#
# Q8_0 2.01x Q4_0 3.04x Q4_K 3.14x Q2_K 3.32x BF16 4.01x Q5_K 4.01x
# Q6_K 4.08x Q3_K 4.16x Q5_1 5.37x Q5_0 5.38x
# SDNQ: int8 2.00x uint4 3.99x int5 4.64x
#
# Q5_0/Q5_1 are the outliers and the reason for the headroom: `dequantize_blocks_Q5_0` expands the
# high bits through a full-size int32 shift table, which coexists with three uint8 temporaries, the
# fp16 product and the cast. The numpy fallback branch, despite going through float32, stays at ~4x.
#
# 6 clears the worst of them. It over-reserves for the 8-bit formats, which costs at most an
# eviction the cache can undo -- where under-reserving costs the swap this reservation exists to
# prevent, so the error belongs on this side. A per-format table would be exact and would silently
# rot the first time a new quant type lands, so the constant is deliberately blunt.
HOST_DEQUANT_PEAK_COPIES = 6
def peak_ggml_linear_dequant_transient_bytes(model: torch.nn.Module) -> int:
"""Peak bytes one forward transiently needs to dequantize this model's GGUF-packed Linear weights.
A packed Linear weight is dequantized on every forward into a full copy in its compute dtype,
which is not part of the model's resident size and so has to fit inside the calling node's
working-memory reservation. The layers run one after another and free their copy before the
next one allocates, so the peak is the largest single layer's: its dequantized copy, the kernels'
intermediates for its quantization type, and the packed bytes, which partial loading copies to
the device for the call. Zero when no Linear weight is packed.
"""
peak = 0
host_intermediates: float | None = None
for module in model.modules():
if not isinstance(module, torch.nn.Linear):
continue
weight = module.weight
if not isinstance(weight, GGMLTensor):
continue
qtype = weight._ggml_quantization_type
if qtype in TORCH_COMPATIBLE_QTYPES or qtype in DEQUANTIZE_FUNCTIONS:
intermediates = _DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT.get(qtype, _DEQUANT_INTERMEDIATE_BYTES_WORST)
else:
if host_intermediates is None:
# Streaming can leave weights on CPU; budget against the session's execution device.
device = TorchDevice.choose_torch_device()
host_intermediates = (
0.0 if device_has_dedicated_vram(device) else _HOST_DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT
)
intermediates = host_intermediates
per_element = weight.compute_dtype.itemsize + intermediates
peak = max(peak, math.ceil(weight.tensor_shape.numel() * per_element) + weight.quantized_data.nbytes)
return peak