okami.mom/strata

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

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

main
5.8 KiB132 linesraw
1"""tools/nvfp4_convert.py - a ModelOpt NVFP4 Qwen3.8-Flash-Next checkpoint -> a GGUF Strata can pack.
2
3    python tools/nvfp4_convert.py --model <ModelOpt NVFP4 dir> --outfile <model.gguf>
4
5This is llama.cpp's own converter (third_party/llama.cpp at the commit setup.py pins), run with the type policy
6Strata's engine needs. The converter already repacks ModelOpt NVFP4 experts into ggml's block_nvfp4 without loss
7(tools/nvfp4_verify.py proves it bit for bit) and writes each expert's weight_scale_2 as a separate F32 tensor
8`blk.N.ffn_{gate,up,down}_exps.scale`, one value per expert. What it does not know is Strata's layout:
9
10  * the small projections the residual, router, GDN, QSA and PLE kernels read as BF16 (iq_pack.BF16_PROJECTIONS)
11    must be BF16 - the converter would otherwise write routers and indexer projections as F32, which iq_pack
12    refuses, and the rest as the --outtype;
13  * everything the engine serves natively (attention, ssm_out, shared experts, output) goes to Q8_0: the native
14    GEMV has no BF16 path, and Q8_0 is the closest to the checkpoint's BF16 it has;
15  * token_embd goes to Q8_0 too. The abliteration edited embed_tokens, so another model's table cannot be reused,
16    and gguf-py cannot write the IQ types the native embedding reads today - the engine learns Q8_0 instead;
17  * the 51.2B-parameter PLE n-gram table is left out. The engine only reads it as IQ4_NL (ngram.cpp), and
18    dequantizing the checkpoint's FP8 copy would need ~205 GB of RAM. The abliteration did not touch this table,
19    so the engine is pointed at ISTA-DASLab's IQ4_NL shard 2 with --ple-gguf. The PLE hash constants and the
20    row width still come from this checkpoint and are written into the metadata.
21
22The MTP head is dropped here as llama.cpp does; tools/mtp_pack.py packs it separately.
23"""
24from __future__ import annotations
25
26import argparse
27import json
28import pathlib
29import sys
30import time
31
32ENGINE = pathlib.Path(__file__).resolve().parents[1]
33sys.path.insert(0, str(ENGINE / "tools"))
34from _paths import add_gguf_py, converter_dir  # noqa: E402  (the vendored gguf-py and converter, third_party/strata-gguf-py)
35
36CONVERTER = pathlib.Path(converter_dir())
37add_gguf_py()
38sys.path.insert(0, str(CONVERTER))
39
40import gguf  # noqa: E402
41from conversion import qwen4exp as Q4  # noqa: E402
42
43T = gguf.GGMLQuantizationType
44
45# Strata reads these as BF16 (tools/iq_pack.py BF16_PROJECTIONS + BF16_OUTPUT, and the routers).
46BF16_SUFFIXES = (
47    "hc_attn_down.weight", "hc_attn_up.weight", "hc_attn_inject.weight",
48    "hc_ffn_down.weight", "hc_ffn_up.weight", "hc_ffn_inject.weight",
49    "ssm_alpha.weight", "ssm_beta.weight", "indexer.q_proj.weight", "indexer.k_proj.weight",
50    "ple_value.weight", "ple_key.weight", "ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight",
51    "output_hc_down.weight", "output_hc_up.weight",
52)
53F16_SUFFIXES = ("ple_conv1d.weight",)
54Q8_NAMES = {"token_embd.weight", "output.weight"}
55
56dropped_ple: list[str] = []
57
58
59def install_policy() -> None:
60    cls = Q4.Qwen4ExpTextModel
61    base_force = cls.tensor_force_quant
62
63    def tensor_force_quant(self, name, new_name, bid, n_dims):
64        if n_dims >= 2:
65            if new_name.endswith(BF16_SUFFIXES):
66                return T.BF16
67            if new_name.endswith(F16_SUFFIXES):
68                return T.F16
69            if new_name in Q8_NAMES:
70                return T.Q8_0
71        return base_force(self, name, new_name, bid, n_dims)
72
73    def place_ple_shard(self, data_torch, name):
74        # Record the shard so the parts check in prepare_tensors still holds, and the row width for the
75        # metadata; write nothing - the table comes from the IQ4_NL PLE GGUF at run time.
76        idx = int(name.rsplit("shard_", 1)[1].split(".", 1)[0])
77        self._ple_shards[idx] = name
78        self._ple_row_dim = int(data_torch.shape[-1])
79        dropped_ple.append(name)
80        return []
81
82    cls.tensor_force_quant = tensor_force_quant
83    cls._place_ple_shard = place_ple_shard
84
85
86def main() -> int:
87    ap = argparse.ArgumentParser()
88    ap.add_argument("--model", required=True, help="the ModelOpt NVFP4 checkpoint directory")
89    ap.add_argument("--outfile", required=True)
90    ap.add_argument("--dry-run", action="store_true")
91    a = ap.parse_args()
92    model = pathlib.Path(a.model)
93    out = pathlib.Path(a.outfile)
94    out.parent.mkdir(parents=True, exist_ok=True)
95
96    install_policy()
97    import convert_hf_to_gguf as C  # noqa: E402  (after the policy is installed on the class)
98
99    argv = [str(model), "--outtype", "q8_0", "--outfile", str(out)]
100    if a.dry_run:
101        argv.append("--dry-run")
102    sys.argv = ["convert_hf_to_gguf.py"] + argv
103    t0 = time.time()
104    rc = C.main()
105    took = time.time() - t0
106
107    commit = ""   # the converter is vendored at the llama.cpp pin: third_party/strata-gguf-py/UPSTREAM.md names it
108    try:
109        for line in (CONVERTER.parent / "UPSTREAM.md").read_text(encoding="utf-8").splitlines():
110            if line.startswith("pin:"):
111                commit = line.split(":", 1)[1].strip()
112                break
113    except OSError:
114        pass
115    manifest = {
116        "source": str(model),
117        "llama_cpp_commit": commit,
118        "policy": {"bf16": list(BF16_SUFFIXES), "f16": list(F16_SUFFIXES), "q8_0": sorted(Q8_NAMES),
119                   "default_2d": "Q8_0", "experts": "NVFP4 (lossless repack) + per-expert F32 .scale"},
120        "ple_table": {"written": False, "shards_dropped": len(dropped_ple),
121                      "use": "--ple-gguf with an IQ4_NL per_layer_token_embd (ISTA-DASLab shard 2)"},
122        "mtp": "dropped here; pack with tools/mtp_pack.py",
123        "seconds": round(took, 1),
124    }
125    if not a.dry_run:
126        out.with_suffix(".manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
127    print("nvfp4_convert: done in %.0f s, PLE shards dropped: %d" % (took, len(dropped_ple)))
128    return rc or 0
129
130
131if __name__ == "__main__":
132    raise SystemExit(main())