v41-quant-worker / v41_quant_experts.py
apetersson's picture
v41 quant expert requantiser
c5ee76b verified
Raw History Blame Contribute Delete
25.1 kB
#!/usr/bin/env python3
"""Streaming requantisation of DeepSeek-V4.1 routed experts to a B200-sized mixed-Q2 checkpoint.
The official V4.1 checkpoint stores routed experts as MXFP4: 16 bytes of packed E2M1
values plus one E8M0 scale byte per 32 weights (4.25 bits/weight). This tool decodes
those blocks exactly, requantises the 40 main-layer expert matrices into ggml block
formats (IQ2_XXS for gate/up ``w1``/``w3``, Q2_K for down ``w2``) and writes a complete
non-Engram checkpoint where every other tensor is preserved byte-for-byte.
Quantisation is not imatrix-based: no activation calibration is collected and no
importance matrix is consumed. IQ2_XXS is called with a constant unit importance
vector, which is the unweighted reference path; the switch is made explicit in the
manifest of every output shard.
Design constraints:
* one pass over the source; no intermediate BF16 copy and no whole-model buffer
* output shards mirror the source shards, so a failed shard is retried alone
* Engram tables (203 GB) stay native and are referenced by hash, never copied
* MTP/DSpark expert tensors stay at native precision because DSpark is disabled
Commands:
plan build plan.json from the source index and shard headers
convert write the quantised checkpoint (parallel, resumable per shard)
verify re-check output headers, sizes and sampled tensor hashes
"""
from __future__ import annotations
import argparse
import ctypes
import hashlib
import json
import multiprocessing as mp
import os
import sys
from collections.abc import Iterable
from concurrent.futures import ProcessPoolExecutor
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
import numpy as np
# --------------------------------------------------------------------------------------
# Recipe
# --------------------------------------------------------------------------------------
# gate/up/down projection -> ggml quantisation type name
DEFAULT_RECIPE = {"w1": "IQ2_XXS", "w3": "IQ2_XXS", "w2": "Q2_K"}
# ggml type ids; values must match enum ggml_type in the pinned llama.cpp revision.
GGML_TYPE_IDS = {
"Q2_K": 10,
"IQ2_XXS": 16,
"F32": 0,
"F16": 1,
"BF16": 30,
"I8": 24,
"F8_E4M3": 35,
"Q8_0": 8,
}
# (block elements, bytes per block) for the quantised expert types.
GGML_BLOCK = {"Q2_K": (256, 84), "IQ2_XXS": (256, 66)}
QUANTIZE_SYMBOLS = {"Q2_K": "quantize_q2_K", "IQ2_XXS": "quantize_iq2_xxs"}
MXFP4_TABLE = np.array(
[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
dtype=np.float32,
)
MXFP4_BLOCK = 32
# Tensors that stay native in the source checkpoint and are therefore not copied.
EXTERNAL_ROLE = "engram-native"
def is_external(name: str) -> bool:
return ".engram." in name or name.startswith("engram.")
def is_main_routed_expert(name: str) -> bool:
"""True for the 40 main-layer routed expert weights this tool requantises."""
if not name.startswith("layers."):
return False
if ".ffn.experts." not in name or "shared_experts" in name:
return False
return name.endswith(".weight")
def expert_projection(name: str) -> str:
return name.rsplit(".", 2)[-2]
def is_expert_scale(name: str) -> bool:
"""MXFP4 E8M0 scale blocks belonging to a requantised expert weight."""
if not name.startswith("layers."):
return False
if ".ffn.experts." not in name or "shared_experts" in name:
return False
return name.endswith(".scale") and name[: -len(".scale")].endswith(("w1", "w2", "w3"))
# --------------------------------------------------------------------------------------
# MXFP4
# --------------------------------------------------------------------------------------
def decode_mxfp4(weight: np.ndarray, scale: np.ndarray) -> np.ndarray:
"""Decode packed E2M1 nibbles with one E8M0 scale per 32 weights along the last axis.
Nibble order follows the official converter: the low nibble of a byte is element 2k
and the high nibble is element 2k+1. The E8M0 byte is a power of two, value 2**(b-127).
"""
if weight.dtype != np.uint8:
raise ValueError(f"packed weights must be uint8, got {weight.dtype}")
if scale.dtype != np.uint8:
raise ValueError(f"MXFP4 scales must be uint8/E8M0 bytes, got {scale.dtype}")
if weight.shape[:-1] != scale.shape[:-1]:
raise ValueError(f"scale leading shape {scale.shape[:-1]} != weight {weight.shape[:-1]}")
if weight.shape[-1] * 2 != scale.shape[-1] * MXFP4_BLOCK:
raise ValueError(
f"packing mismatch: {weight.shape[-1]} bytes/row vs {scale.shape[-1]} scales/row"
)
out = np.empty((*weight.shape[:-1], weight.shape[-1] * 2), dtype=np.float32)
out[..., 0::2] = MXFP4_TABLE[(weight & 0x0F).astype(np.uint8)]
out[..., 1::2] = MXFP4_TABLE[((weight >> 4) & 0x0F).astype(np.uint8)]
# 2**(b-127) in float32; b=0..254 are finite, 255 is the reserved NaN encoding.
scales = np.exp2(scale.astype(np.int16) - np.int16(127)).astype(np.float32, copy=False)
return out * np.repeat(scales, MXFP4_BLOCK, axis=-1)
# --------------------------------------------------------------------------------------
# ggml bridge
# --------------------------------------------------------------------------------------
class GgmlQuantizer:
"""ctypes bridge to the pinned llama.cpp ggml reference quantisers."""
def __init__(self, lib_paths: Iterable[str]):
loaded = []
for path in lib_paths:
if not os.path.exists(path):
raise FileNotFoundError(f"ggml library not found: {path}")
ctypes.CDLL(path, mode=ctypes.RTLD_GLOBAL)
loaded.append(path)
self.core = ctypes.CDLL(loaded[-1])
self.core.ggml_quantize_init.argtypes = [ctypes.c_int]
self.core.ggml_quantize_init.restype = None
self._fns: dict[str, Any] = {}
self._load_paths = tuple(loaded)
def _fn(self, type_name: str):
if type_name not in self._fns:
sym = QUANTIZE_SYMBOLS[type_name]
fn = getattr(self.core, sym)
fn.restype = ctypes.c_size_t
fn.argtypes = [
ctypes.POINTER(ctypes.c_float),
ctypes.c_void_p,
ctypes.c_int64,
ctypes.c_int64,
ctypes.POINTER(ctypes.c_float),
]
self._fns[type_name] = fn
self.core.ggml_quantize_init(GGML_TYPE_IDS[type_name])
return self._fns[type_name]
def quantize(self, weights: np.ndarray, type_name: str, importance: np.ndarray | None = None):
"""Quantise a row-major float32 matrix; returns raw ggml block bytes."""
if weights.ndim != 2 or weights.dtype != np.float32:
raise ValueError("expected a float32 2-D matrix")
block, block_bytes = GGML_BLOCK[type_name]
rows, cols = weights.shape
if cols % block:
raise ValueError(f"{type_name} needs a row length multiple of {block}, got {cols}")
if not weights.flags["C_CONTIGUOUS"]:
weights = np.ascontiguousarray(weights)
out = np.empty(rows * (cols // block) * block_bytes, dtype=np.uint8)
fn = self._fn(type_name)
arg = None
if importance is not None:
if importance.shape != (cols,):
raise ValueError(f"importance must have {cols} entries")
arg = importance.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
written = fn(
weights.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
out.ctypes.data,
ctypes.c_int64(rows),
ctypes.c_int64(cols),
arg,
)
if written != out.nbytes:
raise RuntimeError(f"{type_name}: wrote {written} of {out.nbytes} bytes")
return out
_WORKER: dict[str, Any] = {}
def _worker_init(lib_paths: tuple[str, ...]) -> None:
_WORKER["ggml"] = GgmlQuantizer(lib_paths)
# --------------------------------------------------------------------------------------
# Source layout and plan
# --------------------------------------------------------------------------------------
@dataclass
class SourceTensor:
name: str
shard: str
dtype: str
shape: tuple[int, ...]
begin: int
end: int
data_start: int
role: str = ""
out_shard: str = ""
out_offset: int = 0
out_dtype: str = ""
out_shape: tuple[int, ...] = ()
out_bytes: int = 0
ggml_type: str | None = None
def read_safetensors_header(path: Path) -> tuple[dict[str, Any], int]:
with open(path, "rb") as fh:
raw = fh.read(8)
if len(raw) != 8:
raise ValueError(f"{path}: truncated safetensors header")
length = int.from_bytes(raw, "little")
header = json.loads(fh.read(length))
header.pop("__metadata__", None)
return header, 8 + length
def quantised_shape(name: str, shape: tuple[int, ...], type_name: str) -> tuple[int, ...]:
"""Byte shape of the quantised tensor as stored in the output file."""
logical = (shape[0], shape[1] * 2)
block, block_bytes = GGML_BLOCK[type_name]
if logical[1] % block:
raise ValueError(f"{name}: {logical[1]} is not a multiple of {block}")
return (logical[0], logical[1] // block * block_bytes)
def build_plan(source: Path, recipe: dict[str, str]) -> dict[str, Any]:
index_path = source / "model.safetensors.index.json"
index = json.loads(index_path.read_text())
weight_map: dict[str, str] = index["weight_map"]
headers: dict[str, tuple[dict[str, Any], int]] = {}
tensors: list[SourceTensor] = []
for name, shard in weight_map.items():
if shard not in headers:
headers[shard] = read_safetensors_header(source / shard)
header, data_start = headers[shard]
entry = header[name]
begin, end = entry["data_offsets"]
tensor = SourceTensor(
name=name,
shard=shard,
dtype=entry["dtype"],
shape=tuple(entry["shape"]),
begin=begin,
end=end,
data_start=data_start,
)
if is_external(name):
tensor.role = EXTERNAL_ROLE
elif is_expert_scale(name):
tensor.role = "dropped-expert-scale"
elif is_main_routed_expert(name):
type_name = recipe[expert_projection(name)]
tensor.role = "quantised"
tensor.ggml_type = type_name
tensor.out_dtype = "U8"
tensor.out_shape = quantised_shape(name, tensor.shape, type_name)
tensor.out_bytes = int(np.prod(tensor.out_shape))
else:
tensor.role = "preserved"
tensor.out_dtype = tensor.dtype
tensor.out_shape = tensor.shape
tensor.out_bytes = end - begin
tensors.append(tensor)
# Output shards mirror the source shards; dropped tensors leave no gap.
by_shard: dict[str, list[SourceTensor]] = {}
for tensor in tensors:
if tensor.role in ("preserved", "quantised"):
by_shard.setdefault(tensor.shard, []).append(tensor)
shard_order = sorted(by_shard)
out_names = {
shard: f"quant-{i + 1:05d}-of-{len(shard_order):05d}.safetensors"
for i, shard in enumerate(shard_order)
}
plan_shards = []
for shard in shard_order:
members = sorted(by_shard[shard], key=lambda t: (t.begin, t.name))
offset = 0
for tensor in members:
tensor.out_shard = out_names[shard]
tensor.out_offset = offset
offset += tensor.out_bytes
plan_shards.append(
{
"source_shard": shard,
"output_shard": out_names[shard],
"data_bytes": offset,
"tensors": [asdict(t) for t in members],
}
)
external = [asdict(t) for t in tensors if t.role == EXTERNAL_ROLE]
dropped = [asdict(t) for t in tensors if t.role == "dropped-expert-scale"]
quant = [t for t in tensors if t.role == "quantised"]
preserved = [t for t in tensors if t.role == "preserved"]
return {
"source_dir": str(source),
"source_revision": "2bc89ac599031fa673cab993f1df02fc4a98c673",
"recipe": recipe,
"importance": "unit (no imatrix; no activation calibration)",
"external": external,
"dropped": dropped,
"totals": {
"source_tensors": len(weight_map),
"preserved": len(preserved),
"quantised": len(quant),
"dropped_expert_scales": len(dropped),
"external_native": len(external),
"quantised_logical_weights": sum(t.shape[0] * t.shape[1] * 2 for t in quant),
"preserved_bytes": sum(t.out_bytes for t in preserved),
"quantised_bytes": sum(t.out_bytes for t in quant),
"external_bytes": sum(t.end - t.begin for t in tensors if t.role == EXTERNAL_ROLE),
"dropped_bytes": sum(
t.end - t.begin for t in tensors if t.role == "dropped-expert-scale"
),
"output_bytes": sum(t.out_bytes for t in preserved + quant),
},
"shards": plan_shards,
}
def plan_path(out: Path) -> Path:
return out / "plan.json"
def load_plan(out: Path) -> dict[str, Any]:
path = plan_path(out)
if not path.exists():
raise SystemExit(f"missing plan: run `plan` first ({path})")
return json.loads(path.read_text())
# --------------------------------------------------------------------------------------
# Output writing
# --------------------------------------------------------------------------------------
def safetensors_header(entries: dict[str, dict[str, Any]]) -> bytes:
"""Build a safetensors header whose data offsets are relative to the data section."""
payload = json.dumps(entries, separators=(",", ":")).encode("utf-8")
pad = (-(8 + len(payload))) % 8
return len(payload + b" " * pad).to_bytes(8, "little") + payload + b" " * pad
def _source_slice(fd: int, data_start: int, begin: int, end: int) -> bytes:
return os.pread(fd, end - begin, data_start + begin)
def _convert_tensor(task: dict[str, Any], src_path: str, out_path: str) -> dict[str, Any]:
src_fd = os.open(src_path, os.O_RDONLY)
out_fd = os.open(out_path, os.O_WRONLY)
try:
raw = _source_slice(src_fd, task["data_start"], task["begin"], task["end"])
src_sha = hashlib.sha256(raw).hexdigest()
if task["role"] == "preserved":
payload = raw
else:
source = np.frombuffer(raw, dtype=np.uint8).reshape(task["shape"])
scale_task = task["scale"]
scale_raw = _source_slice(
src_fd, scale_task["data_start"], scale_task["begin"], scale_task["end"]
)
scales = np.frombuffer(scale_raw, dtype=np.uint8).reshape(scale_task["shape"])
weights = decode_mxfp4(source, scales)
type_name = task["ggml_type"]
# IQ2_XXS requires a non-null importance vector; unit weights are the
# unweighted reference path and carry no calibration information.
importance = np.ones(weights.shape[1], dtype=np.float32)
payload = _WORKER["ggml"].quantize(weights, type_name, importance).tobytes()
if len(payload) != task["out_bytes"]:
raise RuntimeError(
f"{task['name']}: produced {len(payload)} bytes, expected {task['out_bytes']}"
)
os.pwrite(out_fd, payload, task["file_offset"])
finally:
os.close(src_fd)
os.close(out_fd)
return {
"name": task["name"],
"source_bytes": len(raw),
"source_sha256": src_sha,
"output_bytes": len(payload),
"output_sha256": hashlib.sha256(payload).hexdigest(),
}
def _convert_worker_init(lib_paths: tuple[str, ...], importance_mode: str) -> None:
_worker_init(lib_paths)
_WORKER["importance"] = {}
if importance_mode == "unit":
return
raise ValueError(f"unsupported importance mode {importance_mode}")
def _pool_context():
"""Prefer fork so workers inherit the loaded ggml library and open file handles."""
methods = mp.get_all_start_methods()
return mp.get_context("fork" if "fork" in methods else methods[0])
def convert_shard(
plan: dict[str, Any],
shard: dict[str, Any],
source: Path,
out_dir: Path,
lib_paths: tuple[str, ...],
jobs: int,
importance_mode: str,
) -> dict[str, Any]:
output = out_dir / shard["output_shard"]
members = shard["tensors"]
scale_map = {t["name"][: -len(".scale")]: t for t in plan["dropped"]}
tasks = []
for tensor in members:
task = dict(tensor)
if tensor["role"] == "quantised":
key = tensor["name"][: -len(".weight")]
scale = scale_map.get(key)
if scale is None:
raise RuntimeError(f"{tensor['name']}: no matching MXFP4 scale tensor")
task["scale"] = scale
tasks.append(task)
header_entries: dict[str, dict[str, Any]] = {}
for tensor in members:
header_entries[tensor["name"]] = {
"dtype": tensor["out_dtype"],
"shape": list(tensor["out_shape"]),
"data_offsets": [tensor["out_offset"], tensor["out_offset"] + tensor["out_bytes"]],
}
blob = safetensors_header(header_entries)
data_start = len(blob)
total = data_start + shard["data_bytes"]
src_path = str(source / shard["source_shard"])
out_fd = os.open(output, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o644)
try:
os.pwrite(out_fd, blob, 0)
os.ftruncate(out_fd, total)
for task in tasks:
task["file_offset"] = data_start + task["out_offset"]
results = []
if jobs <= 1:
_convert_worker_init(lib_paths, importance_mode)
for task in tasks:
results.append(_convert_tensor(task, src_path, str(output)))
else:
with ProcessPoolExecutor(
max_workers=jobs,
mp_context=_pool_context(),
initializer=_convert_worker_init,
initargs=(lib_paths, importance_mode),
) as pool:
futures = [
pool.submit(_convert_tensor, task, src_path, str(output)) for task in tasks
]
for future in futures:
results.append(future.result())
os.fsync(out_fd)
finally:
os.close(out_fd)
manifest = {
"output_shard": shard["output_shard"],
"source_shard": shard["source_shard"],
"source_revision": plan["source_revision"],
"recipe": plan["recipe"],
"importance": plan["importance"],
"data_bytes": shard["data_bytes"],
"file_bytes": total,
"tensors": results,
}
(out_dir / (shard["output_shard"] + ".manifest.json")).write_text(
json.dumps(manifest, indent=1) + "\n"
)
(out_dir / (shard["output_shard"] + ".complete")).write_text(
f"{shard['source_shard']} {total} {len(members)}\n"
)
return manifest
# --------------------------------------------------------------------------------------
# Verification
# --------------------------------------------------------------------------------------
def verify(out_dir: Path, sample: int, rng: np.random.Generator) -> list[str]:
problems: list[str] = []
manifests = sorted(out_dir.glob("quant-*.safetensors.manifest.json"))
if not manifests:
return [f"no manifests in {out_dir}"]
for path in manifests:
manifest = json.loads(path.read_text())
shard = out_dir / manifest["output_shard"]
header, data_start = read_safetensors_header(shard)
if os.path.getsize(shard) != manifest["file_bytes"]:
problems.append(f"{shard.name}: size mismatch")
entries = [t for t in manifest["tensors"]]
picks = (
range(len(entries))
if sample <= 0
else rng.choice(len(entries), size=min(sample, len(entries)), replace=False)
)
with open(shard, "rb") as fh:
for index in picks:
entry = entries[int(index)]
info = header[entry["name"]]
begin, end = info["data_offsets"]
if end - begin != entry["output_bytes"]:
problems.append(f"{shard.name}:{entry['name']}: header size mismatch")
continue
fh.seek(data_start + begin)
digest = hashlib.sha256(fh.read(end - begin)).hexdigest()
if digest != entry["output_sha256"]:
problems.append(f"{shard.name}:{entry['name']}: digest mismatch")
if len(header) != len(entries):
problems.append(
f"{shard.name}: header has {len(header)} tensors, manifest {len(entries)}"
)
return problems
# --------------------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------------------
def lib_paths_from_args(args) -> tuple[str, ...]:
if args.ggml_lib:
return tuple(args.ggml_lib)
return ()
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
sub = parser.add_subparsers(dest="command", required=True)
p_plan = sub.add_parser("plan", help="build the tensor plan")
p_plan.add_argument("--source", type=Path, required=True)
p_plan.add_argument("--out", type=Path, required=True)
p_plan.add_argument("--w1", default=DEFAULT_RECIPE["w1"])
p_plan.add_argument("--w2", default=DEFAULT_RECIPE["w2"])
p_plan.add_argument("--w3", default=DEFAULT_RECIPE["w3"])
p_conv = sub.add_parser("convert", help="write the quantised checkpoint")
p_conv.add_argument("--source", type=Path, required=True)
p_conv.add_argument("--out", type=Path, required=True)
p_conv.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 8) - 2))
p_conv.add_argument(
"--ggml-lib",
action="append",
default=[],
help="ggml shared library (repeat; load order matters)",
)
p_conv.add_argument(
"--only-shard",
action="append",
default=[],
help="source shard name, e.g. model-00009-of-00048.safetensors",
)
p_conv.add_argument("--importance", default="unit", choices=["unit"])
p_conv.add_argument("--resume", action="store_true", help="skip shards with a .complete marker")
p_conv.add_argument("--dry-run", action="store_true")
p_ver = sub.add_parser("verify", help="re-check output shards")
p_ver.add_argument("--out", type=Path, required=True)
p_ver.add_argument("--sample", type=int, default=8, help="tensors hashed per shard (0 = all)")
p_ver.add_argument("--seed", type=int, default=20260910)
args = parser.parse_args(argv)
if args.command == "plan":
plan = build_plan(args.source, {"w1": args.w1, "w2": args.w2, "w3": args.w3})
args.out.mkdir(parents=True, exist_ok=True)
plan_path(args.out).write_text(json.dumps(plan, indent=1) + "\n")
print(json.dumps(plan["totals"], indent=1))
return 0
if args.command == "convert":
plan = load_plan(args.out)
if args.dry_run:
print(json.dumps(plan["totals"], indent=1))
return 0
shards = plan["shards"]
if args.only_shard:
wanted = set(args.only_shard)
shards = [s for s in shards if s["source_shard"] in wanted]
if not shards:
raise SystemExit("no matching shards")
for shard in shards:
marker = args.out / (shard["output_shard"] + ".complete")
if args.resume and marker.exists():
print(f"skip {shard['output_shard']}", flush=True)
continue
manifest = convert_shard(
plan,
shard,
args.source,
args.out,
lib_paths_from_args(args),
args.jobs,
args.importance,
)
print(
f"{manifest['output_shard']} <- {manifest['source_shard']}: "
f"{len(manifest['tensors'])} tensors, {manifest['file_bytes'] / 1e9:.2f} GB",
flush=True,
)
return 0
if args.command == "verify":
problems = verify(args.out, args.sample, np.random.default_rng(args.seed))
for problem in problems:
print("FAIL", problem)
print("verify: OK" if not problems else f"verify: {len(problems)} problems")
return 1 if problems else 0
return 2
if __name__ == "__main__":
sys.exit(main())