Download step3_streaming_surgery_colab.py from doandung/128-IT-Coder: direct link, hf CLI and curl.
- Browser
- Download file 83.5 kB
-
https://huggingface.co/doandung/128-IT-Coder/resolve/main/step3_streaming_surgery_colab.py
- Command line
-
hf download hf://doandung/128-IT-Coder/step3_streaming_surgery_colab.py
-
curl -L -o step3_streaming_surgery_colab.py https://huggingface.co/doandung/128-IT-Coder/resolve/main/step3_streaming_surgery_colab.py
83.5 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STEP 3: DÂY CHUYỀN PHẪU THUẬT CUỐN CHIẾU 61 TẦNG (DEEPSEEK-V4-PRO & V3/R1)
==========================================================================
Thực thi thuật toán "Streaming Surgery" & "Group-Aware Hybrid Peak-Energy"
tương thích 100% với cấu trúc thực tế của `deepseek-ai/DeepSeek-V4-Pro`:
1. Giải nén tức thời (On-the-fly) cả 2 chuẩn trọng số của DeepSeek-V4-Pro:
- Chuẩn FP8 (`float8_e4m3fn` + `.scale` kiểu `float8_e8m0fnu`, block 128x128)
dùng cho Attention (`wq_a`, `wq_b`, `wkv`, `wo_a`, `wo_b`) & `shared_experts`.
- Chuẩn FP4 (`int8` đóng gói 2 giá trị `e2m1fn` mỗi byte + `.scale` kiểu
`float8_e8m0fnu`, block 1x32) dùng cho 384 Ô chuyên gia (`w1`, `w2`, `w3`).
2. Hỗ trợ đầy đủ Hyper-Connections (`hc_mult = 4`, Sinkhorn-Knopp 20 vòng lặp),
hàm chấm điểm Router `sqrtsoftplus` (cũng như `sigmoid`/`softmax`),
Tầng Hash-MoE (`layers.0..2` với bảng ánh xạ `tid2eid`), Tầng Bias-MoE (`layers.3..60`)
và Tầng Dự đoán Đa từ MTP (`mtp.0`).
3. Tại mỗi tầng MoE:
- Chấm điểm chọn chính xác 16 ô/nhóm x 8 nhóm = 128 ô:
* 11 Ghế Đa Năng (Cumulative Weighted Energy, Luồng A nhân 2.5x).
* 5 Ghế Đặc Cách Logic Đỉnh Cao (Phân vị P99.5 trên HighLogicTokens).
- Cắt `ffn.gate.weight` -> [128, 7168], `ffn.gate.bias` -> [128].
- Ánh xạ lại bảng `ffn.gate.tid2eid` [129280, 6] (ở tầng 0, 1, 2) từ 0..383 -> 0..127.
- Đánh số lại 128 ô chiến thắng thành `experts.0` .. `experts.127` (giữ nguyên định dạng
nén FP4/FP8 gốc để không giảm chất lượng).
- Đẩy tự động từng tầng lên Hugging Face (`doandung/128-IT-Coder`), xóa ngay file tạm
cục bộ để ổ cứng Colab luôn giữ ở mức ~45 GB / 200 GB, hỗ trợ Auto-Resume.
"""
import os
import sys
import gc
import re
import json
import math
import time
import shutil
import argparse
from typing import Dict, List, Tuple, Optional, Set
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)
import torch
import torch.nn.functional as F
try:
from safetensors import safe_open
from safetensors.torch import save_file as _save_safetensors
except ImportError:
safe_open = None
_save_safetensors = None
try:
from huggingface_hub import hf_hub_download, HfApi
except ImportError:
hf_hub_download = None
HfApi = None
FP4_TABLE = torch.tensor(
[
0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
],
dtype=torch.float32,
)
def save_safetensors(tensors: Dict[str, torch.Tensor], filename: str) -> None:
"""Lưu file .safetensors chuẩn (hoặc fallback torch.save nếu môi trường thiếu safetensors)."""
if _save_safetensors is not None:
_save_safetensors(tensors, filename)
else:
torch.save(tensors, filename)
# ===========================================================================
# 1. GIẢI NÉN TỨC THỜI FP8 (E4M3 + E8M0) & FP4 (E2M1x2 + E8M0) CỦA DEEPSEEK-V4
# ===========================================================================
def dequantize_weight_auto(
weight: torch.Tensor,
scale: Optional[torch.Tensor] = None,
target_dtype: torch.dtype = torch.bfloat16,
fp8_block_size: int = 128,
fp4_block_size: int = 32,
) -> torch.Tensor:
"""
Tự động nhận diện và giải nén trọng số của DeepSeek-V4-Pro / V3 sang BFloat16/Float32:
- Trường hợp 1 (FP4 Expert Weight): `weight` kiểu `int8` hoặc `uint8` shape [M, N//2],
`scale` kiểu `float8_e8m0fnu` shape [M, N//32].
- Trường hợp 2 (FP8 Block-wise Weight): `weight` kiểu `float8_e4m3fn` shape [M, N],
`scale` kiểu `float8_e8m0fnu` hoặc `float32` shape [ceil(M/128), ceil(N/128)].
- Trường hợp 3 (BF16/FP32): Chuyển kiểu trực tiếp.
"""
if scale is None:
return weight.to(target_dtype)
# Trường hợp 1: Trọng số FP4 đóng gói 2 phần tử trong 1 byte (int8 / uint8)
if weight.dtype in (torch.int8, torch.uint8) and weight.dim() == 2:
out_dim, half_in_dim = weight.shape
in_dim = half_in_dim * 2
if scale.dim() == 2 and scale.shape[0] == out_dim and (
scale.shape[1] * fp4_block_size == in_dim
):
x_u8 = weight.view(torch.uint8)
low = (x_u8 & 0x0F).to(torch.long)
high = ((x_u8 >> 4) & 0x0F).to(torch.long)
table = FP4_TABLE.to(device=weight.device, dtype=target_dtype)
unpacked = torch.stack([table[low], table[high]], dim=-1).flatten(-2)
s_bf16 = scale.to(target_dtype).repeat_interleave(fp4_block_size, dim=-1)[
:, :in_dim
]
return unpacked * s_bf16
# Trường hợp 2: Trọng số FP8 Block-wise (128x128)
w_bf16 = weight.to(target_dtype)
s_bf16 = scale.to(target_dtype)
if w_bf16.dim() == 2 and s_bf16.dim() == 2:
M, N = w_bf16.shape
s_expanded = (
s_bf16.repeat_interleave(fp8_block_size, dim=0)
.repeat_interleave(fp8_block_size, dim=1)[:M, :N]
)
return w_bf16 * s_expanded
return w_bf16 * s_bf16
def get_dequantized_linear_weight(
tensors: Dict[str, torch.Tensor],
prefix: str,
device: str,
dtype: torch.dtype = torch.bfloat16,
cache: Optional[Dict[str, torch.Tensor]] = None,
) -> torch.Tensor:
"""Tìm `.weight` và `.scale` (hoặc `.weight_scale_inv`) để giải nén tức thời trên GPU (có cache theo tầng)."""
if cache is not None and prefix in cache:
return cache[prefix]
w_key = f"{prefix}.weight"
s_key_v4 = f"{prefix}.scale"
s_key_v3 = f"{prefix}.weight_scale_inv"
w = tensors[w_key].to(device)
if s_key_v4 in tensors:
s = tensors[s_key_v4].to(device)
elif s_key_v3 in tensors:
s = tensors[s_key_v3].to(device)
else:
s = None
deq = dequantize_weight_auto(w, s, target_dtype=dtype)
if cache is not None:
cache[prefix] = deq
return deq
def rms_norm(
x: torch.Tensor, weight: torch.Tensor, eps: float = 1e-6
) -> torch.Tensor:
"""Chuẩn hóa RMSNorm chính xác ở Float32."""
orig_dtype = x.dtype
x_fp32 = x.to(torch.float32)
variance = x_fp32.pow(2).mean(dim=-1, keepdim=True)
x_normed = x_fp32 * torch.rsqrt(variance + eps)
return (x_normed * weight.to(torch.float32)).to(orig_dtype)
# ===========================================================================
# 2. HYPER-CONNECTIONS (SINKHORN-KNOPP) CỦA DEEPSEEK-V4-PRO
# ===========================================================================
@torch.no_grad()
def hc_split_sinkhorn_pytorch(
mixes: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
hc_mult: int = 4,
sinkhorn_iters: int = 20,
eps: float = 1e-6,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Thực hiện chính xác thuật toán `hc_split_sinkhorn` của DeepSeek-V4-Pro bằng PyTorch thuần
(tương đương tuyệt đối với TileLang kernel trong `inference/kernel.py`).
"""
mixes_f = mixes.to(torch.float32)
s_f = hc_scale.to(torch.float32)
b_f = hc_base.to(torch.float32)
pre = torch.sigmoid(mixes_f[..., :hc_mult] * s_f[0] + b_f[:hc_mult]) + eps
post = 2.0 * torch.sigmoid(
mixes_f[..., hc_mult : 2 * hc_mult] * s_f[1] + b_f[hc_mult : 2 * hc_mult]
)
comb_raw = mixes_f[..., 2 * hc_mult :] * s_f[2] + b_f[2 * hc_mult :]
comb = comb_raw.unflatten(-1, (hc_mult, hc_mult))
comb = torch.softmax(comb, dim=-1) + eps
comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)
for _ in range(max(0, sinkhorn_iters - 1)):
comb = comb / (comb.sum(dim=-1, keepdim=True) + eps)
comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)
return pre, post, comb
@torch.no_grad()
def hc_pre_step(
x_hc: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
hc_mult: int = 4,
sinkhorn_iters: int = 20,
norm_eps: float = 1e-6,
hc_eps: float = 1e-6,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Gộp `hc_mult` luồng Hyper-Connections `[B, S, hc, D]` về `[B, S, D]`."""
shape = x_hc.shape
orig_dtype = x_hc.dtype
x_flat = x_hc.flatten(2).to(torch.float32) # [B, S, hc * D]
rsqrt = torch.rsqrt(x_flat.pow(2).mean(dim=-1, keepdim=True) + norm_eps)
mixes = F.linear(x_flat, hc_fn.to(torch.float32)) * rsqrt
pre, post, comb = hc_split_sinkhorn_pytorch(
mixes, hc_scale, hc_base, hc_mult=hc_mult, sinkhorn_iters=sinkhorn_iters, eps=hc_eps
)
y = torch.sum(pre.unsqueeze(-1) * x_hc.to(torch.float32).view(shape), dim=2)
return y.to(orig_dtype), post, comb
@torch.no_grad()
def hc_post_step(
x_single: torch.Tensor,
residual_hc: torch.Tensor,
post: torch.Tensor,
comb: torch.Tensor,
) -> torch.Tensor:
"""Mở rộng đầu ra `[B, S, D]` trở lại `[B, S, hc, D]` qua ma trận kết hợp Sinkhorn."""
orig_dtype = x_single.dtype
y = post.unsqueeze(-1) * x_single.to(torch.float32).unsqueeze(-2) + torch.sum(
comb.unsqueeze(-1) * residual_hc.to(torch.float32).unsqueeze(-2), dim=2
)
return y.to(orig_dtype)
def apply_rotary_pos_emb_simple(
q: torch.Tensor, k: torch.Tensor, rope_theta: float = 10000.0
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Áp dụng Rotary Position Embedding (RoPE) trên chiều cuối."""
head_dim = q.shape[-1]
if head_dim < 2:
return q, k
rot_dim = (head_dim // 2) * 2
seq_len = q.shape[1]
device = q.device
inv_freq = 1.0 / (
rope_theta
** (torch.arange(0, rot_dim, 2, device=device, dtype=torch.float32) / rot_dim)
)
t = torch.arange(seq_len, device=device, dtype=torch.float32)
freqs = torch.outer(t, inv_freq)
cos = torch.cos(freqs).unsqueeze(0).unsqueeze(2).to(q.dtype)
sin = torch.sin(freqs).unsqueeze(0).unsqueeze(2).to(q.dtype)
def _rotate(x: torch.Tensor) -> torch.Tensor:
is_3d = x.dim() == 3
if is_3d:
x = x.unsqueeze(2)
x_rot = x[..., :rot_dim]
x_pass = x[..., rot_dim:]
x1 = x_rot[..., 0::2]
x2 = x_rot[..., 1::2]
out1 = x1 * cos - x2 * sin
out2 = x1 * sin + x2 * cos
out = torch.stack([out1, out2], dim=-1).flatten(-2)
res = torch.cat([out, x_pass], dim=-1) if rot_dim < head_dim else out
return res.squeeze(2) if is_3d else res
return _rotate(q), _rotate(k)
# ===========================================================================
# 3. THUẬT TOÁN CHẤM ĐIỂM CHỌN 128 Ô: GROUP-AWARE HYBRID PEAK-ENERGY
# ===========================================================================
class GroupAwareExpertScorer:
"""
Bộ chấm điểm chọn 128/384 ô chuyên gia theo 8 Nhóm (`n_group = 8`):
- Trong mỗi nhóm 48 ô gốc, chọn đúng 16 ô:
* 11 Ghế Đa Năng: Tổng năng lượng có trọng số E_total(e) = sum(w_t * s_{t,e})
* 5 Ghế Đặc Cách Logic: Phân vị 99.5% (P99.5) trên các token thuộc HighLogicTokens
- Sắp xếp và đánh số lại liên tục từ 0..127 (Nhóm g sở hữu [16*g .. 16*g + 15]).
"""
def __init__(
self,
num_experts_old: int = 384,
n_group: int = 8,
general_quota_per_group: int = 11,
logic_quota_per_group: int = 5,
num_hist_bins: int = 2048,
device: str = "cpu",
):
self.num_experts_old = num_experts_old
self.n_group = n_group
self.general_quota = general_quota_per_group
self.logic_quota = logic_quota_per_group
self.experts_per_group_old = num_experts_old // n_group
self.experts_per_group_new = general_quota_per_group + logic_quota_per_group
self.target_experts = self.experts_per_group_new * n_group
self.num_hist_bins = num_hist_bins
self.device = device
self.cumulative_energy = torch.zeros(
num_experts_old, dtype=torch.float64, device=device
)
self.top8_hit_counts = torch.zeros(
num_experts_old, dtype=torch.int64, device=device
)
self.logic_hist = torch.zeros(
(num_experts_old, num_hist_bins), dtype=torch.int64, device=device
)
self.total_valid_tokens = 0
self.total_logic_tokens = 0
@torch.no_grad()
def update_batch(
self,
router_probs: torch.Tensor,
token_weights: torch.Tensor,
high_logic_mask: torch.Tensor,
attention_mask: torch.Tensor,
top_k: int = 6,
) -> None:
probs_flat = router_probs.reshape(-1, self.num_experts_old).to(torch.float32)
weights_flat = token_weights.reshape(-1).to(torch.float32)
logic_flat = high_logic_mask.reshape(-1).to(torch.bool)
valid_flat = attention_mask.reshape(-1).to(torch.bool)
if not valid_flat.any():
return
probs_valid = torch.clamp_min(probs_flat[valid_flat], 0.0)
weights_valid = weights_flat[valid_flat]
logic_valid = logic_flat[valid_flat]
self.total_valid_tokens += int(probs_valid.shape[0])
# 1. Cộng dồn Năng lượng có trọng số: E_total(e) += sum_t (w_t * s_{t, e})
weighted_sum = torch.matmul(weights_valid.unsqueeze(0), probs_valid).squeeze(0)
self.cumulative_energy += weighted_sum.to(self.device, dtype=torch.float64)
# Đếm tần suất lọt vào Top-K
_, topk_idx = torch.topk(
probs_valid, k=min(top_k, self.num_experts_old), dim=-1
)
ones = torch.ones_like(topk_idx, dtype=torch.int64)
hit_counts = torch.zeros(
self.num_experts_old, dtype=torch.int64, device=probs_valid.device
)
hit_counts.scatter_add_(0, topk_idx.reshape(-1), ones.reshape(-1))
self.top8_hit_counts += hit_counts.to(self.device)
# 2. Cập nhật Histogram phân vị P99.5 trên HighLogicTokens
if logic_valid.any():
logic_probs = probs_valid[logic_valid]
self.total_logic_tokens += int(logic_probs.shape[0])
max_val = max(1.0, float(logic_probs.max().item()))
normalized = torch.clamp(logic_probs / max_val, 0.0, 1.0)
bin_indices = torch.clamp(
(normalized * (self.num_hist_bins - 1)).to(torch.int64),
0,
self.num_hist_bins - 1,
)
bin_indices_t = bin_indices.t().contiguous().to(self.device)
src_ones = torch.ones_like(bin_indices_t, dtype=torch.int64)
self.logic_hist.scatter_add_(1, bin_indices_t, src_ones)
@torch.no_grad()
def compute_p995_scores(self) -> torch.Tensor:
if self.total_logic_tokens == 0:
return self.cumulative_energy.to(torch.float32)
cdf = torch.cumsum(self.logic_hist, dim=1)
total_per_expert = cdf[:, -1:].clamp_min(1)
threshold = total_per_expert * 0.995
mask_reached = cdf >= threshold
p995_bin = mask_reached.to(torch.int32).argmax(dim=1).to(torch.float32)
return p995_bin / float(self.num_hist_bins - 1)
@torch.no_grad()
def finalize_selection(self) -> dict:
e_total = self.cumulative_energy.cpu().tolist()
p995 = self.compute_p995_scores().cpu().tolist()
hits = self.top8_hit_counts.cpu().tolist()
selected_old_indices: List[int] = []
old_to_new_map: Dict[int, int] = {}
groups_report: List[dict] = []
for g in range(self.n_group):
g_start = g * self.experts_per_group_old
g_end = (g + 1) * self.experts_per_group_old
group_candidates = list(range(g_start, g_end))
# 11 Ghế Đa năng (Cumulative Weighted Energy)
sorted_by_energy = sorted(
group_candidates,
key=lambda eid: (e_total[eid], p995[eid]),
reverse=True,
)
general_winners = sorted_by_energy[: self.general_quota]
remaining_candidates = sorted_by_energy[self.general_quota :]
# 5 Ghế Đặc cách Logic (P99.5 trên HighLogicTokens)
sorted_by_logic_peak = sorted(
remaining_candidates,
key=lambda eid: (p995[eid], e_total[eid]),
reverse=True,
)
logic_winners = sorted_by_logic_peak[: self.logic_quota]
group_selected_sorted = sorted(general_winners + logic_winners)
assert len(group_selected_sorted) == self.experts_per_group_new
new_group_start = g * self.experts_per_group_new
for local_idx, old_eid in enumerate(group_selected_sorted):
new_eid = new_group_start + local_idx
selected_old_indices.append(old_eid)
old_to_new_map[old_eid] = new_eid
groups_report.append(
{
"group_id": g,
"old_range": [g_start, g_end - 1],
"new_range": [
new_group_start,
new_group_start + self.experts_per_group_new - 1,
],
"general_11_old_ids": sorted(general_winners),
"logic_peak_5_old_ids": sorted(logic_winners),
"selected_16_old_ids": group_selected_sorted,
}
)
assert len(selected_old_indices) == self.target_experts
return {
"num_experts_old": self.num_experts_old,
"num_experts_new": self.target_experts,
"n_group": self.n_group,
"total_valid_tokens": self.total_valid_tokens,
"total_logic_tokens": self.total_logic_tokens,
"selected_old_indices": selected_old_indices,
"old_to_new_map": {str(k): v for k, v in old_to_new_map.items()},
"groups_detail": groups_report,
"expert_metrics_summary": {
str(eid): {
"new_id": old_to_new_map[eid],
"cumulative_energy": round(e_total[eid], 4),
"p995_logic_score": round(p995[eid], 6),
"top_k_hits": hits[eid],
}
for eid in selected_old_indices
},
}
# ===========================================================================
# 4. BỘ QUẢN LÝ ĐỆM TÍN HIỆU KÉP TRÊN Ổ CỨNG (ACTIVATION BUFFER ~25GB)
# ===========================================================================
def quantize_activation_int8(
hidden_states: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Lượng tử hóa đối xứng 8-bit (`int8` + `float16` scale) theo chiều cuối."""
hs_fp32 = hidden_states.detach().to(torch.float32)
amax = hs_fp32.abs().amax(dim=-1, keepdim=True).clamp_min(1e-6)
scale = (amax / 127.0).to(torch.float16)
quantized = torch.clamp(
torch.round(hs_fp32 / scale.to(torch.float32)), -127, 127
).to(torch.int8)
return quantized, scale
def dequantize_activation_int8(
quantized: torch.Tensor,
scale: torch.Tensor,
dtype: torch.dtype = torch.bfloat16,
) -> torch.Tensor:
"""Giải nén tín hiệu 8-bit (`int8` + `float16` scale) về `dtype`."""
return quantized.to(dtype) * scale.to(dtype)
class ActivationBufferManager:
"""
Quản lý 2 bộ đệm luân phiên `buffer_A` và `buffer_B` trên SSD Colab:
- Hỗ trợ cả tensor 3 chiều `[B, S, D]` (V3/R1) lẫn tensor 4 chiều
Hyper-Connections `[B, S, hc_mult, D]` (DeepSeek-V4-Pro).
- Nén đối xứng 8-bit (`int8` + `float16` scale) để giữ trọn bộ đệm trong ~25 GB SSD.
"""
def __init__(self, base_dir: str, compress_8bit: bool = True):
self.base_dir = base_dir
self.compress_8bit = compress_8bit
self.dir_a = os.path.join(base_dir, "buffer_A")
self.dir_b = os.path.join(base_dir, "buffer_B")
os.makedirs(self.dir_a, exist_ok=True)
os.makedirs(self.dir_b, exist_ok=True)
def get_read_write_dirs(self, step_parity: int) -> Tuple[str, str]:
if step_parity % 2 == 0:
return self.dir_a, self.dir_b
return self.dir_b, self.dir_a
def save_chunk(
self, folder: str, chunk_idx: int, hidden_states: torch.Tensor
) -> str:
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, f"chunk_{chunk_idx:04d}.pt")
if self.compress_8bit:
hs_fp32 = hidden_states.detach().to(torch.float32)
amax = hs_fp32.abs().amax(dim=-1, keepdim=True).clamp_min(1e-6)
scale = (amax / 127.0).to(torch.float16)
quantized = torch.clamp(
torch.round(hs_fp32 / scale.to(torch.float32)), -127, 127
).to(torch.int8)
torch.save({"q": quantized.cpu(), "s": scale.cpu()}, path)
else:
torch.save({"bf16": hidden_states.detach().to(torch.bfloat16).cpu()}, path)
return path
def load_chunk(
self, folder: str, chunk_idx: int, device: str, dtype: torch.dtype = torch.bfloat16
) -> torch.Tensor:
path = os.path.join(folder, f"chunk_{chunk_idx:04d}.pt")
data = torch.load(path, map_location=device, weights_only=True)
if "q" in data:
return data["q"].to(dtype) * data["s"].to(dtype)
return data["bf16"].to(dtype)
# ===========================================================================
# 5. BỘ QUẢN LÝ TẢI & XÓA FILE SAFETENSORS (SMART SHARD CACHE)
# ===========================================================================
class SmartShardManager:
def __init__(
self,
model_source: str,
cache_dir: str,
hf_token: Optional[str] = None,
):
self.model_source = model_source
self.cache_dir = cache_dir
self.hf_token = hf_token
self.is_local_dir = os.path.isdir(model_source)
self.local_shard_paths: Dict[str, str] = {}
os.makedirs(cache_dir, exist_ok=True)
def ensure_shards_available(self, shard_filenames: List[str]) -> None:
for shard_name in shard_filenames:
if shard_name in self.local_shard_paths and os.path.isfile(
self.local_shard_paths[shard_name]
):
continue
if self.is_local_dir:
candidate = os.path.join(self.model_source, shard_name)
if not os.path.isfile(candidate):
raise FileNotFoundError(f"Không tìm thấy shard cục bộ: {candidate}")
self.local_shard_paths[shard_name] = candidate
else:
if hf_hub_download is None:
raise RuntimeError("Cần cài đặt `huggingface_hub` để tải shard từ Hub.")
print(f" [↓] Đang tải shard [{shard_name}] từ {self.model_source}...")
local_path = hf_hub_download(
repo_id=self.model_source,
filename=shard_name,
local_dir=self.cache_dir,
token=self.hf_token,
)
self.local_shard_paths[shard_name] = local_path
def load_specific_tensors(
self, tensors_map: Dict[str, str], filter_keys: Optional[Set[str]] = None
) -> Dict[str, torch.Tensor]:
by_shard: Dict[str, List[str]] = {}
for t_name, shard_name in tensors_map.items():
if filter_keys is not None and t_name not in filter_keys:
continue
by_shard.setdefault(shard_name, []).append(t_name)
self.ensure_shards_available(list(by_shard.keys()))
loaded: Dict[str, torch.Tensor] = {}
for shard_name, keys in by_shard.items():
shard_path = self.local_shard_paths[shard_name]
if safe_open is not None and shard_path.endswith(".safetensors"):
with safe_open(shard_path, framework="pt", device="cpu") as f:
for k in keys:
loaded[k] = f.get_tensor(k)
else:
state_dict = torch.load(shard_path, map_location="cpu", weights_only=True)
for k in keys:
loaded[k] = state_dict[k]
return loaded
def delete_finished_shards(self, shards_to_delete: List[str]) -> None:
if self.is_local_dir:
for s in shards_to_delete:
self.local_shard_paths.pop(s, None)
return
for s in shards_to_delete:
p = self.local_shard_paths.pop(s, None)
if p and os.path.isfile(p):
try:
os.remove(p)
print(f" [x] Đã xóa shard gốc [{s}] để giải phóng ổ cứng Colab.")
except OSError as e:
print(f" [!] Không thể xóa {p}: {e}")
# ===========================================================================
# 6. THỰC THI FORWARD CHO DEEPSEEK-V4-PRO (HC + MLA + SQRTSOFTPLUS MOE) & V3
# ===========================================================================
def detect_layer_prefix(tensors_keys: Set[str], layer_idx: int) -> str:
"""Tự động phát hiện tiền tố biến của tầng (`layers.{L}`, `model.layers.{L}`, hoặc `mtp.0`)."""
for k in tensors_keys:
if k.startswith(f"layers.{layer_idx}."):
return f"layers.{layer_idx}"
if k.startswith(f"model.layers.{layer_idx}."):
return f"model.layers.{layer_idx}"
m = re.match(r"^((?:model\.)?mtp\.\d+)\.", k)
if m:
return m.group(1)
return f"layers.{layer_idx}"
@torch.no_grad()
def forward_attention_v4_or_v3(
hidden_states: torch.Tensor,
layer_prefix: str,
attn_tensors: Dict[str, torch.Tensor],
config: dict,
device: str,
dtype: torch.dtype = torch.bfloat16,
dequant_cache: Optional[Dict[str, torch.Tensor]] = None,
) -> Tuple[torch.Tensor, torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]:
"""
Thực thi khối Attention + Chuẩn bị đầu vào cho FFN/MoE:
- Hỗ trợ đầy đủ kiến trúc DeepSeek-V4-Pro (`hc_attn_*`, `attn.wq_a`, `wq_b`, `wkv`,
`wo_a`, `wo_b`, `hc_ffn_*`, `ffn_norm`) với dòng tín hiệu 4 luồng `[B, S, hc_mult, D]`.
- Đồng thời tương thích ngược với DeepSeek-V3/R1 (`input_layernorm`, `self_attn`,
`post_attention_layernorm`) với dòng tín hiệu `[B, S, D]`.
"""
eps = float(config.get("rms_norm_eps", 1e-6))
hc_eps = float(config.get("hc_eps", 1e-6))
hc_mult = int(config.get("hc_mult", 1))
sinkhorn_iters = int(config.get("hc_sinkhorn_iters", 20))
num_heads = int(config.get("num_attention_heads", 128))
rope_theta = float(config.get("rope_theta", 10000.0))
is_v4_hc = f"{layer_prefix}.hc_attn_fn" in attn_tensors
# --- Bước 1: Tiền xử lý Hyper-Connections (V4-Pro) hoặc Input LayerNorm (V3) ---
if is_v4_hc:
hs_hc = hidden_states.to(device, dtype=dtype)
if hs_hc.dim() == 3:
hs_hc = hs_hc.unsqueeze(2).repeat(1, 1, hc_mult, 1)
x_attn_in, post_attn, comb_attn = hc_pre_step(
hs_hc,
attn_tensors[f"{layer_prefix}.hc_attn_fn"].to(device),
attn_tensors[f"{layer_prefix}.hc_attn_scale"].to(device),
attn_tensors[f"{layer_prefix}.hc_attn_base"].to(device),
hc_mult=hc_mult,
sinkhorn_iters=sinkhorn_iters,
norm_eps=eps,
hc_eps=hc_eps,
)
attn_norm_w = attn_tensors[f"{layer_prefix}.attn_norm.weight"].to(device, dtype=dtype)
normed_in = rms_norm(x_attn_in, attn_norm_w, eps=eps)
attn_prefix = f"{layer_prefix}.attn"
else:
hs_single = hidden_states.to(device, dtype=dtype)
norm_key = (
f"{layer_prefix}.input_layernorm.weight"
if f"{layer_prefix}.input_layernorm.weight" in attn_tensors
else f"{layer_prefix}.attn_norm.weight"
)
in_norm_w = attn_tensors[norm_key].to(device, dtype=dtype)
normed_in = rms_norm(hs_single, in_norm_w, eps=eps)
attn_prefix = (
f"{layer_prefix}.self_attn"
if f"{layer_prefix}.self_attn.q_proj.weight" in attn_tensors
or f"{layer_prefix}.self_attn.q_a_proj.weight" in attn_tensors
else f"{layer_prefix}.attn"
)
B, S, D = normed_in.shape
# --- Bước 2: Chạy Attention (DeepSeek-V4-Pro MQA-Latent + Grouped wo_a/wo_b hoặc V3 MLA) ---
if f"{attn_prefix}.wq_a.weight" in attn_tensors and f"{attn_prefix}.wkv.weight" in attn_tensors:
head_dim = int(config.get("head_dim", 512))
rope_dim = int(config.get("qk_rope_head_dim", 64))
o_groups = int(config.get("o_groups", 16))
o_lora_rank = int(config.get("o_lora_rank", 1024))
wq_a = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.wq_a", device, dtype, cache=dequant_cache
)
q_norm_w = attn_tensors[f"{attn_prefix}.q_norm.weight"].to(device, dtype=dtype)
wq_b = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.wq_b", device, dtype, cache=dequant_cache
)
qr = rms_norm(F.linear(normed_in, wq_a), q_norm_w, eps=eps)
q = F.linear(qr, wq_b).view(B, S, num_heads, head_dim)
q = q * torch.rsqrt(q.to(torch.float32).pow(2).mean(dim=-1, keepdim=True) + eps).to(dtype)
wkv = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.wkv", device, dtype, cache=dequant_cache
)
kv_norm_w = attn_tensors[f"{attn_prefix}.kv_norm.weight"].to(device, dtype=dtype)
kv = rms_norm(F.linear(normed_in, wkv), kv_norm_w, eps=eps)
q_pe, kv_pe = apply_rotary_pos_emb_simple(
q[..., -rope_dim:], kv[..., -rope_dim:], rope_theta=rope_theta
)
q = torch.cat([q[..., :-rope_dim], q_pe], dim=-1)
kv = torch.cat([kv[..., :-rope_dim], kv_pe], dim=-1)
q_t = q.transpose(1, 2).to(torch.float32)
kv_t = kv.unsqueeze(1).to(torch.float32)
scale_factor = head_dim ** -0.5
scores = torch.matmul(q_t, kv_t.transpose(-1, -2)) * scale_factor
causal_mask = torch.triu(
torch.ones(S, S, device=device, dtype=torch.bool), diagonal=1
)
scores = scores.masked_fill(causal_mask.view(1, 1, S, S), float("-inf"))
if f"{attn_prefix}.attn_sink" in attn_tensors:
sink = attn_tensors[f"{attn_prefix}.attn_sink"].to(device, dtype=torch.float32)
sink_col = sink.view(1, num_heads, 1, 1).expand(B, num_heads, S, 1)
scores_with_sink = torch.cat([scores, sink_col], dim=-1)
probs = torch.softmax(scores_with_sink, dim=-1)[..., :S]
else:
probs = torch.softmax(scores, dim=-1)
o = torch.matmul(probs.to(dtype), kv_t.to(dtype)).transpose(1, 2).contiguous()
o_pe_inv, _ = apply_rotary_pos_emb_simple(
o[..., -rope_dim:], o[..., -rope_dim:], rope_theta=rope_theta
)
o = torch.cat([o[..., :-rope_dim], o_pe_inv], dim=-1)
o_grouped = o.view(B, S, o_groups, -1)
wo_a_full = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.wo_a", device, dtype, cache=dequant_cache
)
wo_a = wo_a_full.view(o_groups, o_lora_rank, -1)
o_proj_mid = torch.einsum("bsgd,grd->bsgr", o_grouped, wo_a).flatten(2)
wo_b = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.wo_b", device, dtype, cache=dequant_cache
)
attn_out = F.linear(o_proj_mid, wo_b)
else:
if f"{attn_prefix}.q_a_proj.weight" in attn_tensors:
wq_a = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.q_a_proj", device, dtype, cache=dequant_cache
)
q_latent = F.linear(normed_in, wq_a)
if f"{attn_prefix}.q_a_layernorm.weight" in attn_tensors:
wq_norm = attn_tensors[f"{attn_prefix}.q_a_layernorm.weight"].to(device, dtype=dtype)
q_latent = rms_norm(q_latent, wq_norm, eps=eps)
wq_b = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.q_b_proj", device, dtype, cache=dequant_cache
)
q_all = F.linear(q_latent, wq_b)
else:
wq = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.q_proj", device, dtype, cache=dequant_cache
)
q_all = F.linear(normed_in, wq)
if f"{attn_prefix}.kv_a_proj_with_mqa.weight" in attn_tensors:
kv_lora_rank = int(config.get("kv_lora_rank", 512))
qk_nope_dim = int(config.get("qk_nope_head_dim", 128))
qk_rope_dim = int(config.get("qk_rope_head_dim", 64))
v_head_dim = int(config.get("v_head_dim", 128))
wkv_a = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.kv_a_proj_with_mqa", device, dtype, cache=dequant_cache
)
kv_compressed = F.linear(normed_in, wkv_a)
c_kv = kv_compressed[..., :kv_lora_rank]
k_pe_shared = kv_compressed[..., kv_lora_rank:]
if f"{attn_prefix}.kv_a_layernorm.weight" in attn_tensors:
wkv_norm = attn_tensors[f"{attn_prefix}.kv_a_layernorm.weight"].to(device, dtype=dtype)
c_kv = rms_norm(c_kv, wkv_norm, eps=eps)
wkv_b = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.kv_b_proj", device, dtype, cache=dequant_cache
)
kv_full = F.linear(c_kv, wkv_b).view(B, S, num_heads, qk_nope_dim + v_head_dim)
k_nope = kv_full[..., :qk_nope_dim]
v_states = kv_full[..., qk_nope_dim:]
q_head_dim = q_all.shape[-1] // num_heads
q_states = q_all.view(B, S, num_heads, q_head_dim)
if q_head_dim == qk_nope_dim + qk_rope_dim and k_pe_shared.shape[-1] == qk_rope_dim:
q_nope = q_states[..., :qk_nope_dim]
q_pe = q_states[..., qk_nope_dim:]
k_pe = k_pe_shared.unsqueeze(2).expand(B, S, num_heads, qk_rope_dim)
q_pe, k_pe = apply_rotary_pos_emb_simple(q_pe, k_pe, rope_theta=rope_theta)
q_states = torch.cat([q_nope, q_pe], dim=-1)
k_states = torch.cat([k_nope, k_pe], dim=-1)
else:
k_states = k_nope
else:
q_states = q_all.view(B, S, 1, -1)
k_states = q_states
v_states = q_states
attn_out = F.scaled_dot_product_attention(
q_states.transpose(1, 2),
k_states.transpose(1, 2),
v_states.transpose(1, 2),
is_causal=True,
).transpose(1, 2).contiguous().view(B, S, -1)
if f"{attn_prefix}.o_proj.weight" in attn_tensors:
wo = get_dequantized_linear_weight(
attn_tensors, f"{attn_prefix}.o_proj", device, dtype, cache=dequant_cache
)
attn_out = F.linear(attn_out, wo)
# --- Bước 3: Hậu xử lý Hyper-Connections (V4-Pro) hoặc Residual + Post-Attn Norm (V3) ---
if is_v4_hc:
hs_after_attn = hc_post_step(attn_out, hs_hc, post_attn, comb_attn)
x_ffn_in, post_ffn, comb_ffn = hc_pre_step(
hs_after_attn,
attn_tensors[f"{layer_prefix}.hc_ffn_fn"].to(device),
attn_tensors[f"{layer_prefix}.hc_ffn_scale"].to(device),
attn_tensors[f"{layer_prefix}.hc_ffn_base"].to(device),
hc_mult=hc_mult,
sinkhorn_iters=sinkhorn_iters,
norm_eps=eps,
hc_eps=hc_eps,
)
ffn_norm_w = attn_tensors[f"{layer_prefix}.ffn_norm.weight"].to(device, dtype=dtype)
normed_for_ffn = rms_norm(x_ffn_in, ffn_norm_w, eps=eps)
return hs_after_attn, normed_for_ffn, (hs_after_attn, post_ffn, comb_ffn)
else:
post_attn_res = hidden_states.to(device, dtype=dtype) + attn_out
post_norm_key = (
f"{layer_prefix}.post_attention_layernorm.weight"
if f"{layer_prefix}.post_attention_layernorm.weight" in attn_tensors
else f"{layer_prefix}.ffn_norm.weight"
)
post_norm_w = attn_tensors[post_norm_key].to(device, dtype=dtype)
normed_for_ffn = rms_norm(post_attn_res, post_norm_w, eps=eps)
return post_attn_res, normed_for_ffn, None
@torch.no_grad()
def forward_swiglu_expert(
x: torch.Tensor,
tensors: Dict[str, torch.Tensor],
expert_prefix: str,
device: str,
swiglu_limit: float = 0.0,
dtype: torch.dtype = torch.bfloat16,
dequant_cache: Optional[Dict[str, torch.Tensor]] = None,
) -> torch.Tensor:
"""
Tính toán 1 khối SwiGLU Expert hỗ trợ cả chuẩn tên biến của DeepSeek-V4-Pro (`w1`, `w2`, `w3`
với `swiglu_limit = 10.0`) và chuẩn tên biến của DeepSeek-V3 (`gate_proj`, `down_proj`, `up_proj`).
"""
if f"{expert_prefix}.w1.weight" in tensors:
w1 = get_dequantized_linear_weight(
tensors, f"{expert_prefix}.w1", device, dtype, cache=dequant_cache
)
w2 = get_dequantized_linear_weight(
tensors, f"{expert_prefix}.w2", device, dtype, cache=dequant_cache
)
w3 = get_dequantized_linear_weight(
tensors, f"{expert_prefix}.w3", device, dtype, cache=dequant_cache
)
else:
w1 = get_dequantized_linear_weight(
tensors, f"{expert_prefix}.gate_proj", device, dtype, cache=dequant_cache
)
w2 = get_dequantized_linear_weight(
tensors, f"{expert_prefix}.down_proj", device, dtype, cache=dequant_cache
)
w3 = get_dequantized_linear_weight(
tensors, f"{expert_prefix}.up_proj", device, dtype, cache=dequant_cache
)
gate = F.linear(x, w1).to(torch.float32)
up = F.linear(x, w3).to(torch.float32)
if swiglu_limit > 0.0:
up = torch.clamp(up, min=-swiglu_limit, max=swiglu_limit)
gate = torch.clamp(gate, max=swiglu_limit)
act = (F.silu(gate) * up).to(dtype)
return F.linear(act, w2)
@torch.no_grad()
def compute_router_scores(
normed_hidden: torch.Tensor,
gate_weight: torch.Tensor,
scoring_func: str = "sqrtsoftplus",
) -> torch.Tensor:
"""
Tính điểm kích hoạt gốc của Router:
- DeepSeek-V4-Pro (`sqrtsoftplus`): sqrt(softplus(x @ gate_weight.T))
- DeepSeek-V3/R1 (`sigmoid`) : sigmoid(x @ gate_weight.T)
- Chuẩn `softmax` : softmax(x @ gate_weight.T)
"""
logits = F.linear(normed_hidden.to(torch.float32), gate_weight.to(torch.float32))
if scoring_func == "sqrtsoftplus":
return F.softplus(logits).sqrt()
elif scoring_func == "softmax":
return torch.softmax(logits, dim=-1)
return torch.sigmoid(logits)
@torch.no_grad()
def route_tokens_v4_or_v3(
normed_hidden: torch.Tensor,
gate_weight: torch.Tensor,
correction_bias: Optional[torch.Tensor] = None,
tid2eid: Optional[torch.Tensor] = None,
input_ids: Optional[torch.Tensor] = None,
scoring_func: str = "sqrtsoftplus",
n_group: int = 8,
topk_group: int = 4,
top_k: int = 6,
routed_scaling_factor: float = 2.5,
norm_topk_prob: bool = True,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Định tuyến Token qua các Ô chuyên gia (hỗ trợ cả Hash-Routing `tid2eid` của Tầng 0..2 V4-Pro,
Learned-Bias Routing của Tầng 3..60 V4-Pro, và Group-Limited Routing của V3/R1).
"""
orig_shape = normed_hidden.shape
x_flat = normed_hidden.reshape(-1, orig_shape[-1]).to(torch.float32)
num_tokens = x_flat.shape[0]
num_experts = gate_weight.shape[0]
original_scores = compute_router_scores(x_flat, gate_weight, scoring_func=scoring_func)
if tid2eid is not None and input_ids is not None:
flat_ids = input_ids.reshape(-1).to(device=tid2eid.device, dtype=torch.long)
flat_ids = torch.clamp(flat_ids, 0, tid2eid.shape[0] - 1)
topk_indices = tid2eid[flat_ids].to(device=x_flat.device, dtype=torch.long)
topk_indices = torch.clamp(topk_indices, 0, num_experts - 1)
else:
scores_for_choice = (
original_scores + correction_bias.to(torch.float32).unsqueeze(0)
if correction_bias is not None
else original_scores
)
if n_group > 1 and topk_group < n_group and num_experts % n_group == 0:
experts_per_group = num_experts // n_group
grouped_scores = scores_for_choice.view(num_tokens, n_group, experts_per_group)
top2_in_group = torch.topk(
grouped_scores, k=min(2, experts_per_group), dim=-1, sorted=False
).values.sum(dim=-1)
group_idx = torch.topk(
top2_in_group, k=min(topk_group, n_group), dim=-1, sorted=False
).indices
group_mask = torch.zeros_like(top2_in_group, dtype=torch.bool)
group_mask.scatter_(1, group_idx, True)
score_mask = (
group_mask.unsqueeze(-1)
.expand(num_tokens, n_group, experts_per_group)
.reshape(num_tokens, num_experts)
)
masked_scores = scores_for_choice.masked_fill(~score_mask, float("-inf"))
else:
masked_scores = scores_for_choice
actual_k = min(top_k, num_experts)
topk_indices = torch.topk(masked_scores, k=actual_k, dim=-1, sorted=False).indices
topk_weights = original_scores.gather(1, topk_indices)
if norm_topk_prob and scoring_func != "softmax":
denom = topk_weights.sum(dim=-1, keepdim=True).clamp_min(1e-20)
topk_weights = topk_weights / denom
topk_weights = topk_weights * routed_scaling_factor
return original_scores, topk_indices, topk_weights.to(normed_hidden.dtype)
# ===========================================================================
# 7. ÁNH XẠ BẢNG HASH `tid2eid` [129280, 6] & CẮT BIẾN SAFETENSORS (384 -> 128 Ô)
# ===========================================================================
@torch.no_grad()
def remap_hash_tid2eid_table(
tid2eid: torch.Tensor,
gate_weight: torch.Tensor,
selected_old_indices: List[int],
old_to_new_map: Dict[int, int],
n_group: int = 8,
) -> torch.Tensor:
"""
Ánh xạ bảng định tuyến băm `tid2eid` (shape `[vocab_size, 6]`, chứa chỉ số ô cũ `0..383`)
của các tầng Hash-MoE (`layers.0, 1, 2` trong DeepSeek-V4-Pro) sang hệ chỉ số mới `0..127`:
- Nếu ô `old_eid` thuộc 128 ô được giữ lại -> ánh xạ trực tiếp sang `new_id = old_to_new_map[old_eid]`.
- Nếu ô `old_eid` thuộc 256 ô bị cắt -> ánh xạ sang ô được giữ lại trong CÙNG NHÓM
có vector `gate.weight` tương đồng Cosine cao nhất với `gate.weight[old_eid]`.
"""
num_old = gate_weight.shape[0]
w_norm = F.normalize(gate_weight.to(torch.float32), p=2, dim=-1)
selected_tensor = torch.tensor(
selected_old_indices, dtype=torch.long, device=gate_weight.device
)
w_selected = w_norm.index_select(0, selected_tensor) # [128, D]
# Tính ma trận tương đồng Cosine [384, 128]
sim_matrix = torch.matmul(w_norm, w_selected.t())
experts_per_group_old = num_old // n_group
experts_per_group_new = len(selected_old_indices) // n_group
lookup = torch.zeros(num_old, dtype=torch.int32, device=gate_weight.device)
for old_eid in range(num_old):
if old_eid in old_to_new_map:
lookup[old_eid] = int(old_to_new_map[old_eid])
else:
# Ưu tiên chọn ô thay thế nằm trong cùng nhóm g để giữ cấu trúc 8 nhóm
g = old_eid // experts_per_group_old
new_g_start = g * experts_per_group_new
new_g_end = (g + 1) * experts_per_group_new
best_local = int(sim_matrix[old_eid, new_g_start:new_g_end].argmax().item())
lookup[old_eid] = new_g_start + best_local
tid2eid_clamped = torch.clamp(tid2eid.to(gate_weight.device, dtype=torch.long), 0, num_old - 1)
remapped = lookup[tid2eid_clamped].to(torch.int32).cpu()
return remapped
def slice_and_build_pruned_layer_state_dict(
layer_prefix: str,
full_layer_tensors: Dict[str, torch.Tensor],
selected_old_indices: List[int],
old_to_new_map: Dict[int, int],
n_group: int = 8,
) -> Dict[str, torch.Tensor]:
"""
Phẫu thuật cắt các biến Tensor của Tầng MoE (hỗ trợ cả DeepSeek-V4-Pro `ffn.*` và V3 `mlp.*`):
- Giữ nguyên 100%: `hc_*`, `attn.*` / `self_attn.*`, `attn_norm` / `input_layernorm`,
`ffn_norm` / `post_attention_layernorm`, `shared_experts.*`
- Cắt `gate.weight`: [384, 7168] -> [128, 7168]
- Cắt `gate.bias` / `gate.e_score_correction_bias`: [384] -> [128]
- Ánh xạ lại `gate.tid2eid`: [129280, 6] từ miền [0..383] -> [0..127]
- Đổi tên 128 ô được chọn từ `experts.{old_id}.*` -> `experts.{0..127}.*` (bảo toàn cả
`.weight` FP4/FP8 lẫn `.scale` / `.weight_scale_inv`).
"""
pruned_state: Dict[str, torch.Tensor] = {}
idx_tensor = torch.tensor(selected_old_indices, dtype=torch.long)
# Tìm khóa gate.weight để phục vụ remap tid2eid nếu có
gate_w_tensor = None
for k, v in full_layer_tensors.items():
if k.endswith(".gate.weight"):
gate_w_tensor = v
break
exp_pattern = re.compile(
rf"^{re.escape(layer_prefix)}\.(mlp|ffn)\.experts\.(\d+)\.(.+)$"
)
for key, tensor in full_layer_tensors.items():
if key.endswith(".gate.weight"):
pruned_state[key] = tensor.index_select(0, idx_tensor).contiguous()
elif key.endswith(".gate.bias") or key.endswith(".gate.e_score_correction_bias"):
pruned_state[key] = tensor.index_select(0, idx_tensor).contiguous()
elif key.endswith(".gate.scale") or key.endswith(".gate.weight_scale_inv"):
if gate_w_tensor is not None and tensor.shape[0] == gate_w_tensor.shape[0]:
pruned_state[key] = tensor.index_select(0, idx_tensor).contiguous()
else:
pruned_state[key] = tensor.contiguous()
elif key.endswith(".gate.tid2eid") and gate_w_tensor is not None:
pruned_state[key] = remap_hash_tid2eid_table(
tid2eid=tensor,
gate_weight=gate_w_tensor,
selected_old_indices=selected_old_indices,
old_to_new_map=old_to_new_map,
n_group=n_group,
).contiguous()
else:
m_exp = exp_pattern.match(key)
if m_exp:
ffn_kind = m_exp.group(1)
old_eid = int(m_exp.group(2))
suffix = m_exp.group(3)
if old_eid in old_to_new_map:
new_eid = old_to_new_map[old_eid]
new_key = f"{layer_prefix}.{ffn_kind}.experts.{new_eid}.{suffix}"
pruned_state[new_key] = tensor.contiguous()
else:
pruned_state[key] = tensor.contiguous()
return pruned_state
# ===========================================================================
# 8. ENGINE ĐIỀU PHỐI CUỐN CHIẾU TOÀN BỘ CÁC TẦNG + AUTO-RESUME CHECKPOINT
# ===========================================================================
def run_streaming_surgery(
model_source: str,
schedule_path: str = "./surgery_schedule.json",
calibration_path: str = "./calibration_data/calibration_6500_it.pt",
output_dir: str = "./pruned_128_model",
buffer_dir: str = "./activation_buffer",
cache_dir: str = "./hf_cache",
batch_size: int = 25,
device: Optional[str] = None,
hf_Output_repo: Optional[str] = None,
hf_token: Optional[str] = None,
compress_activations: bool = True,
) -> dict:
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
os.makedirs(output_dir, exist_ok=True)
os.makedirs(buffer_dir, exist_ok=True)
with open(schedule_path, "r", encoding="utf-8") as f:
schedule = json.load(f)
local_cfg_path = os.path.join(model_source, "config.json")
if os.path.isfile(local_cfg_path):
with open(local_cfg_path, "r", encoding="utf-8") as f:
config = json.load(f)
else:
cfg_file = hf_hub_download(
repo_id=model_source, filename="config.json", cache_dir=cache_dir, token=hf_token
)
with open(cfg_file, "r", encoding="utf-8") as f:
config = json.load(f)
arch = schedule["architecture_summary"]
n_group = int(arch["n_group"])
topk_group = int(arch["topk_group"])
top_k = int(arch["num_experts_per_tok"])
general_quota = int(arch["general_quota_per_group"])
logic_quota = int(arch["logic_quota_per_group"])
scoring_func = str(config.get("scoring_func", arch.get("scoring_func", "sqrtsoftplus")))
routed_scaling = float(config.get("routed_scaling_factor", 2.5))
norm_topk_prob = bool(config.get("norm_topk_prob", True))
swiglu_limit = float(config.get("swiglu_limit", 0.0))
hc_mult = int(config.get("hc_mult", 1))
calib = torch.load(calibration_path, map_location="cpu", weights_only=True)
input_ids_all: torch.Tensor = calib["input_ids"]
attn_mask_all: torch.Tensor = calib["attention_mask"]
token_weights_all: torch.Tensor = calib["token_weights"]
high_logic_all: torch.Tensor = calib["high_logic_mask"]
num_samples = input_ids_all.shape[0]
num_chunks = math.ceil(num_samples / batch_size)
report_path = os.path.join(output_dir, "expert_selection_report.json")
if not os.path.isfile(report_path) and hf_Output_repo and hf_hub_download is not None:
try:
print(
f"[*] Đang kiểm tra Checkpoint `expert_selection_report.json` trên Hugging Face ({hf_Output_repo})..."
)
downloaded_rep = hf_hub_download(
repo_id=hf_Output_repo,
filename="expert_selection_report.json",
local_dir=output_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 os.path.isfile(report_path):
with open(report_path, "r", encoding="utf-8") as f:
selection_report = json.load(f)
print(
f"[*] Phát hiện Checkpoint tại {report_path}: "
f"Đã hoàn thành {len(selection_report.get('completed_stages', []))} giai đoạn."
)
else:
selection_report = {
"model_source": model_source,
"target_routed_experts": arch["target_routed_experts"],
"n_group": n_group,
"completed_stages": [],
"output_shard_files": {},
"shard_manifests": {},
"layers": {},
}
if "shard_manifests" not in selection_report:
selection_report["shard_manifests"] = {}
buffer_mgr = ActivationBufferManager(
base_dir=buffer_dir, compress_8bit=compress_activations
)
shard_mgr = SmartShardManager(
model_source=model_source, cache_dir=cache_dir, hf_token=hf_token
)
hf_api = HfApi(token=hf_token) if (hf_Output_repo and HfApi is not None) else None
if hf_api is not None:
hf_api.create_repo(repo_id=hf_Output_repo, repo_type="model", exist_ok=True)
stage_plans = schedule["stage_plans"]
total_stages = len(stage_plans)
parity = 0
for st_idx, stage in enumerate(stage_plans):
st_name = stage["stage_name"]
layer_id = stage["layer_id"]
layer_type = stage["layer_type"]
tensors_map: Dict[str, str] = stage["tensors_map"]
out_shard_name = stage.get(
"primary_output_shard", f"model-layer-{layer_id:02d}-of-61.safetensors"
)
read_dir, write_dir = buffer_mgr.get_read_write_dirs(parity)
if st_name in selection_report["completed_stages"]:
print(f"[Skip] Giai đoạn [{st_name}] đã hoàn thành trong Checkpoint trước.")
if layer_type in ("embedding", "dense", "hash_moe", "moe"):
parity += 1
shard_mgr.delete_finished_shards(stage["shards_safe_to_delete"])
continue
# Nếu nối lại (Resume) trên một máy ảo Colab mới tinh (ổ cứng `/content/activation_buffer` trống),
# tự động khởi tạo bộ đệm `read_dir` từ tầng `embed` (1.85 GB, mất ~10 giây) để bắt đầu ngay từ tầng hiện tại
# mà KHÔNG cần tải lại các tầng MoE 13.5 GB đã cắt xong!
if layer_type in ("dense", "hash_moe", "moe", "mtp_moe") and not os.path.isfile(
os.path.join(read_dir, "chunk_0000.pt")
):
print(
f"[*] Phát hiện Resume từ [{st_name}] trên phiên Colab mới (chưa có activation_buffer). "
f"Đang khởi tạo nhanh bộ đệm tín hiệu đầu vào (~10s) để nhảy thẳng tới [{st_name}]...",
flush=True,
)
emb_stage = stage_plans[0]
emb_tensors_init = shard_mgr.load_specific_tensors(emb_stage["tensors_map"])
emb_key_init = next(
k
for k in emb_tensors_init.keys()
if k == "embed.weight" or "embed_tokens.weight" in k
)
emb_w_init = emb_tensors_init[emb_key_init].to(device, dtype=torch.bfloat16)
for c_idx in range(num_chunks):
s_i = c_idx * batch_size
e_i = min(num_samples, (c_idx + 1) * batch_size)
ids_batch = input_ids_all[s_i:e_i].to(device, dtype=torch.long)
ids_batch = torch.clamp(ids_batch, 0, emb_w_init.shape[0] - 1)
hs_batch = F.embedding(ids_batch, emb_w_init)
if hc_mult > 1:
hs_batch = hs_batch.unsqueeze(2).repeat(1, 1, hc_mult, 1)
buffer_mgr.save_chunk(read_dir, c_idx, hs_batch)
del emb_tensors_init, emb_w_init
shard_mgr.delete_finished_shards(emb_stage["shards_safe_to_delete"])
if str(device).startswith("cuda") and torch.cuda.is_available():
torch.cuda.empty_cache()
t0 = time.time()
print(
f"\n[{st_idx + 1}/{total_stages}] Đang xử lý [{st_name}] -> [{out_shard_name}] "
f"(type={layer_type}, tensors={len(tensors_map)})..."
)
# -------------------------------------------------------------------
# TRƯỜNG HỢP A: TẦNG NHÚNG TỪ VỰNG (`embed.weight` / `embed_tokens`)
# -------------------------------------------------------------------
if layer_type == "embedding":
emb_tensors = shard_mgr.load_specific_tensors(tensors_map)
emb_key = next(
k for k in emb_tensors.keys() if k == "embed.weight" or "embed_tokens.weight" in k
)
emb_weight = emb_tensors[emb_key].to(device, dtype=torch.bfloat16)
for c_idx in range(num_chunks):
s_i = c_idx * batch_size
e_i = min(num_samples, (c_idx + 1) * batch_size)
ids_batch = input_ids_all[s_i:e_i].to(device, dtype=torch.long)
ids_batch = torch.clamp(ids_batch, 0, emb_weight.shape[0] - 1)
hs_batch = F.embedding(ids_batch, emb_weight)
if hc_mult > 1:
# Khởi tạo hc_mult bản sao cho Hyper-Connections của DeepSeek-V4-Pro
hs_batch = hs_batch.unsqueeze(2).repeat(1, 1, hc_mult, 1)
buffer_mgr.save_chunk(write_dir, c_idx, hs_batch)
out_shard_path = os.path.join(output_dir, out_shard_name)
save_safetensors(emb_tensors, out_shard_path)
selection_report["output_shard_files"][st_name] = out_shard_name
selection_report["shard_manifests"][st_name] = {
"filename": out_shard_name,
"size_bytes": os.path.getsize(out_shard_path),
"tensors": {
k: [list(v.shape), str(v.dtype)] for k, v in emb_tensors.items()
},
}
del emb_tensors, emb_weight
parity += 1
# -------------------------------------------------------------------
# TRƯỜNG HỢP B: TẦNG DENSE (NẾU CÓ TRONG V3/R1)
# -------------------------------------------------------------------
elif layer_type == "dense":
dense_tensors = shard_mgr.load_specific_tensors(tensors_map)
layer_prefix = detect_layer_prefix(set(dense_tensors.keys()), layer_id)
mlp_prefix = (
f"{layer_prefix}.ffn"
if f"{layer_prefix}.ffn.w1.weight" in dense_tensors
else f"{layer_prefix}.mlp"
)
dense_dequant_cache: Dict[str, torch.Tensor] = {}
for c_idx in range(num_chunks):
hs_in = buffer_mgr.load_chunk(read_dir, c_idx, device=device)
res_state, normed_ffn, hc_ctx = forward_attention_v4_or_v3(
hs_in,
layer_prefix,
dense_tensors,
config,
device,
dequant_cache=dense_dequant_cache,
)
mlp_out = forward_swiglu_expert(
normed_ffn,
dense_tensors,
mlp_prefix,
device,
swiglu_limit=swiglu_limit,
dequant_cache=dense_dequant_cache,
)
if hc_ctx is not None:
hs_out = hc_post_step(mlp_out, hc_ctx[0], hc_ctx[1], hc_ctx[2])
else:
hs_out = res_state + mlp_out
buffer_mgr.save_chunk(write_dir, c_idx, hs_out)
del dense_dequant_cache
out_shard_path = os.path.join(output_dir, out_shard_name)
save_safetensors(dense_tensors, out_shard_path)
selection_report["output_shard_files"][st_name] = out_shard_name
selection_report["shard_manifests"][st_name] = {
"filename": out_shard_name,
"size_bytes": os.path.getsize(out_shard_path),
"tensors": {
k: [list(v.shape), str(v.dtype)] for k, v in dense_tensors.items()
},
}
del dense_tensors
parity += 1
# -------------------------------------------------------------------
# TRƯỜNG HỢP C: TẦNG MOE (`hash_moe`, `moe`, `mtp_moe`) - CẮT 384 -> 128 Ô
# -------------------------------------------------------------------
elif layer_type in ("hash_moe", "moe", "mtp_moe"):
non_expert_keys = {
k for k in tensors_map.keys() if ".experts." not in k
}
core_tensors = shard_mgr.load_specific_tensors(
tensors_map, filter_keys=non_expert_keys
)
layer_prefix = detect_layer_prefix(set(tensors_map.keys()), layer_id)
ffn_kind = (
"ffn"
if any(f"{layer_prefix}.ffn." in k for k in non_expert_keys)
else "mlp"
)
gate_w_key = f"{layer_prefix}.{ffn_kind}.gate.weight"
gate_bias_key = (
f"{layer_prefix}.{ffn_kind}.gate.bias"
if f"{layer_prefix}.{ffn_kind}.gate.bias" in core_tensors
else f"{layer_prefix}.{ffn_kind}.gate.e_score_correction_bias"
)
tid2eid_key = f"{layer_prefix}.{ffn_kind}.gate.tid2eid"
gate_weight = core_tensors[gate_w_key].to(device, dtype=torch.float32)
gate_bias = (
core_tensors[gate_bias_key].to(device, dtype=torch.float32)
if gate_bias_key in core_tensors
else None
)
tid2eid_table = (
core_tensors[tid2eid_key].to(device)
if tid2eid_key in core_tensors
else None
)
num_experts_in_layer = gate_weight.shape[0]
scorer = GroupAwareExpertScorer(
num_experts_old=num_experts_in_layer,
n_group=n_group,
general_quota_per_group=general_quota,
logic_quota_per_group=logic_quota,
device=device,
)
# Tối ưu RAM & tốc độ:
# 1. Cache trọng số Attention giải nén 1 lần duy nhất cho cả tầng.
# 2. Lưu `res_state` trực tiếp xuống `write_dir` trên ổ đĩa (tiết kiệm 47.7 GB CPU RAM!).
# 3. Nén `normed_ffn` sang Int8 trong RAM (~5.9 GB cho 260 chunks).
attn_dequant_cache: Dict[str, torch.Tensor] = {}
mid_normed_q: List[Optional[Tuple[torch.Tensor, torch.Tensor]]] = []
mid_hc_post: List[Optional[Tuple[torch.Tensor, torch.Tensor]]] = []
need_forward_next = layer_type in ("hash_moe", "moe")
for c_idx in range(num_chunks):
s_i = c_idx * batch_size
e_i = min(num_samples, (c_idx + 1) * batch_size)
hs_in = buffer_mgr.load_chunk(read_dir, c_idx, device=device)
ids_batch = input_ids_all[s_i:e_i].to(device, dtype=torch.long)
# Nếu là tầng MTP (`mtp.0`), biến đổi đầu vào qua `hnorm` + `h_proj`
if layer_type == "mtp_moe" and f"{layer_prefix}.hnorm.weight" in core_tensors:
hnorm_w = core_tensors[f"{layer_prefix}.hnorm.weight"].to(
device, dtype=torch.bfloat16
)
hs_in = rms_norm(hs_in, hnorm_w, eps=float(config.get("rms_norm_eps", 1e-6)))
if f"{layer_prefix}.h_proj.weight" in core_tensors:
wh = get_dequantized_linear_weight(
core_tensors,
f"{layer_prefix}.h_proj",
device,
torch.bfloat16,
cache=attn_dequant_cache,
)
hs_in = F.linear(hs_in, wh)
if (
f"{layer_prefix}.attn_norm.weight" in core_tensors
or f"{layer_prefix}.input_layernorm.weight" in core_tensors
):
res_state, normed_ffn, hc_ctx = forward_attention_v4_or_v3(
hs_in,
layer_prefix,
core_tensors,
config,
device,
dequant_cache=attn_dequant_cache,
)
else:
res_state = hs_in
normed_ffn = hs_in[..., 0, :] if hs_in.dim() == 4 else hs_in
hc_ctx = None
# Chấm điểm Router trên toàn bộ 384 ô
router_scores = compute_router_scores(
normed_ffn, gate_weight, scoring_func=scoring_func
)
if gate_bias is not None:
router_scores_for_eval = torch.clamp_min(
router_scores + gate_bias.view(1, 1, -1), 0.0
)
elif tid2eid_table is not None:
# Ở tầng Hash-MoE (0..2), cộng tăng cường cho đúng 6 ô được băm bởi tid2eid
clamped_ids = torch.clamp(ids_batch, 0, tid2eid_table.shape[0] - 1)
hashed_eids = tid2eid_table[clamped_ids].to(torch.long) # [B, S, 6]
hash_bonus = torch.zeros_like(router_scores)
hash_bonus.scatter_add_(
-1,
hashed_eids,
torch.ones_like(hashed_eids, dtype=router_scores.dtype),
)
router_scores_for_eval = router_scores * (1.0 + hash_bonus)
else:
router_scores_for_eval = router_scores
scorer.update_batch(
router_probs=router_scores_for_eval,
token_weights=token_weights_all[s_i:e_i].to(device),
high_logic_mask=high_logic_all[s_i:e_i].to(device),
attention_mask=attn_mask_all[s_i:e_i].to(device),
top_k=top_k,
)
if need_forward_next:
# Lưu tạm `res_state` xuống `write_dir` để không chiếm 47.7 GB CPU RAM
buffer_mgr.save_chunk(write_dir, c_idx, res_state)
q_norm, s_norm = quantize_activation_int8(normed_ffn.detach())
mid_normed_q.append((q_norm.cpu(), s_norm.cpu()))
if hc_ctx is not None:
mid_hc_post.append((hc_ctx[1].cpu(), hc_ctx[2].cpu()))
else:
mid_hc_post.append(None)
if (c_idx + 1) % 65 == 0 or (c_idx + 1) == num_chunks:
print(
f" [Pass 1 - Attention & Router] {st_name}: {c_idx + 1}/{num_chunks} chunks",
flush=True,
)
del attn_dequant_cache
if str(device).startswith("cuda") and torch.cuda.is_available():
torch.cuda.empty_cache()
# Bước C2: Tuyển chọn chính xác 128 ô chiến thắng theo 8 nhóm (16 ô/nhóm)
layer_result = scorer.finalize_selection()
selected_old_indices: List[int] = layer_result["selected_old_indices"]
old_to_new_map: Dict[int, int] = {
int(k): int(v) for k, v in layer_result["old_to_new_map"].items()
}
selection_report["layers"][str(layer_id)] = layer_result
print(
f" [+] {st_name}: Đã chọn {len(selected_old_indices)}/{num_experts_in_layer} ô "
f"(8 nhóm x 16 ô). Ví dụ Nhóm 0: {selected_old_indices[:6]}...",
flush=True,
)
# Bước C3: Chỉ nạp từ đĩa đúng 128 ô vừa được chọn (bỏ qua 256 ô bị loại!)
selected_set = set(selected_old_indices)
selected_expert_keys: Set[str] = set()
exp_regex = re.compile(
rf"^{re.escape(layer_prefix)}\.{ffn_kind}\.experts\.(\d+)\.(.+)$"
)
for k in tensors_map.keys():
m_exp = exp_regex.match(k)
if m_exp and int(m_exp.group(1)) in selected_set:
selected_expert_keys.add(k)
selected_expert_tensors = shard_mgr.load_specific_tensors(
tensors_map, filter_keys=selected_expert_keys
)
full_needed_tensors = {**core_tensors, **selected_expert_tensors}
# Phẫu thuật cắt biến và đổi tên 0..127 (kèm remap tid2eid nếu là tầng 0..2)
pruned_layer_state = slice_and_build_pruned_layer_state_dict(
layer_prefix=layer_prefix,
full_layer_tensors=full_needed_tensors,
selected_old_indices=selected_old_indices,
old_to_new_map=old_to_new_map,
n_group=n_group,
)
del core_tensors, selected_expert_tensors, full_needed_tensors
gc.collect()
# Bước C4: Truyền tín hiệu qua 128 ô đã cắt + Shared Experts để sinh states_out cho Tầng L+1
if need_forward_next:
pruned_gate_w = pruned_layer_state[gate_w_key].to(
device, dtype=torch.float32
)
pruned_gate_b = (
pruned_layer_state[gate_bias_key].to(device, dtype=torch.float32)
if gate_bias_key in pruned_layer_state
else None
)
pruned_tid2eid = (
pruned_layer_state[tid2eid_key].to(device)
if tid2eid_key in pruned_layer_state
else None
)
shared_prefix = f"{layer_prefix}.{ffn_kind}.shared_experts"
has_shared = (
f"{shared_prefix}.w1.weight" in pruned_layer_state
or f"{shared_prefix}.gate_proj.weight" in pruned_layer_state
)
num_new_experts = len(selected_old_indices)
# Chia thành các cửa sổ (window_size = 65 chunks ~ 2.9 GB RAM) để mỗi chuyên gia
# chỉ cần giải nén MXFP4 tối đa 1 lần/cửa sổ thay vì 260 lần, đồng thời giữ CPU RAM < 6 GB
window_size = 65
for w_start in range(0, num_chunks, window_size):
w_end = min(num_chunks, w_start + window_size)
w_len = w_end - w_start
win_x_flat: List[torch.Tensor] = []
win_shapes: List[Tuple[int, int, int]] = []
win_topk_idx: List[torch.Tensor] = []
win_topk_weights: List[torch.Tensor] = []
win_moe_out_flat: List[torch.Tensor] = []
expert_to_win_chunks: Dict[int, List[int]] = {
eid: [] for eid in range(num_new_experts)
}
for local_i, c_idx in enumerate(range(w_start, w_end)):
s_i = c_idx * batch_size
e_i = min(num_samples, (c_idx + 1) * batch_size)
ids_batch = input_ids_all[s_i:e_i].to(device, dtype=torch.long)
q_norm_cpu, s_norm_cpu = mid_normed_q[c_idx] # type: ignore[misc]
normed_ffn = dequantize_activation_int8(
q_norm_cpu.to(device),
s_norm_cpu.to(device),
dtype=torch.bfloat16,
)
B, S, D = normed_ffn.shape
win_shapes.append((B, S, D))
_, topk_idx, topk_weights = route_tokens_v4_or_v3(
normed_hidden=normed_ffn,
gate_weight=pruned_gate_w,
correction_bias=pruned_gate_b,
tid2eid=pruned_tid2eid,
input_ids=ids_batch,
scoring_func=scoring_func,
n_group=n_group,
topk_group=topk_group,
top_k=top_k,
routed_scaling_factor=routed_scaling,
norm_topk_prob=norm_topk_prob,
)
active_eids = torch.unique(topk_idx).tolist()
for eid in active_eids:
if 0 <= int(eid) < num_new_experts:
expert_to_win_chunks[int(eid)].append(local_i)
x_flat_cpu = normed_ffn.view(-1, D).cpu()
win_x_flat.append(x_flat_cpu)
win_topk_idx.append(topk_idx.cpu())
win_topk_weights.append(topk_weights.cpu())
win_moe_out_flat.append(
torch.zeros_like(x_flat_cpu, dtype=torch.bfloat16)
)
# Giải phóng bản nén của chunk này ngay sau khi đưa vào cửa sổ
mid_normed_q[c_idx] = None
# Duyệt theo từng chuyên gia ở vòng ngoài: giải nén MXFP4 đúng 1 lần/cửa sổ!
for new_eid in range(num_new_experts):
active_local_chunks = expert_to_win_chunks[new_eid]
if not active_local_chunks:
continue
exp_prefix = f"{layer_prefix}.{ffn_kind}.experts.{new_eid}"
exp_dequant_cache: Dict[str, torch.Tensor] = {}
for local_i in active_local_chunks:
t_idx = win_topk_idx[local_i]
exp_mask = t_idx == new_eid
token_mask = exp_mask.any(dim=-1)
if not token_mask.any():
continue
tokens_for_e = win_x_flat[local_i][token_mask].to(
device, dtype=torch.bfloat16
)
out_e = forward_swiglu_expert(
tokens_for_e,
pruned_layer_state,
exp_prefix,
device,
swiglu_limit=swiglu_limit,
dequant_cache=exp_dequant_cache,
)
t_weights = win_topk_weights[local_i][token_mask].to(
device, dtype=torch.bfloat16
)
e_mask_sub = exp_mask[token_mask].to(
device, dtype=torch.bfloat16
)
weights_for_e = (t_weights * e_mask_sub).sum(
dim=-1, keepdim=True
)
weighted_out = (out_e * weights_for_e).cpu()
win_moe_out_flat[local_i][token_mask] += weighted_out
del exp_dequant_cache
# Cộng Shared Experts (giải nén 1 lần) và kết hợp với `res_state` từ `write_dir`
shared_dequant_cache: Dict[str, torch.Tensor] = {}
for local_i, c_idx in enumerate(range(w_start, w_end)):
B, S, D = win_shapes[local_i]
moe_out = win_moe_out_flat[local_i].to(
device, dtype=torch.bfloat16
).view(B, S, D)
if has_shared:
normed_ffn = win_x_flat[local_i].to(
device, dtype=torch.bfloat16
).view(B, S, D)
shared_out = forward_swiglu_expert(
normed_ffn,
pruned_layer_state,
shared_prefix,
device,
swiglu_limit=swiglu_limit,
dequant_cache=shared_dequant_cache,
)
moe_out = moe_out + shared_out
res_state = buffer_mgr.load_chunk(
write_dir, c_idx, device=device
)
hc_pair = mid_hc_post[c_idx]
if hc_pair is not None:
post_ffn = hc_pair[0].to(device, dtype=torch.float32)
comb_ffn = hc_pair[1].to(device, dtype=torch.float32)
hs_out = hc_post_step(
moe_out, res_state, post_ffn, comb_ffn
)
else:
hs_out = res_state + moe_out
buffer_mgr.save_chunk(write_dir, c_idx, hs_out)
del (
shared_dequant_cache,
win_x_flat,
win_topk_idx,
win_topk_weights,
win_moe_out_flat,
)
if str(device).startswith("cuda") and torch.cuda.is_available():
torch.cuda.empty_cache()
print(
f" [Pass 2 - Pruned MoE Forward] {st_name}: {w_end}/{num_chunks} chunks",
flush=True,
)
parity += 1
del mid_normed_q, mid_hc_post
# Bước C5: Lưu file .safetensors đã cắt của Tầng L
out_shard_path = os.path.join(output_dir, out_shard_name)
save_safetensors(pruned_layer_state, out_shard_path)
selection_report["output_shard_files"][st_name] = out_shard_name
selection_report["shard_manifests"][st_name] = {
"filename": out_shard_name,
"size_bytes": os.path.getsize(out_shard_path),
"tensors": {
k: [list(v.shape), str(v.dtype)]
for k, v in pruned_layer_state.items()
},
}
del pruned_layer_state
# -------------------------------------------------------------------
# TRƯỜNG HỢP D: TẦNG NORM CUỐI & HEAD (`hc_head_*`, `norm`, `head`)
# -------------------------------------------------------------------
elif layer_type == "head_and_norm":
head_tensors = shard_mgr.load_specific_tensors(tensors_map)
out_shard_path = os.path.join(output_dir, out_shard_name)
save_safetensors(head_tensors, out_shard_path)
selection_report["output_shard_files"][st_name] = out_shard_name
selection_report["shard_manifests"][st_name] = {
"filename": out_shard_name,
"size_bytes": os.path.getsize(out_shard_path),
"tensors": {
k: [list(v.shape), str(v.dtype)] for k, v in head_tensors.items()
},
}
del head_tensors
# -------------------------------------------------------------------
# CẬP NHẬT CHECKPOINT, ĐẨY LÊN HUGGING FACE & XÓA SHARD ĐÃ DÙNG XONG
# -------------------------------------------------------------------
if st_name not in selection_report["completed_stages"]:
selection_report["completed_stages"].append(st_name)
with open(report_path, "w", encoding="utf-8") as f:
json.dump(selection_report, f, indent=2, ensure_ascii=False)
if hf_api is not None:
out_shard_name = selection_report["output_shard_files"][st_name]
out_shard_path = os.path.join(output_dir, out_shard_name)
print(f" [↑] Đang đẩy [{out_shard_name}] lên Hugging Face ({hf_Output_repo})...")
hf_api.upload_file(
path_or_fileobj=out_shard_path,
path_in_repo=out_shard_name,
repo_id=hf_Output_repo,
repo_type="model",
)
hf_api.upload_file(
path_or_fileobj=report_path,
path_in_repo="expert_selection_report.json",
repo_id=hf_Output_repo,
repo_type="model",
)
if os.path.isfile(out_shard_path):
try:
os.remove(out_shard_path)
print(
f" [x] Đã xóa bản cục bộ [{out_shard_name}] sau khi upload lên HF để giữ trống ổ cứng Colab."
)
except OSError:
pass
shard_mgr.delete_finished_shards(stage["shards_safe_to_delete"])
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
elapsed = time.time() - t0
print(f" [✓] Hoàn tất [{st_name}] trong {elapsed:.2f}s.")
print("\n" + "=" * 76)
print(f"[HOÀN TẤT BƯỚC 3] Đã phẫu thuật xong toàn bộ {total_stages} giai đoạn!")
print(f" - Báo cáo chọn 128 ô / tầng : {report_path}")
print(f" - Thư mục chứa Model 128 ô : {output_dir}")
print("=" * 76)
return selection_report
def parse_args():
parser = argparse.ArgumentParser(
description="Bước 3: Chạy phẫu thuật cuốn chiếu 61 tầng (384 -> 128 ô) trên Google Colab Pro."
)
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 model gốc.",
)
parser.add_argument(
"--schedule-path",
type=str,
default="./surgery_schedule.json",
help="Đường dẫn file lịch trình từ Bước 2.",
)
parser.add_argument(
"--calibration-path",
type=str,
default="./calibration_data/calibration_6500_it.pt",
help="Đường dẫn bộ đề mồi 6.500 cuộc hội thoại từ Bước 1.",
)
parser.add_argument(
"--output-dir",
type=str,
default="./pruned_128_model",
help="Thư mục xuất các file .safetensors đã cắt còn 128 ô.",
)
parser.add_argument(
"--buffer-dir",
type=str,
default="./activation_buffer",
help="Thư mục bộ đệm kép states_in / states_out trên SSD.",
)
parser.add_argument(
"--cache-dir",
type=str,
default="./hf_cache",
help="Thư mục tải tạm shard gốc của từng tầng.",
)
parser.add_argument(
"--batch-size",
type=int,
default=25,
help="Số cuộc hội thoại xử lý mỗi lô trên GPU (mặc định: 25).",
)
parser.add_argument(
"--push-to-hub",
type=str,
default="doandung/128-IT-Coder",
help="Repo ID trên Hugging Face để đẩy từng tầng ngay sau khi cắt.",
)
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()
run_streaming_surgery(
model_source=args.model_source,
schedule_path=args.schedule_path,
calibration_path=args.calibration_path,
output_dir=args.output_dir,
buffer_dir=args.buffer_dir,
cache_dir=args.cache_dir,
batch_size=args.batch_size,
hf_Output_repo=args.push_to_hub,
hf_token=args.hf_token,
)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STEP 3: DÂY CHUYỀN PHẪU THUẬT CUỐN CHIẾU 61 TẦNG (DEEPSEEK-V4-PRO & V3/R1)
==========================================================================
Thực thi thuật toán "Streaming Surgery" & "Group-Aware Hybrid Peak-Energy"
tương thích 100% với cấu trúc thực tế của `deepseek-ai/DeepSeek-V4-Pro`:
1. Giải nén tức thời (On-the-fly) cả 2 chuẩn trọng số của DeepSeek-V4-Pro:
- Chuẩn FP8 (`float8_e4m3fn` + `.scale` kiểu `float8_e8m0fnu`, block 128x128)
dùng cho Attention (`wq_a`, `wq_b`, `wkv`, `wo_a`, `wo_b`) & `shared_experts`.
- Chuẩn FP4 (`int8` đóng gói 2 giá trị `e2m1fn` mỗi byte + `.scale` kiểu
`float8_e8m0fnu`, block 1x32) dùng cho 384 Ô chuyên gia (`w1`, `w2`, `w3`).
2. Hỗ trợ đầy đủ Hyper-Connections (`hc_mult = 4`, Sinkhorn-Knopp 20 vòng lặp),
hàm chấm điểm Router `sqrtsoftplus` (cũng như `sigmoid`/`softmax`),
Tầng Hash-MoE (`layers.0..2` với bảng ánh xạ `tid2eid`), Tầng Bias-MoE (`layers.3..60`)
và Tầng Dự đoán Đa từ MTP (`mtp.0`).
3. Tại mỗi tầng MoE:
- Chấm điểm chọn chính xác 16 ô/nhóm x 8 nhóm = 128 ô:
* 11 Ghế Đa Năng (Cumulative Weighted Energy, Luồng A nhân 2.5x).
* 5 Ghế Đặc Cách Logic Đỉnh Cao (Phân vị P99.5 trên HighLogicTokens).
- Cắt `ffn.gate.weight` -> [128, 7168], `ffn.gate.bias` -> [128].
- Ánh xạ lại bảng `ffn.gate.tid2eid` [129280, 6] (ở tầng 0, 1, 2) từ 0..383 -> 0..127.
- Đánh số lại 128 ô chiến thắng thành `experts.0` .. `experts.127` (giữ nguyên định dạng
nén FP4/FP8 gốc để không giảm chất lượng).
- Đẩy tự động từng tầng lên Hugging Face (`doandung/128-IT-Coder`), xóa ngay file tạm
cục bộ để ổ cứng Colab luôn giữ ở mức ~45 GB / 200 GB, hỗ trợ Auto-Resume.
"""
import os
import sys
import gc
import re
import json
import math
import time
import shutil
import argparse
from typing import Dict, List, Tuple, Optional, Set
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)
import torch
import torch.nn.functional as F
try:
from safetensors import safe_open
from safetensors.torch import save_file as _save_safetensors
except ImportError:
safe_open = None
_save_safetensors = None
try:
from huggingface_hub import hf_hub_download, HfApi
except ImportError:
hf_hub_download = None
HfApi = None
FP4_TABLE = torch.tensor(
[
0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
],
dtype=torch.float32,
)
def save_safetensors(tensors: Dict[str, torch.Tensor], filename: str) -> None:
"""Lưu file .safetensors chuẩn (hoặc fallback torch.save nếu môi trường thiếu safetensors)."""
if _save_safetensors is not None:
_save_safetensors(tensors, filename)
else:
torch.save(tensors, filename)
# ===========================================================================
# 1. GIẢI NÉN TỨC THỜI FP8 (E4M3 + E8M0) & FP4 (E2M1x2 + E8M0) CỦA DEEPSEEK-V4
# ===========================================================================
def dequantize_weight_auto(
weight: torch.Tensor,
scale: Optional[torch.Tensor] = None,
target_dtype: torch.dtype = torch.bfloat16,
fp8_block_size: int = 128,
fp4_block_size: int = 32,
) -> torch.Tensor:
"""
Tự động nhận diện và giải nén trọng số của DeepSeek-V4-Pro / V3 sang BFloat16/Float32:
- Trường hợp 1 (FP4 Expert Weight): `weight` kiểu `int8` hoặc `uint8` shape [M, N//2],
`scale` kiểu `float8_e8m0fnu` shape [M, N//32].
- Trường hợp 2 (FP8 Block-wise Weight): `weight` kiểu `float8_e4m3fn` shape [M, N],
`scale` kiểu `float8_e8m0fnu` hoặc `float32` shape [ceil(M/128), ceil(N/128)].
- Trường hợp 3 (BF16/FP32): Chuyển kiểu trực tiếp.
"""
if scale is None:
return weight.to(target_dtype)