Soulfate24 commited on
Commit
31b4e70
·
verified ·
1 Parent(s): 5466dec

Delete 90_attribution-probe.py

Browse files
Files changed (1) hide show
  1. 90_attribution-probe.py +0 -344
90_attribution-probe.py DELETED
@@ -1,344 +0,0 @@
1
- #!/usr/bin/env python3
2
- """90_attribution-probe.py — Marginal KO probes on the ASHQ1 Mini operating point.
3
-
4
- v2: surfaces quantize exit code + output tails; retries a failed quantize with
5
- inherited console handles (the invocation channel of every past success);
6
- pre-flight disk guard; fail-fast after consecutive failures; size-based sanity
7
- validation; resume-safe CSV (retriable rows lack kld)."""
8
- import argparse,csv,os,re,shutil,subprocess,sys,time
9
- sys.path.insert(0,os.path.dirname(os.path.abspath(__file__)))
10
-
11
- SCRIPT_DIR=os.path.dirname(os.path.abspath(__file__))
12
- def _pick_first(cands,fallback):
13
- return next((os.path.join(SCRIPT_DIR,c) for c in cands if os.path.isfile(os.path.join(SCRIPT_DIR,c))),os.path.join(SCRIPT_DIR,fallback))
14
-
15
- SRC=_pick_first(["model-no-mtp-BF16.gguf","model-BF16-no-mtp.gguf","model-BF16.gguf","model-no-mtp-F16.gguf","model-F16.gguf"],"model-no-mtp-BF16.gguf")
16
- IMAT=_pick_first(["imatrix.gguf","imatrix.dat","AutoRound-imatrix.gguf"],"imatrix.gguf")
17
- CORPUS=os.path.join(SCRIPT_DIR,"wiki.test.raw")
18
- BASE_REF=os.path.join(SCRIPT_DIR,"kld-bf16.dat")
19
- BASE_EMBD="IQ4_XS"
20
- BASE_TYPE="iq4_xs"
21
- MIN_DISK_MIB=7*1024
22
-
23
- HYB="([0-2]|[4-6]|(?:8|9|10)|(?:12|13|14)|(?:16|17|18)|(?:20|21|22)|(?:24|25|26)|(?:28|29|30))"
24
- ATT="(3|7|11|15|19|23|27|31)"
25
- BIG="([6-8]|(?:10|11)|(?:13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))"
26
- SMALL="([0-5]|9|12)"
27
-
28
- BASE_RULES=[
29
- f'(blk|BLK)\\.{HYB}\\.ssm_alpha\\.weight=Q8_0',
30
- f'(blk|BLK)\\.{HYB}\\.ssm_beta\\.weight=Q8_0',
31
- f'(blk|BLK)\\.{HYB}\\.attn_gate\\.weight=Q6_K',
32
- r'(blk|BLK)\.(3)\.attn_k\.weight=IQ4_NL',
33
- f'(blk|BLK)\\.{BIG}\\.ffn_up\\.weight=IQ4_XS',
34
- f'(blk|BLK)\\.{HYB}\\.attn_qkv\\.weight=IQ4_XS',
35
- f'(blk|BLK)\\.{ATT}\\.attn_q\\.weight=IQ4_XS',
36
- f'(blk|BLK)\\.{HYB}\\.ssm_out\\.weight=IQ4_XS',
37
- f'(blk|BLK)\\.{ATT}\\.attn_v\\.weight=IQ4_XS',
38
- f'(blk|BLK)\\.(7|11|15|19|23|27|31)\\.attn_k\\.weight=IQ4_XS',
39
- f'(blk|BLK)\\.{BIG}\\.ffn_gate\\.weight=IQ4_XS',
40
- f'(blk|BLK)\\.{ATT}\\.attn_output\\.weight=IQ4_XS',
41
- f'(blk|BLK)\\.{SMALL}\\.ffn_gate\\.weight=IQ3_S',
42
- f'(blk|BLK)\\.{SMALL}\\.ffn_up\\.weight=IQ3_S',
43
- r'(blk|BLK)\.\d+\.ffn_down\.weight=IQ4_XS',
44
- ]
45
-
46
- # Multi-model portability: probe-rules.txt replaces the hardcoded grid.
47
- # Line formats: 'pattern=TIER', 'embd=X', 'output=X', 'base=X', '#comment'
48
- _RULES_PATH=os.path.join(SCRIPT_DIR,"probe-rules.txt")
49
- OUTPUT_TYPE=None
50
- BASE_TYPE_OVERRIDE=None
51
- RULES_FAMILY=None
52
- if not os.path.isfile(_RULES_PATH):
53
- # The default grid below is qwen35-calibrated: on any other family its
54
- # embd floor and layer bands silently rebuild the operating point and
55
- # every marginal runs confounded. The load banner is the token — its
56
- # absence means the fallback is active and the arms are not comparable.
57
- print("[rules] probe-rules.txt ABSENT — qwen35 default grid active: marginals INVALID on other families (write embd=/base=/gate lines for this family)")
58
- if os.path.isfile(_RULES_PATH):
59
- _loaded=[]
60
- for ln in open(_RULES_PATH,encoding="utf-8"):
61
- s=ln.strip()
62
- if not s or s.startswith("#"):continue
63
- key=s.split("=",1)[0].strip().lower()
64
- val=s.split("=",1)[1].strip() if "=" in s else ""
65
- if key=="embd":BASE_EMBD=val;continue
66
- if key=="output":OUTPUT_TYPE=val;continue
67
- if key=="family":RULES_FAMILY=val;continue
68
- if key=="base":BASE_TYPE_OVERRIDE=val;continue
69
- while s.startswith("--tensor-type"):s=s[len("--tensor-type"):].lstrip()
70
- s=s.strip('"').strip("'").strip()
71
- if s:_loaded.append(s)
72
- if _loaded:
73
- BASE_RULES=_loaded
74
- print(f"[rules] {len(BASE_RULES)} rule(s) loaded from probe-rules.txt")
75
-
76
- def _alt(nums):return "|".join(str(n) for n in nums)
77
-
78
- HYB_LAYERS=[0,1,2,4,5,6,8,9,10,12,13,14,16,17,18,20,21,22,24,25,26,28,29,30]
79
-
80
- def gdn_band(lo,hi,tier):
81
- ns=_alt([n for n in HYB_LAYERS if lo<=n<hi])
82
- return[f'(blk|BLK)\\.({ns})\\.attn_qkv\\.weight={tier}',f'(blk|BLK)\\.({ns})\\.ssm_out\\.weight={tier}']
83
-
84
- PROBES={
85
- "baseline-mini":{"rules":[],"embd":None,"desc":"Mini grid verbatim — reference zero"},
86
- "embd-q6k":{"embd":"q6_K","desc":"H1: token embedding carries global KLD"},
87
- "embd-q8k":{"embd":"q8_0","desc":"H1 ceiling"},
88
- "gdn-core-q6k":{"rules":[r'(blk|BLK)\.\d+\.attn_qkv\.weight=q6_K',r'(blk|BLK)\.\d+\.ssm_out\.weight=q6_K'],"desc":"H2: GDN fused projects dominate RMS drift"},
89
- "gdn-core-q8k":{"rules":[r'(blk|BLK)\.\d+\.attn_qkv\.weight=q8_0',r'(blk|BLK)\.\d+\.ssm_out\.weight=q8_0'],"desc":"H2 ceiling"},
90
- "ffn-down-q6k":{"rules":[r'(blk|BLK)\.\d+\.ffn_down\.weight=q6_K'],"desc":"H3: diffuse volumetric culprit"},
91
- "ffn-down-iq3s":{"rules":[r'(blk|BLK)\.\d+\.ffn_down\.weight=iq3_s'],"desc":"H3 inverse: savings headroom"},
92
- "gateup-univ-q6k":{"rules":[r'(blk|BLK)\.\d+\.ffn_gate\.weight=q6_K',r'(blk|BLK)\.\d+\.ffn_up\.weight=q6_K'],"desc":"gate/up raised everywhere"},
93
- "gateup-univ-iq3s":{"rules":[r'(blk|BLK)\.\d+\.ffn_gate\.weight=iq3_s',r'(blk|BLK)\.\d+\.ffn_up\.weight=iq3_s'],"desc":"spread IQ3_S bands"},
94
- "attn-full-q6k":{"rules":[f'(blk|BLK)\\.{ATT}\\.attn_q\\.weight=q6_K',f'(blk|BLK)\\.{ATT}\\.attn_k\\.weight=q6_K',f'(blk|BLK)\\.{ATT}\\.attn_v\\.weight=q6_K',f'(blk|BLK)\\.{ATT}\\.attn_output\\.weight=q6_K'],"desc":"full-attention blocks = long-range memory"},
95
- "gdn-p0-q6k":{"rules":gdn_band(0,8,"q6_K"),"desc":"GDN depth 0-7"},
96
- "gdn-p1-q6k":{"rules":gdn_band(8,16,"q6_K"),"desc":"GDN depth 8-15"},
97
- "gdn-p2-q6k":{"rules":gdn_band(16,24,"q6_K"),"desc":"GDN depth 16-23"},
98
- "gdn-p3-q6k":{"rules":gdn_band(24,32,"q6_K"),"desc":"GDN depth 24-31"},
99
- }
100
-
101
- CSV_FIELDS=["tag","status","mib","ppl","kld","rms","top_p","d_kld"]
102
-
103
- def binaries():
104
- for mod_name in("ASHQ1","ASHQ1-Remix","ASHQ1_Remix"):
105
- try:
106
- mod=__import__(mod_name)
107
- if hasattr(mod,"_find_binary"):
108
- return mod._find_binary("llama-quantize"),mod._find_binary("llama-perplexity")
109
- except ImportError:pass
110
- from shutil import which
111
- exe_ext=".exe" if sys.platform=="win32" else ""
112
- q=which("llama-quantize"+exe_ext) or os.path.join(SCRIPT_DIR,"llama-cpp","llama-quantize"+exe_ext)
113
- p=which("llama-perplexity"+exe_ext) or os.path.join(SCRIPT_DIR,"llama-cpp","llama-perplexity"+exe_ext)
114
- return (q if os.path.isfile(q) else ""), (p if os.path.isfile(p) else "")
115
-
116
- def build_cmd(qexe,pr,dst):
117
- embd=pr.get("embd") or BASE_EMBD
118
- cmd=[qexe,"--imatrix",IMAT,"--token-embedding-type",embd]
119
- outt=pr.get("output") or OUTPUT_TYPE
120
- if outt:cmd+=["--output-tensor-type",outt]
121
- base=BASE_TYPE_OVERRIDE or BASE_TYPE
122
- for r in pr.get("rules",[]):cmd+=["--tensor-type",r]
123
- for r in BASE_RULES:cmd+=["--tensor-type",r]
124
- return cmd+[SRC,dst,base]
125
-
126
- def _tails(r):
127
- out=(r.stdout or "").strip().splitlines()
128
- err=(r.stderr or "").strip().splitlines()
129
- for label,lines in(("STDOUT",out[-6:] if len(out)>6 else out),("STDERR",err[-6:] if len(err)>6 else err)):
130
- for ln in lines:print(f" |{label}| {ln.strip()}")
131
-
132
- def _disk_guard():
133
- try:
134
- free_mib=shutil.disk_usage(SCRIPT_DIR).free//(1024*1024)
135
- except OSError:return
136
- if free_mib<MIN_DISK_MIB:
137
- print(f"\n ! Only {free_mib//1024} GiB free on the output drive — aborting before wasting time.")
138
- print(" Free >= 7 GiB and rerun; completed rows are preserved in the CSV.")
139
- sys.exit(2)
140
-
141
- def quantize(qexe,pr,dst):
142
- _disk_guard()
143
- cmd=build_cmd(qexe,pr,dst)
144
- t0=time.perf_counter()
145
- r=subprocess.run(cmd,capture_output=True,text=True,encoding="utf-8",errors="replace")
146
- blob=(r.stdout or "")+"\n"+(r.stderr or "")
147
- m=re.search(r"quant\s*size\s*[=:]\s*([\d.]+)\s*MiB",blob,re.I)
148
- parsed=float(m.group(1)) if m else None
149
- fsz=os.path.getsize(dst)/(1024*1024) if os.path.isfile(dst) else 0.0
150
- if r.returncode==0 and fsz>200:
151
- shown=parsed if parsed else fsz
152
- print(f" quantize: {shown:.0f} MiB rc=0 ({time.perf_counter()-t0:.0f}s)")
153
- return shown
154
- print(f" x quantize FAILED after {time.perf_counter()-t0:.0f}s (rc={r.returncode}, parsed={parsed}, disk={fsz:.0f} MiB, file={'yes' if os.path.isfile(dst) else 'absent'})")
155
- if os.path.isfile(dst):
156
- try:print(f" leftover: {os.path.getsize(dst)//(1024*1024)} MiB on disk")
157
- except OSError:pass
158
- _tails(r)
159
- # Retry with inherited console handles — the channel every past success used.
160
- if os.path.isfile(dst):
161
- try:os.remove(dst)
162
- except OSError:pass
163
- print(" -> retry with inherited console (live output below):")
164
- retry=subprocess.run(cmd)
165
- if retry.returncode==0 and os.path.isfile(dst) and os.path.getsize(dst)>200*1024*1024:
166
- print(f" retry OK ({time.perf_counter()-t0:.0f}s total)")
167
- m2=re.search(r"quant size=\s*([\d.]+)\s*MiB",str(retry.stdout or ""))
168
- return os.path.getsize(dst)/(1024*1024)
169
- print(" x retry FAILED — failing fast; read the live output above for the true cause.")
170
- return None
171
-
172
- def evaluate(pexe,dst,threads):
173
- cmd=[pexe,"-m",dst,"-f",CORPUS,"-c","512","-b","512","-ub","512","-t",str(threads),"--no-warmup","-fa","auto","--kl-divergence","--kl-divergence-base",BASE_REF]
174
- try:
175
- r=subprocess.run(cmd,capture_output=True,text=True,encoding="utf-8",errors="replace",timeout=7200)
176
- except subprocess.TimeoutExpired:
177
- # One hung probe must not kill the sweep: the row stays retriable
178
- # (no kld) and the remaining probes keep running
179
- print(" x evaluate timed out after 120 min — row left retriable, sweep continues")
180
- return{"ppl":"","kld":"","rms":"","top_p":""}
181
- blob=(r.stdout or "")+"\n"+(r.stderr or "")
182
- def grab(rx):
183
- m=re.search(rx,blob,re.I)
184
- return m.group(1) if m else ""
185
- ppl=grab(r"Mean\s+PPL\(Q\)[^\n]*?:\s*([\d.]+)") or grab(r"Final estimate:\s*PPL\s*=\s*([\d.]+)")
186
- return{"ppl":ppl,"kld":grab(r"Mean\s+KLD[^\n]*?:\s*([\d.]+)"),"rms":grab(r"RMS\s+\S{0,3}p\s*:\s*([\d.]+)"),"top_p":grab(r"Same\s+top\s+p\s*:\s*([\d.]+)")}
187
-
188
- def append_csv(path,row):
189
- exists=os.path.isfile(path)
190
- with open(path,"a",newline="",encoding="utf-8") as f:
191
- w=csv.DictWriter(f,fieldnames=CSV_FIELDS)
192
- if not exists:w.writeheader()
193
- w.writerow(row)
194
-
195
- # Canonical ledger, transcribed verbatim from consoles of runs A-C
196
- KNOWN_RESULTS=[
197
- {"tag":"baseline-mini","status":"ok","mib":"2169","ppl":"9.432678","kld":"0.041735","rms":"5.559","top_p":"89.170","d_kld":""},
198
- {"tag":"embd-q8k","status":"ok","mib":"2491","ppl":"9.369886","kld":"0.033035","rms":"4.898","top_p":"91.234","d_kld":""},
199
- {"tag":"gdn-core-q6k","status":"ok","mib":"2377","ppl":"9.374032","kld":"0.035988","rms":"5.175","top_p":"89.746","d_kld":""},
200
- {"tag":"ffn-down-iq3s","status":"ok","mib":"2096","ppl":"9.587181","kld":"0.057610","rms":"6.580","top_p":"87.651","d_kld":""},
201
- {"tag":"attn-full-q6k","status":"ok","mib":"2250","ppl":"9.385684","kld":"0.037998","rms":"5.316","top_p":"89.548","d_kld":""},
202
- {"tag":"gdn-p0-q6k","status":"ok","mib":"2221","ppl":"9.407983","kld":"0.039227","rms":"5.367","top_p":"89.400","d_kld":""},
203
- {"tag":"gdn-p2-q6k","status":"ok","mib":"2221","ppl":"9.415274","kld":"0.040624","rms":"5.495","top_p":"89.271","d_kld":""},
204
- ]
205
-
206
- def seed_known(path):
207
- missing=[r for r in KNOWN_RESULTS if r["tag"] not in load_done(path)[0]]
208
- for r in missing:append_csv(path,r)
209
- if missing:print(f"[seed] {len(missing)} measurement(s) restored")
210
-
211
- def load_done(path):
212
- # Mixed-schema CSVs silently shift DictReader columns: archive anything
213
- # not matching the current header instead of misreading measurements
214
- if os.path.isfile(path):
215
- with open(path,"r",encoding="utf-8-sig") as f:first=f.readline().strip()
216
- if first!=",".join(CSV_FIELDS):
217
- bak=path+".bak-legacy"
218
- os.replace(path,bak)
219
- print(f"[csv] Legacy header detected — archived to {bak}")
220
- rows=[]
221
- if not os.path.isfile(path):return{},[]
222
- with open(path,"r",newline="",encoding="utf-8") as f:
223
- for row in csv.DictReader(f):
224
- rows.append(row)
225
- done={r["tag"]:r for r in rows if r.get("kld")}
226
- return done,rows
227
-
228
- def main():
229
- ap=argparse.ArgumentParser(description="Marginal KO probes at the Mini operating point")
230
- ap.add_argument("--only",default=None,help="comma list of probe tags")
231
- ap.add_argument("--keep",action="store_true",help="retain probe GGUF files")
232
- ap.add_argument("--csv",default=os.path.join(SCRIPT_DIR,"attribution-results.csv"))
233
- ap.add_argument("--seed-known",action="store_true",help="restore measured ledger (runs A-C) then show the consolidated table")
234
- ap.add_argument("--rule",action="append",default=[],help="composite rule injected before the grid (repeatable)")
235
- ap.add_argument("--embd-type",default=None,help="composite token embedding type (e.g. q6_K)")
236
- ap.add_argument("--name",default="remix",help="composite probe name (stored as mix-<name>)")
237
- ap.add_argument("--list",action="store_true",help="print available probe tags and exit")
238
- args=ap.parse_args()
239
- if args.list:
240
- for tag,pr in PROBES.items():
241
- print(f" {tag:<20} {len(pr.get('rules',[]))} override(s) · {pr['desc']}")
242
- return 0
243
- qexe,pexe=binaries()
244
- if not qexe or not pexe:
245
- print("Error: llama-quantize / llama-perplexity not found");return 1
246
- print(f"quantize : {qexe}")
247
- print(f"perplexity : {pexe}")
248
- if not(os.path.isfile(SRC) and os.path.isfile(IMAT) and os.path.isfile(BASE_REF)):
249
- print("Error: source model, imatrix or kld-bf16.dat missing");return 1
250
- # Staleness guard (mirror of the absence guard): rules written for one
251
- # family silently rebuild another family's operating point — the tag
252
- # makes the mismatch loud instead of confounded.
253
- if RULES_FAMILY:
254
- try:
255
- from ASHQ1 import _arch_of
256
- src_arch=(_arch_of(SRC) or "").lower()
257
- if src_arch and RULES_FAMILY.lower() not in(src_arch,src_arch.replace("_","")):
258
- print(f"Error: probe-rules.txt declares family '{RULES_FAMILY}' but the source is '{src_arch}'.")
259
- print(" Rewrite the rules for this family (family=/embd=/base=) before probing — arms would run confounded.")
260
- return 1
261
- except ImportError:pass
262
- order=list(PROBES)
263
- if args.only:
264
- want=[s.strip() for s in args.only.split(",")]
265
- bad=[w for w in want if w not in PROBES]
266
- if bad:
267
- print(f"Unknown probes: {bad}");print(f"Known: {order}");return 1
268
- order=[w for w in PROBES if w in want]
269
- if args.rule or args.embd_type:
270
- tag=f"mix-{args.name}"
271
- PROBES[tag]={"rules":list(args.rule),"embd":args.embd_type,"desc":f"composite · {len(args.rule)} rule(s)"}
272
- order=[tag]
273
- if args.seed_known:
274
- seed_known(args.csv)
275
- order=[]
276
- done,_=load_done(args.csv)
277
- base_row=done.get("baseline-mini")
278
- TAG_W=max([18]+[len(t) for t in order])
279
- # One thread per physical core (8 on a 5700): SMT siblings contend on the
280
- # shared vector units through the CPU-side perplexity passes
281
- threads=max(1,(os.cpu_count() or 4)//2)
282
- consec_fail=0
283
- for tag in order:
284
- pr=PROBES[tag]
285
- dst=os.path.join(SCRIPT_DIR,f"_attr-probe-{tag}.gguf")
286
- if tag in done:
287
- if os.path.exists(dst) and not args.keep:
288
- try:os.remove(dst)
289
- except OSError:pass
290
- print(f"[skip] {tag}: result already in CSV")
291
- continue
292
- _disk_guard()
293
- if os.path.isfile(dst):
294
- try:print(f" removing stale leftover: {os.path.getsize(dst)//(1024*1024)} MiB");os.remove(dst)
295
- except OSError:pass
296
- print(f"\n{'='*TAG_W}")
297
- print(f" [{tag}] {pr['desc']} ({[t for t in order].index(tag)+1}/{len(order)})")
298
- print("="*TAG_W)
299
- row={"tag":tag,"status":"fail","mib":"","ppl":"","kld":"","rms":"","top_p":"","d_kld":""}
300
- size=quantize(qexe,pr,dst)
301
- if size:
302
- res=evaluate(pexe,dst,threads)
303
- row.update(res)
304
- row["mib"]=round(size)
305
- ref=(base_row or {}).get("kld","")
306
- if res["kld"] and ref:
307
- d=float(res["kld"])-float(ref)
308
- row["d_kld"]=f"{d:+.5f}"
309
- elif res["kld"]:
310
- row["d_kld"]="(needs baseline)"
311
- print(f" KLD={res['kld']} · ΔKLD={row['d_kld']} · RMS={res['rms']}% · top-p={res['top_p']}% · PPL={res['ppl']}")
312
- row["status"]="ok"
313
- consec_fail=0
314
- if tag=="baseline-mini":
315
- base_row={"tag":tag,"kld":res["kld"]}
316
- else:
317
- consec_fail+=1
318
- append_csv(args.csv,row)
319
- if not args.keep and os.path.exists(dst):
320
- try:os.remove(dst)
321
- except OSError:pass
322
- if consec_fail>=2:
323
- print("\nAbort: two consecutive quantize failures — fix the underlying cause, then rerun.")
324
- print("Completed rows stay in the CSV; failing tags retry automatically.")
325
- return 2
326
- pool={}
327
- for r in load_done(args.csv)[1]:
328
- if r.get("status")=="ok" and r.get("kld"):pool[r["tag"]]={"tag":r["tag"],"mib":float(r.get("mib") or 0),"kld_f":float(r["kld"]),"rms":r.get("rms",""),"top_p":r.get("top_p","")}
329
- valid=list(pool.values())
330
- ref=pool.get("baseline-mini")
331
- def dk(r):return r["kld_f"]-(ref["kld_f"] if ref else 0.0)
332
- print("\n"+"="*100)
333
- print(f" ATTRIBUTION SUMMARY — noise floor reference {'%.4f'%ref['kld_f'] if ref else 'n/a'} · |ΔKLD| < 0.001 = noise, > 0.002 = signal")
334
- print("="*100)
335
- for r in sorted(valid,key=lambda x:dk(x) if x["tag"]!="baseline-mini" else -9e9,reverse=True):
336
- d=dk(r)
337
- verdict="REF ZERO " if r["tag"]=="baseline-mini" else("<<< SIGNAL" if abs(d)>=0.002 else("noise " if abs(d)<0.001 else "borderline"))
338
- print(f" {r['tag']:<{TAG_W}} {r['mib']:>7.0f} MiB KLD={r['kld_f']:.4f} d={d:+.4f} RMS={r.get('rms','')}% top-p={r.get('top_p','')}% {verdict}")
339
- print(f"\n CSV: {args.csv}")
340
- print(" Next step: fold winners into class weights (_push_upgrade/_push_downgrade) and TIER_FLOORS.")
341
- return 0
342
-
343
- if __name__=="__main__":
344
- sys.exit(main())