128-IT-Coder / step2_inspect_model_index.py
doandung's picture
Upload step2_inspect_model_index.py with huggingface_hub
709a638 verified
Raw History Blame Contribute Delete
17.1 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
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)
=============================================================================================
Đọc `config.json` và `model.safetensors.index.json` của `deepseek-ai/DeepSeek-V4-Pro`
(hoặc họ DeepSeek 61 tầng / 384 ô) để:
1. Tự động nhận diện chuẩn đặt tên biến của DeepSeek-V4-Pro:
- Nhúng từ vựng: `embed.weight` (shard 00001)
- 61 tầng chính: `layers.{0..60}.*` (shards 00002..00062), gồm:
* Tầng 0, 1, 2: Hash-Routed MoE (`num_hash_layers = 3`, có `ffn.gate.tid2eid` & `ffn.gate.weight`)
* Tầng 3..60 : Learned-Bias Routed MoE (`ffn.gate.bias` & `ffn.gate.weight`)
* Hyper-Connections (`hc_mult = 4`): `hc_attn_*`, `hc_ffn_*`
* Attention MLA + Compressor + Indexer: `attn.*` (FP8 `e4m3fn` + `e8m0` scale)
* 384 Routed Experts: `ffn.experts.{0..383}.{w1,w2,w3}.{weight,scale}` (FP4 `e2m1fn_x2` + `e8m0` scale)
- Tầng Head & Norm: `hc_head_*`, `norm.weight`, `head.weight` (shard 00063)
- Tầng Dự đoán Đa từ MTP: `mtp.0.*` (shard 00064, cũng có 384 ô chuyên gia)
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`).
3. Lập lịch tải & xóa file thông minh (`Smart Shard Cache`) cho Google Colab Pro 200GB.
"""
import os
import sys
import re
import json
import argparse
from collections import defaultdict
from typing import Dict, List, Set, Tuple, Optional
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
try:
from huggingface_hub import hf_hub_download
except ImportError:
hf_hub_download = None
LAYER_REGEX = re.compile(r"^(?:model\.)?layers\.(\d+)\.(.+)$")
MTP_REGEX = re.compile(r"^(?:model\.)?mtp\.(\d+)\.(.+)$")
EXPERT_REGEX = re.compile(
r"^(?:model\.)?(?:layers|mtp)\.(\d+)\.(?:mlp|ffn)\.experts\.(\d+)\.(.+)$"
)
def load_json_from_source(
model_source: str, filename: str, cache_dir: str, hf_token: Optional[str] = None
) -> dict:
"""Tải file JSON từ thư mục cục bộ hoặc trực tiếp từ Hugging Face Hub."""
local_candidate = os.path.join(model_source, filename)
if os.path.isfile(local_candidate):
with open(local_candidate, "r", encoding="utf-8") as f:
return json.load(f)
if hf_hub_download is None:
raise RuntimeError(
f"Không tìm thấy {local_candidate} và thư viện `huggingface_hub` chưa được cài đặt."
)
downloaded_path = hf_hub_download(
repo_id=model_source,
filename=filename,
cache_dir=cache_dir,
token=hf_token,
)
with open(downloaded_path, "r", encoding="utf-8") as f:
return json.load(f)
def build_surgery_schedule(
config: dict,
index_data: dict,
target_experts: int = 128,
general_quota_per_group: int = 11,
logic_quota_per_group: int = 5,
) -> dict:
"""
Phân tích toàn bộ `weight_map` trong `model.safetensors.index.json` của DeepSeek-V4-Pro
(hoặc V3/R1) và tạo bản đồ điều phối cuốn chiếu từng tầng (`surgery_schedule`).
"""
weight_map: Dict[str, str] = index_data.get("weight_map", {})
metadata: dict = index_data.get("metadata", {})
model_type = str(config.get("model_type", "deepseek_v4"))
num_hidden_layers = int(config.get("num_hidden_layers", 61))
first_k_dense = int(config.get("first_k_dense_replace", 0))
num_hash_layers = int(config.get("num_hash_layers", 0))
n_routed_experts = int(config.get("n_routed_experts", 384))
n_group = int(config.get("n_group", 8))
topk_group = int(config.get("topk_group", 4))
num_experts_per_tok = int(config.get("num_experts_per_tok", 6))
hidden_size = int(config.get("hidden_size", 7168))
hc_mult = int(config.get("hc_mult", 1))
scoring_func = str(config.get("scoring_func", "sqrtsoftplus"))
expert_dtype = str(config.get("expert_dtype", "fp4"))
effective_n_group = n_group if n_group > 1 else 8
assert n_routed_experts % effective_n_group == 0, (
f"Số ô gốc ({n_routed_experts}) phải chia hết cho số nhóm ({effective_n_group})!"
)
assert target_experts % effective_n_group == 0, (
f"Số ô mục tiêu ({target_experts}) phải chia hết cho số nhóm ({effective_n_group})!"
)
experts_per_group_old = n_routed_experts // effective_n_group
experts_per_group_new = target_experts // effective_n_group
assert general_quota_per_group + logic_quota_per_group == experts_per_group_new, (
f"Tổng ghế Đa năng ({general_quota_per_group}) + Logic ({logic_quota_per_group}) "
f"phải bằng số ô mỗi nhóm mới ({experts_per_group_new})!"
)
# Phân loại toàn bộ các biến trong weight_map theo giai đoạn
embed_tensors: Dict[str, str] = {}
head_norm_tensors: Dict[str, str] = {}
layer_tensors: Dict[int, Dict[str, str]] = defaultdict(dict)
mtp_tensors: Dict[int, Dict[str, str]] = defaultdict(dict)
layer_experts_found: Dict[int, Set[int]] = defaultdict(set)
mtp_experts_found: Dict[int, Set[int]] = defaultdict(set)
shard_to_stages: Dict[str, List[str]] = defaultdict(list)
for tensor_name, shard_file in weight_map.items():
m_layer = LAYER_REGEX.match(tensor_name)
m_mtp = MTP_REGEX.match(tensor_name)
if m_layer:
layer_idx = int(m_layer.group(1))
layer_tensors[layer_idx][tensor_name] = shard_file
stage_id = f"layer_{layer_idx}"
if stage_id not in shard_to_stages[shard_file]:
shard_to_stages[shard_file].append(stage_id)
m_exp = EXPERT_REGEX.match(tensor_name)
if m_exp:
layer_experts_found[layer_idx].add(int(m_exp.group(2)))
elif m_mtp:
mtp_idx = int(m_mtp.group(1))
mtp_tensors[mtp_idx][tensor_name] = shard_file
stage_id = f"mtp_{mtp_idx}"
if stage_id not in shard_to_stages[shard_file]:
shard_to_stages[shard_file].append(stage_id)
m_exp = EXPERT_REGEX.match(tensor_name)
if m_exp:
mtp_experts_found[mtp_idx].add(int(m_exp.group(2)))
elif tensor_name.startswith("embed.") or "embed_tokens" in tensor_name:
embed_tensors[tensor_name] = shard_file
if "embed" not in shard_to_stages[shard_file]:
shard_to_stages[shard_file].append("embed")
else:
head_norm_tensors[tensor_name] = shard_file
if "head_norm" not in shard_to_stages[shard_file]:
shard_to_stages[shard_file].append("head_norm")
all_detected_layers = sorted(layer_tensors.keys())
all_detected_mtp = sorted(mtp_tensors.keys())
# Chuỗi giai đoạn: embed -> layer_0 .. layer_60 -> head_norm -> mtp_0 (nếu có)
ordered_stages = (
["embed"]
+ [f"layer_{i}" for i in all_detected_layers]
+ ["head_norm"]
+ [f"mtp_{m}" for m in all_detected_mtp]
)
stage_index_map = {st: idx for idx, st in enumerate(ordered_stages)}
shard_last_stage_idx: Dict[str, int] = {}
for shard_file, stages in shard_to_stages.items():
shard_last_stage_idx[shard_file] = max(stage_index_map[st] for st in stages)
active_shards: Set[str] = set()
stage_plans: List[dict] = []
for st_idx, st_name in enumerate(ordered_stages):
if st_name == "embed":
tensors_map = embed_tensors
layer_id = -1
layer_type = "embedding"
detected_exp = 0
elif st_name == "head_norm":
tensors_map = head_norm_tensors
layer_id = 999
layer_type = "head_and_norm"
detected_exp = 0
elif st_name.startswith("mtp_"):
mtp_id = int(st_name.split("_")[1])
layer_id = num_hidden_layers + mtp_id
tensors_map = mtp_tensors[mtp_id]
detected_exp = len(mtp_experts_found[mtp_id])
layer_type = "mtp_moe" if detected_exp > 0 else "dense"
else:
layer_id = int(st_name.split("_")[1])
tensors_map = layer_tensors[layer_id]
detected_exp = len(layer_experts_found[layer_id])
if detected_exp > 0:
if layer_id < num_hash_layers or any(
k.endswith(".tid2eid") for k in tensors_map.keys()
):
layer_type = "hash_moe"
elif layer_id >= num_hidden_layers:
layer_type = "mtp_moe"
else:
layer_type = "moe"
else:
layer_type = "dense"
required_shards = sorted(set(tensors_map.values()))
shards_to_download = [s for s in required_shards if s not in active_shards]
active_shards.update(required_shards)
shards_to_delete = sorted(
[s for s in active_shards if shard_last_stage_idx.get(s, -1) <= st_idx]
)
shards_retained = sorted(
[s for s in active_shards if shard_last_stage_idx.get(s, -1) > st_idx]
)
for s in shards_to_delete:
active_shards.remove(s)
# 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)
primary_output_shard = (
required_shards[0]
if len(required_shards) == 1
else (
"model-embed-tokens.safetensors"
if layer_type == "embedding"
else "model-norm-and-lm-head.safetensors"
if layer_type == "head_and_norm"
else f"model-layer-{layer_id:02d}-of-61.safetensors"
)
)
stage_plans.append(
{
"stage_name": st_name,
"layer_id": layer_id,
"layer_type": layer_type,
"num_tensors": len(tensors_map),
"detected_routed_experts": detected_exp,
"primary_output_shard": primary_output_shard,
"required_shards": required_shards,
"shards_to_download": shards_to_download,
"shards_retained_for_next": shards_retained,
"shards_safe_to_delete": shards_to_delete,
"tensors_map": tensors_map,
}
)
schedule = {
"architecture_summary": {
"model_type": model_type,
"num_hidden_layers": num_hidden_layers,
"num_hash_layers": num_hash_layers,
"num_mtp_layers": len(all_detected_mtp),
"all_detected_layers": all_detected_layers,
"all_detected_mtp": all_detected_mtp,
"first_k_dense_replace": first_k_dense,
"hidden_size": hidden_size,
"hc_mult": hc_mult,
"scoring_func": scoring_func,
"expert_dtype": expert_dtype,
"original_routed_experts": n_routed_experts,
"target_routed_experts": target_experts,
"n_group": effective_n_group,
"topk_group": topk_group,
"num_experts_per_tok": num_experts_per_tok,
"experts_per_group_old": experts_per_group_old,
"experts_per_group_new": experts_per_group_new,
"general_quota_per_group": general_quota_per_group,
"logic_quota_per_group": logic_quota_per_group,
"total_source_shards": len(set(weight_map.values())),
"total_source_bytes": metadata.get("total_size", 0),
},
"group_mapping_blueprint": [
{
"group_id": g,
"old_expert_range": [
g * experts_per_group_old,
(g + 1) * experts_per_group_old - 1,
],
"new_expert_range": [
g * experts_per_group_new,
(g + 1) * experts_per_group_new - 1,
],
"quota": f"{general_quota_per_group} General + {logic_quota_per_group} Peak-Logic = {experts_per_group_new}",
}
for g in range(effective_n_group)
],
"stage_plans": stage_plans,
}
return schedule
def inspect_and_export_schedule(
model_source: str,
output_path: str = "./surgery_schedule.json",
cache_dir: str = "./hf_cache",
target_experts: int = 128,
hf_token: Optional[str] = None,
) -> dict:
"""Đọ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."""
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
print(f"[*] Đang đọc config.json và model.safetensors.index.json từ: {model_source}")
config = load_json_from_source(model_source, "config.json", cache_dir, hf_token)
index_data = load_json_from_source(
model_source, "model.safetensors.index.json", cache_dir, hf_token
)
schedule = build_surgery_schedule(
config=config,
index_data=index_data,
target_experts=target_experts,
)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(schedule, f, indent=2, ensure_ascii=False)
arch = schedule["architecture_summary"]
hash_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "hash_moe"]
moe_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "moe"]
mtp_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "mtp_moe"]
dense_stages = [s for s in schedule["stage_plans"] if s["layer_type"] == "dense"]
max_concurrent_shards = max(
len(s["required_shards"]) for s in schedule["stage_plans"]
)
total_gb = arch["total_source_bytes"] / (1024 ** 3) if arch["total_source_bytes"] else 0
print("\n" + "=" * 78)
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]")
print("=" * 78)
print(f" - Nguồn mô hình : {model_source} ({arch['model_type']})")
print(f" - Dung lượng gốc & Số Shards : {total_gb:.2f} GB ({arch['total_source_shards']} files .safetensors)")
print(
f" - Cấu trúc Tầng phát hiện : {len(arch['all_detected_layers'])} tầng chính "
f"({len(hash_stages)} Hash-MoE, {len(dense_stages)} Dense, {len(moe_stages)} Bias-MoE) "
f"+ {len(mtp_stages)} tầng MTP"
)
print(
f" - Kiến trúc Đặc trưng : hc_mult={arch['hc_mult']}, "
f"scoring_func={arch['scoring_func']}, expert_dtype={arch['expert_dtype']}"
)
print(
f" - Số Ô Chuyên Gia Gốc / Tầng : {arch['original_routed_experts']} ô "
f"({arch['n_group']} nhóm x {arch['experts_per_group_old']} ô/nhóm)"
)
print(
f" - Số Ô Chuyên Gia Mục Tiêu : {arch['target_routed_experts']} ô "
f"({arch['n_group']} nhóm x {arch['experts_per_group_new']} ô/nhóm)"
)
print(
f" - Cơ cấu Ghế mỗi Nhóm : {arch['general_quota_per_group']} Đa năng "
f"+ {arch['logic_quota_per_group']} Đặc cách Logic P99.5"
)
print(
f" - Số file .safetensors tối đa : {max_concurrent_shards} file tại 1 thời điểm (~13.5 GB/file)"
)
print(f" - Đã xuất lịch trình chi tiết : {output_path}")
print("=" * 78)
return schedule
def parse_args():
parser = argparse.ArgumentParser(
description="Bước 2: Phân tích model.safetensors.index.json và lập lịch phẫu thuật 61 tầng."
)
parser.add_argument(
"--model-source",
type=str,
default="deepseek-ai/DeepSeek-V4-Pro",
help="Hugging Face Repo ID hoặc đường dẫn thư mục chứa config.json & model.safetensors.index.json.",
)
parser.add_argument(
"--output-path",
type=str,
default="./surgery_schedule.json",
help="Đường dẫn lưu file lịch trình phẫu thuật JSON.",
)
parser.add_argument(
"--target-experts",
type=int,
default=128,
help="Số ô chuyên gia giữ lại trên mỗi tầng (mặc định: 128).",
)
parser.add_argument(
"--cache-dir",
type=str,
default="./hf_cache",
help="Thư mục đệm khi tải file index.",
)
parser.add_argument(
"--hf-token",
type=str,
default=os.environ.get("HF_TOKEN", None),
help="Hugging Face Token.",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
inspect_and_export_schedule(
model_source=args.model_source,
output_path=args.output_path,
cache_dir=args.cache_dir,
target_experts=args.target_experts,
hf_token=args.hf_token,
)