#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ STEP 4: ĐÓNG GÓI MỤC LỤC SAFETENSORS, CẬP NHẬT CONFIG & KIỂM ĐỊNH TOÀN VẸN 61 TẦNG ================================================================================== Thực hiện Giai đoạn 3 (hỗ trợ chuẩn DeepSeek-V4-Pro & V3/R1): 1. Quét toàn bộ các file `.safetensors` đã phẫu thuật (128 ô) hoặc `shard_manifests` để lập mục lục `model.safetensors.index.json` mới. 2. Cập nhật `config.json` (và `inference/config.json` của DeepSeek-V4-Pro): - "n_routed_experts": 128 3. Kiểm định toàn vẹn 100% cấu trúc Tensor (Integrity Audit) cho cả 61 tầng + MTP: - Kiểm tra `gate.weight` có đúng kích thước `[128, hidden_size]`. - Kiểm tra `gate.bias` / `e_score_correction_bias` có đúng kích thước `[128]`. - Kiểm tra các ô chuyên gia được đánh số liên tục `0..127` (không sót, không thừa). - Kiểm tra bảo toàn 8 nhóm (`16 ô/nhóm`). """ import os import sys import re import json import shutil import argparse 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") import torch try: from safetensors import safe_open except ImportError: safe_open = None try: from huggingface_hub import hf_hub_download, HfApi except ImportError: hf_hub_download = None HfApi = None AUXILIARY_MODEL_FILES = [ "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "generation_config.json", "modeling_deepseek.py", "configuration_deepseek.py", ] def inspect_safetensors_headers( shard_path: str, ) -> Tuple[Dict[str, Tuple[List[int], str]], int]: tensor_specs: Dict[str, Tuple[List[int], str]] = {} total_bytes = os.path.getsize(shard_path) if safe_open is not None and shard_path.endswith(".safetensors"): with safe_open(shard_path, framework="pt", device="cpu") as f: for key in f.keys(): slice_obj = f.get_slice(key) shape = list(slice_obj.get_shape()) dtype_str = str(slice_obj.get_dtype()) tensor_specs[key] = (shape, dtype_str) else: state = torch.load(shard_path, map_location="cpu", weights_only=True) for key, val in state.items(): tensor_specs[key] = (list(val.shape), str(val.dtype)) return tensor_specs, total_bytes def finalize_and_verify_model( model_source: str, pruned_dir: str = "./pruned_128_model", target_experts: int = 128, n_group: int = 8, topk_group: int = 4, num_experts_per_tok: Optional[int] = None, cache_dir: str = "./hf_cache", hf_Output_repo: Optional[str] = None, hf_token: Optional[str] = None, ) -> dict: os.makedirs(pruned_dir, exist_ok=True) report_path = os.path.join(pruned_dir, "expert_selection_report.json") if not os.path.isfile(report_path) and hf_Output_repo and hf_hub_download is not None: try: downloaded_rep = hf_hub_download( repo_id=hf_Output_repo, filename="expert_selection_report.json", local_dir=pruned_dir, token=hf_token, ) if os.path.isfile(downloaded_rep) and downloaded_rep != report_path: shutil.copy2(downloaded_rep, report_path) except Exception: pass if not os.path.isfile(report_path): raise FileNotFoundError( f"Không tìm thấy báo cáo phẫu thuật tại {report_path}. Hãy chạy Bước 3 trước!" ) with open(report_path, "r", encoding="utf-8") as f: selection_report = json.load(f) # 1. Đọc và cập nhật config.json local_cfg = os.path.join(model_source, "config.json") if os.path.isfile(local_cfg): with open(local_cfg, "r", encoding="utf-8") as f: config = json.load(f) else: cfg_downloaded = hf_hub_download( repo_id=model_source, filename="config.json", cache_dir=cache_dir, token=hf_token ) with open(cfg_downloaded, "r", encoding="utf-8") as f: config = json.load(f) old_experts = config.get("n_routed_experts", 384) config["n_routed_experts"] = target_experts if num_experts_per_tok is not None: config["num_experts_per_tok"] = num_experts_per_tok if "n_group" in config or config.get("model_type") != "deepseek_v4": config["n_group"] = n_group config["topk_group"] = topk_group new_cfg_path = os.path.join(pruned_dir, "config.json") with open(new_cfg_path, "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False) # 2. Quét tất cả các file shard đầu ra hoặc shard_manifests output_shard_files: Dict[str, str] = selection_report.get("output_shard_files", {}) shard_manifests: Dict[str, dict] = selection_report.get("shard_manifests", {}) weight_map: Dict[str, str] = {} all_specs: Dict[str, Tuple[List[int], str]] = {} total_size_bytes = 0 for stage_name, shard_filename in output_shard_files.items(): shard_path = os.path.join(pruned_dir, shard_filename) if os.path.isfile(shard_path): specs, fsize = inspect_safetensors_headers(shard_path) elif stage_name in shard_manifests: manifest = shard_manifests[stage_name] fsize = int(manifest.get("size_bytes", 0)) specs = { k: (list(v[0]), str(v[1])) for k, v in manifest.get("tensors", {}).items() } else: raise FileNotFoundError( f"Thiếu file shard [{shard_filename}] và không có thông tin trong shard_manifests của [{stage_name}]!" ) total_size_bytes += fsize for t_name, spec in specs.items(): weight_map[t_name] = shard_filename all_specs[t_name] = spec new_index = { "metadata": { "total_size": total_size_bytes, "format": "pt", "pruned_from_experts": old_experts, "pruned_to_experts": target_experts, "n_group": n_group, }, "weight_map": weight_map, } new_index_path = os.path.join(pruned_dir, "model.safetensors.index.json") with open(new_index_path, "w", encoding="utf-8") as f: json.dump(new_index, f, indent=2, ensure_ascii=False) # 3. Kiểm định toàn vẹn từng tầng MoE (Verification Audit) moe_layer_ids = sorted(int(k) for k in selection_report.get("layers", {}).keys()) hidden_size = int(config.get("hidden_size", 7168)) num_hidden_layers = int(config.get("num_hidden_layers", 61)) first_k_dense = int(config.get("first_k_dense_replace", 0)) expected_min_moe_layers = max(1, num_hidden_layers - first_k_dense) experts_per_group_new = target_experts // n_group audit_errors: List[str] = [] if len(moe_layer_ids) < expected_min_moe_layers: completed = selection_report.get("completed_stages", []) audit_errors.append( f"Bước 3 chưa hoàn tất! Mới cắt được {len(moe_layer_ids)}/{expected_min_moe_layers} tầng MoE " f"(completed_stages={completed}). Hãy chạy tiếp step3_streaming_surgery_colab.py (tự động resume)!" ) for layer_id in moe_layer_ids: # Xác định prefix thực tế của tầng trong all_specs (`layers.{L}`, `model.layers.{L}`, hoặc `mtp.{M}`) candidates = [ f"layers.{layer_id}", f"model.layers.{layer_id}", f"mtp.{layer_id - num_hidden_layers}", f"model.mtp.{layer_id - num_hidden_layers}", ] layer_prefix = None ffn_kind = "ffn" for cand in candidates: if f"{cand}.ffn.gate.weight" in all_specs: layer_prefix = cand ffn_kind = "ffn" break if f"{cand}.mlp.gate.weight" in all_specs: layer_prefix = cand ffn_kind = "mlp" break if layer_prefix is None: audit_errors.append(f"Tầng {layer_id}: Không tìm thấy biến gate.weight!") continue gate_key = f"{layer_prefix}.{ffn_kind}.gate.weight" g_shape, _ = all_specs[gate_key] if g_shape != [target_experts, hidden_size]: audit_errors.append( f"Tầng {layer_id}: Sai kích thước {gate_key} = {g_shape}, " f"kỳ vọng [{target_experts}, {hidden_size}]" ) for b_suffix in ("bias", "e_score_correction_bias"): bias_key = f"{layer_prefix}.{ffn_kind}.gate.{b_suffix}" if bias_key in all_specs: b_shape, _ = all_specs[bias_key] if b_shape != [target_experts]: audit_errors.append( f"Tầng {layer_id}: Sai kích thước {bias_key} = {b_shape}, " f"kỳ vọng [{target_experts}]" ) # Kiểm tra đủ đúng 128 ô (0..127) found_experts: Set[int] = set() exp_pat = re.compile( rf"^{re.escape(layer_prefix)}\.{ffn_kind}\.experts\.(\d+)\.(?:w1|gate_proj)\.weight$" ) for t_name in all_specs.keys(): m = exp_pat.match(t_name) if m: found_experts.add(int(m.group(1))) expected_experts = set(range(target_experts)) if found_experts != expected_experts: missing = expected_experts - found_experts extra = found_experts - expected_experts audit_errors.append( f"Tầng {layer_id} ({layer_prefix}): Danh sách ô không khớp 0..{target_experts - 1} " f"(Thiếu={sorted(missing)[:5]}, Thừa={sorted(extra)[:5]})" ) layer_info = selection_report["layers"][str(layer_id)] groups_detail = layer_info.get("groups_detail", []) if len(groups_detail) != n_group: audit_errors.append( f"Tầng {layer_id}: Số nhóm trong báo cáo ({len(groups_detail)}) != {n_group}" ) for g_item in groups_detail: if len(g_item["selected_16_old_ids"]) != experts_per_group_new: audit_errors.append( f"Tầng {layer_id} Nhóm {g_item['group_id']}: " f"Số ô được chọn != {experts_per_group_new}" ) for aux_file in AUXILIARY_MODEL_FILES: src_file = os.path.join(model_source, aux_file) dst_file = os.path.join(pruned_dir, aux_file) if os.path.isfile(src_file) and not os.path.isfile(dst_file): shutil.copy2(src_file, dst_file) quant_script_path = os.path.join(pruned_dir, "run_mixed_precision_quant_and_serve.sh") quant_script_content = f"""#!/usr/bin/env bash # ============================================================================== # KỊCH BẢN CHUYỂN ĐỔI & CHẠY THỰC CHIẾN DEEPSEEK-V4-PRO 128 Ô IT-CODER # ============================================================================== # Trong DeepSeek-V4-Pro: # - Cụm Attention (MLA + Compressor + Indexer) & Shared Experts đã ở chuẩn FP8 (e4m3fn + ue8m0) # - 128 Ô chuyên gia (ffn.experts.0..127) đã ở chuẩn siêu nén MXFP4 (e2m1fn_x2 + ue8m0)! # -> Nhờ vậy dung lượng toàn bộ 61 tầng sau khi cắt 384 -> 128 ô giảm ngay về ~300 GB # mà không cần nén lại làm giảm IQ! # ============================================================================== set -e PRUNED_MODEL_DIR="{os.path.abspath(pruned_dir)}" echo "[1/2] Chuyển đổi sang định dạng chạy trực tiếp (Model Parallelism) bằng inference/convert.py:" # python inference/convert.py \\ # --hf-ckpt-path "${{PRUNED_MODEL_DIR}}" \\ # --save-path "${{PRUNED_MODEL_DIR}}_mp" \\ # --n-experts {target_experts} \\ # --model-parallel 1 \\ # --expert-dtype fp4 echo "[2/2] Hoặc chạy với KTransformers / vLLM / SGLang:" # python inference/generate.py --ckpt-path "${{PRUNED_MODEL_DIR}}_mp" --config inference/config.json --interactive """ with open(quant_script_path, "w", encoding="utf-8") as f: f.write(quant_script_content) verification_summary = { "status": "PASSED" if len(audit_errors) == 0 else "FAILED", "total_tensors_indexed": len(weight_map), "total_shards": len(output_shard_files), "total_size_gb": round(total_size_bytes / (1024 ** 3), 4), "moe_layers_verified": len(moe_layer_ids), "target_routed_experts": target_experts, "n_group": n_group, "topk_group": topk_group, "audit_errors": audit_errors, } verify_path = os.path.join(pruned_dir, "verification_audit.json") with open(verify_path, "w", encoding="utf-8") as f: json.dump(verification_summary, f, indent=2, ensure_ascii=False) if hf_Output_repo and HfApi is not None: api = HfApi(token=hf_token) for fname in [ "config.json", "model.safetensors.index.json", "verification_audit.json", "run_mixed_precision_quant_and_serve.sh", ]: fpath = os.path.join(pruned_dir, fname) if os.path.isfile(fpath): api.upload_file( path_or_fileobj=fpath, path_in_repo=fname, repo_id=hf_Output_repo, repo_type="model", ) print("\n" + "=" * 76) print("[BÁO CÁO KIỂM ĐỊNH & ĐÓNG GÓI MÔ HÌNH CHUYÊN GIA IT-CODER 128 Ô]") print("=" * 76) print(f" - Trạng thái Kiểm định (Audit) : {verification_summary['status']}") print(f" - Tổng số biến Tensor lập chỉ mục: {verification_summary['total_tensors_indexed']:,} biến") print(f" - Tổng số tầng MoE đã kiểm tra : {verification_summary['moe_layers_verified']} tầng") print(f" - Cấu hình định tuyến mới : {target_experts} ô ({n_group} nhóm x {experts_per_group_new} ô)") print(f" - File mục lục mới : {new_index_path}") print(f" - File cấu hình mới : {new_cfg_path}") if audit_errors: print(" [!] Các lỗi phát hiện:") for err in audit_errors: print(f" - {err}") print("=" * 76) if audit_errors: raise AssertionError(f"Kiểm định thất bại với {len(audit_errors)} lỗi!") return verification_summary def parse_args(): parser = argparse.ArgumentParser( description="Bước 4: Đóng gói model.safetensors.index.json, cập nhật config.json và kiểm định." ) parser.add_argument( "--model-source", type=str, default="deepseek-ai/DeepSeek-V4-Pro", help="Hugging Face Repo ID hoặc thư mục chứa config.json gốc.", ) parser.add_argument( "--pruned-dir", type=str, default="./pruned_128_model", help="Thư mục chứa các file .safetensors đã phẫu thuật từ Bước 3.", ) parser.add_argument( "--target-experts", type=int, default=128, help="Số ô chuyên gia mỗi tầng sau phẫu thuật (mặc định: 128).", ) parser.add_argument( "--n-group", type=int, default=8, help="Số nhóm định tuyến (mặc định: 8).", ) parser.add_argument( "--topk-group", type=int, default=4, help="Số nhóm chọn mỗi token (mặc định: 4).", ) parser.add_argument( "--num-experts-per-tok", type=int, default=None, help="Số ô kích hoạt mỗi token (mặc định giữ nguyên theo model gốc: 6 cho V4-Pro, 8 cho V3).", ) parser.add_argument( "--push-to-hub", type=str, default="doandung/128-IT-Coder", help="Repo ID trên Hugging Face để upload config.json & model.safetensors.index.json.", ) parser.add_argument( "--hf-token", type=str, default=os.environ.get("HF_TOKEN", None), help="Hugging Face Token có quyền Write.", ) return parser.parse_args() if __name__ == "__main__": args = parse_args() finalize_and_verify_model( model_source=args.model_source, pruned_dir=args.pruned_dir, target_experts=args.target_experts, n_group=args.n_group, topk_group=args.topk_group, num_experts_per_tok=args.num_experts_per_tok, hf_Output_repo=args.push_to_hub, hf_token=args.hf_token, )