Upload scripts/extract_300.py with huggingface_hub
Browse files- scripts/extract_300.py +73 -0
scripts/extract_300.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extrae los 300 expertos seleccionados por capa del 397B-FP8 -> modelo 300exp-FP8.
|
| 2 |
+
Prunea experts + gate (router 512->300), mantiene shared_expert/atencion/vision, quita MTP.
|
| 3 |
+
"""
|
| 4 |
+
import json, os, re, time
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from safetensors import safe_open
|
| 8 |
+
from safetensors.torch import save_file
|
| 9 |
+
|
| 10 |
+
MODEL="/model"; OUT="/model300"
|
| 11 |
+
os.makedirs(OUT, exist_ok=True)
|
| 12 |
+
sel=np.load("/expert_selection.npy") # [L,300]
|
| 13 |
+
L,N=sel.shape
|
| 14 |
+
print(f"seleccion [{L},{N}]", flush=True)
|
| 15 |
+
idx=json.load(open(f"{MODEL}/model.safetensors.index.json"))
|
| 16 |
+
wmap=idx["weight_map"]
|
| 17 |
+
files=sorted(set(wmap.values()))
|
| 18 |
+
handles={f:safe_open(os.path.join(MODEL,f),framework="pt",device="cpu") for f in files}
|
| 19 |
+
def get(k): return handles[wmap[k]].get_tensor(k)
|
| 20 |
+
|
| 21 |
+
# mapa: experto original -> nuevo indice, por capa
|
| 22 |
+
remap={l:{int(o):n for n,o in enumerate(sel[l])} for l in range(L)}
|
| 23 |
+
|
| 24 |
+
new={}; t0=time.time()
|
| 25 |
+
exp_re=re.compile(r"^model\.language_model\.layers\.(\d+)\.mlp\.experts\.(\d+)\.(.+)$")
|
| 26 |
+
gate_re=re.compile(r"^model\.language_model\.layers\.(\d+)\.mlp\.gate\.weight$")
|
| 27 |
+
for ki,k in enumerate(wmap.keys()):
|
| 28 |
+
if k.startswith("mtp."):
|
| 29 |
+
continue # quitar MTP
|
| 30 |
+
me=exp_re.match(k)
|
| 31 |
+
if me:
|
| 32 |
+
l,e,rest=int(me.group(1)),int(me.group(2)),me.group(3)
|
| 33 |
+
if e in remap[l]:
|
| 34 |
+
ne=remap[l][e]
|
| 35 |
+
new[f"model.language_model.layers.{l}.mlp.experts.{ne}.{rest}"]=get(k)
|
| 36 |
+
continue
|
| 37 |
+
mg=gate_re.match(k)
|
| 38 |
+
if mg:
|
| 39 |
+
l=int(mg.group(1))
|
| 40 |
+
w=get(k) # [512, hidden]
|
| 41 |
+
new[k]=w[sel[l]].contiguous() # [300, hidden]
|
| 42 |
+
continue
|
| 43 |
+
# resto (atencion, shared_expert, norms, embeds, vision, lm_head): copiar
|
| 44 |
+
new[k]=get(k)
|
| 45 |
+
if ki%5000==0: print(f" {ki} tensores, {time.time()-t0:.0f}s", flush=True)
|
| 46 |
+
|
| 47 |
+
print(f"nuevo state: {len(new)} tensores. guardando shards...", flush=True)
|
| 48 |
+
# guardar en shards ~5GB
|
| 49 |
+
items=list(new.items()); shard=[]; sz=0; si=0; sidx={}
|
| 50 |
+
SHARD_MAX=5e9
|
| 51 |
+
def flush_shard(shard,si):
|
| 52 |
+
fn=f"model-{si:05d}.safetensors"
|
| 53 |
+
save_file(dict(shard), os.path.join(OUT,fn), metadata={"format":"pt"})
|
| 54 |
+
for kk,_ in shard: sidx[kk]=fn
|
| 55 |
+
return fn
|
| 56 |
+
for k,v in items:
|
| 57 |
+
shard.append((k,v)); sz+=v.numel()*v.element_size()
|
| 58 |
+
if sz>=SHARD_MAX:
|
| 59 |
+
flush_shard(shard,si); print(f" shard {si} ({sz/1e9:.1f}GB)",flush=True); shard=[]; sz=0; si+=1
|
| 60 |
+
if shard: flush_shard(shard,si)
|
| 61 |
+
# index + config
|
| 62 |
+
json.dump({"metadata":{},"weight_map":sidx}, open(os.path.join(OUT,"model.safetensors.index.json"),"w"))
|
| 63 |
+
cfg=json.load(open(f"{MODEL}/config.json"))
|
| 64 |
+
cfg["text_config"]["num_experts"]=N
|
| 65 |
+
cfg["text_config"]["mtp_num_hidden_layers"]=0
|
| 66 |
+
json.dump(cfg, open(os.path.join(OUT,"config.json"),"w"), indent=2)
|
| 67 |
+
# copiar tokenizer/processor configs
|
| 68 |
+
import shutil
|
| 69 |
+
for f in os.listdir(MODEL):
|
| 70 |
+
if f.endswith(".json") and "index" not in f and f!="config.json" or "token" in f.lower() or "processor" in f.lower() or "merges" in f or "vocab" in f:
|
| 71 |
+
try: shutil.copy(os.path.join(MODEL,f), os.path.join(OUT,f))
|
| 72 |
+
except: pass
|
| 73 |
+
print(f"DONE: 300exp guardado en {OUT}, {si+1} shards, {time.time()-t0:.0f}s", flush=True)
|