Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio GGUF: load IQ1_S / IQ1_M / IQ2_XXS / IQ2_XS / IQ2_S / IQ3_XXS / IQ3_S on the diffusers path (#17071)

Daniel Han66eb0c2ea5fa
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 6745d41c3ec..e0239e14d6c 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -320,6 +320,7 @@ from .diffusion_offload_prefetch import cross_forward_render, cross_forward_step
from .diffusion_vae_fp16 import enable_fp16_vae_decode
from .diffusion_vae_upcast import pipeline_upcasts_keep_storage
from .diffusion_vae_tiling import install as install_wide_vae_tiles
+from .diffusion_gguf_lowbit import install_lowbit_iq
from .diffusion_attention import (
apply_attention_backend,
attention_status_reason,
@@ -9924,6 +9925,8 @@ class DiffusionBackend:
# Before the prefix shim, which cannot wrap an unregistered class.
_register_unregistered_single_file_classes(logger)
if kind == "gguf":
+ # IQ1 / IQ2 / IQ3 tensors diffusers' table lacks would refuse the file
+ install_lowbit_iq(logger)
# Dequantise the GGUF transformer on-device at the compute dtype.
sf_kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(
compute_dtype = dtype
diff --git a/studio/backend/core/inference/diffusion_gguf_lowbit.py b/studio/backend/core/inference/diffusion_gguf_lowbit.py
new file mode 100644
index 00000000000..c09b8663934
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_gguf_lowbit.py
@@ -0,0 +1,359 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Torch dequant for the GGUF types diffusers' table lacks (IQ1_S, IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S), so a
+GGUF holding them loads on the diffusers path instead of being refused, and its weights stay packed on the device.
+Each function is gguf-py's numpy ``dequantize_blocks`` op for op (the same fp32 order, so the same bits) on gguf-py's
+own grids; types diffusers already handles are never replaced. UNSLOTH_DIFFUSION_GGUF_LOWBIT_IQ=0 keeps the refusal."""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+LOWBIT_IQ_ENV = "UNSLOTH_DIFFUSION_GGUF_LOWBIT_IQ"
+_QK_K = 256
+# table -> gguf-py's grid / sign table on the CPU
+_HOST: dict = {}
+# (table, device) -> that table on the device
+_CONSTS: dict = {}
+_TABLES = {
+ "IQ1_S": ("IQ1_S",),
+ "IQ1_M": ("IQ1_S",),
+ "IQ2_XXS": ("ksigns", "IQ2_XXS"),
+ "IQ2_XS": ("ksigns", "IQ2_XS"),
+ "IQ2_S": ("IQ2_S",),
+ "IQ3_XXS": ("ksigns", "IQ3_XXS"),
+ "IQ3_S": ("IQ3_S",),
+}
+
+
+def lowbit_iq_enabled() -> bool:
+ return os.environ.get(LOWBIT_IQ_ENV, "").strip().lower() not in ("0", "false", "no", "off")
+
+
+def _host(name: str) -> Any:
+ value = _HOST.get(name)
+ if value is not None:
+ return value
+ import numpy as np
+ import torch
+ from gguf import quants
+
+ if name == "ksigns":
+ table = np.frombuffer(quants.IQ2_XXS.ksigns, dtype = np.uint8).astype(np.int64)
+ else:
+ cls = getattr(quants, name)
+ cls.init_grid()
+ table = np.ascontiguousarray(cls.grid.reshape(cls.grid_shape), dtype = np.float32)
+ value = torch.from_numpy(table.copy())
+ _HOST[name] = value
+ return value
+
+
+def _build(name: str, device: Any) -> Any:
+ value = _host(name).to(device)
+ _CONSTS[(name, str(device))] = value
+ return value
+
+
+def _const(name: str, device: Any) -> Any:
+ value = _CONSTS.get((name, str(device)))
+ if value is not None:
+ return value
+ import torch
+
+ if torch.compiler.is_compiling():
+ host = _HOST.get(name)
+ if host is not None:
+ # unprepared device: a traceable copy, no graph break
+ return host.to(device)
+ # only without install_lowbit_iq
+ return torch.compiler.disable(_build)(name, device)
+ return _build(name, device)
+
+
+def prepare_lowbit_iq_tables(device: Any, *modules: Any) -> list:
+ """Build on ``device`` before compile so graphs hold a device constant; with ``modules``, only what their IQ weights need."""
+ try:
+ import torch
+
+ if modules:
+ types = set()
+ for module in modules:
+ for param in getattr(module, "parameters", lambda: ())():
+ qtype = getattr(param, "quant_type", None)
+ name = getattr(qtype, "name", None)
+ if name in _TABLES:
+ types.add(name)
+ names = sorted({t for name in types for t in _TABLES[name]})
+ else:
+ names = sorted({t for tables in _TABLES.values() for t in tables})
+ if not names:
+ return []
+ # "cuda" -> "cuda:0", the key a weight's device gives
+ device = torch.empty(0, device = device).device
+ for name in names:
+ if (name, str(device)) not in _CONSTS:
+ _build(name, device)
+ return names
+ except Exception: # noqa: BLE001 - optimisation only: the lookup still builds traceably
+ return []
+
+
+def _shifts(values: tuple, like: Any) -> Any:
+ import torch
+ return torch.tensor(values, device = like.device, dtype = like.dtype)
+
+
+def _words(raw: Any, width: int) -> Any:
+ """Little-endian ``width``-byte unsigned words of a uint8 tensor, as int64 (last dim / width words)."""
+ b = raw.reshape(*raw.shape[:-1], -1, width).long()
+ out = b[..., 0]
+ for i in range(1, width):
+ out = out | (b[..., i] << (8 * i))
+ return out
+
+
+def _f16(raw: Any) -> Any:
+ import torch
+ return raw.contiguous().view(torch.float16).to(torch.float32)
+
+
+def _sign_bits(byte: Any) -> Any:
+ """Each byte's 8 bits, low first, as +1 (bit clear) / -1 (bit set), fp32."""
+ import torch
+
+ bit = (byte.unsqueeze(-1) >> _shifts(tuple(range(8)), byte)) & 1
+ return torch.where(bit == 0, 1.0, -1.0).to(torch.float32)
+
+
+def _ksign_bits(index: Any) -> Any:
+ return _sign_bits(_const("ksigns", index.device)[index])
+
+
+def _grid(name: str, index: Any) -> Any:
+ return _const(name, index.device)[index]
+
+
+def dequantize_blocks_IQ2_XXS(
+ blocks: Any,
+ block_size: Any,
+ type_size: Any,
+ dtype: Any = None,
+) -> Any:
+ n = blocks.shape[0]
+ d = _f16(blocks[:, :2])
+ qs = blocks[:, 2:].reshape(
+ n, -1, 2, 4
+ ) # per 32 values: 4 grid bytes, then a word of 4 sign indices + scale
+ aux = _words(qs[:, :, 1], 4)[..., 0]
+ db = d * (0.5 + (aux >> 28).float()) * 0.25
+ db = db.reshape(n, -1, 1, 1)
+ signs = (aux.unsqueeze(-1) >> _shifts((0, 7, 14, 21), aux)) & 0x7F
+ signs = _ksign_bits(signs).reshape(n, -1, 4, 8)
+ grid = _grid("IQ2_XXS", qs[:, :, 0].long()).reshape(n, -1, 4, 8)
+ return (db * grid * signs).reshape(n, -1)
+
+
+def dequantize_blocks_IQ2_XS(
+ blocks: Any,
+ block_size: Any,
+ type_size: Any,
+ dtype: Any = None,
+) -> Any:
+ n = blocks.shape[0]
+ d = _f16(blocks[:, :2])
+ qs = _words(blocks[:, 2 : 2 + 2 * _QK_K // 8], 2)
+ scales = blocks[:, 2 + 2 * _QK_K // 8 :]
+ scales = ((scales.reshape(n, -1, 1) >> _shifts((0, 4), scales)) & 0x0F).reshape(n, -1)
+ db = d * (0.5 + scales.float()) * 0.25
+ db = db.reshape(n, -1, 1, 1)
+ signs = _ksign_bits(qs >> 9).reshape(n, -1, 2, 8)
+ grid = _grid("IQ2_XS", qs & 511).reshape(n, -1, 2, 8)
+ return (db * grid * signs).reshape(n, -1)
+
+
+def dequantize_blocks_IQ2_S(
+ blocks: Any,
+ block_size: Any,
+ type_size: Any,
+ dtype: Any = None,
+) -> Any:
+ n = blocks.shape[0]
+ q = _QK_K // 8
+ d = _f16(blocks[:, :2])
+ qs = blocks[:, 2 : 2 + q]
+ signs = blocks[:, 2 + q : 2 + 2 * q]
+ qh = blocks[:, 2 + 2 * q : 2 + 2 * q + _QK_K // 32]
+ scales = blocks[:, 2 + 2 * q + _QK_K // 32 :]
+ scales = ((scales.reshape(n, -1, 1) >> _shifts((0, 4), scales)) & 0x0F).reshape(n, -1)
+ db = d * (0.5 + scales.float()) * 0.25
+ db = db.reshape(n, -1, 1, 1)
+ signs = _sign_bits(signs).reshape(n, -1, 2, 8)
+ qh = qh.reshape(n, -1, 1) >> _shifts((0, 2, 4, 6), qh)
+ index = qs.long() | ((qh & 0x03).long() << 8).reshape(n, -1)
+ grid = _grid("IQ2_S", index).reshape(n, -1, 2, 8)
+ return (db * grid * signs).reshape(n, -1)
+
+
+def dequantize_blocks_IQ3_XXS(
+ blocks: Any,
+ block_size: Any,
+ type_size: Any,
+ dtype: Any = None,
+) -> Any:
+ n = blocks.shape[0]
+ d = _f16(blocks[:, :2])
+ qs = blocks[:, 2 : 2 + _QK_K // 4]
+ scales = _words(blocks[:, 2 + _QK_K // 4 :], 4)
+ db = d * (0.5 + (scales >> 28).float()) * 0.5
+ db = db.reshape(n, -1, 1, 1)
+ signs = (scales.unsqueeze(-1) >> _shifts((0, 7, 14, 21), scales)) & 0x7F
+ signs = _ksign_bits(signs).reshape(n, -1, 4, 8)
+ grid = _grid("IQ3_XXS", qs.long()).reshape(n, -1, 4, 8)
+ return (db * grid * signs).reshape(n, -1)
+
+
+def dequantize_blocks_IQ3_S(
+ blocks: Any,
+ block_size: Any,
+ type_size: Any,
+ dtype: Any = None,
+) -> Any:
+ n = blocks.shape[0]
+ d = _f16(blocks[:, :2])
+ o = 2
+ qs = blocks[:, o : o + _QK_K // 4]
+ o += _QK_K // 4
+ qh = blocks[:, o : o + _QK_K // 32]
+ o += _QK_K // 32
+ signs = blocks[:, o : o + _QK_K // 8]
+ scales = blocks[:, o + _QK_K // 8 :]
+ scales = ((scales.reshape(n, -1, 1) >> _shifts((0, 4), scales)) & 0x0F).reshape(n, -1)
+ db = d * (1 + 2 * scales.long()).float()
+ db = db.reshape(n, -1, 1, 1)
+ signs = _sign_bits(signs).reshape(n, -1, 4, 8)
+ qh = ((qh.reshape(n, -1, 1) >> _shifts(tuple(range(8)), qh)) & 0x01).long().reshape(n, -1)
+ index = qs.long() | (qh << 8)
+ grid = _grid("IQ3_S", index).reshape(n, -1, 4, 8)
+ return (db * grid * signs).reshape(n, -1)
+
+
+def _iq1_delta() -> float:
+ value = _HOST.get("iq1_delta")
+ if value is None:
+ from gguf import quants
+ value = _HOST["iq1_delta"] = float(quants.IQ1_S.delta)
+ return value
+
+
+def dequantize_blocks_IQ1_S(
+ blocks: Any,
+ block_size: Any,
+ type_size: Any,
+ dtype: Any = None,
+) -> Any:
+ import torch
+
+ n = blocks.shape[0]
+ d = _f16(blocks[:, :2])
+ qs = blocks[:, 2 : 2 + _QK_K // 8]
+ qh = _words(blocks[:, 2 + _QK_K // 8 :], 2)
+ dl = d * (2 * ((qh >> 12) & 7) + 1).float()
+ dl = dl.reshape(n, -1, 1, 1)
+ delta = _iq1_delta()
+ delta = torch.where((qh & 0x8000) == 0, delta, -delta).to(torch.float32).reshape(n, -1, 1, 1)
+ qh = qh.reshape(n, -1, 1) >> _shifts((0, 3, 6, 9), qh)
+ index = qs.long() | ((qh & 7) << 8).reshape(n, -1)
+ grid = _grid("IQ1_S", index).reshape(n, -1, 4, 8)
+ return (dl * (grid + delta)).reshape(n, -1)
+
+
+def dequantize_blocks_IQ1_M(
+ blocks: Any,
+ block_size: Any,
+ type_size: Any,
+ dtype: Any = None,
+) -> Any:
+ import torch
+
+ n = blocks.shape[0]
+ qs = blocks[:, : _QK_K // 8]
+ qh = blocks[:, _QK_K // 8 : _QK_K // 8 + _QK_K // 16]
+ scales = _words(blocks[:, _QK_K // 8 + _QK_K // 16 :], 2)
+ # the fp16 super-scale is spread over the top nibble of the four scale words
+ d = (scales.reshape(n, 4) & 0xF000) >> _shifts((12, 8, 4, 0), scales)
+ d = d[..., 0] | d[..., 1] | d[..., 2] | d[..., 3]
+ d = d.to(torch.int16).view(torch.float16).to(torch.float32).reshape(n, 1)
+ scales = ((scales.reshape(n, -1, 1) >> _shifts((0, 3, 6, 9), scales)) & 0x07).reshape(n, -1)
+ dl = d * (2 * scales + 1).float()
+ dl = dl.reshape(n, -1, 2, 1, 1)
+ qh = qh.reshape(n, -1, 1) >> _shifts((0, 4), qh)
+ index = qs.long() | ((qh & 0x07).long() << 8).reshape(n, -1)
+ delta = _iq1_delta()
+ delta = torch.where((qh & 0x08) == 0, delta, -delta).to(torch.float32).reshape(n, -1, 2, 2, 1)
+ grid = _grid("IQ1_S", index).reshape(n, -1, 2, 2, 8)
+ return (dl * (grid + delta)).reshape(n, -1)
+
+
+_FUNCTIONS = {
+ "IQ1_S": dequantize_blocks_IQ1_S,
+ "IQ1_M": dequantize_blocks_IQ1_M,
+ "IQ2_XXS": dequantize_blocks_IQ2_XXS,
+ "IQ2_XS": dequantize_blocks_IQ2_XS,
+ "IQ2_S": dequantize_blocks_IQ2_S,
+ "IQ3_XXS": dequantize_blocks_IQ3_XXS,
+ "IQ3_S": dequantize_blocks_IQ3_S,
+}
+_added: list = []
+
+
+def install_lowbit_iq(logger: Any = None) -> list:
+ """Add the missing IQ types to diffusers' table in place (the loader reads the same dict); never replaces one."""
+ if not lowbit_iq_enabled():
+ return []
+ try:
+ import gguf
+ from diffusers.quantizers.gguf import utils as gguf_utils
+ except Exception: # noqa: BLE001 - no GGUF support in this diffusers: nothing to extend
+ return []
+ table = getattr(gguf_utils, "dequantize_functions", None)
+ supported = getattr(gguf_utils, "SUPPORTED_GGUF_QUANT_TYPES", None)
+ if not isinstance(table, dict) or not isinstance(supported, list):
+ return []
+ added = []
+ for name, fn in _FUNCTIONS.items():
+ qtype = getattr(gguf.GGMLQuantizationType, name, None)
+ if qtype is None or qtype in table:
+ continue
+ table[qtype] = fn
+ if qtype not in supported:
+ supported.append(qtype)
+ added.append(name)
+ _added.append(qtype)
+ if _added:
+ try:
+ for name in sorted({t for tables in _TABLES.values() for t in tables}):
+ _host(name)
+ _iq1_delta()
+ except Exception: # noqa: BLE001 - the eager lookup builds them on first use
+ pass
+ if added and logger is not None:
+ logger.info("diffusion.gguf: dequantising %s on the device", ", ".join(added))
+ return added
+
+
+def uninstall_lowbit_iq() -> None:
+ """Take back exactly the types ``install_lowbit_iq`` added. Idempotent."""
+ try:
+ from diffusers.quantizers.gguf import utils as gguf_utils
+ except Exception: # noqa: BLE001
+ _added.clear()
+ return
+ for qtype in _added:
+ if gguf_utils.dequantize_functions.get(qtype) in _FUNCTIONS.values():
+ del gguf_utils.dequantize_functions[qtype]
+ if qtype in gguf_utils.SUPPORTED_GGUF_QUANT_TYPES:
+ gguf_utils.SUPPORTED_GGUF_QUANT_TYPES.remove(qtype)
+ _added.clear()
diff --git a/studio/backend/core/inference/diffusion_gguf_pipeline.py b/studio/backend/core/inference/diffusion_gguf_pipeline.py
index 2a9d60b77a7..7839975a955 100644
--- a/studio/backend/core/inference/diffusion_gguf_pipeline.py
+++ b/studio/backend/core/inference/diffusion_gguf_pipeline.py
@@ -66,6 +66,9 @@ def load_whole_pipeline_gguf(
import diffusers.loaders.single_file as single_file_mod
from diffusers.loaders.single_file_utils import load_single_file_checkpoint
+ from .diffusion_gguf_lowbit import install_lowbit_iq
+
+ install_lowbit_iq() # diffusers' reader refuses unknown types, so before the read
checkpoint = load_single_file_checkpoint(
path,
local_files_only = pipe_kwargs.get("local_files_only"),
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 15d9f218c34..fbc15e11417 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -522,6 +522,8 @@ def apply_speed_optims(
return applied
if mode in (SPEED_DEFAULT, SPEED_MAX):
_pin_compile_defaults()
+ if is_gguf:
+ _prepare_lowbit_iq_tables(pipe, target)
if getattr(target, "backend", None) == "rocm":
try:
@@ -684,6 +686,24 @@ def apply_speed_optims(
return applied
+def _prepare_lowbit_iq_tables(pipe: Any, target: Any) -> None:
+ """Low-bit IQ lookup tables on the execution device before compile, so a compiled block reads a device constant."""
+ device = getattr(target, "torch_device", None)
+ if not isinstance(device, str) or not device:
+ return
+ try:
+ from .diffusion_gguf_lowbit import prepare_lowbit_iq_tables
+
+ modules = list(_denoiser_dits(pipe))
+ unet = _denoiser_unet(pipe)
+ if unet is not None:
+ modules.append(unet)
+ if modules:
+ prepare_lowbit_iq_tables(device, *modules)
+ except Exception: # noqa: BLE001 - optimisation only: the lookup still builds traceably
+ pass
+
+
def _onload_device(target: Any) -> Optional[str]:
"""Onload device of an offloaded denoiser, else None. NVIDIA only: ROCm runs int8 weight-only, never this GEMM."""
if getattr(target, "device", None) != "cuda" or getattr(target, "backend", "cuda") != "cuda":
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 2a82a3ec040..6a7d9a76f53 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -9867,6 +9867,8 @@ class VideoBackend:
"local_files_only": local_files_only,
}
if kind == "gguf":
+ from .diffusion_gguf_lowbit import install_lowbit_iq
+ install_lowbit_iq(logger)
sf_kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(
compute_dtype = dtype
)
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index 89a5ee5ec7e..2c14cc8cb9f 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -1330,6 +1330,8 @@ def load_ltx23_transformer(
# The load plan's commit for that hub-id config (absent for an unpinned load).
kwargs.update(pinned_revision_kwargs(base_repo))
if is_gguf:
+ from .diffusion_gguf_lowbit import install_lowbit_iq
+ install_lowbit_iq()
kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(compute_dtype = torch_dtype)
elif device is not None:
# Else the meta load copies every tensor back to the host.
@@ -1632,6 +1634,9 @@ def _assemble_ltx23_pipeline(
if state is None and transformer_override is not None and not is_gguf:
state = _load_checkpoint_without_dit(checkpoint_path)
if state is None:
+ if is_gguf:
+ from .diffusion_gguf_lowbit import install_lowbit_iq
+ install_lowbit_iq() # before the read: diffusers' reader refuses unknown types
state = load_single_file_checkpoint(str(checkpoint_path))
groups = _split_checkpoint(state)
del state
diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.py
index ce7e90d511f..cdf1e16573d 100644
--- a/studio/backend/core/inference/video_ltx25.py
+++ b/studio/backend/core/inference/video_ltx25.py
@@ -361,6 +361,9 @@ def load_ltx25_transformer(
from .video_ltx2 import _ltx23_pre_convert, ltx23_is_dit_key
+ if is_gguf:
+ from .diffusion_gguf_lowbit import install_lowbit_iq
+ install_lowbit_iq() # before the read: diffusers' reader refuses unknown types
state = load_single_file_checkpoint(str(checkpoint_path))
dit_state = _ltx23_pre_convert({k: v for k, v in state.items() if ltx23_is_dit_key(k)})
del state
@@ -587,6 +590,10 @@ def _read_tensors(path: str, keep: Callable[[str], bool]) -> dict[str, Any]:
"""The tensors of ``path`` whose names pass ``keep``, read selectively (GGUF files are read whole)."""
if not str(path).lower().endswith(".safetensors"):
from diffusers.loaders.single_file_utils import load_single_file_checkpoint
+
+ from .diffusion_gguf_lowbit import install_lowbit_iq
+
+ install_lowbit_iq()
return {k: v for k, v in load_single_file_checkpoint(str(path)).items() if keep(k)}
from safetensors import safe_open
diff --git a/studio/backend/tests/test_diffusion_gguf_lowbit.py b/studio/backend/tests/test_diffusion_gguf_lowbit.py
new file mode 100644
index 00000000000..5df3dd99aad
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_gguf_lowbit.py
@@ -0,0 +1,236 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The low-bit IQ types diffusers' GGUF table lacks: bit-identical to gguf-py's dequant, loadable, reversible."""
+
+from __future__ import annotations
+
+import pytest
+
+torch = pytest.importorskip("torch")
+np = pytest.importorskip("numpy")
+gguf = pytest.importorskip("gguf")
+gguf_utils = pytest.importorskip("diffusers.quantizers.gguf.utils")
+
+from core.inference import diffusion_gguf_lowbit as lb # noqa: E402
+
+T = gguf.GGMLQuantizationType
+TYPES = ["IQ1_S", "IQ1_M", "IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S"]
+
+
[email protected](autouse = True)
+def _clean(monkeypatch):
+ monkeypatch.delenv(lb.LOWBIT_IQ_ENV, raising = False)
+ lb.uninstall_lowbit_iq()
+ yield
+ lb.uninstall_lowbit_iq()
+
+
+def _blocks(
+ name,
+ rows,
+ per_row = 2,
+ seed = 0,
+):
+ """Random blocks with a finite fp16 super-scale (IQ1_M keeps its scale in the top nibbles of its scale words)."""
+ qtype = getattr(T, name)
+ _, size = gguf.GGML_QUANT_SIZES[qtype]
+ rng = np.random.default_rng(seed)
+ raw = rng.integers(0, 256, size = (rows * per_row, size), dtype = np.uint8)
+ scale = (
+ (np.abs(rng.standard_normal(rows * per_row)) * 0.01 + 1e-3)
+ .astype(np.float16)
+ .view(np.uint16)
+ )
+ if name == "IQ1_M":
+ words = (
+ raw[:, -8:].copy().view(np.uint16)
+ ) # 4 words; nibble k of the scale in the top nibble of word k
+ for k in range(4):
+ words[:, k] = (words[:, k] & 0x0FFF) | (((scale >> (4 * k)) & 0xF) << 12)
+ raw[:, -8:] = words.view(np.uint8)
+ else:
+ raw[:, :2] = scale.view(np.uint8).reshape(-1, 2)
+ return raw.reshape(rows, -1)
+
+
[email protected]("rows", [1023, 1024])
[email protected]("name", TYPES)
+def test_dequant_is_bit_identical_to_gguf_py(name, rows):
+ qtype = getattr(T, name)
+ raw = _blocks(name, rows, seed = rows)
+ want = gguf.quants.dequantize(raw, qtype).astype(np.float32)
+ block, size = gguf.GGML_QUANT_SIZES[qtype]
+ blocks = torch.from_numpy(raw).reshape(-1, size)
+ got = lb._FUNCTIONS[name](blocks, block, size).reshape(rows, -1)
+ assert got.dtype == torch.float32 and tuple(got.shape) == want.shape
+ assert np.array_equal(got.numpy().view(np.uint32), want.view(np.uint32))
+
+
[email protected]("name", TYPES)
+def test_raw_random_blocks_match_gguf_py_too(name):
+ # any scale bits, NaN and inf included: same values, same NaN positions
+ qtype = getattr(T, name)
+ block, size = gguf.GGML_QUANT_SIZES[qtype]
+ raw = np.random.default_rng(9).integers(0, 256, size = (64, size), dtype = np.uint8)
+ with np.errstate(all = "ignore"):
+ want = gguf.quants.dequantize(raw, qtype).astype(np.float32)
+ got = lb._FUNCTIONS[name](torch.from_numpy(raw), block, size).numpy()
+ nan = np.isnan(want)
+ assert np.array_equal(nan, np.isnan(got))
+ assert np.array_equal(got[~nan].view(np.uint32), want[~nan].view(np.uint32))
+
+
+def _write_gguf(path, tensors):
+ writer = gguf.GGUFWriter(str(path), "flux")
+ for name, (qtype, raw, shape) in tensors.items():
+ writer.add_tensor(name, raw, raw_dtype = qtype) # raw: the byte shape
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+
+
+def test_a_gguf_with_low_bit_iq_tensors_loads_and_runs(tmp_path):
+ from diffusers.models.model_loading_utils import load_gguf_checkpoint
+
+ rows, cols = 64, 512
+ tensors = {}
+ for i, name in enumerate(TYPES):
+ raw = _blocks(name, rows, per_row = cols // 256, seed = i)
+ tensors[f"blocks.{i}.weight"] = (getattr(T, name), raw, (rows, cols))
+ path = tmp_path / "lowbit.gguf"
+ _write_gguf(path, tensors)
+ with pytest.raises(ValueError, match = "unsupported"):
+ load_gguf_checkpoint(str(path)) # the stock table refuses the file
+
+ assert lb.install_lowbit_iq() == TYPES
+ state = load_gguf_checkpoint(str(path))
+ x = torch.randn(3, cols, generator = torch.Generator().manual_seed(1))
+ for i, name in enumerate(TYPES):
+ weight = state[f"blocks.{i}.weight"]
+ assert isinstance(weight, gguf_utils.GGUFParameter) and weight.quant_type == getattr(
+ T, name
+ )
+ lin = gguf_utils.GGUFLinear(cols, rows, bias = False, compute_dtype = torch.float32)
+ lin.weight = weight
+ dense = torch.from_numpy(
+ gguf.quants.dequantize(tensors[f"blocks.{i}.weight"][1], getattr(T, name))
+ )
+ assert torch.equal(lin.forward_native(x), torch.nn.functional.linear(x, dense.float()))
+
+
+def test_kill_switch_install_idempotence_and_uninstall(monkeypatch):
+ before = dict(gguf_utils.dequantize_functions), list(gguf_utils.SUPPORTED_GGUF_QUANT_TYPES)
+ monkeypatch.setenv(lb.LOWBIT_IQ_ENV, "0")
+ assert lb.install_lowbit_iq() == [] and T.IQ2_XXS not in gguf_utils.dequantize_functions
+ monkeypatch.delenv(lb.LOWBIT_IQ_ENV)
+ assert lb.install_lowbit_iq() == TYPES
+ assert lb.install_lowbit_iq() == []
+ assert all(getattr(T, n) in gguf_utils.SUPPORTED_GGUF_QUANT_TYPES for n in TYPES)
+ assert gguf_utils.dequantize_functions[T.IQ4_XS] is before[0][T.IQ4_XS]
+ lb.uninstall_lowbit_iq()
+ assert dict(gguf_utils.dequantize_functions) == before[0]
+ assert list(gguf_utils.SUPPORTED_GGUF_QUANT_TYPES) == before[1]
+
+
+def test_compiled_dequant_matches_eager():
+ # Studio compiles dequantize_gguf_tensor on the default tier; the new types must trace and keep their bits
+ lb.install_lowbit_iq()
+ compiled = torch.compile(gguf_utils.dequantize_gguf_tensor, dynamic = True)
+ for name in ("IQ2_XXS", "IQ3_S", "IQ1_M"):
+ raw = torch.from_numpy(_blocks(name, 32, seed = 4))
+ weight = gguf_utils.GGUFParameter(raw, quant_type = getattr(T, name))
+ eager = gguf_utils.dequantize_gguf_tensor(weight)
+ got = compiled(weight)
+ assert torch.equal(got.view(torch.int32), eager.view(torch.int32))
+
+
+def _oracle(name, raw):
+ qtype = getattr(T, name)
+ return torch.from_numpy(gguf.quants.dequantize(raw.numpy(), qtype).astype(np.float32))
+
+
[email protected]("name", TYPES)
+def test_cold_fullgraph_dequant_has_no_graph_break(name):
+ # Studio's resident max tier compiles blocks with fullgraph=True before any eager forward: no device table yet
+ from torch._dynamo.testing import CompileCounter
+
+ lb.install_lowbit_iq()
+ lb._CONSTS.clear()
+ torch._dynamo.reset()
+ counter = CompileCounter()
+ compiled = torch.compile(
+ gguf_utils.dequantize_gguf_tensor, backend = counter, fullgraph = True, dynamic = True
+ )
+ raw = torch.from_numpy(_blocks(name, 8, seed = 5))
+ for rows in (2, 3, 8):
+ part = raw[:rows].contiguous()
+ got = compiled(gguf_utils.GGUFParameter(part, quant_type = getattr(T, name)))
+ assert torch.equal(got.float().view(torch.int32), _oracle(name, part).view(torch.int32))
+ assert counter.frame_count == 1 # no break, no recompile
+ torch._dynamo.reset()
+
+
+def test_prepared_tables_are_per_type_and_recompile_at_most_once():
+ from torch._dynamo.testing import CompileCounter
+
+ lb.install_lowbit_iq()
+ lb._CONSTS.clear()
+ module = torch.nn.Module()
+ raw = torch.from_numpy(_blocks("IQ2_XS", 4, seed = 6))
+ module.weight = gguf_utils.GGUFParameter(raw, quant_type = T.IQ2_XS, requires_grad = False)
+ assert lb.prepare_lowbit_iq_tables("cpu", torch.nn.Linear(2, 2)) == []
+ assert lb._CONSTS == {}
+ torch._dynamo.reset()
+ counter = CompileCounter()
+ compiled = torch.compile(
+ gguf_utils.dequantize_gguf_tensor, backend = counter, fullgraph = True, dynamic = True
+ )
+ cold = compiled(module.weight)
+ assert lb.prepare_lowbit_iq_tables("cpu", module) == ["IQ2_XS", "ksigns"]
+ assert set(lb._CONSTS) == {("IQ2_XS", "cpu"), ("ksigns", "cpu")}
+ warm = compiled(module.weight)
+ assert torch.equal(cold, warm) and torch.equal(warm.float(), _oracle("IQ2_XS", raw))
+ assert counter.frame_count <= 2 # a prepared table recompiles at most once
+ torch._dynamo.reset()
+
+
+class _ReadStop(Exception):
+ pass
+
+
+def _read_sites():
+ from core.inference import diffusion_gguf_pipeline as pipe_mod, video_ltx2, video_ltx25
+ return {
+ "whole_pipeline": lambda p: pipe_mod.load_whole_pipeline_gguf(
+ object, object, p, {}, dtype = torch.bfloat16
+ ),
+ "ltx23_assembly": lambda p: video_ltx2._assemble_ltx23_pipeline(
+ p, base_repo = "x", torch_dtype = torch.bfloat16, is_gguf = True
+ ),
+ "ltx25_transformer": lambda p: video_ltx25.load_ltx25_transformer(
+ p, base_repo = "x", torch_dtype = torch.bfloat16, is_gguf = True, hf_token = None
+ ),
+ "ltx25_read_tensors": lambda p: video_ltx25._read_tensors(p, lambda key: True),
+ }
+
+
+ "site", ["whole_pipeline", "ltx23_assembly", "ltx25_transformer", "ltx25_read_tensors"]
+)
+def test_every_gguf_read_sees_the_low_bit_types_on_a_first_load(site, monkeypatch):
+ # diffusers' GGUF reader refuses unknown types, so the types must be in its table before the file is read
+ import diffusers.loaders.single_file_utils as sfu
+
+ seen = []
+
+ def read(path, *args, **kwargs):
+ seen.append(T.IQ2_XXS in gguf_utils.dequantize_functions)
+ raise _ReadStop
+
+ monkeypatch.setattr(sfu, "load_single_file_checkpoint", read)
+ assert T.IQ2_XXS not in gguf_utils.dequantize_functions
+ with pytest.raises(_ReadStop):
+ _read_sites()[site]("model.gguf")
+ assert seen == [True]