ds41-dismantle / scripts /build_final.py
grantabejar's picture
Upload folder using huggingface_hub
c7267b1 verified
Raw History Blame Contribute Delete
5.48 kB
#!/usr/bin/env python3
"""Build the corrected smaller DS4.1 pack.
- expert prune to K (usage scores)
- drop MTP tensors + disable DSpark (num_nextn_predict_layers 0)
- drop vision/aligner tensors AND clear the vision config gate so it loads
- engram slimmed to ONE layer (engram_layer_ids [1]) so the pack is self-contained
usage: build_final.py SRC DST K SCORES_JSON [ENGRAM_SPEC=1] (N, or "14", or "1,14")
"""
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]
SPEC = sys.argv[5] if len(sys.argv) > 5 else "1"
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"] = []
# vision config gate: engine refuses load without vision weights while this is set
cfg.pop("vision_config", None)
cfg["image_token_id"] = 0
tc.pop("image_token_id", None)
# engram slim: SPEC is "N" (first N layers) or an explicit comma list like "14" / "1,14"
all_layers = list(tc["engram_layer_ids"])
all_rows = list(tc["engram_num_embeddings"])
if "," in SPEC or SPEC.isdigit() and int(SPEC) > len(all_layers):
want = [int(x) for x in SPEC.split(",")]
idxs = [i for i, l in enumerate(all_layers) if l in want]
else:
idxs = list(range(min(int(SPEC), len(all_layers))))
layers = [all_layers[i] for i in idxs]
rows = [all_rows[i] for i in idxs]
tc["engram_layer_ids"] = layers
tc["engram_num_embeddings"] = rows
om = cfg.get("omlx_deepseek_v41", {})
om["preserve_mtp"] = False
tabs = om.get("engram_tables", {})
om["engram_tables"] = {k: v for k, v in tabs.items()
if any(k.startswith(f"language_model.layers.{l}.engram") for l in layers)}
os.makedirs(DST, exist_ok=True)
scores = json.load(open(SCORES))["layers"]
keep = {int(l): np.sort(np.argsort(-np.asarray(d["w_norms"]))[:K].astype(np.int64))
for l, d in scores.items()}
idx = json.load(open(os.path.join(SRC, "model.safetensors.index.json")))
wm = idx["weight_map"]
DROP = ("language_model.mtp.", "vision.", "aligner.", "image_")
drop = {k for k in wm if k.startswith(DROP)}
# drop engram wkv/q/k for engram layers we removed
for l in set(list(json.load(open(os.path.join(SRC, "config.json")))["text_config"]["engram_layer_ids"])) - set(layers):
drop |= {k for k in wm if k.startswith(f"language_model.layers.{l}.engram")}
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):
p = k.split(".")
if len(p) < 5 or p[0] != "language_model" or p[1] != "layers":
return None
try:
l = int(p[2])
except ValueError:
return None
if l not in keep:
return None
rest = ".".join(p[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()
out_hdr, out_data = {}, bytearray()
for k in sorted(k for k in header if k != "__metadata__" and k in kept_wm):
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)
rb = len(raw) // 384
arr = np.frombuffer(raw, dtype=np.uint8).reshape(384, rb)
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())
# copy ONLY the engram shard(s) the slim needs (real files, not symlinks)
os.makedirs(os.path.join(DST, "engram"), exist_ok=True)
for l in layers:
spec = tabs.get(f"language_model.layers.{l}.engram.embed")
if not spec:
continue
src = os.path.join(SRC, spec["weight_file"])
dst = os.path.join(DST, spec["weight_file"])
if not os.path.exists(dst):
os.makedirs(os.path.dirname(dst), exist_ok=True)
with open(src, "rb") as a, open(dst, "wb") as b:
while True:
chunk = a.read(1 << 24)
if not chunk:
break
b.write(chunk)
print("copied engram shard", spec["weight_file"], flush=True)
print("built", DST, "K", K, "engram layers", layers, "dropped", len(drop), "bytes", total)