#!/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("