doandung commited on
Commit
709a638
·
verified ·
1 Parent(s): 25f3165

Upload step2_inspect_model_index.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. step2_inspect_model_index.py +410 -0
step2_inspect_model_index.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ STEP 2: PHÂN TÍCH MỤC LỤC SAFETENSORS & LẬP LỊCH PHẪU THUẬT CUỐN CHIẾU (DEEPSEEK-V4-PRO / V3)
5
+ =============================================================================================
6
+ Đọc `config.json` và `model.safetensors.index.json` của `deepseek-ai/DeepSeek-V4-Pro`
7
+ (hoặc họ DeepSeek 61 tầng / 384 ô) để:
8
+ 1. Tự động nhận diện chuẩn đặt tên biến của DeepSeek-V4-Pro:
9
+ - Nhúng từ vựng: `embed.weight` (shard 00001)
10
+ - 61 tầng chính: `layers.{0..60}.*` (shards 00002..00062), gồm:
11
+ * Tầng 0, 1, 2: Hash-Routed MoE (`num_hash_layers = 3`, có `ffn.gate.tid2eid` & `ffn.gate.weight`)
12
+ * Tầng 3..60 : Learned-Bias Routed MoE (`ffn.gate.bias` & `ffn.gate.weight`)
13
+ * Hyper-Connections (`hc_mult = 4`): `hc_attn_*`, `hc_ffn_*`
14
+ * Attention MLA + Compressor + Indexer: `attn.*` (FP8 `e4m3fn` + `e8m0` scale)
15
+ * 384 Routed Experts: `ffn.experts.{0..383}.{w1,w2,w3}.{weight,scale}` (FP4 `e2m1fn_x2` + `e8m0` scale)
16
+ - Tầng Head & Norm: `hc_head_*`, `norm.weight`, `head.weight` (shard 00063)
17
+ - Tầng Dự đoán Đa từ MTP: `mtp.0.*` (shard 00064, cũng có 384 ô chuyên gia)
18
+ 2. Quy hoạch cắt từ 384 ô về 128 ô theo 8 Nhóm (`16 ô/nhóm = 11 Đa năng + 5 Logic P99.5`).
19
+ 3. Lập lịch tải & xóa file thông minh (`Smart Shard Cache`) cho Google Colab Pro 200GB.
20
+ """
21
+
22
+ import os
23
+ import sys
24
+ import re
25
+ import json
26
+ import argparse
27
+ from collections import defaultdict
28
+ from typing import Dict, List, Set, Tuple, Optional
29
+
30
+ if hasattr(sys.stdout, "reconfigure"):
31
+ sys.stdout.reconfigure(encoding="utf-8")
32
+ if hasattr(sys.stderr, "reconfigure"):
33
+ sys.stderr.reconfigure(encoding="utf-8")
34
+
35
+ try:
36
+ from huggingface_hub import hf_hub_download
37
+ except ImportError:
38
+ hf_hub_download = None
39
+
40
+
41
+ LAYER_REGEX = re.compile(r"^(?:model\.)?layers\.(\d+)\.(.+)$")
42
+ MTP_REGEX = re.compile(r"^(?:model\.)?mtp\.(\d+)\.(.+)$")
43
+ EXPERT_REGEX = re.compile(
44
+ r"^(?:model\.)?(?:layers|mtp)\.(\d+)\.(?:mlp|ffn)\.experts\.(\d+)\.(.+)$"
45
+ )
46
+
47
+
48
+ def load_json_from_source(
49
+ model_source: str, filename: str, cache_dir: str, hf_token: Optional[str] = None
50
+ ) -> dict:
51
+ """Tải file JSON từ thư mục cục bộ hoặc trực tiếp từ Hugging Face Hub."""
52
+ local_candidate = os.path.join(model_source, filename)
53
+ if os.path.isfile(local_candidate):
54
+ with open(local_candidate, "r", encoding="utf-8") as f:
55
+ return json.load(f)
56
+
57
+ if hf_hub_download is None:
58
+ raise RuntimeError(
59
+ f"Không tìm thấy {local_candidate} và thư viện `huggingface_hub` chưa được cài đặt."
60
+ )
61
+
62
+ downloaded_path = hf_hub_download(
63
+ repo_id=model_source,
64
+ filename=filename,
65
+ cache_dir=cache_dir,
66
+ token=hf_token,
67
+ )
68
+ with open(downloaded_path, "r", encoding="utf-8") as f:
69
+ return json.load(f)
70
+
71
+
72
+ def build_surgery_schedule(
73
+ config: dict,
74
+ index_data: dict,
75
+ target_experts: int = 128,
76
+ general_quota_per_group: int = 11,
77
+ logic_quota_per_group: int = 5,
78
+ ) -> dict:
79
+ """
80
+ Phân tích toàn bộ `weight_map` trong `model.safetensors.index.json` của DeepSeek-V4-Pro
81
+ (hoặc V3/R1) và tạo bản đồ điều phối cuốn chiếu từng tầng (`surgery_schedule`).
82
+ """
83
+ weight_map: Dict[str, str] = index_data.get("weight_map", {})
84
+ metadata: dict = index_data.get("metadata", {})
85
+
86
+ model_type = str(config.get("model_type", "deepseek_v4"))
87
+ num_hidden_layers = int(config.get("num_hidden_layers", 61))
88
+ first_k_dense = int(config.get("first_k_dense_replace", 0))
89
+ num_hash_layers = int(config.get("num_hash_layers", 0))
90
+ n_routed_experts = int(config.get("n_routed_experts", 384))
91
+ n_group = int(config.get("n_group", 8))
92
+ topk_group = int(config.get("topk_group", 4))
93
+ num_experts_per_tok = int(config.get("num_experts_per_tok", 6))
94
+ hidden_size = int(config.get("hidden_size", 7168))
95
+ hc_mult = int(config.get("hc_mult", 1))
96
+ scoring_func = str(config.get("scoring_func", "sqrtsoftplus"))
97
+ expert_dtype = str(config.get("expert_dtype", "fp4"))
98
+
99
+ effective_n_group = n_group if n_group > 1 else 8
100
+ assert n_routed_experts % effective_n_group == 0, (
101
+ f"Số ô gốc ({n_routed_experts}) phải chia hết cho số nhóm ({effective_n_group})!"
102
+ )
103
+ assert target_experts % effective_n_group == 0, (
104
+ f"Số ô mục tiêu ({target_experts}) phải chia hết cho số nhóm ({effective_n_group})!"
105
+ )
106
+
107
+ experts_per_group_old = n_routed_experts // effective_n_group
108
+ experts_per_group_new = target_experts // effective_n_group
109
+ assert general_quota_per_group + logic_quota_per_group == experts_per_group_new, (
110
+ f"Tổng ghế Đa năng ({general_quota_per_group}) + Logic ({logic_quota_per_group}) "
111
+ f"phải bằng số ô mỗi nhóm mới ({experts_per_group_new})!"
112
+ )
113
+
114
+ # Phân loại toàn bộ các biến trong weight_map theo giai đoạn
115
+ embed_tensors: Dict[str, str] = {}
116
+ head_norm_tensors: Dict[str, str] = {}
117
+ layer_tensors: Dict[int, Dict[str, str]] = defaultdict(dict)
118
+ mtp_tensors: Dict[int, Dict[str, str]] = defaultdict(dict)
119
+ layer_experts_found: Dict[int, Set[int]] = defaultdict(set)
120
+ mtp_experts_found: Dict[int, Set[int]] = defaultdict(set)
121
+ shard_to_stages: Dict[str, List[str]] = defaultdict(list)
122
+
123
+ for tensor_name, shard_file in weight_map.items():
124
+ m_layer = LAYER_REGEX.match(tensor_name)
125
+ m_mtp = MTP_REGEX.match(tensor_name)
126
+ if m_layer:
127
+ layer_idx = int(m_layer.group(1))
128
+ layer_tensors[layer_idx][tensor_name] = shard_file
129
+ stage_id = f"layer_{layer_idx}"
130
+ if stage_id not in shard_to_stages[shard_file]:
131
+ shard_to_stages[shard_file].append(stage_id)
132
+
133
+ m_exp = EXPERT_REGEX.match(tensor_name)
134
+ if m_exp:
135
+ layer_experts_found[layer_idx].add(int(m_exp.group(2)))
136
+ elif m_mtp:
137
+ mtp_idx = int(m_mtp.group(1))
138
+ mtp_tensors[mtp_idx][tensor_name] = shard_file
139
+ stage_id = f"mtp_{mtp_idx}"
140
+ if stage_id not in shard_to_stages[shard_file]:
141
+ shard_to_stages[shard_file].append(stage_id)
142
+
143
+ m_exp = EXPERT_REGEX.match(tensor_name)
144
+ if m_exp:
145
+ mtp_experts_found[mtp_idx].add(int(m_exp.group(2)))
146
+ elif tensor_name.startswith("embed.") or "embed_tokens" in tensor_name:
147
+ embed_tensors[tensor_name] = shard_file
148
+ if "embed" not in shard_to_stages[shard_file]:
149
+ shard_to_stages[shard_file].append("embed")
150
+ else:
151
+ head_norm_tensors[tensor_name] = shard_file
152
+ if "head_norm" not in shard_to_stages[shard_file]:
153
+ shard_to_stages[shard_file].append("head_norm")
154
+
155
+ all_detected_layers = sorted(layer_tensors.keys())
156
+ all_detected_mtp = sorted(mtp_tensors.keys())
157
+
158
+ # Chuỗi giai đoạn: embed -> layer_0 .. layer_60 -> head_norm -> mtp_0 (nếu có)
159
+ ordered_stages = (
160
+ ["embed"]
161
+ + [f"layer_{i}" for i in all_detected_layers]
162
+ + ["head_norm"]
163
+ + [f"mtp_{m}" for m in all_detected_mtp]
164
+ )
165
+ stage_index_map = {st: idx for idx, st in enumerate(ordered_stages)}
166
+
167
+ shard_last_stage_idx: Dict[str, int] = {}
168
+ for shard_file, stages in shard_to_stages.items():
169
+ shard_last_stage_idx[shard_file] = max(stage_index_map[st] for st in stages)
170
+
171
+ active_shards: Set[str] = set()
172
+ stage_plans: List[dict] = []
173
+
174
+ for st_idx, st_name in enumerate(ordered_stages):
175
+ if st_name == "embed":
176
+ tensors_map = embed_tensors
177
+ layer_id = -1
178
+ layer_type = "embedding"
179
+ detected_exp = 0
180
+ elif st_name == "head_norm":
181
+ tensors_map = head_norm_tensors
182
+ layer_id = 999
183
+ layer_type = "head_and_norm"
184
+ detected_exp = 0
185
+ elif st_name.startswith("mtp_"):
186
+ mtp_id = int(st_name.split("_")[1])
187
+ layer_id = num_hidden_layers + mtp_id
188
+ tensors_map = mtp_tensors[mtp_id]
189
+ detected_exp = len(mtp_experts_found[mtp_id])
190
+ layer_type = "mtp_moe" if detected_exp > 0 else "dense"
191
+ else:
192
+ layer_id = int(st_name.split("_")[1])
193
+ tensors_map = layer_tensors[layer_id]
194
+ detected_exp = len(layer_experts_found[layer_id])
195
+ if detected_exp > 0:
196
+ if layer_id < num_hash_layers or any(
197
+ k.endswith(".tid2eid") for k in tensors_map.keys()
198
+ ):
199
+ layer_type = "hash_moe"
200
+ elif layer_id >= num_hidden_layers:
201
+ layer_type = "mtp_moe"
202
+ else:
203
+ layer_type = "moe"
204
+ else:
205
+ layer_type = "dense"
206
+
207
+ required_shards = sorted(set(tensors_map.values()))
208
+ shards_to_download = [s for s in required_shards if s not in active_shards]
209
+ active_shards.update(required_shards)
210
+
211
+ shards_to_delete = sorted(
212
+ [s for s in active_shards if shard_last_stage_idx.get(s, -1) <= st_idx]
213
+ )
214
+ shards_retained = sorted(
215
+ [s for s in active_shards if shard_last_stage_idx.get(s, -1) > st_idx]
216
+ )
217
+ for s in shards_to_delete:
218
+ active_shards.remove(s)
219
+
220
+ # Giữ nguyên tên file shard gốc nếu mỗi giai đoạn nằm gọn trong 1 shard (như 00001..00064 của V4-Pro)
221
+ primary_output_shard = (
222
+ required_shards[0]
223
+ if len(required_shards) == 1
224
+ else (
225
+ "model-embed-tokens.safetensors"
226
+ if layer_type == "embedding"
227
+ else "model-norm-and-lm-head.safetensors"
228
+ if layer_type == "head_and_norm"
229
+ else f"model-layer-{layer_id:02d}-of-61.safetensors"
230
+ )
231
+ )
232
+
233
+ stage_plans.append(
234
+ {
235
+ "stage_name": st_name,
236
+ "layer_id": layer_id,
237
+ "layer_type": layer_type,
238
+ "num_tensors": len(tensors_map),
239
+ "detected_routed_experts": detected_exp,
240
+ "primary_output_shard": primary_output_shard,
241
+ "required_shards": required_shards,
242
+ "shards_to_download": shards_to_download,
243
+ "shards_retained_for_next": shards_retained,
244
+ "shards_safe_to_delete": shards_to_delete,
245
+ "tensors_map": tensors_map,
246
+ }
247
+ )
248
+
249
+ schedule = {
250
+ "architecture_summary": {
251
+ "model_type": model_type,
252
+ "num_hidden_layers": num_hidden_layers,
253
+ "num_hash_layers": num_hash_layers,
254
+ "num_mtp_layers": len(all_detected_mtp),
255
+ "all_detected_layers": all_detected_layers,
256
+ "all_detected_mtp": all_detected_mtp,
257
+ "first_k_dense_replace": first_k_dense,
258
+ "hidden_size": hidden_size,
259
+ "hc_mult": hc_mult,
260
+ "scoring_func": scoring_func,
261
+ "expert_dtype": expert_dtype,
262
+ "original_routed_experts": n_routed_experts,
263
+ "target_routed_experts": target_experts,
264
+ "n_group": effective_n_group,
265
+ "topk_group": topk_group,
266
+ "num_experts_per_tok": num_experts_per_tok,
267
+ "experts_per_group_old": experts_per_group_old,
268
+ "experts_per_group_new": experts_per_group_new,
269
+ "general_quota_per_group": general_quota_per_group,
270
+ "logic_quota_per_group": logic_quota_per_group,
271
+ "total_source_shards": len(set(weight_map.values())),
272
+ "total_source_bytes": metadata.get("total_size", 0),
273
+ },
274
+ "group_mapping_blueprint": [
275
+ {
276
+ "group_id": g,
277
+ "old_expert_range": [
278
+ g * experts_per_group_old,
279
+ (g + 1) * experts_per_group_old - 1,
280
+ ],
281
+ "new_expert_range": [
282
+ g * experts_per_group_new,
283
+ (g + 1) * experts_per_group_new - 1,
284
+ ],
285
+ "quota": f"{general_quota_per_group} General + {logic_quota_per_group} Peak-Logic = {experts_per_group_new}",
286
+ }
287
+ for g in range(effective_n_group)
288
+ ],
289
+ "stage_plans": stage_plans,
290
+ }
291
+ return schedule
292
+
293
+
294
+ def inspect_and_export_schedule(
295
+ model_source: str,
296
+ output_path: str = "./surgery_schedule.json",
297
+ cache_dir: str = "./hf_cache",
298
+ target_experts: int = 128,
299
+ hf_token: Optional[str] = None,
300
+ ) -> dict:
301
+ """Đọc cấu hình & mục lục model gốc, xuất file kế hoạch phẫu thuật cuốn chiếu."""
302
+ os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
303
+ os.makedirs(cache_dir, exist_ok=True)
304
+
305
+ print(f"[*] Đang đọc config.json và model.safetensors.index.json từ: {model_source}")
306
+ config = load_json_from_source(model_source, "config.json", cache_dir, hf_token)
307
+ index_data = load_json_from_source(
308
+ model_source, "model.safetensors.index.json", cache_dir, hf_token
309
+ )
310
+
311
+ schedule = build_surgery_schedule(
312
+ config=config,
313
+ index_data=index_data,
314
+ target_experts=target_experts,
315
+ )
316
+
317
+ with open(output_path, "w", encoding="utf-8") as f:
318
+ json.dump(schedule, f, indent=2, ensure_ascii=False)
319
+
320
+ arch = schedule["architecture_summary"]
321
+ hash_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "hash_moe"]
322
+ moe_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "moe"]
323
+ mtp_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "mtp_moe"]
324
+ dense_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "dense"]
325
+ max_concurrent_shards = max(
326
+ len(s["required_shards"]) for s in schedule["stage_plans"]
327
+ )
328
+ total_gb = arch["total_source_bytes"] / (1024 ** 3) if arch["total_source_bytes"] else 0
329
+
330
+ print("\n" + "=" * 78)
331
+ print("[BÁO CÁO PHÂN TÍCH MỤC LỤC DEEPSEEK-V4-PRO & LỊCH PHẪU THUẬT CUỐN CHIẾU]")
332
+ print("=" * 78)
333
+ print(f" - Nguồn mô hình : {model_source} ({arch['model_type']})")
334
+ print(f" - Dung lượng gốc & Số Shards : {total_gb:.2f} GB ({arch['total_source_shards']} files .safetensors)")
335
+ print(
336
+ f" - Cấu trúc Tầng phát hiện : {len(arch['all_detected_layers'])} tầng chính "
337
+ f"({len(hash_stages)} Hash-MoE, {len(dense_stages)} Dense, {len(moe_stages)} Bias-MoE) "
338
+ f"+ {len(mtp_stages)} tầng MTP"
339
+ )
340
+ print(
341
+ f" - Kiến trúc Đặc trưng : hc_mult={arch['hc_mult']}, "
342
+ f"scoring_func={arch['scoring_func']}, expert_dtype={arch['expert_dtype']}"
343
+ )
344
+ print(
345
+ f" - Số Ô Chuyên Gia Gốc / Tầng : {arch['original_routed_experts']} ô "
346
+ f"({arch['n_group']} nhóm x {arch['experts_per_group_old']} ô/nhóm)"
347
+ )
348
+ print(
349
+ f" - Số Ô Chuyên Gia Mục Tiêu : {arch['target_routed_experts']} ô "
350
+ f"({arch['n_group']} nhóm x {arch['experts_per_group_new']} ô/nhóm)"
351
+ )
352
+ print(
353
+ f" - Cơ cấu Ghế mỗi Nhóm : {arch['general_quota_per_group']} Đa năng "
354
+ f"+ {arch['logic_quota_per_group']} Đặc cách Logic P99.5"
355
+ )
356
+ print(
357
+ f" - Số file .safetensors tối đa : {max_concurrent_shards} file tại 1 thời điểm (~13.5 GB/file)"
358
+ )
359
+ print(f" - Đã xuất lịch trình chi tiết : {output_path}")
360
+ print("=" * 78)
361
+
362
+ return schedule
363
+
364
+
365
+ def parse_args():
366
+ parser = argparse.ArgumentParser(
367
+ description="Bước 2: Phân tích model.safetensors.index.json và lập lịch phẫu thuật 61 tầng."
368
+ )
369
+ parser.add_argument(
370
+ "--model-source",
371
+ type=str,
372
+ default="deepseek-ai/DeepSeek-V4-Pro",
373
+ help="Hugging Face Repo ID hoặc đường dẫn thư mục chứa config.json & model.safetensors.index.json.",
374
+ )
375
+ parser.add_argument(
376
+ "--output-path",
377
+ type=str,
378
+ default="./surgery_schedule.json",
379
+ help="Đường dẫn lưu file lịch trình phẫu thuật JSON.",
380
+ )
381
+ parser.add_argument(
382
+ "--target-experts",
383
+ type=int,
384
+ default=128,
385
+ help="Số ô chuyên gia giữ lại trên mỗi tầng (mặc định: 128).",
386
+ )
387
+ parser.add_argument(
388
+ "--cache-dir",
389
+ type=str,
390
+ default="./hf_cache",
391
+ help="Thư mục đệm khi tải file index.",
392
+ )
393
+ parser.add_argument(
394
+ "--hf-token",
395
+ type=str,
396
+ default=os.environ.get("HF_TOKEN", None),
397
+ help="Hugging Face Token.",
398
+ )
399
+ return parser.parse_args()
400
+
401
+
402
+ if __name__ == "__main__":
403
+ args = parse_args()
404
+ inspect_and_export_schedule(
405
+ model_source=args.model_source,
406
+ output_path=args.output_path,
407
+ cache_dir=args.cache_dir,
408
+ target_experts=args.target_experts,
409
+ hf_token=args.hf_token,
410
+ )