#!/usr/bin/env python3 """ Clean-cut expert slicer: slices Broot-65B-LoopUD-IQ4_XS.basalt (NE=256) down to NE = 128 (1/4 QFN), 64 (1/8 QFN), or 32 (1/16 QFN) using the real routing frequency ranking in qwen4exp-48x256.prof, plus slices ckpt_final_groot256.safetensors and qwen4exp-48x256.prof identically. """ import argparse, json, os, re, shutil, struct, sys, time from pathlib import Path import numpy as np ADAMANT = Path(r"C:\Users\Travis\.gemini\antigravity\scratch\adamant") sys.path.insert(0, str(ADAMANT / "tools")) from model_file import ModelFile, ModelWriter def load_prof256(path: Path): raw = path.read_bytes() ver, nl, ne, total, count = struct.unpack_from("<5I", raw, 0) assert ver == 1 and nl == 48 and ne == 256 and len(raw) == 20 + count * 4, (ver, nl, ne, total, count, len(raw)) pairs = [] for i in range(count): l, e = struct.unpack_from(" [new_ne, 16] m_core = re.search(r"core_steps\.(\d+)\.layer\.mlp\.gate\.lora_b", name) m_coda = re.search(r"coda\.(\d+)\.mlp\.gate\.lora_b", name) layer = None if m_core: layer = 16 + int(m_core.group(1)) elif m_coda: layer = 40 + int(m_coda.group(1)) if layer is not None and len(shape) == 2 and shape[0] == 256: bpe = 2 if dtype in ("BF16", "F16") else 4 arr = np.frombuffer(raw, dtype=np.uint8).reshape(256, shape[1] * bpe) raw = arr[keep_by_layer.get(layer, list(range(new_ne)))].tobytes() shape[0] = new_ne sliced_count += 1 new_hdr[name] = {"dtype": dtype, "shape": shape, "data_offsets": [off, off + len(raw)]} chunks.append(raw) off += len(raw) assert sliced_count == 24, f"Expected 24 sliced router LoRA tensors, got {sliced_count}" hdr_bytes = json.dumps(new_hdr, separators=(",", ":")).encode("utf-8") pad = (-len(hdr_bytes)) % 8 hdr_bytes += b" " * pad with open(dst_st, "wb") as out: out.write(struct.pack(" new_ne) dense_off_in_file, _ = base.section("dense") new_dense_parts = [] new_dense_index = [] d_cur = 0 with open(src_path, "rb") as f: for line in dense_index_lines: if not line.strip(): continue if line.startswith("#"): new_dense_index.append(line) continue parts = line.split() name = parts[0] old_off = int(parts[3]) old_sz = int(parts[4]) f.seek(dense_off_in_file + old_off) raw = f.read(old_sz) m = re.match(r"^blk\.(\d+)\.ffn_gate_inp\.weight$", name) if m: layer = int(m.group(1)) # BF16 [256, 2560] -> [new_ne, 2560] row_bytes = old_sz // 256 arr = np.frombuffer(raw, dtype=np.uint8).reshape(256, row_bytes) raw = arr[keep_by_layer.get(layer, list(range(new_ne)))].tobytes() parts[4] = str(len(raw)) parts[6] = str(len(raw)) parts[8] = str(new_ne) pad = (-d_cur) % 64 if pad: new_dense_parts.append(b"\0" * pad) d_cur += pad parts[3] = str(d_cur) parts[5] = str(d_cur) new_dense_parts.append(raw) d_cur += len(raw) new_dense_index.append(" ".join(parts)) new_dense_bytes = b"".join(new_dense_parts) new_dense_index_bytes = ("\n".join(new_dense_index) + "\n").encode("utf-8") # Update meta meta["name"] = out_path.stem if "gguf_kv" in meta: meta["gguf_kv"]["qwen4exp.expert_count"] = new_ne for tname, tinfo in meta.get("tensors", {}).items(): if re.match(r"^blk\.(\d+)\.ffn_gate_inp\.weight$", tname): tinfo["shape"] = [2560, new_ne] tinfo["bytes"] = 2560 * new_ne * 4 elif re.match(r"^blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$", tname): if len(tinfo.get("shape", [])) == 3 and tinfo["shape"][2] == 256: tinfo["shape"][2] = new_ne tinfo["bytes"] = tinfo["bytes"] * new_ne // 256 # Write output .basalt if out_path.exists(): out_path.unlink() w = ModelWriter(str(out_path)) ok = False try: for name in base.names(): if name == "meta": continue elif name == "experts": w.add_chunks("experts", expert_chunks()) elif name == "experts.layout": w.add_bytes("experts.layout", layout_bytes) elif name == "dense": w.add_bytes("dense", new_dense_bytes) elif name == "dense.index": w.add_bytes("dense.index", new_dense_index_bytes) else: off, sz = base.section(name) w.add_file(name, str(src_path), off, sz) w.add_bytes("meta", json.dumps(meta, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) w.close() ok = True print(f"DONE {out_path.name}: {out_path.stat().st_size/1024**3:.2f} GiB (experts {total_exp_bytes/1024**3:.2f} GiB) in {time.time()-t0:.1f}s", flush=True) finally: if not ok and out_path.exists(): try: w.f.close() except Exception: pass out_path.unlink() def main(): ap = argparse.ArgumentParser() ap.add_argument("--ne", type=int, required=True, choices=[128, 64, 32]) a = ap.parse_args() ne = a.ne prof256 = ADAMANT / "data" / "profiles" / "qwen4exp-48x256.prof" pairs = load_prof256(prof256) keep_by_layer = {l: [] for l in range(48)} for l, e in pairs: if len(keep_by_layer[l]) < ne: keep_by_layer[l].append(e) # Sort kept expert indices ascending within each layer for clean locality, and build remap remap = {} for l in range(48): assert len(keep_by_layer[l]) == ne, f"Layer {l} only had {len(keep_by_layer[l])} experts" keep_by_layer[l].sort() for new_idx, old_idx in enumerate(keep_by_layer[l]): remap[(l, old_idx)] = new_idx # Write sliced .prof preserving exact global hotness rank order new_pairs = [(l, remap[(l, e)]) for (l, e) in pairs if (l, e) in remap] out_prof = ADAMANT / "data" / "profiles" / f"qwen4exp-48x{ne}.prof" write_prof(out_prof, 48, ne, new_pairs) print(f"Wrote {out_prof} ({len(new_pairs)} ranked pairs)", flush=True) # Slice loop adapter src_st = ADAMANT / "models" / "looped-adapter" / "ckpt_final_groot256.safetensors" out_st = ADAMANT / "models" / "looped-adapter" / f"ckpt_final_groot{ne}.safetensors" slice_safetensors(src_st, out_st, keep_by_layer, ne) print(f"Wrote {out_st} ({out_st.stat().st_size/1024**2:.1f} MiB)", flush=True) # Slice .basalt src_b = ADAMANT / "models" / "Broot-65B-LoopUD-IQ4_XS.basalt" out_b = ADAMANT / "models" / f"Broot-NE{ne}-LoopUD-IQ4_XS.basalt" slice_basalt(src_b, out_b, keep_by_layer, ne) if __name__ == "__main__": main()