jon1012 commited on
Commit
dfce15b
·
verified ·
1 Parent(s): 2e573a9

Final card and build scripts: measured numbers, Engram caveat, pruning analysis

Browse files
Files changed (1) hide show
  1. finalize_repo.py +95 -0
finalize_repo.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Write config.json + copy the auxiliary files for the re-packed checkpoint.
3
+
4
+ The weight re-packer only emits safetensors and an index. This adds everything else a
5
+ consumer needs, and -- importantly -- writes a quantization_config that DESCRIBES what we
6
+ actually did, because no released engine reads `deepseek_v41` yet and we are therefore
7
+ defining the convention rather than matching one.
8
+
9
+ Changes vs upstream config.json:
10
+ expert_dtype "fp4" -> "nvfp4" experts are now block-16 E2M1 + E4M3 scale
11
+ + FP32 per-tensor global scale
12
+ expert_block_size (new) 16
13
+ expert_scale_fmt (new) "e4m3"
14
+ engram_dtype (new) "fp4" Engram tables are now E2M1
15
+ engram_block_size (new) 32 keeping the source's own block/scale layout
16
+ engram_scale_fmt (new) "ue8m0"
17
+ Everything else (dense fp8 block 32x32 / ue8m0) is untouched and left exactly as shipped.
18
+ """
19
+ import glob, json, os, shutil, struct, sys
20
+
21
+ src, out = sys.argv[1], sys.argv[2]
22
+
23
+
24
+ def rebuild_index(out_dir):
25
+ """Rebuild model.safetensors.index.json by reading every output shard's header.
26
+
27
+ The re-packer is run in more than one pass (experts, then the two 94.5 GiB Engram
28
+ shards), and each pass writes an index covering only its own shards -- so the last
29
+ pass would otherwise clobber the rest. Reading the headers back is also a real check
30
+ that every shard on disk is a valid safetensors file.
31
+ """
32
+ DT = {"I8": 1, "U8": 1, "F8_E4M3": 1, "F8_E8M0": 1, "BF16": 2, "F16": 2,
33
+ "F32": 4, "F64": 8, "I32": 4, "I64": 8, "BOOL": 1}
34
+ wmap, total = {}, 0
35
+ shards = sorted(glob.glob(os.path.join(out_dir, "*.safetensors")))
36
+ for path in shards:
37
+ with open(path, "rb") as fh:
38
+ n = struct.unpack("<Q", fh.read(8))[0]
39
+ hdr = json.loads(fh.read(n))
40
+ base = os.path.basename(path)
41
+ for k, v in hdr.items():
42
+ if k == "__metadata__":
43
+ continue
44
+ assert k not in wmap, f"tensor {k} appears in two shards"
45
+ wmap[k] = base
46
+ cnt = 1
47
+ for d in v["shape"]:
48
+ cnt *= d
49
+ total += cnt * DT[v["dtype"]]
50
+ return {"metadata": {"total_size": total}, "weight_map": wmap}, len(shards), total
51
+
52
+
53
+ idx, n_shards, total = rebuild_index(out)
54
+ json.dump(idx, open(os.path.join(out, "model.safetensors.index.json"), "w"), indent=1)
55
+ print(f"rebuilt index from {n_shards} shards: {len(idx['weight_map']):,} tensors, "
56
+ f"{total/2**30:.1f} GiB")
57
+
58
+ cfg = json.load(open(os.path.join(src, "config.json")))
59
+ q = dict(cfg.get("quantization_config", {}))
60
+ assert q.get("expert_dtype") == "fp4", f"unexpected upstream quantization_config: {q}"
61
+ q.update({
62
+ "expert_dtype": "nvfp4",
63
+ "expert_block_size": 16,
64
+ "expert_scale_fmt": "e4m3",
65
+ "expert_global_scale": True,
66
+ "engram_dtype": "fp4",
67
+ "engram_block_size": 32,
68
+ "engram_scale_fmt": "ue8m0",
69
+ "repacked_by": "LibertAI/dsv41_fp4_stream.py",
70
+ })
71
+ cfg["quantization_config"] = q
72
+ json.dump(cfg, open(os.path.join(out, "config.json"), "w"), indent=2)
73
+ print("wrote config.json:", json.dumps(q))
74
+
75
+ FILES = ["tokenizer.json", "tokenizer_config.json", "LICENSE",
76
+ "DeepSeek_V41_Tech_Report.pdf"]
77
+ DIRS = ["encoding", "inference"]
78
+ for fn in FILES:
79
+ p = os.path.join(src, fn)
80
+ if os.path.exists(p):
81
+ shutil.copy2(p, os.path.join(out, fn)); print(" copied", fn)
82
+ for d in DIRS:
83
+ p = os.path.join(src, d)
84
+ if os.path.isdir(p):
85
+ shutil.copytree(p, os.path.join(out, d), dirs_exist_ok=True); print(" copied", d + "/")
86
+
87
+ # sanity: index must cover every tensor the source had, minus the scale tensors we folded
88
+ si = json.load(open(os.path.join(src, "model.safetensors.index.json")))["weight_map"]
89
+ oi = json.load(open(os.path.join(out, "model.safetensors.index.json")))["weight_map"]
90
+ print(f"\nsource tensors {len(si):,} -> output tensors {len(oi):,}")
91
+ missing = [k for k in si if k not in oi and not k.endswith(".scale")]
92
+ extra = [k for k in oi if k not in si and not k.endswith((".weight_scale", ".weight_scale_2"))]
93
+ print(f"missing (non-scale): {len(missing)} {missing[:3]}")
94
+ print(f"unexpected new: {len(extra)} {extra[:3]}")
95
+ assert not missing, "output is missing tensors the source had"