Soulfate24 commited on
Commit
5466dec
·
verified ·
1 Parent(s): 2417ee3

Delete 90_arch-inspect.py

Browse files
Files changed (1) hide show
  1. 90_arch-inspect.py +0 -337
90_arch-inspect.py DELETED
@@ -1,337 +0,0 @@
1
- #!/usr/bin/env python3
2
- """90_arch-inspect.py — Architecture dissection for GGUF models and safetensors folders.
3
-
4
- Five lenses:
5
- 1. Tensor inventory — suffix → MiB, dtype, shapes
6
- 2. Per-layer signatures — deviation layers (MTP heads, unique blocks, hybrids)
7
- 3. Novelty scan — tensor names outside llama.cpp's known taxonomy
8
- 4. Binary support — arch + every tensor name cross-checked against llama-arch.cpp
9
- 5. Imatrix coverage — tensors without activation statistics (floor-driven in ASHQ1)
10
-
11
- Usage:
12
- python 90_arch-inspect.py model-no-mtp-BF16.gguf --imatrix imatrix.gguf
13
- python 90_arch-inspect.py XHToken_Spark-X2.5-4B
14
- """
15
- import argparse,collections,json,os,re,sys
16
- import numpy as np
17
-
18
- SCRIPT_DIR=os.path.dirname(os.path.abspath(__file__))
19
- sys.path.insert(0,SCRIPT_DIR)
20
- sys.path.insert(0,os.path.join(SCRIPT_DIR,"llama-cpp","gguf-py"))
21
- import gguf
22
-
23
- # Canonical GGUF tensor names from llama-arch.cpp (LLM_TENSOR_*). A suffix outside
24
- # this set is a candidate novel block — confirm with lens 4 before trusting inference.
25
- KNOWN_SUFFIX={
26
- "token_embd","token_embd_norm","output","output_norm","output_b",
27
- "attn_norm","attn_norm_2","attn_post_norm","attn_q_norm","attn_k_norm","attn_v_norm",
28
- "attn_q","attn_k","attn_v","attn_qkv","attn_output","attn_gate","attn_sinks",
29
- "attn_q_a","attn_q_b","attn_kv_a_mqa","attn_kv_b","attn_q_a_norm","attn_k_b","attn_v_b",
30
- "rope_freqs","rope_factors","shortconv","conv","in_proj","in_proj_a","in_proj_b",
31
- # Converter-emitted compound names (lfm2 shortconv stack) — the bare "shortconv"
32
- # entry alone leaves these flagged as novel
33
- "shortconv.conv","shortconv.in_proj","shortconv.out_proj",
34
- "in_proj_qkv","in_proj_z","out_proj",
35
- "ssm_in","ssm_conv1d","ssm_dt","ssm_a","ssm_b","ssm_c","ssm_d","ssm_norm","ssm_out",
36
- "ssm_alpha","ssm_beta","ssm_beta_alpha","ssm_ba","ssm_dt_b","ssm_dt_norm",
37
- "ssm_b_norm","ssm_c_norm","ssm_mix","ssm_dt_a","ssm_dt_d",
38
- "ffn_gate","ffn_up","ffn_down","ffn_norm","ffn_post_norm",
39
- "ffn_gate_inp","ffn_gate_exps","ffn_up_exps","ffn_down_exps","exp_probs_b",
40
- "ffn_gate_shexp","ffn_up_shexp","ffn_down_shexp","ffn_gate_inp_shexp","router",
41
- "layer_output_scale","post_attention_norm","post_ffw_norm","per_layer_token_embd",
42
- "per_layer_model_proj","per_layer_proj_norm","per_layer_attn_q","per_layer_attn_k",
43
- "per_layer_attn_v","per_layer_attn_out","per_layer_attn_norm","per_layer_post_norm",
44
- "altup_corr_coef","altup_project","altup_correct","altup_unembd_proj","laurel_proj",
45
- "nextn_eh_proj","eh_proj","enorm","hnorm","mtp_fc","fc","embed_proj",
46
- "pre_fc_norm","post_fc_norm","head","norm","scale","b","a","d","dt","bias","weight",
47
- "mm_0","mm_1","mm_2","mm_input_norm","mm_soft_emb_norm","mm_proj","mm_patch_merger",
48
- "patch_embd","patch_embedding","position_embd","v_enc_embd",
49
- "pre_ln","post_ln","ln1","ln2","ln_q","ln_post",
50
- "v_post_attn_norm","v_pre_ffn_norm","v_post_ffn_norm","v_attn_norm","v_ffn_norm",
51
- "v_proj","v_token_embd","v_output_norm","v_output",
52
- }
53
-
54
- LAYER_RX=re.compile(r"^(?:[va]\.)?blk\.(\d+)\.(.+?)(?:\.(?:weight|bias))?$")
55
-
56
- _META_KEYS=("block_count","embedding_length","context_length","num_loops",
57
- "attention.head_count","attention.head_count_kv","attention.key_length","attention.value_length",
58
- "attention.sliding_window","rope.theta","rope.theta_swa","rope.dimension_count",
59
- "expert_count","expert_used_count","expert_feed_forward_length")
60
-
61
- # HF transformers naming → canonical GGUF naming (mirror of convert_hf_to_gguf.py),
62
- # so safetensors folders and converted GGUFs produce the same analysis
63
- # Replacements produce the BARE GGUF path: _normalize_hf_name re-attaches the
64
- # .weight/.bias suffix itself — embedding ".weight" here too would double it
65
- HF_NAME_MAP=(
66
- (re.compile(r"^model\.(?:language_model\.)?embed_tokens$"),"token_embd"),
67
- (re.compile(r"^model\.(?:language_model\.)?embedding$"),"token_embd"),
68
- (re.compile(r"^model\.(?:language_model\.)?norm$"),"output_norm"),
69
- (re.compile(r"^lm_head$"),"output"),
70
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.input_layernorm$"),r"blk.\1.attn_norm"),
71
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.post_attention_layernorm$"),r"blk.\1.ffn_norm"),
72
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.q_k_v_proj$"),r"blk.\1.attn_qkv"),
73
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.out_proj$"),r"blk.\1.attn_output"),
74
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.o_proj$"),r"blk.\1.attn_output"),
75
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.g_proj$"),r"blk.\1.attn_gate"),
76
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.q_proj$"),r"blk.\1.attn_q"),
77
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.k_proj$"),r"blk.\1.attn_k"),
78
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.v_proj$"),r"blk.\1.attn_v"),
79
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.q_norm$"),r"blk.\1.attn_q_norm"),
80
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.self_attn\.k_norm$"),r"blk.\1.attn_k_norm"),
81
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.in_proj_qkv$"),r"blk.\1.attn_qkv"),
82
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.in_proj_z$"),r"blk.\1.attn_gate"),
83
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.in_proj_a$"),r"blk.\1.ssm_alpha"),
84
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.in_proj_b$"),r"blk.\1.ssm_beta"),
85
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.out_proj$"),r"blk.\1.ssm_out"),
86
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.conv1d$"),r"blk.\1.ssm_conv1d"),
87
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.norm$"),r"blk.\1.ssm_norm"),
88
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.A_log$"),r"blk.\1.ssm_a"),
89
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.linear_attn\.dt_bias$"),r"blk.\1.ssm_dt"),
90
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.mlp\.gate_proj$"),r"blk.\1.ffn_gate"),
91
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.mlp\.up_proj$"),r"blk.\1.ffn_up"),
92
- (re.compile(r"^model\.(?:language_model\.)?layers\.(\d+)\.mlp\.down_proj$"),r"blk.\1.ffn_down"),
93
- # LFM2 naming: SwiGLU w1/w3/w2, shortconv operator stack, per-layer norms.
94
- # The converter emits blk.N.shortconv.* — mirror it exactly so lens 4 matches
95
- # the declared llama-arch.cpp templates.
96
- (re.compile(r"^model\.embed_tokens$"),"token_embd"),
97
- (re.compile(r"^model\.embedding_norm$"),"output_norm"),
98
- (re.compile(r"^model\.layers\.(\d+)\.ffn_norm$"),r"blk.\1.ffn_norm"),
99
- (re.compile(r"^model\.layers\.(\d+)\.operator_norm$"),r"blk.\1.attn_norm"),
100
- (re.compile(r"^model\.layers\.(\d+)\.self_attn\.q_layernorm$"),r"blk.\1.attn_q_norm"),
101
- (re.compile(r"^model\.layers\.(\d+)\.self_attn\.k_layernorm$"),r"blk.\1.attn_k_norm"),
102
- (re.compile(r"^model\.layers\.(\d+)\.conv\.in_proj$"),r"blk.\1.shortconv.in_proj"),
103
- (re.compile(r"^model\.layers\.(\d+)\.conv\.out_proj$"),r"blk.\1.shortconv.out_proj"),
104
- (re.compile(r"^model\.layers\.(\d+)\.conv\.conv$"),r"blk.\1.shortconv.conv"),
105
- (re.compile(r"^model\.layers\.(\d+)\.feed_forward\.w1$"),r"blk.\1.ffn_gate"),
106
- (re.compile(r"^model\.layers\.(\d+)\.feed_forward\.w2$"),r"blk.\1.ffn_down"),
107
- (re.compile(r"^model\.layers\.(\d+)\.feed_forward\.w3$"),r"blk.\1.ffn_up"),
108
- )
109
-
110
- def _normalize_hf_name(name):
111
- # Safetensors keys carry the .weight/.bias suffix the regexes do not cover:
112
- # split it off first, match the bare HF path, then re-attach it
113
- suffix=""
114
- for suf in(".weight",".bias"):
115
- if name.endswith(suf):
116
- suffix=name[-len(suf):]
117
- name=name[:-len(suf)]
118
- break
119
- for rx,rep in HF_NAME_MAP:
120
- new=rx.sub(rep,name)
121
- if new!=name:return new+suffix
122
- return name+suffix
123
-
124
- def suffix_of(name):
125
- m=LAYER_RX.match(name)
126
- if m:return m.group(2)
127
- s=name
128
- for suf in(".weight",".bias"):
129
- if s.endswith(suf):s=s[:-len(suf)];break
130
- return s
131
-
132
- def _field_value(v):
133
- if hasattr(v,"contents"):
134
- try:
135
- c=v.contents()
136
- if c is not None:
137
- return c.tolist() if hasattr(c,"tolist") else c
138
- except Exception:pass
139
- try:part=v.parts[v.data[0]]
140
- except Exception:return "?"
141
- arr=np.asarray(part)
142
- if arr.dtype==np.uint8:
143
- return bytes(arr).decode("utf-8","replace")
144
- if arr.size==1:
145
- item=arr.flatten()[0]
146
- return item.decode("utf-8","replace") if isinstance(item,bytes) else item.item()
147
- return arr.tolist()
148
-
149
- def _type_size(t):
150
- try:return gguf.ggml_type_size(t.tensor_type)
151
- except Exception:return 2
152
-
153
- def _dtype_str(t):
154
- # IntEnum str() yields the raw number since Python 3.11 — prefer .name
155
- try:return t.tensor_type.name
156
- except Exception:return "?"
157
-
158
- def read_gguf(path):
159
- r=gguf.GGUFReader(path)
160
- meta={k:_field_value(v) for k,v in r.fields.items() if not k.startswith("GGUF.")}
161
- tensors={}
162
- for t in r.tensors:
163
- # n_elements is a property (int) in current gguf-py, a method in older ones
164
- n_el=t.n_elements if isinstance(t.n_elements,int) else t.n_elements()
165
- tensors[t.name]={"shape":[int(d) for d in t.shape],"dtype":_dtype_str(t),
166
- "mib":n_el*_type_size(t)/1024/1024}
167
- return meta,tensors
168
-
169
- def load_safetensors(path):
170
- cfg_p=os.path.join(path,"config.json")
171
- _cfg={}
172
- if os.path.isfile(cfg_p):
173
- with open(cfg_p,encoding="utf-8") as _f:_cfg=json.load(_f)
174
- meta={"safetensors.config":_cfg}
175
- tensors={}
176
- dt_bytes={"F32":4,"float32":4,"I32":4,"int32":4,"I8":1,"int8":1,"U8":1,"uint8":1}
177
- for fn in sorted(f for f in os.listdir(path) if f.endswith(".safetensors")):
178
- with open(os.path.join(path,fn),"rb") as f:
179
- import struct
180
- hlen=struct.unpack("<Q",f.read(8))[0]
181
- hdr=json.loads(f.read(hlen).decode("utf-8","replace"))
182
- for k,v in hdr.items():
183
- if k=="__metadata__":continue
184
- sh=v.get("shape",[])
185
- n=1
186
- for d in sh:n*=d
187
- dtype_str=str(v.get("dtype","?"))
188
- bpe=dt_bytes.get(dtype_str,2)
189
- tensors[_normalize_hf_name(k)]={"shape":sh,"dtype":dtype_str,"mib":n*bpe/1024/1024}
190
- return meta,tensors
191
-
192
- def print_inventory(tensors):
193
- inv=collections.defaultdict(lambda:{"n":0,"mib":0.0,"dtypes":set(),"shapes":set()})
194
- for name,info in tensors.items():
195
- e=inv[suffix_of(name)]
196
- e["n"]+=1
197
- e["mib"]+=info["mib"]
198
- e["dtypes"].add(info["dtype"])
199
- e["shapes"].add(tuple(info["shape"]))
200
- print(f"\n{'='*76}\n 1. TENSOR INVENTORY ({len(tensors)} tensors, {sum(e['mib'] for e in inv.values()):.0f} MiB)\n{'='*76}")
201
- for suf,e in sorted(inv.items(),key=lambda kv:-kv[1]["mib"]):
202
- shapes="/".join("x".join(map(str,s)) for s in sorted(e["shapes"])[:2])
203
- flag="multi-shape!" if len(e["shapes"])>1 else ""
204
- print(f" {suf:<28}{e['n']:>4}× {flag:<12}{','.join(sorted(e['dtypes'])):<8}{e['mib']:>9.1f} MiB {shapes[:52]}")
205
-
206
- def print_signatures(tensors):
207
- layers=collections.defaultdict(set)
208
- for name in tensors:
209
- m=LAYER_RX.match(name)
210
- if m:layers[int(m.group(1))].add(suffix_of(m.group(2)))
211
- if not layers:
212
- print("\n (no blk.N layers — non-transformer or mmproj-only file)")
213
- return
214
- idx=sorted(layers)
215
- sigs=collections.Counter(frozenset(layers[i]) for i in idx)
216
- major=sigs.most_common(1)[0][0]
217
- print(f"\n{'='*76}\n 2. PER-LAYER SIGNATURES ({len(idx)} layers, {len(sigs)} distinct signature(s))\n{'='*76}")
218
- print(f" Dominant signature: {len(major)} tensor classes × {sigs[major]} layer(s)")
219
- for s,c in sigs.most_common():
220
- if s==major:continue
221
- hit=[i for i in idx if frozenset(layers[i])==s]
222
- print(f" ⚠ DEVIANT: blk {hit} — {len(s)} classes")
223
- extra=sorted(s-major)
224
- missing=sorted(major-s)
225
- if extra:print(f" extra vs dominant: {', '.join(extra[:12])}")
226
- if missing:print(f" missing vs dominant: {', '.join(missing[:12])}")
227
- outside=sorted({suffix_of(n) for n in tensors if not LAYER_RX.match(n)})
228
- print(f" Non-layer tensors: {', '.join(outside) if outside else '(none)'}")
229
-
230
- def print_novelty(tensors):
231
- unknown=sorted({suffix_of(n) for n in tensors if suffix_of(n) not in KNOWN_SUFFIX})
232
- print(f"\n{'='*76}\n 3. NOVELTY SCAN (suffixes outside the llama.cpp known taxonomy)\n{'='*76}")
233
- if not unknown:
234
- print(" ✓ Every tensor suffix maps to a known llama.cpp tensor class")
235
- return
236
- for suf in unknown:
237
- names=[n for n in tensors if suffix_of(n)==suf]
238
- print(f" ? {suf:<28}{len(names):>4}× shape={'x'.join(map(str,tensors[names[0]]['shape']))}")
239
- print(" → Novel is not fatal: check lens 4 before trusting inference")
240
-
241
- def _gguf_template(name):
242
- # llama-arch.cpp declares tensor names as printf templates ("blk.%d.attn_qkv"):
243
- # collapse layer indices and strip weight/bias before matching
244
- s=re.sub(r"\.(?:weight|bias)$","",name)
245
- return re.sub(r"\.\d+",".%d",s)
246
-
247
- def print_support(arch,tensors,llama_dir,model_type=None):
248
- print(f"\n{'='*76}\n 4. LLAMA.CPP SUPPORT CROSS-CHECK\n{'='*76}")
249
- arch_cpp=os.path.join(llama_dir,"src","llama-arch.cpp")
250
- if not os.path.isfile(arch_cpp):
251
- print(f" ✗ llama-arch.cpp not found under {llama_dir} — pass --llama-dir")
252
- return
253
- with open(arch_cpp,"r",encoding="utf-8",errors="ignore") as _f:src=_f.read()
254
- models_dir=os.path.join(llama_dir,"src","models")
255
- if os.path.isdir(models_dir):
256
- for f in os.listdir(models_dir):
257
- if f.endswith(".cpp"):
258
- with open(os.path.join(models_dir,f),"r",encoding="utf-8",errors="ignore") as _f:src+=_f.read()
259
- # Accept the GGUF id, HF class name, and underscore-free variants (qwen3_5 -> qwen35)
260
- ids=[a for a in(arch,model_type) if isinstance(a,str) and a]
261
- ids+=[a.replace("_","") for a in ids if "_" in a]
262
- arch_hit=any(a in src or a.lower() in src for a in ids)
263
- if not arch_hit:
264
- # HF compound model_types carry the GGUF arch id as their head token
265
- # ("paddleocr_vl" -> "paddleocr"): try the head before declaring a miss
266
- heads=[a.split("_")[0] for a in(arch,model_type) if isinstance(a,str) and a and "_" in a]
267
- arch_hit=any(a in src or a.lower() in src for a in heads)
268
- print(f" Architecture '{arch}': {'✓ declared in llama-arch.cpp' if arch_hit else '✗ NOT declared — runtime will reject the GGUF'}")
269
- miss=sorted({n for n in tensors if f'"{_gguf_template(n)}"' not in src})
270
- if miss:
271
- print(f" ⚠ {len(miss)} tensor name(s) absent from llama-arch.cpp — silently dropped at load:")
272
- for s in miss:print(f" {s}")
273
- else:
274
- print(" ✓ Every tensor name is declared in llama-arch.cpp")
275
-
276
- def print_imatrix_coverage(tensor_names,imatrix_path):
277
- r=gguf.GGUFReader(imatrix_path)
278
- covered=set()
279
- for t in r.tensors:
280
- n=t.name
281
- for suf in(".in_sum2",".counts",".in_sum"):
282
- if n.endswith(suf):n=n[:-len(suf)];break
283
- covered.add(n)
284
- covered_sufs={suffix_of(n) for n in covered}
285
- missing=sorted(n for n in tensor_names if n not in covered and suffix_of(n) not in covered_sufs)
286
- print(f"\n{'='*76}\n 5. IMATRIX COVERAGE ({os.path.basename(imatrix_path)})\n{'='*76}")
287
- if not missing:
288
- print(f" ✓ All {len(tensor_names)} model tensors covered")
289
- return
290
- print(f" ⚠ {len(missing)} tensor(s) WITHOUT activation statistics (ASHQ1 floors drive them):")
291
- for n in missing[:15]:print(f" {n}")
292
- if len(missing)>15:print(f" … +{len(missing)-15} more")
293
-
294
- def main():
295
- ap=argparse.ArgumentParser(description="Architecture dissection: inventory, signatures, novelty, support, imatrix")
296
- ap.add_argument("target",help="GGUF file or safetensors folder")
297
- ap.add_argument("--imatrix",default=None,help="imatrix .gguf/.dat for coverage check")
298
- ap.add_argument("--llama-dir",default=os.path.join(SCRIPT_DIR,"llama-cpp"),help="llama.cpp sources for the support cross-check")
299
- args=ap.parse_args()
300
- target=os.path.abspath(args.target)
301
- model_type=None
302
- is_gguf=False
303
- if os.path.isfile(target):
304
- with open(target,"rb") as _fh:is_gguf=_fh.read(4)==b"GGUF"
305
- if is_gguf:
306
- meta,tensors=read_gguf(target)
307
- arch=meta.get("general.architecture","?")
308
- print(f"\n Target: {target}\n Architecture: {arch}")
309
- print(" Key metadata:")
310
- for k in sorted(meta):
311
- if isinstance(k,str) and any(k.endswith("."+mk) for mk in _META_KEYS):
312
- print(f" {k} = {meta[k]}")
313
- else:
314
- if not os.path.isdir(target):
315
- sys.exit(f"✗ Not a GGUF file nor a folder: {target}")
316
- cfg_p=os.path.join(target,"config.json")
317
- cfg={}
318
- if os.path.isfile(cfg_p):
319
- with open(cfg_p,encoding="utf-8") as _f:cfg=json.load(_f)
320
- arch=(cfg.get("architectures") or ["?"])[0]
321
- model_type=cfg.get("model_type")
322
- print(f"\n Target: {target} (safetensors folder)\n Architecture: {arch} model_type: {cfg.get('model_type','?')}")
323
- for k in("sliding_window","rope_scaling","mtp_num_hidden_layers","tie_word_embeddings","num_hidden_layers"):
324
- if k in cfg:print(f" {k} = {json.dumps(cfg[k])[:120]}")
325
- meta,tensors=load_safetensors(target)
326
- if not tensors:
327
- sys.exit("✗ No tensors readable in target.")
328
- print_inventory(tensors)
329
- print_signatures(tensors)
330
- print_novelty(tensors)
331
- print_support(arch,tensors,args.llama_dir,model_type=model_type)
332
- if args.imatrix and os.path.isfile(args.imatrix):
333
- print_imatrix_coverage(set(tensors),args.imatrix)
334
- print()
335
-
336
- if __name__=="__main__":
337
- main()