File size: 6,143 Bytes
8c2847c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | """Offline NVFP4 quantizer for Clover-Preview-VL: routed-expert weights only.
Produces an SGLang `modelopt_mixed` (MIXED_PRECISION) checkpoint: every
`.mlp.experts` layer declared NVFP4 (group_size 16), dense / linear-attention /
router / embeddings / vision stay bf16. Expert keys switch from the fused bf16
`experts.gate_up_proj` / `experts.down_proj` to per-expert quant tensors
(`experts.<e>.gate_proj.weight[_scale|_weight_scale_2|_input_scale]`), which is
the layout FusedMoE.make_expert_params_mapping matches.
python quantize_nvfp4.py --in /root/ckpt --out /root/fp4 [--shard-gb 5]
"""
import argparse
import glob
import json
import os
import torch
from safetensors.torch import load_file, save_file
GROUP = 16
E2M1_MIDPOINTS = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0])
FP8_MAX = 448.0
EXPERT_IN = "experts.gate_up_proj"
EXPERT_OUT = "experts.down_proj"
def quant_fp4(w: torch.Tensor):
"""[out, in] bf16 -> (packed uint8 [out, in/2] low-nibble-even,
e4m3 block scales [out, in/16], fp32 per-tensor scale)."""
wf = w.float()
s2 = max(wf.abs().amax().item() / (6.0 * FP8_MAX), 1e-12)
out, inp = wf.shape
blocks = wf.view(out, inp // GROUP, GROUP)
s_block = (blocks.abs().amax(-1) / (6.0 * s2)).clamp(0, FP8_MAX)
s_block = s_block.to(torch.float8_e4m3fn)
x = (blocks / (s_block.float().unsqueeze(-1) * s2)).clamp(-6.0, 6.0)
mag = torch.bucketize(x.abs(), E2M1_MIDPOINTS.to(x.device))
code = (mag | ((x < 0).to(torch.uint8) << 3)).to(torch.uint8)
packed = (code[..., 0::2] | (code[..., 1::2] << 4)).reshape(out, inp // 2)
return packed.contiguous(), s_block.contiguous(), s2
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--in", dest="src", required=True)
ap.add_argument("--out", dest="dst", required=True)
ap.add_argument("--shard-gb", type=float, default=5.0)
args = ap.parse_args()
index = json.load(open(os.path.join(args.src, "model.safetensors.index.json")))
weight_map = index["weight_map"]
expert_layers = sorted(
{k.split(".")[2] for k in weight_map if EXPERT_IN in k}, key=int
)
print(f"{len(expert_layers)} MoE layers: {expert_layers[:3]}...")
os.makedirs(args.dst, exist_ok=True)
shards = sorted(set(weight_map.values()))
out_index, out_shard, out_size, out_count = {}, {}, 0, 0
def emit(key, tensor):
nonlocal out_shard, out_size, out_count
if out_size + tensor.nbytes > args.shard_gb * 1e9 and out_size > 0:
save_file(out_shard, os.path.join(args.dst, f"model-{out_count:05d}-of-XXXXX.safetensors"),
metadata={"format": "pt"})
out_shard, out_size, out_count = {}, 0, out_count + 1
out_shard[key] = tensor
out_size += tensor.nbytes
return f"model-{out_count:05d}-of-XXXXX.safetensors"
for shard in shards:
tensors = load_file(os.path.join(args.src, shard))
for key, t in tensors.items():
if EXPERT_IN in key or EXPERT_OUT in key:
prefix = key.split(EXPERT_IN if EXPERT_IN in key else EXPERT_OUT)[0]
e_count, dim2, dim_in = t.shape
is_gate_up = EXPERT_IN in key
if is_gate_up:
i_per = dim2 // 2
mats = {"gate_proj": t[:, :i_per], "up_proj": t[:, i_per:]}
else:
i_per = dim_in
mats = {"down_proj": t}
for e in range(e_count):
for proj, w in mats.items():
wq, ws, s2 = quant_fp4(w[e])
for suffix, v in (("weight", wq), ("weight_scale", ws),
("weight_scale_2", torch.tensor(s2)),
("input_scale", torch.tensor(1.0))):
k = f"{prefix}experts.{e}.{proj}.{suffix}"
out_index[k] = emit(k, v)
print(f"{key}: {e_count} experts, in={dim_in}, i_per={i_per}")
else:
out_index[key] = emit(key, t)
del tensors
if out_shard:
save_file(out_shard, os.path.join(args.dst, f"model-{out_count:05d}-of-XXXXX.safetensors"),
metadata={"format": "pt"})
# Rename placeholder shard names to the real total, then rebuild the index.
old_files = sorted(glob.glob(os.path.join(args.dst, "model-*-of-XXXXX.safetensors")))
n_total = len(old_files)
remap = {}
for i, f in enumerate(old_files):
new = f"model-{i:05d}-of-{n_total:05d}.safetensors"
os.rename(f, os.path.join(args.dst, new))
remap[os.path.basename(f)] = new
final_index = {"metadata": {"total_size": 0}, "weight_map": {}}
for key, old in out_index.items():
new = remap[os.path.basename(old)]
final_index["weight_map"][key] = new
for key in final_index["weight_map"]:
final_index["metadata"]["total_size"] += os.path.getsize(
os.path.join(args.dst, final_index["weight_map"][key]))
json.dump(final_index, open(os.path.join(args.dst, "model.safetensors.index.json"), "w"), indent=2)
qcfg = {
"producer": {"name": "kaivoss", "version": "1.0"},
"quantization": {
"quant_algo": "MIXED_PRECISION",
"kv_cache_quant_algo": None,
"exclude_modules": [],
"quantized_layers": {
f"model.layers.{l}.mlp.experts": {"quant_algo": "NVFP4", "group_size": GROUP}
for l in expert_layers
},
},
}
json.dump(qcfg, open(os.path.join(args.dst, "hf_quant_config.json"), "w"), indent=2)
for f in ("config.json", "generation_config.json", "tokenizer.json",
"tokenizer_config.json", "chat_template.jinja",
"preprocessor_config.json", "video_preprocessor_config.json"):
src = os.path.join(args.src, f)
if os.path.exists(src):
import shutil
shutil.copyfile(src, os.path.join(args.dst, f))
print("done:", sorted(os.listdir(args.dst))[:8], "…")
if __name__ == "__main__":
main()
|