okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
4.9 KiB104 linesraw
1#!/usr/bin/env python3
2"""dense_requant.py - the dense matrices of a DeepSeek-V4.1 pack (attention, compressor, indexer, shared experts; BF16 in the
3unsloth GGUF) in a ggml K-quant, through ggml's own quantizer (libggml-base, ctypes), written beside the model as a small file the
4pack reads instead of the originals - the experts, the Engram and the embedding/head are not touched, nothing big is copied:
5
6    python tools/dsv41/dense_requant.py --pack PACK --out DIR --type Q5_K [--lib libggml-base.so] [--jobs 8]
7    python tools/dsv41/pack_gguf.py --model GGUF_DIR --out PACK2 --dense-override DIR
8
9DIR/dense.bin holds the quantized tensors (4096-aligned), DIR/dense.json {tensor name: [type, file, offset, bytes, shape]}.
10Types: Q4_K (4.5 bpw), Q5_K (5.5), Q6_K (6.56), Q8_0 (8.5).  --include / --exclude are regexes on the checkpoint name
11(default: layers.N.attn.* and layers.N.ffn.shared_experts.*, the main layers only, matrices whose rows are whole 256 blocks).
12"""
13import argparse
14import ctypes
15import json
16import multiprocessing as mp
17import os
18import pathlib
19import re
20import sys
21import time
22
23import numpy as np
24
25GT = {"Q8_0": (8, 32, 34), "Q4_K": (12, 256, 144), "Q5_K": (13, 256, 176), "Q6_K": (14, 256, 210)}
26_lib = None
27
28
29def _init(libpath):
30    global _lib
31    try:
32        os.nice(10)
33    except OSError:
34        pass
35    _lib = ctypes.CDLL(libpath)
36    _lib.ggml_quantize_chunk.restype = ctypes.c_size_t
37    _lib.ggml_quantize_chunk.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64,
38                                         ctypes.c_int64, ctypes.c_void_p]
39
40
41def _job(j):
42    name, path, off, nbytes, rows, cols, tid, qrb, out_path, out_off = j
43    raw = np.memmap(path, dtype=np.uint16, mode="r", offset=off, shape=(rows * cols,))
44    x = (raw.astype(np.uint32) << 16).view(np.float32).reshape(rows, cols)
45    x = np.ascontiguousarray(x)
46    dst = np.empty(rows * qrb, dtype=np.uint8)
47    got = _lib.ggml_quantize_chunk(tid, x.ctypes.data, dst.ctypes.data, 0, rows, cols, None)
48    if got != rows * qrb:
49        raise RuntimeError("%s: ggml_quantize_chunk wrote %d of %d bytes" % (name, got, rows * qrb))
50    # relative error of the result against the source (dequantize by the type's own reference is not exposed here:
51    # the engine's tests compare the kernels; this tool only checks the size)
52    fd = os.open(out_path, os.O_WRONLY)
53    os.pwrite(fd, dst.tobytes(), out_off)
54    os.close(fd)
55    return name, rows * qrb
56
57
58def main():
59    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
60    ap.add_argument("--pack", required=True)
61    ap.add_argument("--out", required=True)
62    ap.add_argument("--type", required=True, choices=sorted(GT))
63    ap.add_argument("--lib", default="/data/dsv41/build-hip/bin/libggml-base.so")
64    ap.add_argument("--jobs", type=int, default=8)
65    ap.add_argument("--include", default=r"^layers\.\d+\.(attn\.|ffn\.shared_experts\.)")
66    ap.add_argument("--exclude", default=r"(norm|sink|gate\.bias|\.gate\.weight$|hc_|weights_proj)")
67    a = ap.parse_args()
68    tid, per, bpb = GT[a.type]
69    files, tensors, cfg = {}, [], {}
70    for line in open(os.path.join(a.pack, "tensors.txt"), encoding="utf-8"):
71        f = line.split()
72        if f and f[0] == "file":
73            files[int(f[1])] = line.split(None, 2)[2].strip()
74        elif f and f[0] == "t":
75            tensors.append((f[1], f[2], int(f[3]), int(f[4]), int(f[5]), [int(x) for x in f[6:]]))
76    for line in open(os.path.join(a.pack, "ds4.txt"), encoding="utf-8"):
77        k, _, v = line.strip().partition(" ")
78        cfg[k] = v
79    model_dir = cfg["model_dir"]
80    inc, exc = re.compile(a.include), re.compile(a.exclude)
81    sel = [t for t in tensors if t[1] == "BF16" and len(t[5]) == 2 and t[5][1] % per == 0 and inc.search(t[0]) and not exc.search(t[0])]
82    os.makedirs(a.out, exist_ok=True)
83    out_path = os.path.join(a.out, "dense.bin")
84    jobs, idx, off = [], {}, 0
85    for name, dt, fi, o, nb, shape in sel:
86        rows, cols = shape
87        qrb = cols // per * bpb
88        jobs.append((name, os.path.join(model_dir, files[fi]), o, nb, rows, cols, tid, qrb, out_path, off))
89        idx[name] = [a.type, "dense.bin", off, rows * qrb, shape]
90        off += (rows * qrb + 4095) // 4096 * 4096
91    with open(out_path, "wb") as f:
92        f.truncate(off)
93    src_b = sum(t[4] for t in sel)
94    t0 = time.time()
95    with mp.get_context("fork").Pool(a.jobs, initializer=_init, initargs=(a.lib,)) as pool:
96        for i, (name, n) in enumerate(pool.imap_unordered(_job, jobs)):
97            if i % 40 == 0:
98                print("%d/%d %s %.0f s" % (i, len(jobs), name, time.time() - t0), flush=True)
99    json.dump(idx, open(os.path.join(a.out, "dense.json"), "w"))
100    print("dense %s: %d tensors, %.2f GB BF16 -> %.2f GB, %.0f s" % (a.type, len(sel), src_b / 1e9, sum(v[3] for v in idx.values()) / 1e9, time.time() - t0))
101
102
103if __name__ == "__main__":
104    main()