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.

bigconv: detect the source checkpoint format (formats command, preflight input-format check), classify FP8/MXFP4/NVFP4 scale layouts, shared reader entry

YanissAmz475d566d87f1
diff --git a/tests/bigconv/test_formats.py b/tests/bigconv/test_formats.py
new file mode 100644
index 0000000..0a0fa61
--- /dev/null
+++ b/tests/bigconv/test_formats.py
@@ -0,0 +1,115 @@
+"""bigconv: source-format detection (formats CLI, preflight check), adapter classification of vendor scale layouts,
+and the shared reader, on small synthetic checkpoints with the vendor tensor names."""
+import importlib.util
+import json
+import os
+import re
+import subprocess
+import sys
+
+import numpy as np
+import pytest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+spec = importlib.util.spec_from_file_location("tvi_for_bigconv", os.path.join(ROOT, "tests", "test_vendor_input_cpu.py"))
+H = importlib.util.module_from_spec(spec)
+sys.modules["tvi_for_bigconv"] = H
+try:
+ spec.loader.exec_module(H)
+except BaseException as e: # torch / ml_dtypes missing on this host
+ pytest.skip(f"vendor_input tests unavailable: {e}", allow_module_level=True)
+
+from bigconv import formats, preflight # noqa: E402
+from bigconv.arch import TableAdapter # noqa: E402
+
+vi = H.vi
+
+
+def ckpt(tmp_path, fmt):
+ r = H.rng
+ q = "model.layers.0.self_attn.q_proj"
+ T = {"model.embed_tokens.weight": ("BF16", (16, 64), r.integers(0, 0x7F00, size=(16, 64)).astype(np.uint16)),
+ "model.norm.weight": H.t("F32", np.ones(64, np.float32))}
+ cfg = {}
+ if fmt == "bf16":
+ T[q + ".weight"] = ("BF16", (64, 128), r.integers(0, 0x7F00, size=(64, 128)).astype(np.uint16))
+ elif fmt == "fp8_block":
+ T[q + ".weight"] = H.t("F8_E4M3", H.e4m3_bytes((64, 128), 0, 0x60))
+ T[q + ".weight_scale_inv"] = H.t("F32", H.f32_scale((2, 2)))
+ cfg = {"quantization_config": {"quant_method": "fp8", "weight_block_size": [32, 64]}}
+ elif fmt == "fp8_channel":
+ T[q + ".weight"] = H.t("F8_E4M3", H.e4m3_bytes((64, 128), 0, 0x60))
+ T[q + ".weight_scale"] = H.t("F32", H.f32_scale((64, 1)))
+ elif fmt == "mxfp4":
+ T[q + ".weight"] = H.t("U8", H.pack_nibbles(r.integers(0, 16, size=(64, 128)).astype(np.uint8)))
+ T[q + ".weight_scale"] = H.t("U8", r.integers(120, 132, size=(64, 4)).astype(np.uint8))
+ elif fmt == "nvfp4":
+ nib, packed, sc, g = H.nvfp4_case(64, 128)
+ T[q + ".weight"] = H.t("U8", packed)
+ T[q + ".weight_scale"] = H.t("F8_E4M3", sc)
+ T[q + ".weight_scale_2"] = H.t("F32", np.array(g, np.float32))
+ T[q + ".input_scale"] = H.t("F32", np.array(1.0, np.float32))
+ cfg = {"quantization_config": {"quant_algo": "NVFP4"}}
+ H.write_st(tmp_path / "model.safetensors", T)
+ json.dump(cfg, open(tmp_path / "config.json", "w"))
+ return str(tmp_path)
+
+
+class Gen(TableAdapter):
+ name = "gen_test"
+ layer_re = re.compile(r"^model\.layers\.(\d+)\.")
+ expert_re = re.compile(r"^(model\.layers\.(\d+))\.mlp\.experts\.(\d+)\.(w1)\.weight$")
+ ROLES = [(re.compile(r"proj\.weight(_packed)?$"), "attn", "q", None)]
+
+
[email protected]("fmt,primary", [("bf16", "dense_bf16"), ("fp8_block", "fp8_block"), ("fp8_channel", "fp8_channel"),
+ ("mxfp4", "mxfp4"), ("nvfp4", "nvfp4")])
+def test_detect_cli_and_preflight_report_the_format(tmp_path, fmt, primary):
+ d = ckpt(tmp_path, fmt)
+ info, cfg = formats.load_source(d)
+ assert formats.detect(info, cfg)["primary"] == primary
+ out = subprocess.run([sys.executable, "-m", "bigconv", "formats", "--src", d], capture_output=True, text=True, cwd=str(tmp_path),
+ env={**os.environ, "PYTHONPATH": os.path.join(ROOT, "tools")})
+ assert out.returncode == 0 and primary in out.stdout, out.stderr
+ name, status, msg = formats.check_input_format(info, cfg)
+ assert (name, status) == ("input-format", "ok") and primary in msg
+ res = preflight.run(str(tmp_path / "work"), 1.0, src=d)
+ assert [m for n, s, m in res if n == "input-format"][0].startswith(primary)
+
+
+def test_tensor_map_input(tmp_path):
+ tm = {"tensors": {"l.weight": {"dtype": "U8", "shape": [8, 32]}, "l.weight_scale": {"dtype": "F8_E4M3", "shape": [8, 4]},
+ "l.weight_scale_2": {"dtype": "F32", "shape": []}}}
+ json.dump(tm, open(tmp_path / "m.json", "w"))
+ info, cfg = formats.load_source(map_path=str(tmp_path / "m.json"))
+ assert formats.detect(info, cfg)["primary"] == "nvfp4"
+
+
+def test_unsupported_integer_quant_fails_preflight():
+ info = {"l.qweight": ("I32", (8, 8)), "l.qzeros": ("I32", (1, 1)), "l.scales": ("F16", (1, 8)), "l.weight": ("U8", (8, 8))}
+ assert formats.check_input_format(info)[1] == "FAIL"
+
+
[email protected]("fmt,scale,in_f", [("fp8_block", ".weight_scale_inv", 128), ("fp8_channel", ".weight_scale", 128),
+ ("mxfp4", ".weight_scale", 128), ("nvfp4", ".weight_scale", 128)])
+def test_adapter_classifies_every_scale_layout(tmp_path, fmt, scale, in_f):
+ d = ckpt(tmp_path, fmt)
+ info, _ = formats.load_source(d)
+ T = {n: {"dtype": t, "shape": list(s)} for n, (t, s) in info.items()}
+ ad = Gen({})
+ q = "model.layers.0.self_attn.q_proj"
+ c = ad.classify(q + ".weight", T)
+ assert c.action == "quant" and c.fmt == fmt and c.scale == q + scale and c.out_f == 64
+ if fmt in ("nvfp4", "mxfp4"):
+ assert c.in_f == in_f # packed bytes x 2
+ for n in T:
+ if n.startswith(q) and n != q + ".weight":
+ assert ad.classify(n, T).action == "skip", n # scale, global scale and activation scale are consumed with the weight
+ assert ad.classify("model.norm.weight", T).action == "copy"
+
+
[email protected]("fmt", ["fp8_block", "mxfp4", "nvfp4", "bf16"])
+def test_reader_streams_one_linear(tmp_path, fmt):
+ d = ckpt(tmp_path, fmt)
+ w = formats.read_linear(d, "model.layers.0.self_attn.q_proj")
+ assert w.dtype == np.float32 and w.shape[0] == 64 and np.isfinite(w).all()
diff --git a/tools/bigconv/__main__.py b/tools/bigconv/__main__.py
index 3f93508..f803675 100644
--- a/tools/bigconv/__main__.py
+++ b/tools/bigconv/__main__.py
@@ -55,6 +55,16 @@ def main(argv=None):
f.add_argument("--scratch", help="capture memmap scratch dir (must be tmpfs)")
f.add_argument("--memmap-gb", type=float, default=0.0, help="sheet: capture disk (row state + X + Y)")
+ f.add_argument("--src", help="source checkpoint dir: report the detected input format (BF16 / FP8 / MXFP4 / NVFP4)")
+ f.add_argument("--map", help="tensor_map.json instead of --src (remote model)")
+ f.add_argument("--config", help="config.json next to --map")
+
+ o = sub.add_parser("formats", help="detect the source checkpoint format from headers only")
+ o.add_argument("--src", help="checkpoint dir (config.json + *.safetensors)")
+ o.add_argument("--map", help="tensor_map.json instead of --src")
+ o.add_argument("--config", help="config.json next to --map")
+ o.add_argument("--json", action="store_true")
+
k = sub.add_parser("check", help="release-day arch check: new config.json + index.json against an adapter")
k.add_argument("--arch", required=True, choices=sorted(ADAPTERS))
k.add_argument("--config", required=True)
@@ -65,6 +75,9 @@ def main(argv=None):
if a.cmd == "preflight":
from . import preflight
preflight.cli(a)
+ elif a.cmd == "formats":
+ from . import formats
+ formats.cli(a)
elif a.cmd == "check":
from . import archcheck
archcheck.cli(a)
diff --git a/tools/bigconv/arch.py b/tools/bigconv/arch.py
index 644cad4..f4eb147 100644
--- a/tools/bigconv/arch.py
+++ b/tools/bigconv/arch.py
@@ -56,6 +56,8 @@ class Cls:
expert: Optional[Expert] = None
role: Optional[str] = None
slices: Optional[list] = None
+ fmt: Optional[str] = None # source storage format (vendor_input.classify_linear): fp8_block, nvfp4, mxfp4, dense_bf16 ...
+ scale2: Optional[str] = None # NVFP4 global scale tensor
class ArchAdapter:
@@ -168,11 +170,25 @@ class TableAdapter(ArchAdapter):
return None
return Expert(lp, li, int(m.group(3)), m.group(4))
+ _SCALE_SFX = (".weight_scale_inv", ".weight_scale", ".scale", ".weight_scale_2", ".weight_global_scale",
+ ".input_scale", ".input_global_scale")
+
+ def _src_info(self, T):
+ """{name: (dtype, shape)} of the tensor map, cached per map (vendor_input.classify_linear works on it)."""
+ c = getattr(self, "_info_cache", None)
+ if c is None or c[0] is not T:
+ from .formats import info_from_map
+ c = self._info_cache = (T, info_from_map({"tensors": T}))
+ return c[1]
+
def classify(self, name, T):
t = T[name]
if self.scale_suffix and name.endswith(self.scale_suffix) and name[:-len(self.scale_suffix)] + ".weight" in T:
return Cls("skip")
- if not name.endswith(".weight") or len(t.get("shape") or [0, 0]) != 2:
+ sfx = next((x for x in self._SCALE_SFX if name.endswith(x)), None)
+ if sfx and (name[:-len(sfx)] + ".weight" in T or name[:-len(sfx)] + ".weight_packed" in T):
+ return Cls("skip") # scale / global scale / activation scale consumed with its weight (any vendor layout)
+ if not name.endswith((".weight", ".weight_packed")) or len(t.get("shape") or [0, 0]) != 2:
return Cls("copy")
if self.lang_prefixes and not name.startswith(self.lang_prefixes):
return Cls("copy")
@@ -184,8 +200,18 @@ class TableAdapter(ArchAdapter):
sname = name[:-7] + self.scale_suffix if self.scale_suffix else None
if sname not in T:
sname = None
- c = dict(action="quant", weight=name, scale=sname, out_f=t["shape"][0], in_f=t["shape"][1], base=name[:-7],
- role=role)
+ src = None
+ if name.endswith(".weight") or name.endswith(".weight_packed"):
+ from .formats import vendor_input
+ base = name.rsplit(".", 1)[0]
+ src = vendor_input().classify_linear(self._src_info(T), base)
+ in_f = t["shape"][1]
+ if src and src["fmt"] in ("nvfp4", "mxfp4"):
+ in_f *= 2 # two e2m1 nibbles per stored byte
+ if sname is None and src and src.get("scale"):
+ sname = src["scale"]
+ c = dict(action="quant", weight=name, scale=sname, out_f=t["shape"][0], in_f=in_f, base=name.rsplit(".", 1)[0],
+ role=role, fmt=src["fmt"] if src else None, scale2=(src or {}).get("scale2"))
if kind == "routed":
ex = self.expert_of(name)
if ex is not None:
diff --git a/tools/bigconv/formats.py b/tools/bigconv/formats.py
new file mode 100644
index 0000000..84af636
--- /dev/null
+++ b/tools/bigconv/formats.py
@@ -0,0 +1,96 @@
+"""Source-checkpoint format detection and the shared reader (header level; weights are only read by `read_linear`).
+
+ python -m bigconv formats --src CKPT_DIR [--json] (config.json + *.safetensors headers)
+ python -m bigconv formats --map tensor_map.json --config config.json (a remote model: no weights needed)
+
+The reader itself is exllamav3/foreign_quant/vendor_input.py (numpy only, shared with the Mac converter and the
+Linear loader); it is loaded by path so bigconv's plan side stays torch-free.
+"""
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import sys
+
+_VI = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "exllamav3", "foreign_quant", "vendor_input.py")
+_vi = None
+
+
+def vendor_input():
+ global _vi
+ if _vi is None:
+ if "bigconv_vendor_input" in sys.modules:
+ _vi = sys.modules["bigconv_vendor_input"]
+ else:
+ spec = importlib.util.spec_from_file_location("bigconv_vendor_input", os.path.normpath(_VI))
+ _vi = importlib.util.module_from_spec(spec)
+ sys.modules["bigconv_vendor_input"] = _vi
+ spec.loader.exec_module(_vi)
+ return _vi
+
+
+def info_from_map(tmap: dict) -> dict:
+ """tensor_map.json (bigconv.tensor_map) -> {name: (dtype tag, shape)}."""
+ return {n: (t["dtype"], tuple(t["shape"])) for n, t in tmap["tensors"].items() if t.get("shape") is not None}
+
+
+def detect(info: dict, config: dict | None = None) -> dict:
+ return vendor_input().detect_checkpoint(info, config)
+
+
+def describe(rep: dict) -> str:
+ cnt = ", ".join(f"{k} x{v}" for k, v in sorted(rep["counts"].items()))
+ ex = "; ".join(f"{k}: {v['prefix']} [{v['detail']}]" for k, v in rep["examples"].items() if not k.startswith("dense_"))
+ qc = rep.get("quantization_config") or {}
+ return f"{rep['primary']} ({cnt})" + (f"; config {json.dumps(qc)}" if qc else "") + (f"; e.g. {ex}" if ex else "")
+
+
+def check_input_format(info: dict, config: dict | None = None):
+ """preflight check: (name, status, message). FAIL only for integer payloads no reader understands."""
+ rep = detect(info, config)
+ msg = describe(rep)
+ if rep["primary"] == "unsupported-integer-quant":
+ return ("input-format", "FAIL", f"{msg}; {rep['unsupported_integer_linears']} integer linears without a known scale layout "
+ f"(GPTQ / AWQ?), e.g. {rep['unsupported_examples']}")
+ if rep["unsupported_integer_linears"]:
+ return ("input-format", "warn", f"{msg}; {rep['unsupported_integer_linears']} integer linears left unread: {rep['unsupported_examples']}")
+ if rep["primary"] == "unknown":
+ return ("input-format", "warn", "no linear weights recognised in the headers")
+ return ("input-format", "ok", msg)
+
+
+def load_source(src=None, map_path=None, config_path=None):
+ """-> (info, config). src = checkpoint dir; map_path = tensor_map.json."""
+ vi = vendor_input()
+ if src:
+ ck = vi.Checkpoint(src)
+ try:
+ return ck.info(), ck.config
+ finally:
+ ck.close()
+ info = info_from_map(json.load(open(map_path)))
+ return info, (json.load(open(config_path)) if config_path else {})
+
+
+def read_linear(src_dir_or_ck, prefix, block=None):
+ """float32 [out, in] of the source linear `prefix` (any detected format); one linear at a time."""
+ vi = vendor_input()
+ if isinstance(src_dir_or_ck, str):
+ ck = vi.Checkpoint(src_dir_or_ck)
+ try:
+ return vi.load_linear(ck, prefix, block)
+ finally:
+ ck.close()
+ return vi.load_linear(src_dir_or_ck, prefix, block)
+
+
+def cli(a):
+ info, cfg = load_source(a.src, a.map, a.config)
+ rep = detect(info, cfg)
+ if a.json:
+ print(json.dumps(rep, indent=1, default=str))
+ else:
+ name, status, msg = check_input_format(info, cfg)
+ print(f"{status:5s} {name:12s} {msg}")
+ raise SystemExit(1 if rep["primary"] == "unsupported-integer-quant" else 0)
diff --git a/tools/bigconv/preflight.py b/tools/bigconv/preflight.py
index 8d40b7a..a0ad13d 100644
--- a/tools/bigconv/preflight.py
+++ b/tools/bigconv/preflight.py
@@ -119,13 +119,16 @@ def check_gpurun_exempt(gpurun_path, who):
def run(root, spool_gb, capture_min_per_layer=None, rows=None, row_len=None, gpurun=None, who=None, qlc=True, floor_gb=None,
- scratch=None, memmap_gb=0.0):
+ scratch=None, memmap_gb=0.0, src=None, tmap=None, config=None):
os.makedirs(root, exist_ok=True)
free = shutil.disk_usage(root).free / 1e9
res = [check_dirty(), check_disk(root, floor_gb, 0.0), check_spool(free, spool_gb, capture_min_per_layer, qlc, floor_gb),
check_fstrim(), check_calib(rows or DEFAULTS["rows"], row_len or DEFAULTS["row_len"])]
if scratch:
res.append(check_scratch(scratch, memmap_gb))
+ if src or tmap:
+ from .formats import check_input_format, load_source
+ res.append(check_input_format(*load_source(src, tmap, config)))
if gpurun:
res.append(check_gpurun_exempt(gpurun, who or DEFAULTS["quantizer_who_prefix"] + "0"))
return res
@@ -133,7 +136,7 @@ def run(root, spool_gb, capture_min_per_layer=None, rows=None, row_len=None, gpu
def cli(a):
res = run(a.root, a.spool_gb, a.capture_min_per_layer, a.rows, a.row_len, a.gpurun, a.who, not a.no_qlc, a.floor_gb,
- a.scratch, a.memmap_gb)
+ a.scratch, a.memmap_gb, a.src, a.map, a.config)
for n, s, m in res:
print(f"{s:5s} {n:12s} {m}")
raise SystemExit(1 if any(s == "FAIL" for _, s, _ in res) else 0)