Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Legacy-type prefill dequant: one Triton launch per projection (EXL3_LEGACY_PREFILL_DQ)

YanissAmz6d79c07677d9
diff --git a/exllamav3/foreign_quant/legacy_dq.py b/exllamav3/foreign_quant/legacy_dq.py
new file mode 100644
index 0000000..1ced33e
--- /dev/null
+++ b/exllamav3/foreign_quant/legacy_dq.py
@@ -0,0 +1,76 @@
+"""EXL3_LEGACY_PREFILL_DQ: one Triton launch dequantizing GGUF Q4_0 / Q5_0 rows to fp16 (prefill attention projections, rows > 1).
+
+Replaces gap_formats.dequant (about 15 torch ops per projection). Bit-identical to it: element j of a block is d * v in fp32 (one rounded multiply, fp16 d
+widened), then rounded to fp16. Q4_0 block = [d fp16][16 nibble bytes] (v = q - 8); Q5_0 = [d fp16][qh u32][16 nibble bytes] (v = (q | bit << 4) - 16);
+elements 0..15 are the low nibbles, 16..31 the high nibbles. Q5_1 already has its own Triton dequant in gap_formats and is not routed here.
+"""
+from __future__ import annotations
+
+import numpy as np
+import torch
+
+try:
+ import triton
+ import triton.language as tl
+ HAVE_TRITON = True
+except Exception: # pragma: no cover
+ HAVE_TRITON = False
+
+BB = {"q4_0": 18, "q5_0": 22}
+QOFF = {"q4_0": 2, "q5_0": 6}
+
+
+def ref_dequant_np(fmt: str, raw: np.ndarray) -> np.ndarray:
+ """Numpy reference: raw uint8 [rows, nb * BB] -> fp16 [rows, nb * 32] (float32 d * v, one rounding to fp16)."""
+ n = raw.shape[0]
+ b = raw.reshape(-1, BB[fmt])
+ d = np.ascontiguousarray(b[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1, 1)
+ qs = b[:, QOFF[fmt]:QOFF[fmt] + 16].astype(np.int32)
+ q = np.concatenate([qs & 15, qs >> 4], axis=1)
+ if fmt == "q4_0":
+ v = (q - 8).astype(np.float32)
+ else:
+ qh = np.ascontiguousarray(b[:, 2:6]).view("<u4").reshape(-1, 1).astype(np.uint32)
+ hb = ((qh >> np.arange(32, dtype=np.uint32)[None, :]) & 1).astype(np.int32)
+ v = ((q | (hb << 4)) - 16).astype(np.float32)
+ return (d * v).astype(np.float16).reshape(n, -1)
+
+
+if HAVE_TRITON:
+ @triton.jit
+ def _dq_legacy(src, dst, nblk, HAS_QH: tl.constexpr, BBYTES: tl.constexpr, QO: tl.constexpr, BLOCKS: tl.constexpr):
+ pid = tl.program_id(0)
+ bi = pid * BLOCKS + tl.arange(0, BLOCKS)
+ ok = bi < nblk
+ j = tl.arange(0, 32)
+ base = bi.to(tl.int64) * BBYTES
+ b0 = tl.load(src + base, mask=ok, other=0).to(tl.uint32)
+ b1 = tl.load(src + base + 1, mask=ok, other=0).to(tl.uint32)
+ d = (b0 | (b1 << 8)).to(tl.uint16).to(tl.float16, bitcast=True).to(tl.float32)
+ qs = tl.load(src + base[:, None] + QO + (j % 16)[None, :], mask=ok[:, None], other=0).to(tl.uint32)
+ lo = tl.where((j < 16)[None, :], qs & 15, qs >> 4).to(tl.int32)
+ if HAS_QH:
+ b2 = tl.load(src + base + 2, mask=ok, other=0).to(tl.uint32)
+ b3 = tl.load(src + base + 3, mask=ok, other=0).to(tl.uint32)
+ b4 = tl.load(src + base + 4, mask=ok, other=0).to(tl.uint32)
+ b5 = tl.load(src + base + 5, mask=ok, other=0).to(tl.uint32)
+ qh = b2 | (b3 << 8) | (b4 << 16) | (b5 << 24)
+ hb = ((qh[:, None] >> j[None, :].to(tl.uint32)) & 1).to(tl.int32)
+ v = ((lo | (hb << 4)) - 16).to(tl.float32)
+ else:
+ v = (lo - 8).to(tl.float32)
+ o = d[:, None] * v
+ tl.store(dst + bi.to(tl.int64)[:, None] * 32 + j[None, :], o.to(tl.float16), mask=ok[:, None])
+
+
+def dequant(fmt: str, raw: torch.Tensor) -> torch.Tensor:
+ """raw uint8 [rows, nb * BB] (CUDA) -> fresh fp16 [rows, nb * 32]; ONE launch. The caller frees it after its matmul."""
+ bb = BB[fmt]
+ rows, w = raw.shape
+ assert w % bb == 0
+ nblk = rows * (w // bb)
+ out = torch.empty((rows, (w // bb) * 32), dtype=torch.half, device=raw.device)
+ B = 64
+ _dq_legacy[(triton.cdiv(nblk, B),)](raw.contiguous(), out, nblk, HAS_QH=(fmt == "q5_0"), BBYTES=bb, QO=QOFF[fmt], BLOCKS=B,
+ enable_fp_fusion=False)
+ return out
diff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.py
index c676d08..24029d7 100644
--- a/exllamav3/modules/foreign_linear.py
+++ b/exllamav3/modules/foreign_linear.py
@@ -127,6 +127,12 @@ def q8_share_end() -> None:
_Q8S["key"] = None
+# EXL3_LEGACY_PREFILL_DQ (default 0, CUDA only, read at call time): Q4_0 / Q5_0 weights at rows > 1 dequantize with ONE Triton launch into a per-call fp16 tensor
+# (freed after the matmul, nothing resident) instead of the ~15 torch ops of gap_formats.dequant. Output bit-identical. Q5_1 already has its own Triton dequant.
+def _legacy_dq_on() -> bool:
+ return os.environ.get("EXL3_LEGACY_PREFILL_DQ", "0") == "1" and bool(torch.version.cuda) and not torch.version.hip
+
+
_DEQ_IQ_ID = {"iq2_xs": 1, "iq2_s": 2, "iq3_xxs": 3, "iq3_s": 4, "iq4_nl": 5}
if os.environ.get("BOLT_FQ_DEQ_Q3K", "1") != "0": # CUDA and HIP
_DEQ_IQ_ID["q3_k"] = 10 # native Q3_K dequant (prefill dequant + GEMM; the torch gap_dequant is ~2.5x slower at 8K) # fq_dequant_iq format ids (the others have native dequants already)
@@ -253,6 +259,10 @@ class ForeignLinear(Module):
out = torch.empty((count, self.in_features), dtype=torch.float16, device=dev)
ext.fq_dequant_iq(self.packed[first:first + count].reshape(count, -1).contiguous(), out, _DEQ_IQ_ID[self.format])
return out
+ if self.format in ("q4_0", "q5_0") and _legacy_dq_on() and self.packed.is_cuda:
+ from ..foreign_quant import legacy_dq
+ if legacy_dq.HAVE_TRITON:
+ return legacy_dq.dequant(self.format, self.packed[first:first + count])
if self.format in _GAP_FORMATS:
return gap_dequant(self.format, self.packed[first:first + count])
if self.format in _KQ_FORMATS:
diff --git a/tests/test_legacy_prefill_dq_cpu.py b/tests/test_legacy_prefill_dq_cpu.py
new file mode 100644
index 0000000..892a3e2
--- /dev/null
+++ b/tests/test_legacy_prefill_dq_cpu.py
@@ -0,0 +1,85 @@
+"""CPU checks for EXL3_LEGACY_PREFILL_DQ (foreign_quant/legacy_dq.py): exact dequant vs gap_formats + dispatch in ForeignLinear._dequant_rows.
+No GPU, no kernel launch: the extension is replaced by stubs. Needs the repo importable (exllamav3 package, built extension present so the
+import does not start a build); skipped otherwise. Run: CUDA_VISIBLE_DEVICES= python -m pytest tests/test_legacy_prefill_dq_cpu.py -q"""
+import glob
+import os
+import sys
+import types
+
+import numpy as np
+import pytest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+if not glob.glob(os.path.join(ROOT, "exllamav3_ext*.so")):
+ pytest.skip("extension not built in " + ROOT + " (importing exllamav3 would start the build)", allow_module_level=True)
+sys.path.insert(0, ROOT)
+import torch
+
+
+
+def test_legacy_dequant_exact():
+ import torch
+ from exllamav3.foreign_quant.gap_formats import dequant
+ from exllamav3.foreign_quant import legacy_dq
+ rng = np.random.default_rng(4)
+ for fmt in ("q4_0", "q5_0"):
+ raw = rng.integers(0, 256, size=(24, 40 * legacy_dq.BB[fmt]), dtype=np.uint8) # fully random bytes incl. NaN / inf fp16 scales
+ ref = legacy_dq.ref_dequant_np(fmt, raw)
+ eng = dequant(fmt, torch.from_numpy(raw)).numpy()
+ assert ref.shape == eng.shape, (ref.shape, eng.shape)
+ nan = np.isnan(ref)
+ assert np.array_equal(nan, np.isnan(eng)), fmt
+ assert np.array_equal(ref.view(np.uint16)[~nan], eng.view(np.uint16)[~nan]), f"{fmt}: numpy reference != gap_formats.dequant"
+ print(f"legacy dequant {fmt}: numpy reference == gap_formats.dequant bit-exact on {ref.size} random elements ({int(nan.sum())} NaN)")
+ # the Triton kernel itself through the CPU interpreter, when available
+ if legacy_dq.HAVE_TRITON:
+ os.environ["TRITON_INTERPRET"] = "1"
+ try:
+ import importlib
+ importlib.reload(legacy_dq)
+ for fmt in ("q4_0", "q5_0"):
+ raw = rng.integers(0, 256, size=(6, 4 * legacy_dq.BB[fmt]), dtype=np.uint8)
+ out = legacy_dq.dequant(fmt, torch.from_numpy(raw)).numpy()
+ ref = legacy_dq.ref_dequant_np(fmt, raw); nan = np.isnan(ref)
+ assert np.array_equal(ref.view(np.uint16)[~nan], out.view(np.uint16)[~nan]), fmt
+ print(f"legacy dequant {fmt}: Triton kernel (interpreter, CPU) == numpy reference")
+ except Exception as e: # the interpreter is optional: the GPU cell compares the real kernel
+ print("triton interpreter check skipped:", type(e).__name__, str(e)[:120])
+ finally:
+ os.environ.pop("TRITON_INTERPRET", None)
+
+
+class _FakeCudaBias:
+ """Stand-in for a CUDA half bias on a CPU box."""
+ is_cuda = True
+ dtype = torch.half
+ def __init__(self, n): self.n = n
+ def is_contiguous(self): return True
+ def numel(self): return self.n
+
+
[email protected](params=["0", "1"])
+def flag(request, monkeypatch):
+ monkeypatch.setattr(torch.version, "cuda", "13.0", raising=False)
+ monkeypatch.setattr(torch.version, "hip", None, raising=False)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ return request.param == "1"
+
+def test_dispatch(flag, monkeypatch):
+ from exllamav3.modules import foreign_linear as fl
+ from exllamav3.foreign_quant import legacy_dq
+ monkeypatch.setenv("EXL3_LEGACY_PREFILL_DQ", "1" if flag else "0")
+ called = []
+ monkeypatch.setattr(legacy_dq, "HAVE_TRITON", True)
+ monkeypatch.setattr(legacy_dq, "dequant", lambda fmt, raw: (called.append(fmt), torch.from_numpy(legacy_dq.ref_dequant_np(fmt, raw.numpy())))[1])
+ gcalled = []
+ monkeypatch.setattr(fl, "gap_dequant", lambda fmt, raw: (gcalled.append(fmt), torch.zeros(raw.shape[0], 64, dtype=torch.half))[1])
+ class FP(torch.Tensor):
+ is_cuda = property(lambda s: True)
+ for fmt in ("q4_0", "q5_0", "q5_1"):
+ mm = object.__new__(fl.ForeignLinear); mm.format = fmt; mm.in_features = 64; mm.out_features = 8; mm.key = "t"
+ mm.packed = torch.zeros(8, 2 * legacy_dq.BB.get(fmt, 24), dtype=torch.uint8).as_subclass(FP)
+ called.clear(); gcalled.clear()
+ mm._dequant_rows(0, 8)
+ on = flag and fmt in ("q4_0", "q5_0")
+ assert called == ([fmt] if on else []) and gcalled == ([] if on else [fmt]), (fmt, called, gcalled)