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.

Linear: read NVFP4 inputs (ModelOpt and compressed-tensors), ceil-div FP8 scale grids under either scale name, F8_E5M2 dtype

YanissAmze4e50511cfc0
diff --git a/exllamav3/loader/safetensors.py b/exllamav3/loader/safetensors.py
index d8fd38c..63d2169 100644
--- a/exllamav3/loader/safetensors.py
+++ b/exllamav3/loader/safetensors.py
@@ -38,6 +38,7 @@ def convert_dtype(dt: str):
elif dt == "BF16": return torch.bfloat16, None, 2
elif dt == "F32": return torch.float, np.float32, 4
elif dt == "F8_E4M3": return torch.float8_e4m3fn, None, 1
+ elif dt == "F8_E5M2": return torch.float8_e5m2, None, 1
elif dt == "U8": return torch.uint8, np.uint8, 1
else:
raise ValueError(f"Unknown dtype {dt}")
diff --git a/exllamav3/modules/linear.py b/exllamav3/modules/linear.py
index 16d14ac..dee7257 100644
--- a/exllamav3/modules/linear.py
+++ b/exllamav3/modules/linear.py
@@ -41,6 +41,34 @@ def _mxfp4_dequant(blocks: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
return w.view(blocks.shape[0], -1).half()
+def _scale_block(n: int, s: int, block: int | None) -> int:
+ """Block length along an axis of n elements covered by s scales (config block first, else exact division)."""
+ if block and -(-n // block) == s:
+ return block
+ assert n % s == 0, f"scale grid {s} does not cover {n} elements (block {block})"
+ return n // s
+
+
+def apply_scale_grid(w: torch.Tensor, scale: torch.Tensor, block: tuple | None = None) -> torch.Tensor:
+ """float32 w [rows, cols] x scale (scalar, [rows], [rows, 1] or a [sr, sc] grid with ceil-div blocks) -> float32.
+ Torch twin of foreign_quant.vendor_input.apply_scales (tests assert bit equality). `block` = (rows, cols)."""
+ w = w.float()
+ scale = scale.float()
+ if scale.numel() == 1:
+ return w * scale.reshape(())
+ rows, cols = w.shape
+ if scale.dim() == 1:
+ assert scale.shape[0] in (rows, cols), f"1D scale {tuple(scale.shape)} fits neither {rows} nor {cols}"
+ return w * (scale[:, None] if scale.shape[0] == rows else scale[None, :])
+ sr, sc = scale.shape
+ bo = _scale_block(rows, sr, block[0] if block else None)
+ bi = _scale_block(cols, sc, block[1] if block else None)
+ if rows % bo == 0 and cols % bi == 0:
+ return (w.view(sr, bo, sc, bi) * scale.view(sr, 1, sc, 1)).view(rows, cols)
+ full = scale.repeat_interleave(bo, 0).repeat_interleave(bi, 1)[:rows, :cols]
+ return w * full
+
+
class Linear(Module):
def __init__(
@@ -151,30 +179,47 @@ class Linear(Module):
return padded.contiguous()
- # Row scales (Transformers-specific?)
+ def quant_block_(self):
+ """weight_block_size of the checkpoint's quantization_config as (rows, cols) of the CHECKPOINT orientation,
+ swapped when the weight is loaded transposed. None = infer the block from the scale grid."""
+ qc = getattr(self.config, "config_dict", {}).get("quantization_config") or {}
+ b = qc.get("weight_block_size")
+ if not b or len(b) != 2:
+ return None
+ return (b[1], b[0]) if self.transposed_load else (b[0], b[1])
+
+
+ # FP8 scales: per-tensor, per-channel or a block grid (ceil-div), always MULTIPLIED, whether the tensor is
+ # called weight_scale or weight_scale_inv (DeepSeek / Qwen3-FP8 / GLM / MiniMax name the multiplier "inv")
def apply_fp8_scales_(self, weight: torch.Tensor, scale: torch.Tensor):
- ws = weight.shape
- ss = scale.shape
- assert len(ss) == 0 or len(ws) == len(ss) == 2
- if len(ss) == 2:
- if 1 < ss[0] < ws[0]:
- scale = torch.nn.functional.pad(scale, (0, 0, 0, ws[0] - ss[0]), "constant", 1)
- if 1 < ss[1] < ws[1]:
- scale = torch.nn.functional.pad(scale, (0, ws[1] - ss[1]), "constant", 1)
- weight = weight.float() * scale
- return weight.view(ws).half()
+ return apply_scale_grid(weight, scale, self.quant_block_()).half()
def apply_fp8_scales_inv_(self, weight: torch.Tensor, scale_inv: torch.Tensor):
- ws = weight.shape
- ss = scale_inv.shape
- if len(ss) > 0:
- assert len(ws) == len(ss) == 2
- assert all(w == s * 128 for w, s in zip(ws, ss))
- weight = weight.view(ss[0], 128, ss[1], 128)
- scale_inv = scale_inv.view(ss[0], 1, ss[1], 1)
- weight = weight.float() * scale_inv
- return weight.view(ws).half()
+ return apply_scale_grid(weight, scale_inv, self.quant_block_()).half()
+
+
+ # NVFP4: packed e2m1 (U8 [out, in/2], low nibble first) x E4M3 scale per 16 inputs x one fp32 global scale.
+ # ModelOpt: weight / weight_scale / weight_scale_2 (multiplier); compressed-tensors: weight_packed /
+ # weight_scale / weight_global_scale (divisor). Returns (out, in) fp16 in checkpoint orientation, or None.
+ def dequant_nvfp4_(self, key: str, dev) -> torch.Tensor | None:
+ stc = self.config.stc
+ wname = ".weight_packed" if stc.has_tensor(key + ".weight_packed") else ".weight"
+ ws = stc.get_tensor(key + ".weight_scale", dev, optional = True, no_defer = True)
+ if ws is None or ws.dtype != torch.float8_e4m3fn or ws.dim() != 2:
+ return None
+ inv = False
+ g = stc.get_tensor(key + ".weight_scale_2", dev, optional = True, no_defer = True)
+ if g is None:
+ g = stc.get_tensor(key + ".weight_global_scale", dev, optional = True, no_defer = True)
+ inv = g is not None
+ assert g is not None, f"{key}: NVFP4 weight without weight_scale_2 / weight_global_scale"
+ u8 = stc.get_tensor(key + wname, dev, no_defer = True).contiguous().view(torch.uint8)
+ lut = torch.tensor(_MXFP4_LUT, dtype = torch.float, device = u8.device)
+ w = torch.stack((lut[(u8 & 0x0F).long()], lut[(u8 >> 4).long()]), dim = -1).view(u8.shape[0], -1)
+ w = apply_scale_grid(w, ws.float(), None)
+ g = g.float().reshape(-1)[0]
+ return ((w / g) if inv else (w * g)).half()
# DeepSeek-V4-style quantized checkpoint tensors, dequantized to FP16 at load (they get
@@ -205,7 +250,8 @@ class Linear(Module):
def load_fp16(self, key: str | list[str]) -> bool:
- if self.config.stc.has_tensor_group(key, ["weight"]):
+ if self.config.stc.has_tensor_group(key, ["weight"]) or \
+ (isinstance(key, str) and self.config.stc.has_tensor(key + ".weight_packed")):
self.used_alt_key = key == self.alt_key
if self.used_alt_key and isinstance(key, list):
@@ -219,7 +265,8 @@ class Linear(Module):
pad1 = (self.out_features,) if not self.is_sliced else None
pad2 = (self.in_features, self.out_features) if not self.is_sliced else None
scale_q = self.config.stc.get_tensor(key + ".scale", dev, optional = True, no_defer = True)
- if scale_q is None and self.config.stc.has_tensor(key + ".weight_scale"):
+ nv = self.dequant_nvfp4_(key, dev) if scale_q is None and self.config.stc.has_tensor(key + ".weight_scale") else None
+ if nv is None and scale_q is None and self.config.stc.has_tensor(key + ".weight_scale"):
# MiMo-V2 routed experts: same E8M0 block grid, named "weight_scale" and
# stored as U8 exponent bytes. Only 2D uint8 scales route here; float
# "weight_scale" tensors keep the per-row/per-tensor fp8 path below. Fetched
@@ -227,7 +274,13 @@ class Linear(Module):
ws_q = self.config.stc.get_tensor(key + ".weight_scale", dev, optional = True, no_defer = True)
if ws_q is not None and ws_q.dim() == 2 and ws_q.dtype == torch.uint8:
scale_q = ws_q
- if scale_q is not None and scale_q.dim() == 2:
+ if nv is not None:
+ # NVFP4 (ModelOpt / compressed-tensors): dequantized in checkpoint orientation above
+ weight = nv.T if self.transposed_load else nv
+ weight = weight.contiguous() if self.is_sliced else self.pad_out(weight.contiguous())
+ bias = self.config.stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, pad_to = pad1, no_defer = True)
+ scale = scale_inv = None
+ elif scale_q is not None and scale_q.dim() == 2:
# DeepSeek-V4 style: fp8/fp4 blocks + E8M0 scale grid, checkpoint
# orientation (out, in); dequant first, then orient/pad like a plain load
w_raw = self.config.stc.get_tensor(key + ".weight", dev, no_defer = True)
diff --git a/tests/test_linear_vendor_load_cpu.py b/tests/test_linear_vendor_load_cpu.py
new file mode 100644
index 0000000..3b80f85
--- /dev/null
+++ b/tests/test_linear_vendor_load_cpu.py
@@ -0,0 +1,114 @@
+"""CPU tests of Linear.load_fp16 on synthetic vendor checkpoints (FP8 grids, MXFP4, NVFP4, BF16): the weight the
+converter sees must equal the numpy reference dequant (foreign_quant.vendor_input) after the fp16 cast."""
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import sys
+import types
+
+import numpy as np
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("ml_dtypes")
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+
+def _load_helpers():
+ spec = importlib.util.spec_from_file_location("tvi_under_test", os.path.join(HERE, "test_vendor_input_cpu.py"))
+ m = importlib.util.module_from_spec(spec)
+ sys.modules["tvi_under_test"] = m
+ spec.loader.exec_module(m)
+ return m
+
+
+H = _load_helpers()
+vi = H.vi
+
+try:
+ from exllamav3.loader.safetensors import SafetensorsCollection
+ from exllamav3.modules.linear import Linear, apply_scale_grid
+except Exception as e: # extension not built on this host
+ pytest.skip(f"exllamav3 not importable: {e}", allow_module_level=True)
+
+
+def make_linear(tmp_path, tensors, cfg, key, out, in_):
+ H.write_st(tmp_path / "model.safetensors", tensors)
+ json.dump(cfg, open(tmp_path / "config.json", "w"))
+ conf = types.SimpleNamespace(stc=SafetensorsCollection(str(tmp_path), load_method="python"), config_dict=cfg)
+ lin = Linear(conf, key, in_, out, pad_to=1)
+ lin.load(torch.device("cpu"))
+ return lin.inner.weight # (in, out) fp16
+
+
+def check(w, ref): # fp16 cast of the float32 reference, bit equal
+ exp = torch.from_numpy(ref).half().T
+ assert w.shape == exp.shape and torch.equal(w.view(torch.int16), exp.contiguous().view(torch.int16))
+
+
[email protected]("shape,grid,block", [((256, 384), (2, 3), [128, 128]), ((200, 300), (2, 3), [128, 128]), ((96, 128), (3, 4), None)])
[email protected]("sname", ["weight_scale_inv", "weight_scale"])
+def test_fp8_block_grids(tmp_path, shape, grid, block, sname):
+ wb, s = H.e4m3_bytes(shape, 0, 0x60), H.f32_scale(grid, -3, 1)
+ cfg = {"quantization_config": {"quant_method": "fp8"}}
+ if block:
+ cfg["quantization_config"]["weight_block_size"] = block
+ T = {"l.weight": H.t("F8_E4M3", wb), f"l.{sname}": H.t("F32", s)}
+ w = make_linear(tmp_path, T, cfg, "l", *shape)
+ check(w, vi.dequant_fp8(wb, "F8_E4M3", s, tuple(block) if block else None))
+
+
+def test_fp8_per_tensor_and_channel(tmp_path):
+ wb = H.e4m3_bytes((64, 96), 0, 0x60)
+ for i, s in enumerate((np.array(0.3, np.float32), H.f32_scale((64, 1), -3, 1))):
+ d = tmp_path / str(i)
+ d.mkdir()
+ w = make_linear(d, {"l.weight": H.t("F8_E4M3", wb), "l.weight_scale": H.t("F32", s)}, {}, "l", 64, 96)
+ check(w, vi.dequant_fp8(wb, "F8_E4M3", s))
+
+
+def test_mxfp4_linear_u8_and_e8m0(tmp_path):
+ nib = H.rng.integers(0, 16, size=(64, 128)).astype(np.uint8)
+ sb = H.rng.integers(120, 132, size=(64, 4)).astype(np.uint8)
+ ref = vi.dequant_mxfp4_linear(H.pack_nibbles(nib), vi.e8m0_to_f32(sb))
+ for i, (wsn, tag) in enumerate((("weight_scale", "U8"), ("scale", "F8_E8M0"))):
+ d = tmp_path / str(i)
+ d.mkdir()
+ w = make_linear(d, {"l.weight": H.t("I8", H.pack_nibbles(nib).view(np.int8)), f"l.{wsn}": H.t(tag, sb)}, {}, "l", 64, 128)
+ check(w, ref)
+
+
[email protected]("flavour", ["modelopt", "compressed-tensors"])
+def test_nvfp4_both_conventions(tmp_path, flavour):
+ nib, packed, sc, g = H.nvfp4_case(48, 128)
+ if flavour == "modelopt":
+ T = {"l.weight": H.t("U8", packed), "l.weight_scale": H.t("F8_E4M3", sc), "l.weight_scale_2": H.t("F32", np.array(g, np.float32))}
+ ref = vi.dequant_nvfp4(packed, sc, g)
+ else:
+ gi = np.array([1.0 / g], np.float32)
+ T = {"l.weight_packed": H.t("U8", packed), "l.weight_scale": H.t("F8_E4M3", sc), "l.weight_global_scale": H.t("F32", gi)}
+ ref = vi.dequant_nvfp4(packed, sc, gi, inverse_global=True)
+ T["l.bias"] = H.t("F32", np.arange(48, dtype=np.float32))
+ H.write_st(tmp_path / "model.safetensors", T)
+ json.dump({}, open(tmp_path / "config.json", "w"))
+ conf = types.SimpleNamespace(stc=SafetensorsCollection(str(tmp_path), load_method="python"), config_dict={})
+ lin = Linear(conf, "l", 128, 48, pad_to=1)
+ lin.load(torch.device("cpu"))
+ check(lin.inner.weight, ref)
+ assert torch.equal(lin.inner.bias.float(), torch.arange(48, dtype=torch.float))
+
+
+def test_bf16_dense(tmp_path):
+ bf = torch.randn(32, 64).bfloat16()
+ w = make_linear(tmp_path, {"l.weight": ("BF16", (32, 64), bf.view(torch.int16).numpy().view(np.uint16))}, {}, "l", 32, 64)
+ assert torch.equal(w, bf.half().T)
+
+
[email protected]("shape,grid,block", [((256, 384), (2, 3), None), ((200, 300), (2, 3), (128, 128)), ((7, 5), (), None)])
+def test_torch_grid_equals_numpy_grid(shape, grid, block):
+ w = torch.randn(*shape)
+ s = torch.from_numpy(H.f32_scale(grid, -3, 1)) if grid else torch.tensor(0.7)
+ got = apply_scale_grid(w, s, block).numpy()
+ assert H.same(got, vi.apply_scales(w.numpy(), s.numpy(), block))