"""Int8 ConvRot weights for the denoiser's image-path linear layers. ConvRot (rotation-based int8 for diffusion transformers) multiplies each run of ``CONVROT_GROUP_SIZE`` input features by a normalised regular Hadamard matrix ``H`` before quantizing. Because ``H`` is orthogonal, ``x W^T = (x H)(W H)^T``: the weights are rotated and quantized once, at release time, to int8 with one float32 scale per output row; at inference each activation row is rotated, quantized to int8 with its own scale, multiplied in int8 and rescaled. The rotation spreads outlier channels over their group, so no calibration data is needed. Only the 120 linear layers of the 30 image blocks are quantized (``qkv`` and ``proj_out`` of the attention, ``up`` and ``down`` of the MLP); the text refiner, embeddings, AdaLN projections, norms and the velocity head stay in their stored dtypes. The quantized tensors ship in ``model_int8.safetensors`` beside ``model.safetensors``, which still supplies everything else. ``H`` follows comfy_kitchen's ConvRot convention (Kronecker powers of a fixed 4x4 regular Hadamard), so its CUDA kernels apply the same rotation online. """ from __future__ import annotations import hashlib from collections.abc import Mapping from pathlib import Path from typing import TYPE_CHECKING import torch import torch.nn.functional as F from safetensors import safe_open from torch import Tensor, nn from .precision import DENOISER_PREFIX from .types import InferencePrecision if TYPE_CHECKING: from .configuration import DFlowConfig INT8_FILENAME = "model_int8.safetensors" CONVROT_GROUP_SIZE = 256 INT8_FORMAT = "dflow-convrot-w8a8" INT8_FORMAT_VERSION = "1" WEIGHT_INT8_SUFFIX = ".weight_int8" WEIGHT_SCALE_SUFFIX = ".weight_scale" INT8_MAX = 127.0 _SCALE_FLOOR = 1e-12 # comfy_kitchen's 4x4 regular Hadamard (unnormalised); H is its Kronecker power. _HADAMARD_4 = ( (1.0, 1.0, 1.0, -1.0), (1.0, 1.0, -1.0, 1.0), (1.0, -1.0, 1.0, 1.0), (-1.0, 1.0, 1.0, 1.0), ) def op_namespace(module_name: str) -> str: """A ``torch.library`` namespace unique to a module's import name. ComfyUI imports custom nodes under their folder path (``/`` and ``\\`` included), which is no valid namespace; a hash of the full name is, and importing the package under two names registers two separate operators. """ digest = hashlib.sha1(module_name.encode("utf-8")).hexdigest()[:16] return f"dflow_{digest}" def regular_hadamard(size: int) -> Tensor: """The normalised regular Hadamard matrix of order ``size`` (float32, CPU). Symmetric and orthogonal (``H @ H = I``). Raises: ValueError: If ``size`` is not a power of 4 of at least 4. """ base = torch.tensor(_HADAMARD_4, dtype=torch.float32, device="cpu") matrix = base order = 4 while order < size: matrix = torch.kron(matrix, base) order *= 4 if order != size: raise ValueError(f"ConvRot group size must be a power of 4, got {size}") return matrix / size**0.5 def rotate_groups(values: Tensor, hadamard: Tensor) -> Tensor: """Multiply every run of ``hadamard.shape[0]`` trailing features by it. Raises: ValueError: If the trailing size is not a multiple of the group size. """ group = int(hadamard.shape[0]) features = int(values.shape[-1]) if features % group: raise ValueError(f"{features} features are not a multiple of group {group}") grouped = values.reshape(*values.shape[:-1], features // group, group) return (grouped @ hadamard).reshape(values.shape) def quantize_convrot_weight(weight: Tensor) -> tuple[Tensor, Tensor]: """Rotate a linear weight ``[out, in]`` and quantize it per output row. Computed in float32. Returns the int8 weight ``[out, in]`` and its float32 scales ``[out]`` (``weight ~= dequantized @ H``, row by row). Raises: ValueError: If ``weight`` is not 2-D or ``in`` is not a multiple of ``CONVROT_GROUP_SIZE``. """ if weight.dim() != 2: raise ValueError(f"Expected a 2-D linear weight, got {tuple(weight.shape)}") hadamard = regular_hadamard(CONVROT_GROUP_SIZE).to(device=weight.device) rotated = rotate_groups(weight.to(dtype=torch.float32), hadamard) scale = (rotated.abs().amax(dim=1) / INT8_MAX).clamp(min=_SCALE_FLOOR) quantized = torch.round(rotated / scale[:, None]).clamp(-INT8_MAX, INT8_MAX) return quantized.to(dtype=torch.int8).contiguous(), scale.contiguous() def quantized_linear_shapes(config: DFlowConfig) -> dict[str, tuple[int, int]]: """``{module path: (out, in)}`` of every quantized linear (no prefix).""" width = config.width shapes = { "attn.qkv": (3 * width, width), "attn.proj_out": (width, width), "mlp.up": (config.mlp_hidden_width, width), "mlp.down": (width, config.mlp_hidden_width), } stacks = ( ("prefix_layers", config.prefix_depth), ("middle_layers", config.middle_depth), ("suffix_layers", config.suffix_depth), ) return { f"{stack}.{index}.{leaf}": shape for stack, depth in stacks for index in range(depth) for leaf, shape in shapes.items() } def quantize_release_tensors( tensors: Mapping[str, Tensor], config: DFlowConfig ) -> dict[str, Tensor]: """The ``model_int8.safetensors`` tensors of a release's ``model.safetensors``. Raises: KeyError: If a quantized layer's weight is missing from ``tensors``. ValueError: If a weight has another shape than ``config`` gives. """ out: dict[str, Tensor] = {} for path, shape in quantized_linear_shapes(config).items(): weight = tensors[f"{DENOISER_PREFIX}{path}.weight"] if tuple(weight.shape) != shape: raise ValueError(f"{path}.weight is {tuple(weight.shape)}, not {shape}") quantized, scale = quantize_convrot_weight(weight) out[f"{DENOISER_PREFIX}{path}{WEIGHT_INT8_SUFFIX}"] = quantized out[f"{DENOISER_PREFIX}{path}{WEIGHT_SCALE_SUFFIX}"] = scale return out def int8_file_metadata() -> dict[str, str]: """The safetensors header metadata of ``model_int8.safetensors``.""" return { "format": INT8_FORMAT, "format_version": INT8_FORMAT_VERSION, "group_size": str(CONVROT_GROUP_SIZE), } def read_int8_tensors(directory: Path, config: DFlowConfig) -> dict[str, Tensor]: """Read and validate a release's ``model_int8.safetensors`` (on the CPU). Raises: FileNotFoundError: If the file is missing. ValueError: If its format, names, shapes or dtypes do not match. """ path = directory / INT8_FILENAME if not path.is_file(): raise FileNotFoundError( f"Missing {path}: this release has no int8 weights (releases from " "0.31 on ship them)." ) with safe_open(str(path), framework="pt", device="cpu") as handle: metadata = handle.metadata() if metadata != int8_file_metadata(): raise ValueError( f"{path} has metadata {metadata}; this package reads " f"{int8_file_metadata()}" ) tensors = {name: handle.get_tensor(name) for name in handle.keys()} # noqa: SIM118 expected: dict[str, tuple[tuple[int, ...], torch.dtype]] = {} for module, (rows, columns) in quantized_linear_shapes(config).items(): name = f"{DENOISER_PREFIX}{module}" expected[name + WEIGHT_INT8_SUFFIX] = ((rows, columns), torch.int8) expected[name + WEIGHT_SCALE_SUFFIX] = ((rows,), torch.float32) if set(tensors) != set(expected): missing = sorted(set(expected) - set(tensors))[:3] extra = sorted(set(tensors) - set(expected))[:3] raise ValueError(f"{path}: missing {missing}, unexpected {extra}") for name, (shape, dtype) in expected.items(): tensor = tensors[name] if tuple(tensor.shape) != shape or tensor.dtype != dtype: raise ValueError( f"{path}: {name} is {tensor.dtype} {tuple(tensor.shape)}, " f"expected {dtype} {shape}" ) return tensors class Int8ConvRotLinear(nn.Module): """A linear layer with ConvRot int8 weights. ``INT8`` multiplies int8 activations by the int8 weights on the kernel of the device given to ``bind_kernel`` (the loader calls it once the model is on its device); ``INT8_WEIGHT_ONLY`` rotates the activations and multiplies them by the dequantized weights in bfloat16, on any device. Inputs are cast to bfloat16 (as bf16 autocast does for ``nn.Linear``) and the output is bfloat16. """ weight_int8: Tensor weight_scale: Tensor hadamard: Tensor bias: nn.Parameter | None in_features: int out_features: int precision: InferencePrecision def __init__( self, in_features: int, out_features: int, *, bias: bool, precision: InferencePrecision, ) -> None: """Allocate the int8 weight, its scales and the optional bf16 bias. Raises: ValueError: If ``precision`` is not an int8 precision. """ super().__init__() self.in_features = in_features self.out_features = out_features self.register_buffer( "weight_int8", torch.empty(out_features, in_features, dtype=torch.int8) ) self.register_buffer( "weight_scale", torch.empty(out_features, dtype=torch.float32) ) self.register_buffer( "hadamard", regular_hadamard(CONVROT_GROUP_SIZE).to(dtype=torch.bfloat16), persistent=False, ) self.bias = ( nn.Parameter(torch.empty(out_features, dtype=torch.bfloat16)) if bias else None ) self.precision = precision match precision: case InferencePrecision.INT8: self._implementation = self._forward_unbound case InferencePrecision.INT8_WEIGHT_ONLY: self._implementation = self._forward_weight_only case other: raise ValueError( f"Int8ConvRotLinear needs an int8 precision, got {other}" ) def bind_kernel(self, device: torch.device) -> None: """Pick the int8 kernel of ``device`` (``INT8`` only; weight-only layers need none). Raises: ValueError: For ``INT8`` on a device other than CUDA or MPS. """ if self.precision is not InferencePrecision.INT8: return match device.type: case "cuda": from .int8_kernels import cuda_int8_convrot_linear self._kernel = cuda_int8_convrot_linear case "mps": from .int8_metal import metal_int8_convrot_linear self._kernel = metal_int8_convrot_linear case other: raise ValueError(f"int8 kernels run on CUDA or MPS, got {other}") self._implementation = self._forward_int8 def forward(self, x: Tensor) -> Tensor: """``x W^T + b`` for ``x`` ``[..., in_features]``, in bfloat16.""" return self._implementation(x.to(dtype=torch.bfloat16)) def _forward_unbound(self, x: Tensor) -> Tensor: """Refuse to run before ``bind_kernel``. Raises: RuntimeError: Always. """ del x raise RuntimeError( "Int8ConvRotLinear has no kernel: call bind_kernel(device) after " "moving it to its device (load_dflow_denoiser does)." ) def _forward_int8(self, x: Tensor) -> Tensor: """int8 activations times int8 weights on the device's kernel.""" return self._kernel( x.contiguous(), self.weight_int8, self.weight_scale, self.bias ) def _forward_weight_only(self, x: Tensor) -> Tensor: """Rotated activations times the dequantized (rotated) weights.""" weight = self.weight_int8.to(dtype=torch.bfloat16) * self.weight_scale.to( dtype=torch.bfloat16 ).unsqueeze(1) return F.linear(rotate_groups(x, self.hadamard), weight, self.bias)