ds41-dismantle / scripts /build_mini.py
grantabejar's picture
Upload folder using huggingface_hub
c7267b1 verified
Raw History Blame Contribute Delete
3.57 kB
#!/usr/bin/env python3
"""Build a smaller DS4.1 pack: expert-prune to K (usage scores), strip MTP/vision/aligner
tensors, disable DSpark (num_nextn_predict_layers=0), keep engram (symlink).
usage: build_mini.py SRC DST K SCORES_JSON"""
import json, struct, os, sys
import numpy as np
SRC, DST, K, SCORES = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
cfg = json.load(open(os.path.join(SRC, "config.json")))
tc = cfg["text_config"]
tc["n_routed_experts"] = K
tc["num_nextn_predict_layers"] = 0
tc["dspark_target_layer_ids"] = []
if "omlx_deepseek_v41" in cfg:
cfg["omlx_deepseek_v41"]["preserve_mtp"] = False
os.makedirs(DST, exist_ok=True)
scores = json.load(open(SCORES))["layers"]
keep = {}
for l, d in scores.items():
wn = np.asarray(d["w_norms"])
keep[int(l)] = np.sort(np.argsort(-wn)[:K].astype(np.int64))
idx = json.load(open(os.path.join(SRC, "model.safetensors.index.json")))
wm = idx["weight_map"]
DROP = ("language_model.mtp.",)
drop = {k for k in wm if k.startswith(DROP)}
kept_wm = {k: v for k, v in wm.items() if k not in drop}
shards = sorted(set(kept_wm.values()))
def trunk_rows(k):
parts = k.split(".")
if len(parts) < 5 or parts[0] != "language_model" or parts[1] != "layers":
return None
try:
l = int(parts[2])
except ValueError:
return None
if l not in keep:
return None
rest = ".".join(parts[3:])
if rest.startswith("ffn.experts.w") and rest.split(".")[-1] in ("weight", "scales", "biases"):
return l
if rest in ("ffn.gate.weight", "ffn.gate.bias", "ffn.gate.bias_vl"):
return l
return None
total = 0
for si, shard in enumerate(shards, 1):
with open(os.path.join(SRC, shard), "rb") as fh:
hlen = struct.unpack("<Q", fh.read(8))[0]
header = json.loads(fh.read(hlen))
data = fh.read()
keys = sorted(k for k in header if k != "__metadata__" and k in kept_wm)
out_hdr, out_data = {}, bytearray()
for k in keys:
h = header[k]; dtype = h["dtype"]; shape = list(h["shape"])
off, end = h["data_offsets"]; raw = data[off:end]
l = trunk_rows(k)
if l is not None:
assert shape[0] == 384, (k, shape)
rowbytes = len(raw) // 384
arr = np.frombuffer(raw, dtype=np.uint8).reshape(384, rowbytes)
raw2 = np.ascontiguousarray(arr[keep[l]]).tobytes()
shape = [K] + shape[1:]
else:
raw2 = raw
o = len(out_data); out_data += raw2
out_hdr[k] = {"dtype": dtype, "shape": shape, "data_offsets": [o, o + len(raw2)]}
hb = json.dumps(out_hdr, separators=(",", ":")).encode()
with open(os.path.join(DST, shard), "wb") as fh:
fh.write(struct.pack("<Q", len(hb))); fh.write(hb); fh.write(out_data)
total += len(out_data)
print("shard %d/%d %.2f GB" % (si, len(shards), len(out_data) / 1e9), flush=True)
idx["metadata"] = {"total_size": total}
idx["weight_map"] = kept_wm
json.dump(cfg, open(os.path.join(DST, "config.json"), "w"), indent=1)
json.dump(idx, open(os.path.join(DST, "model.safetensors.index.json"), "w"))
for f in ("tokenizer.json", "tokenizer_config.json", "LICENSE"):
if os.path.exists(os.path.join(SRC, f)):
with open(os.path.join(SRC, f), "rb") as a, open(os.path.join(DST, f), "wb") as b:
b.write(a.read())
eng = os.path.join(SRC, "engram")
if os.path.isdir(eng) and not os.path.exists(os.path.join(DST, "engram")):
os.symlink(eng, os.path.join(DST, "engram"))
print("built", DST, "K", K, "dropped", len(drop), "bytes", total)