Optimize RAM (<6GB) and 65x speed in step3 + audit check in step4
Browse files- step3_streaming_surgery_colab.py +301 -122
step3_streaming_surgery_colab.py
CHANGED
|
@@ -38,9 +38,9 @@ import argparse
|
|
| 38 |
from typing import Dict, List, Tuple, Optional, Set
|
| 39 |
|
| 40 |
if hasattr(sys.stdout, "reconfigure"):
|
| 41 |
-
sys.stdout.reconfigure(encoding="utf-8")
|
| 42 |
if hasattr(sys.stderr, "reconfigure"):
|
| 43 |
-
sys.stderr.reconfigure(encoding="utf-8")
|
| 44 |
|
| 45 |
import torch
|
| 46 |
import torch.nn.functional as F
|
|
@@ -134,8 +134,12 @@ def get_dequantized_linear_weight(
|
|
| 134 |
prefix: str,
|
| 135 |
device: str,
|
| 136 |
dtype: torch.dtype = torch.bfloat16,
|
|
|
|
| 137 |
) -> torch.Tensor:
|
| 138 |
-
"""Tìm `.weight` và `.scale` (hoặc `.weight_scale_inv`) để giải nén tức thời trên GPU."""
|
|
|
|
|
|
|
|
|
|
| 139 |
w_key = f"{prefix}.weight"
|
| 140 |
s_key_v4 = f"{prefix}.scale"
|
| 141 |
s_key_v3 = f"{prefix}.weight_scale_inv"
|
|
@@ -146,7 +150,10 @@ def get_dequantized_linear_weight(
|
|
| 146 |
s = tensors[s_key_v3].to(device)
|
| 147 |
else:
|
| 148 |
s = None
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
|
| 152 |
def rms_norm(
|
|
@@ -464,6 +471,28 @@ class GroupAwareExpertScorer:
|
|
| 464 |
# 4. BỘ QUẢN LÝ ĐỆM TÍN HIỆU KÉP TRÊN Ổ CỨNG (ACTIVATION BUFFER ~25GB)
|
| 465 |
# ===========================================================================
|
| 466 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 467 |
class ActivationBufferManager:
|
| 468 |
"""
|
| 469 |
Quản lý 2 bộ đệm luân phiên `buffer_A` và `buffer_B` trên SSD Colab:
|
|
@@ -619,6 +648,7 @@ def forward_attention_v4_or_v3(
|
|
| 619 |
config: dict,
|
| 620 |
device: str,
|
| 621 |
dtype: torch.dtype = torch.bfloat16,
|
|
|
|
| 622 |
) -> Tuple[torch.Tensor, torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]:
|
| 623 |
"""
|
| 624 |
Thực thi khối Attention + Chuẩn bị đầu vào cho FFN/MoE:
|
|
@@ -626,10 +656,6 @@ def forward_attention_v4_or_v3(
|
|
| 626 |
`wo_a`, `wo_b`, `hc_ffn_*`, `ffn_norm`) với dòng tín hiệu 4 luồng `[B, S, hc_mult, D]`.
|
| 627 |
- Đồng thời tương thích ngược với DeepSeek-V3/R1 (`input_layernorm`, `self_attn`,
|
| 628 |
`post_attention_layernorm`) với dòng tín hiệu `[B, S, D]`.
|
| 629 |
-
Trả về:
|
| 630 |
-
- `residual_state`: Trạng thái Residual sau Attention (`[B, S, hc, D]` hoặc `[B, S, D]`)
|
| 631 |
-
- `normed_for_ffn`: Tín hiệu `[B, S, D]` đã chuẩn hóa để đưa vào Router & MoE
|
| 632 |
-
- `hc_ffn_ctx`: Bộ 3 `(residual_hc, post_ffn, comb_ffn)` nếu dùng Hyper-Connections
|
| 633 |
"""
|
| 634 |
eps = float(config.get("rms_norm_eps", 1e-6))
|
| 635 |
hc_eps = float(config.get("hc_eps", 1e-6))
|
|
@@ -678,38 +704,40 @@ def forward_attention_v4_or_v3(
|
|
| 678 |
|
| 679 |
# --- Bước 2: Chạy Attention (DeepSeek-V4-Pro MQA-Latent + Grouped wo_a/wo_b hoặc V3 MLA) ---
|
| 680 |
if f"{attn_prefix}.wq_a.weight" in attn_tensors and f"{attn_prefix}.wkv.weight" in attn_tensors:
|
| 681 |
-
# Kiến trúc Attention của DeepSeek-V4-Pro
|
| 682 |
head_dim = int(config.get("head_dim", 512))
|
| 683 |
rope_dim = int(config.get("qk_rope_head_dim", 64))
|
| 684 |
o_groups = int(config.get("o_groups", 16))
|
| 685 |
o_lora_rank = int(config.get("o_lora_rank", 1024))
|
| 686 |
|
| 687 |
-
wq_a = get_dequantized_linear_weight(
|
|
|
|
|
|
|
| 688 |
q_norm_w = attn_tensors[f"{attn_prefix}.q_norm.weight"].to(device, dtype=dtype)
|
| 689 |
-
wq_b = get_dequantized_linear_weight(
|
|
|
|
|
|
|
| 690 |
|
| 691 |
qr = rms_norm(F.linear(normed_in, wq_a), q_norm_w, eps=eps)
|
| 692 |
q = F.linear(qr, wq_b).view(B, S, num_heads, head_dim)
|
| 693 |
q = q * torch.rsqrt(q.to(torch.float32).pow(2).mean(dim=-1, keepdim=True) + eps).to(dtype)
|
| 694 |
|
| 695 |
-
wkv = get_dequantized_linear_weight(
|
|
|
|
|
|
|
| 696 |
kv_norm_w = attn_tensors[f"{attn_prefix}.kv_norm.weight"].to(device, dtype=dtype)
|
| 697 |
-
kv = rms_norm(F.linear(normed_in, wkv), kv_norm_w, eps=eps)
|
| 698 |
|
| 699 |
-
# Áp dụng RoPE lên `rope_dim` chiều cuối của q và kv
|
| 700 |
q_pe, kv_pe = apply_rotary_pos_emb_simple(
|
| 701 |
q[..., -rope_dim:], kv[..., -rope_dim:], rope_theta=rope_theta
|
| 702 |
)
|
| 703 |
q = torch.cat([q[..., :-rope_dim], q_pe], dim=-1)
|
| 704 |
kv = torch.cat([kv[..., :-rope_dim], kv_pe], dim=-1)
|
| 705 |
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
q_t = q.transpose(1, 2).to(torch.float32) # [B, H, S, head_dim]
|
| 709 |
-
kv_t = kv.unsqueeze(1).to(torch.float32) # [B, 1, S, head_dim]
|
| 710 |
scale_factor = head_dim ** -0.5
|
| 711 |
|
| 712 |
-
scores = torch.matmul(q_t, kv_t.transpose(-1, -2)) * scale_factor
|
| 713 |
causal_mask = torch.triu(
|
| 714 |
torch.ones(S, S, device=device, dtype=torch.bool), diagonal=1
|
| 715 |
)
|
|
@@ -717,15 +745,13 @@ def forward_attention_v4_or_v3(
|
|
| 717 |
|
| 718 |
if f"{attn_prefix}.attn_sink" in attn_tensors:
|
| 719 |
sink = attn_tensors[f"{attn_prefix}.attn_sink"].to(device, dtype=torch.float32)
|
| 720 |
-
# Thêm cột sink vào softmax để giữ chuẩn phân phối chú ý của V4-Pro
|
| 721 |
sink_col = sink.view(1, num_heads, 1, 1).expand(B, num_heads, S, 1)
|
| 722 |
scores_with_sink = torch.cat([scores, sink_col], dim=-1)
|
| 723 |
probs = torch.softmax(scores_with_sink, dim=-1)[..., :S]
|
| 724 |
else:
|
| 725 |
probs = torch.softmax(scores, dim=-1)
|
| 726 |
|
| 727 |
-
o = torch.matmul(probs.to(dtype), kv_t.to(dtype)).transpose(1, 2).contiguous()
|
| 728 |
-
# Inverse RoPE trên chiều cuối như trong inference/model.py dòng 534
|
| 729 |
o_pe_inv, _ = apply_rotary_pos_emb_simple(
|
| 730 |
o[..., -rope_dim:], o[..., -rope_dim:], rope_theta=rope_theta
|
| 731 |
)
|
|
@@ -733,27 +759,32 @@ def forward_attention_v4_or_v3(
|
|
| 733 |
|
| 734 |
o_grouped = o.view(B, S, o_groups, -1)
|
| 735 |
wo_a_full = get_dequantized_linear_weight(
|
| 736 |
-
attn_tensors, f"{attn_prefix}.wo_a", device, dtype
|
| 737 |
)
|
| 738 |
wo_a = wo_a_full.view(o_groups, o_lora_rank, -1)
|
| 739 |
o_proj_mid = torch.einsum("bsgd,grd->bsgr", o_grouped, wo_a).flatten(2)
|
| 740 |
wo_b = get_dequantized_linear_weight(
|
| 741 |
-
attn_tensors, f"{attn_prefix}.wo_b", device, dtype
|
| 742 |
)
|
| 743 |
attn_out = F.linear(o_proj_mid, wo_b)
|
| 744 |
|
| 745 |
else:
|
| 746 |
-
# Kiến trúc Attention của DeepSeek-V3/R1
|
| 747 |
if f"{attn_prefix}.q_a_proj.weight" in attn_tensors:
|
| 748 |
-
wq_a = get_dequantized_linear_weight(
|
|
|
|
|
|
|
| 749 |
q_latent = F.linear(normed_in, wq_a)
|
| 750 |
if f"{attn_prefix}.q_a_layernorm.weight" in attn_tensors:
|
| 751 |
wq_norm = attn_tensors[f"{attn_prefix}.q_a_layernorm.weight"].to(device, dtype=dtype)
|
| 752 |
q_latent = rms_norm(q_latent, wq_norm, eps=eps)
|
| 753 |
-
wq_b = get_dequantized_linear_weight(
|
|
|
|
|
|
|
| 754 |
q_all = F.linear(q_latent, wq_b)
|
| 755 |
else:
|
| 756 |
-
wq = get_dequantized_linear_weight(
|
|
|
|
|
|
|
| 757 |
q_all = F.linear(normed_in, wq)
|
| 758 |
|
| 759 |
if f"{attn_prefix}.kv_a_proj_with_mqa.weight" in attn_tensors:
|
|
@@ -763,7 +794,7 @@ def forward_attention_v4_or_v3(
|
|
| 763 |
v_head_dim = int(config.get("v_head_dim", 128))
|
| 764 |
|
| 765 |
wkv_a = get_dequantized_linear_weight(
|
| 766 |
-
attn_tensors, f"{attn_prefix}.kv_a_proj_with_mqa", device, dtype
|
| 767 |
)
|
| 768 |
kv_compressed = F.linear(normed_in, wkv_a)
|
| 769 |
c_kv = kv_compressed[..., :kv_lora_rank]
|
|
@@ -772,7 +803,7 @@ def forward_attention_v4_or_v3(
|
|
| 772 |
wkv_norm = attn_tensors[f"{attn_prefix}.kv_a_layernorm.weight"].to(device, dtype=dtype)
|
| 773 |
c_kv = rms_norm(c_kv, wkv_norm, eps=eps)
|
| 774 |
wkv_b = get_dequantized_linear_weight(
|
| 775 |
-
attn_tensors, f"{attn_prefix}.kv_b_proj", device, dtype
|
| 776 |
)
|
| 777 |
kv_full = F.linear(c_kv, wkv_b).view(B, S, num_heads, qk_nope_dim + v_head_dim)
|
| 778 |
k_nope = kv_full[..., :qk_nope_dim]
|
|
@@ -800,7 +831,9 @@ def forward_attention_v4_or_v3(
|
|
| 800 |
is_causal=True,
|
| 801 |
).transpose(1, 2).contiguous().view(B, S, -1)
|
| 802 |
if f"{attn_prefix}.o_proj.weight" in attn_tensors:
|
| 803 |
-
wo = get_dequantized_linear_weight(
|
|
|
|
|
|
|
| 804 |
attn_out = F.linear(attn_out, wo)
|
| 805 |
|
| 806 |
# --- Bước 3: Hậu xử lý Hyper-Connections (V4-Pro) hoặc Residual + Post-Attn Norm (V3) ---
|
|
@@ -839,19 +872,32 @@ def forward_swiglu_expert(
|
|
| 839 |
device: str,
|
| 840 |
swiglu_limit: float = 0.0,
|
| 841 |
dtype: torch.dtype = torch.bfloat16,
|
|
|
|
| 842 |
) -> torch.Tensor:
|
| 843 |
"""
|
| 844 |
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`
|
| 845 |
với `swiglu_limit = 10.0`) và chuẩn tên biến của DeepSeek-V3 (`gate_proj`, `down_proj`, `up_proj`).
|
| 846 |
"""
|
| 847 |
if f"{expert_prefix}.w1.weight" in tensors:
|
| 848 |
-
w1 = get_dequantized_linear_weight(
|
| 849 |
-
|
| 850 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 851 |
else:
|
| 852 |
-
w1 = get_dequantized_linear_weight(
|
| 853 |
-
|
| 854 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 855 |
|
| 856 |
gate = F.linear(x, w1).to(torch.float32)
|
| 857 |
up = F.linear(x, w3).to(torch.float32)
|
|
@@ -1182,12 +1228,24 @@ def run_streaming_surgery(
|
|
| 1182 |
"primary_output_shard", f"model-layer-{layer_id:02d}-of-61.safetensors"
|
| 1183 |
)
|
| 1184 |
|
|
|
|
|
|
|
| 1185 |
if st_name in selection_report["completed_stages"]:
|
| 1186 |
-
|
| 1187 |
-
|
| 1188 |
-
|
| 1189 |
-
|
| 1190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1191 |
|
| 1192 |
t0 = time.time()
|
| 1193 |
print(
|
|
@@ -1195,8 +1253,6 @@ def run_streaming_surgery(
|
|
| 1195 |
f"(type={layer_type}, tensors={len(tensors_map)})..."
|
| 1196 |
)
|
| 1197 |
|
| 1198 |
-
read_dir, write_dir = buffer_mgr.get_read_write_dirs(parity)
|
| 1199 |
-
|
| 1200 |
# -------------------------------------------------------------------
|
| 1201 |
# TRƯỜNG HỢP A: TẦNG NHÚNG TỪ VỰNG (`embed.weight` / `embed_tokens`)
|
| 1202 |
# -------------------------------------------------------------------
|
|
@@ -1243,14 +1299,25 @@ def run_streaming_surgery(
|
|
| 1243 |
if f"{layer_prefix}.ffn.w1.weight" in dense_tensors
|
| 1244 |
else f"{layer_prefix}.mlp"
|
| 1245 |
)
|
|
|
|
| 1246 |
|
| 1247 |
for c_idx in range(num_chunks):
|
| 1248 |
hs_in = buffer_mgr.load_chunk(read_dir, c_idx, device=device)
|
| 1249 |
res_state, normed_ffn, hc_ctx = forward_attention_v4_or_v3(
|
| 1250 |
-
hs_in,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1251 |
)
|
| 1252 |
mlp_out = forward_swiglu_expert(
|
| 1253 |
-
normed_ffn,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1254 |
)
|
| 1255 |
if hc_ctx is not None:
|
| 1256 |
hs_out = hc_post_step(mlp_out, hc_ctx[0], hc_ctx[1], hc_ctx[2])
|
|
@@ -1258,6 +1325,7 @@ def run_streaming_surgery(
|
|
| 1258 |
hs_out = res_state + mlp_out
|
| 1259 |
buffer_mgr.save_chunk(write_dir, c_idx, hs_out)
|
| 1260 |
|
|
|
|
| 1261 |
out_shard_path = os.path.join(output_dir, out_shard_name)
|
| 1262 |
save_safetensors(dense_tensors, out_shard_path)
|
| 1263 |
selection_report["output_shard_files"][st_name] = out_shard_name
|
|
@@ -1318,9 +1386,14 @@ def run_streaming_surgery(
|
|
| 1318 |
device=device,
|
| 1319 |
)
|
| 1320 |
|
| 1321 |
-
|
| 1322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1323 |
mid_hc_post: List[Optional[Tuple[torch.Tensor, torch.Tensor]]] = []
|
|
|
|
| 1324 |
|
| 1325 |
for c_idx in range(num_chunks):
|
| 1326 |
s_i = c_idx * batch_size
|
|
@@ -1336,7 +1409,11 @@ def run_streaming_surgery(
|
|
| 1336 |
hs_in = rms_norm(hs_in, hnorm_w, eps=float(config.get("rms_norm_eps", 1e-6)))
|
| 1337 |
if f"{layer_prefix}.h_proj.weight" in core_tensors:
|
| 1338 |
wh = get_dequantized_linear_weight(
|
| 1339 |
-
core_tensors,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1340 |
)
|
| 1341 |
hs_in = F.linear(hs_in, wh)
|
| 1342 |
|
|
@@ -1345,7 +1422,12 @@ def run_streaming_surgery(
|
|
| 1345 |
or f"{layer_prefix}.input_layernorm.weight" in core_tensors
|
| 1346 |
):
|
| 1347 |
res_state, normed_ffn, hc_ctx = forward_attention_v4_or_v3(
|
| 1348 |
-
hs_in,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1349 |
)
|
| 1350 |
else:
|
| 1351 |
res_state = hs_in
|
|
@@ -1382,12 +1464,25 @@ def run_streaming_surgery(
|
|
| 1382 |
top_k=top_k,
|
| 1383 |
)
|
| 1384 |
|
| 1385 |
-
|
| 1386 |
-
|
| 1387 |
-
|
| 1388 |
-
|
| 1389 |
-
|
| 1390 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1391 |
|
| 1392 |
# Bước C2: Tuyển chọn chính xác 128 ô chiến thắng theo 8 nhóm (16 ô/nhóm)
|
| 1393 |
layer_result = scorer.finalize_selection()
|
|
@@ -1399,7 +1494,8 @@ def run_streaming_surgery(
|
|
| 1399 |
|
| 1400 |
print(
|
| 1401 |
f" [+] {st_name}: Đã chọn {len(selected_old_indices)}/{num_experts_in_layer} ô "
|
| 1402 |
-
f"(8 nhóm x 16 ô). Ví dụ Nhóm 0: {selected_old_indices[:6]}..."
|
|
|
|
| 1403 |
)
|
| 1404 |
|
| 1405 |
# Bước C3: Chỉ nạp từ đĩa đúng 128 ô vừa được chọn (bỏ qua 256 ô bị loại!)
|
|
@@ -1428,9 +1524,10 @@ def run_streaming_surgery(
|
|
| 1428 |
)
|
| 1429 |
|
| 1430 |
del core_tensors, selected_expert_tensors, full_needed_tensors
|
|
|
|
| 1431 |
|
| 1432 |
# Bước C4: Truyền tín hiệu qua 128 ô đã cắt + Shared Experts để sinh states_out cho Tầng L+1
|
| 1433 |
-
if
|
| 1434 |
pruned_gate_w = pruned_layer_state[gate_w_key].to(
|
| 1435 |
device, dtype=torch.float32
|
| 1436 |
)
|
|
@@ -1449,78 +1546,160 @@ def run_streaming_surgery(
|
|
| 1449 |
f"{shared_prefix}.w1.weight" in pruned_layer_state
|
| 1450 |
or f"{shared_prefix}.gate_proj.weight" in pruned_layer_state
|
| 1451 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1452 |
|
| 1453 |
-
|
| 1454 |
-
|
| 1455 |
-
|
| 1456 |
-
|
| 1457 |
-
|
| 1458 |
-
|
| 1459 |
-
|
| 1460 |
-
|
| 1461 |
-
|
| 1462 |
-
|
| 1463 |
-
|
| 1464 |
-
|
| 1465 |
-
|
| 1466 |
-
|
| 1467 |
-
correction_bias=pruned_gate_b,
|
| 1468 |
-
tid2eid=pruned_tid2eid,
|
| 1469 |
-
input_ids=ids_batch,
|
| 1470 |
-
scoring_func=scoring_func,
|
| 1471 |
-
n_group=n_group,
|
| 1472 |
-
topk_group=topk_group,
|
| 1473 |
-
top_k=top_k,
|
| 1474 |
-
routed_scaling_factor=routed_scaling,
|
| 1475 |
-
norm_topk_prob=norm_topk_prob,
|
| 1476 |
-
)
|
| 1477 |
-
|
| 1478 |
-
moe_out_flat = torch.zeros_like(x_flat)
|
| 1479 |
-
unique_active_experts = torch.unique(topk_idx).tolist()
|
| 1480 |
|
| 1481 |
-
|
| 1482 |
-
|
| 1483 |
-
|
| 1484 |
-
if not
|
| 1485 |
continue
|
| 1486 |
exp_prefix = f"{layer_prefix}.{ffn_kind}.experts.{new_eid}"
|
| 1487 |
-
|
| 1488 |
-
|
| 1489 |
-
|
| 1490 |
-
|
| 1491 |
-
|
| 1492 |
-
|
| 1493 |
-
|
| 1494 |
-
|
| 1495 |
-
|
| 1496 |
-
|
| 1497 |
-
|
| 1498 |
-
|
| 1499 |
-
|
| 1500 |
-
|
| 1501 |
-
|
| 1502 |
-
|
| 1503 |
-
|
| 1504 |
-
|
| 1505 |
-
|
| 1506 |
-
|
| 1507 |
-
|
| 1508 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1509 |
)
|
| 1510 |
-
|
| 1511 |
-
|
| 1512 |
-
|
| 1513 |
-
|
| 1514 |
-
|
| 1515 |
-
|
| 1516 |
-
|
| 1517 |
-
|
| 1518 |
-
|
| 1519 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1520 |
|
| 1521 |
parity += 1
|
| 1522 |
|
| 1523 |
-
del
|
| 1524 |
|
| 1525 |
# Bước C5: Lưu file .safetensors đã cắt của Tầng L
|
| 1526 |
out_shard_path = os.path.join(output_dir, out_shard_name)
|
|
|
|
| 38 |
from typing import Dict, List, Tuple, Optional, Set
|
| 39 |
|
| 40 |
if hasattr(sys.stdout, "reconfigure"):
|
| 41 |
+
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
|
| 42 |
if hasattr(sys.stderr, "reconfigure"):
|
| 43 |
+
sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)
|
| 44 |
|
| 45 |
import torch
|
| 46 |
import torch.nn.functional as F
|
|
|
|
| 134 |
prefix: str,
|
| 135 |
device: str,
|
| 136 |
dtype: torch.dtype = torch.bfloat16,
|
| 137 |
+
cache: Optional[Dict[str, torch.Tensor]] = None,
|
| 138 |
) -> torch.Tensor:
|
| 139 |
+
"""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)."""
|
| 140 |
+
if cache is not None and prefix in cache:
|
| 141 |
+
return cache[prefix]
|
| 142 |
+
|
| 143 |
w_key = f"{prefix}.weight"
|
| 144 |
s_key_v4 = f"{prefix}.scale"
|
| 145 |
s_key_v3 = f"{prefix}.weight_scale_inv"
|
|
|
|
| 150 |
s = tensors[s_key_v3].to(device)
|
| 151 |
else:
|
| 152 |
s = None
|
| 153 |
+
deq = dequantize_weight_auto(w, s, target_dtype=dtype)
|
| 154 |
+
if cache is not None:
|
| 155 |
+
cache[prefix] = deq
|
| 156 |
+
return deq
|
| 157 |
|
| 158 |
|
| 159 |
def rms_norm(
|
|
|
|
| 471 |
# 4. BỘ QUẢN LÝ ĐỆM TÍN HIỆU KÉP TRÊN Ổ CỨNG (ACTIVATION BUFFER ~25GB)
|
| 472 |
# ===========================================================================
|
| 473 |
|
| 474 |
+
def quantize_activation_int8(
|
| 475 |
+
hidden_states: torch.Tensor,
|
| 476 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 477 |
+
"""Lượng tử hóa đối xứng 8-bit (`int8` + `float16` scale) theo chiều cuối."""
|
| 478 |
+
hs_fp32 = hidden_states.detach().to(torch.float32)
|
| 479 |
+
amax = hs_fp32.abs().amax(dim=-1, keepdim=True).clamp_min(1e-6)
|
| 480 |
+
scale = (amax / 127.0).to(torch.float16)
|
| 481 |
+
quantized = torch.clamp(
|
| 482 |
+
torch.round(hs_fp32 / scale.to(torch.float32)), -127, 127
|
| 483 |
+
).to(torch.int8)
|
| 484 |
+
return quantized, scale
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def dequantize_activation_int8(
|
| 488 |
+
quantized: torch.Tensor,
|
| 489 |
+
scale: torch.Tensor,
|
| 490 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 491 |
+
) -> torch.Tensor:
|
| 492 |
+
"""Giải nén tín hiệu 8-bit (`int8` + `float16` scale) về `dtype`."""
|
| 493 |
+
return quantized.to(dtype) * scale.to(dtype)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
class ActivationBufferManager:
|
| 497 |
"""
|
| 498 |
Quản lý 2 bộ đệm luân phiên `buffer_A` và `buffer_B` trên SSD Colab:
|
|
|
|
| 648 |
config: dict,
|
| 649 |
device: str,
|
| 650 |
dtype: torch.dtype = torch.bfloat16,
|
| 651 |
+
dequant_cache: Optional[Dict[str, torch.Tensor]] = None,
|
| 652 |
) -> Tuple[torch.Tensor, torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]:
|
| 653 |
"""
|
| 654 |
Thực thi khối Attention + Chuẩn bị đầu vào cho FFN/MoE:
|
|
|
|
| 656 |
`wo_a`, `wo_b`, `hc_ffn_*`, `ffn_norm`) với dòng tín hiệu 4 luồng `[B, S, hc_mult, D]`.
|
| 657 |
- Đồng thời tương thích ngược với DeepSeek-V3/R1 (`input_layernorm`, `self_attn`,
|
| 658 |
`post_attention_layernorm`) với dòng tín hiệu `[B, S, D]`.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 659 |
"""
|
| 660 |
eps = float(config.get("rms_norm_eps", 1e-6))
|
| 661 |
hc_eps = float(config.get("hc_eps", 1e-6))
|
|
|
|
| 704 |
|
| 705 |
# --- Bước 2: Chạy Attention (DeepSeek-V4-Pro MQA-Latent + Grouped wo_a/wo_b hoặc V3 MLA) ---
|
| 706 |
if f"{attn_prefix}.wq_a.weight" in attn_tensors and f"{attn_prefix}.wkv.weight" in attn_tensors:
|
|
|
|
| 707 |
head_dim = int(config.get("head_dim", 512))
|
| 708 |
rope_dim = int(config.get("qk_rope_head_dim", 64))
|
| 709 |
o_groups = int(config.get("o_groups", 16))
|
| 710 |
o_lora_rank = int(config.get("o_lora_rank", 1024))
|
| 711 |
|
| 712 |
+
wq_a = get_dequantized_linear_weight(
|
| 713 |
+
attn_tensors, f"{attn_prefix}.wq_a", device, dtype, cache=dequant_cache
|
| 714 |
+
)
|
| 715 |
q_norm_w = attn_tensors[f"{attn_prefix}.q_norm.weight"].to(device, dtype=dtype)
|
| 716 |
+
wq_b = get_dequantized_linear_weight(
|
| 717 |
+
attn_tensors, f"{attn_prefix}.wq_b", device, dtype, cache=dequant_cache
|
| 718 |
+
)
|
| 719 |
|
| 720 |
qr = rms_norm(F.linear(normed_in, wq_a), q_norm_w, eps=eps)
|
| 721 |
q = F.linear(qr, wq_b).view(B, S, num_heads, head_dim)
|
| 722 |
q = q * torch.rsqrt(q.to(torch.float32).pow(2).mean(dim=-1, keepdim=True) + eps).to(dtype)
|
| 723 |
|
| 724 |
+
wkv = get_dequantized_linear_weight(
|
| 725 |
+
attn_tensors, f"{attn_prefix}.wkv", device, dtype, cache=dequant_cache
|
| 726 |
+
)
|
| 727 |
kv_norm_w = attn_tensors[f"{attn_prefix}.kv_norm.weight"].to(device, dtype=dtype)
|
| 728 |
+
kv = rms_norm(F.linear(normed_in, wkv), kv_norm_w, eps=eps)
|
| 729 |
|
|
|
|
| 730 |
q_pe, kv_pe = apply_rotary_pos_emb_simple(
|
| 731 |
q[..., -rope_dim:], kv[..., -rope_dim:], rope_theta=rope_theta
|
| 732 |
)
|
| 733 |
q = torch.cat([q[..., :-rope_dim], q_pe], dim=-1)
|
| 734 |
kv = torch.cat([kv[..., :-rope_dim], kv_pe], dim=-1)
|
| 735 |
|
| 736 |
+
q_t = q.transpose(1, 2).to(torch.float32)
|
| 737 |
+
kv_t = kv.unsqueeze(1).to(torch.float32)
|
|
|
|
|
|
|
| 738 |
scale_factor = head_dim ** -0.5
|
| 739 |
|
| 740 |
+
scores = torch.matmul(q_t, kv_t.transpose(-1, -2)) * scale_factor
|
| 741 |
causal_mask = torch.triu(
|
| 742 |
torch.ones(S, S, device=device, dtype=torch.bool), diagonal=1
|
| 743 |
)
|
|
|
|
| 745 |
|
| 746 |
if f"{attn_prefix}.attn_sink" in attn_tensors:
|
| 747 |
sink = attn_tensors[f"{attn_prefix}.attn_sink"].to(device, dtype=torch.float32)
|
|
|
|
| 748 |
sink_col = sink.view(1, num_heads, 1, 1).expand(B, num_heads, S, 1)
|
| 749 |
scores_with_sink = torch.cat([scores, sink_col], dim=-1)
|
| 750 |
probs = torch.softmax(scores_with_sink, dim=-1)[..., :S]
|
| 751 |
else:
|
| 752 |
probs = torch.softmax(scores, dim=-1)
|
| 753 |
|
| 754 |
+
o = torch.matmul(probs.to(dtype), kv_t.to(dtype)).transpose(1, 2).contiguous()
|
|
|
|
| 755 |
o_pe_inv, _ = apply_rotary_pos_emb_simple(
|
| 756 |
o[..., -rope_dim:], o[..., -rope_dim:], rope_theta=rope_theta
|
| 757 |
)
|
|
|
|
| 759 |
|
| 760 |
o_grouped = o.view(B, S, o_groups, -1)
|
| 761 |
wo_a_full = get_dequantized_linear_weight(
|
| 762 |
+
attn_tensors, f"{attn_prefix}.wo_a", device, dtype, cache=dequant_cache
|
| 763 |
)
|
| 764 |
wo_a = wo_a_full.view(o_groups, o_lora_rank, -1)
|
| 765 |
o_proj_mid = torch.einsum("bsgd,grd->bsgr", o_grouped, wo_a).flatten(2)
|
| 766 |
wo_b = get_dequantized_linear_weight(
|
| 767 |
+
attn_tensors, f"{attn_prefix}.wo_b", device, dtype, cache=dequant_cache
|
| 768 |
)
|
| 769 |
attn_out = F.linear(o_proj_mid, wo_b)
|
| 770 |
|
| 771 |
else:
|
|
|
|
| 772 |
if f"{attn_prefix}.q_a_proj.weight" in attn_tensors:
|
| 773 |
+
wq_a = get_dequantized_linear_weight(
|
| 774 |
+
attn_tensors, f"{attn_prefix}.q_a_proj", device, dtype, cache=dequant_cache
|
| 775 |
+
)
|
| 776 |
q_latent = F.linear(normed_in, wq_a)
|
| 777 |
if f"{attn_prefix}.q_a_layernorm.weight" in attn_tensors:
|
| 778 |
wq_norm = attn_tensors[f"{attn_prefix}.q_a_layernorm.weight"].to(device, dtype=dtype)
|
| 779 |
q_latent = rms_norm(q_latent, wq_norm, eps=eps)
|
| 780 |
+
wq_b = get_dequantized_linear_weight(
|
| 781 |
+
attn_tensors, f"{attn_prefix}.q_b_proj", device, dtype, cache=dequant_cache
|
| 782 |
+
)
|
| 783 |
q_all = F.linear(q_latent, wq_b)
|
| 784 |
else:
|
| 785 |
+
wq = get_dequantized_linear_weight(
|
| 786 |
+
attn_tensors, f"{attn_prefix}.q_proj", device, dtype, cache=dequant_cache
|
| 787 |
+
)
|
| 788 |
q_all = F.linear(normed_in, wq)
|
| 789 |
|
| 790 |
if f"{attn_prefix}.kv_a_proj_with_mqa.weight" in attn_tensors:
|
|
|
|
| 794 |
v_head_dim = int(config.get("v_head_dim", 128))
|
| 795 |
|
| 796 |
wkv_a = get_dequantized_linear_weight(
|
| 797 |
+
attn_tensors, f"{attn_prefix}.kv_a_proj_with_mqa", device, dtype, cache=dequant_cache
|
| 798 |
)
|
| 799 |
kv_compressed = F.linear(normed_in, wkv_a)
|
| 800 |
c_kv = kv_compressed[..., :kv_lora_rank]
|
|
|
|
| 803 |
wkv_norm = attn_tensors[f"{attn_prefix}.kv_a_layernorm.weight"].to(device, dtype=dtype)
|
| 804 |
c_kv = rms_norm(c_kv, wkv_norm, eps=eps)
|
| 805 |
wkv_b = get_dequantized_linear_weight(
|
| 806 |
+
attn_tensors, f"{attn_prefix}.kv_b_proj", device, dtype, cache=dequant_cache
|
| 807 |
)
|
| 808 |
kv_full = F.linear(c_kv, wkv_b).view(B, S, num_heads, qk_nope_dim + v_head_dim)
|
| 809 |
k_nope = kv_full[..., :qk_nope_dim]
|
|
|
|
| 831 |
is_causal=True,
|
| 832 |
).transpose(1, 2).contiguous().view(B, S, -1)
|
| 833 |
if f"{attn_prefix}.o_proj.weight" in attn_tensors:
|
| 834 |
+
wo = get_dequantized_linear_weight(
|
| 835 |
+
attn_tensors, f"{attn_prefix}.o_proj", device, dtype, cache=dequant_cache
|
| 836 |
+
)
|
| 837 |
attn_out = F.linear(attn_out, wo)
|
| 838 |
|
| 839 |
# --- Bước 3: Hậu xử lý Hyper-Connections (V4-Pro) hoặc Residual + Post-Attn Norm (V3) ---
|
|
|
|
| 872 |
device: str,
|
| 873 |
swiglu_limit: float = 0.0,
|
| 874 |
dtype: torch.dtype = torch.bfloat16,
|
| 875 |
+
dequant_cache: Optional[Dict[str, torch.Tensor]] = None,
|
| 876 |
) -> torch.Tensor:
|
| 877 |
"""
|
| 878 |
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`
|
| 879 |
với `swiglu_limit = 10.0`) và chuẩn tên biến của DeepSeek-V3 (`gate_proj`, `down_proj`, `up_proj`).
|
| 880 |
"""
|
| 881 |
if f"{expert_prefix}.w1.weight" in tensors:
|
| 882 |
+
w1 = get_dequantized_linear_weight(
|
| 883 |
+
tensors, f"{expert_prefix}.w1", device, dtype, cache=dequant_cache
|
| 884 |
+
)
|
| 885 |
+
w2 = get_dequantized_linear_weight(
|
| 886 |
+
tensors, f"{expert_prefix}.w2", device, dtype, cache=dequant_cache
|
| 887 |
+
)
|
| 888 |
+
w3 = get_dequantized_linear_weight(
|
| 889 |
+
tensors, f"{expert_prefix}.w3", device, dtype, cache=dequant_cache
|
| 890 |
+
)
|
| 891 |
else:
|
| 892 |
+
w1 = get_dequantized_linear_weight(
|
| 893 |
+
tensors, f"{expert_prefix}.gate_proj", device, dtype, cache=dequant_cache
|
| 894 |
+
)
|
| 895 |
+
w2 = get_dequantized_linear_weight(
|
| 896 |
+
tensors, f"{expert_prefix}.down_proj", device, dtype, cache=dequant_cache
|
| 897 |
+
)
|
| 898 |
+
w3 = get_dequantized_linear_weight(
|
| 899 |
+
tensors, f"{expert_prefix}.up_proj", device, dtype, cache=dequant_cache
|
| 900 |
+
)
|
| 901 |
|
| 902 |
gate = F.linear(x, w1).to(torch.float32)
|
| 903 |
up = F.linear(x, w3).to(torch.float32)
|
|
|
|
| 1228 |
"primary_output_shard", f"model-layer-{layer_id:02d}-of-61.safetensors"
|
| 1229 |
)
|
| 1230 |
|
| 1231 |
+
read_dir, write_dir = buffer_mgr.get_read_write_dirs(parity)
|
| 1232 |
+
|
| 1233 |
if st_name in selection_report["completed_stages"]:
|
| 1234 |
+
# Kiểm tra xem bộ đệm tín hiệu trên ổ cứng Colab có còn tồn tại không
|
| 1235 |
+
expected_next_chunk = os.path.join(write_dir, "chunk_0000.pt")
|
| 1236 |
+
if layer_type in ("embedding", "dense", "hash_moe", "moe") and not os.path.isfile(
|
| 1237 |
+
expected_next_chunk
|
| 1238 |
+
):
|
| 1239 |
+
print(
|
| 1240 |
+
f"[!] Giai đoạn [{st_name}] có trong Checkpoint nhưng bộ đệm SSD [{expected_next_chunk}] "
|
| 1241 |
+
f"trống (do Colab reset máy ảo). Đang tái tạo lại tín hiệu cho [{st_name}]..."
|
| 1242 |
+
)
|
| 1243 |
+
else:
|
| 1244 |
+
print(f"[Skip] Giai đoạn [{st_name}] đã hoàn thành trong Checkpoint trước.")
|
| 1245 |
+
if layer_type in ("embedding", "dense", "hash_moe", "moe"):
|
| 1246 |
+
parity += 1
|
| 1247 |
+
shard_mgr.delete_finished_shards(stage["shards_safe_to_delete"])
|
| 1248 |
+
continue
|
| 1249 |
|
| 1250 |
t0 = time.time()
|
| 1251 |
print(
|
|
|
|
| 1253 |
f"(type={layer_type}, tensors={len(tensors_map)})..."
|
| 1254 |
)
|
| 1255 |
|
|
|
|
|
|
|
| 1256 |
# -------------------------------------------------------------------
|
| 1257 |
# TRƯỜNG HỢP A: TẦNG NHÚNG TỪ VỰNG (`embed.weight` / `embed_tokens`)
|
| 1258 |
# -------------------------------------------------------------------
|
|
|
|
| 1299 |
if f"{layer_prefix}.ffn.w1.weight" in dense_tensors
|
| 1300 |
else f"{layer_prefix}.mlp"
|
| 1301 |
)
|
| 1302 |
+
dense_dequant_cache: Dict[str, torch.Tensor] = {}
|
| 1303 |
|
| 1304 |
for c_idx in range(num_chunks):
|
| 1305 |
hs_in = buffer_mgr.load_chunk(read_dir, c_idx, device=device)
|
| 1306 |
res_state, normed_ffn, hc_ctx = forward_attention_v4_or_v3(
|
| 1307 |
+
hs_in,
|
| 1308 |
+
layer_prefix,
|
| 1309 |
+
dense_tensors,
|
| 1310 |
+
config,
|
| 1311 |
+
device,
|
| 1312 |
+
dequant_cache=dense_dequant_cache,
|
| 1313 |
)
|
| 1314 |
mlp_out = forward_swiglu_expert(
|
| 1315 |
+
normed_ffn,
|
| 1316 |
+
dense_tensors,
|
| 1317 |
+
mlp_prefix,
|
| 1318 |
+
device,
|
| 1319 |
+
swiglu_limit=swiglu_limit,
|
| 1320 |
+
dequant_cache=dense_dequant_cache,
|
| 1321 |
)
|
| 1322 |
if hc_ctx is not None:
|
| 1323 |
hs_out = hc_post_step(mlp_out, hc_ctx[0], hc_ctx[1], hc_ctx[2])
|
|
|
|
| 1325 |
hs_out = res_state + mlp_out
|
| 1326 |
buffer_mgr.save_chunk(write_dir, c_idx, hs_out)
|
| 1327 |
|
| 1328 |
+
del dense_dequant_cache
|
| 1329 |
out_shard_path = os.path.join(output_dir, out_shard_name)
|
| 1330 |
save_safetensors(dense_tensors, out_shard_path)
|
| 1331 |
selection_report["output_shard_files"][st_name] = out_shard_name
|
|
|
|
| 1386 |
device=device,
|
| 1387 |
)
|
| 1388 |
|
| 1389 |
+
# Tối ưu RAM & tốc độ:
|
| 1390 |
+
# 1. Cache trọng số Attention giải nén 1 lần duy nhất cho cả tầng.
|
| 1391 |
+
# 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!).
|
| 1392 |
+
# 3. Nén `normed_ffn` sang Int8 trong RAM (~5.9 GB cho 260 chunks).
|
| 1393 |
+
attn_dequant_cache: Dict[str, torch.Tensor] = {}
|
| 1394 |
+
mid_normed_q: List[Optional[Tuple[torch.Tensor, torch.Tensor]]] = []
|
| 1395 |
mid_hc_post: List[Optional[Tuple[torch.Tensor, torch.Tensor]]] = []
|
| 1396 |
+
need_forward_next = layer_type in ("hash_moe", "moe")
|
| 1397 |
|
| 1398 |
for c_idx in range(num_chunks):
|
| 1399 |
s_i = c_idx * batch_size
|
|
|
|
| 1409 |
hs_in = rms_norm(hs_in, hnorm_w, eps=float(config.get("rms_norm_eps", 1e-6)))
|
| 1410 |
if f"{layer_prefix}.h_proj.weight" in core_tensors:
|
| 1411 |
wh = get_dequantized_linear_weight(
|
| 1412 |
+
core_tensors,
|
| 1413 |
+
f"{layer_prefix}.h_proj",
|
| 1414 |
+
device,
|
| 1415 |
+
torch.bfloat16,
|
| 1416 |
+
cache=attn_dequant_cache,
|
| 1417 |
)
|
| 1418 |
hs_in = F.linear(hs_in, wh)
|
| 1419 |
|
|
|
|
| 1422 |
or f"{layer_prefix}.input_layernorm.weight" in core_tensors
|
| 1423 |
):
|
| 1424 |
res_state, normed_ffn, hc_ctx = forward_attention_v4_or_v3(
|
| 1425 |
+
hs_in,
|
| 1426 |
+
layer_prefix,
|
| 1427 |
+
core_tensors,
|
| 1428 |
+
config,
|
| 1429 |
+
device,
|
| 1430 |
+
dequant_cache=attn_dequant_cache,
|
| 1431 |
)
|
| 1432 |
else:
|
| 1433 |
res_state = hs_in
|
|
|
|
| 1464 |
top_k=top_k,
|
| 1465 |
)
|
| 1466 |
|
| 1467 |
+
if need_forward_next:
|
| 1468 |
+
# Lưu tạm `res_state` xuống `write_dir` để không chiếm 47.7 GB CPU RAM
|
| 1469 |
+
buffer_mgr.save_chunk(write_dir, c_idx, res_state)
|
| 1470 |
+
q_norm, s_norm = quantize_activation_int8(normed_ffn.detach())
|
| 1471 |
+
mid_normed_q.append((q_norm.cpu(), s_norm.cpu()))
|
| 1472 |
+
if hc_ctx is not None:
|
| 1473 |
+
mid_hc_post.append((hc_ctx[1].cpu(), hc_ctx[2].cpu()))
|
| 1474 |
+
else:
|
| 1475 |
+
mid_hc_post.append(None)
|
| 1476 |
+
|
| 1477 |
+
if (c_idx + 1) % 65 == 0 or (c_idx + 1) == num_chunks:
|
| 1478 |
+
print(
|
| 1479 |
+
f" [Pass 1 - Attention & Router] {st_name}: {c_idx + 1}/{num_chunks} chunks",
|
| 1480 |
+
flush=True,
|
| 1481 |
+
)
|
| 1482 |
+
|
| 1483 |
+
del attn_dequant_cache
|
| 1484 |
+
if str(device).startswith("cuda") and torch.cuda.is_available():
|
| 1485 |
+
torch.cuda.empty_cache()
|
| 1486 |
|
| 1487 |
# Bước C2: Tuyển chọn chính xác 128 ô chiến thắng theo 8 nhóm (16 ô/nhóm)
|
| 1488 |
layer_result = scorer.finalize_selection()
|
|
|
|
| 1494 |
|
| 1495 |
print(
|
| 1496 |
f" [+] {st_name}: Đã chọn {len(selected_old_indices)}/{num_experts_in_layer} ô "
|
| 1497 |
+
f"(8 nhóm x 16 ô). Ví dụ Nhóm 0: {selected_old_indices[:6]}...",
|
| 1498 |
+
flush=True,
|
| 1499 |
)
|
| 1500 |
|
| 1501 |
# Bước C3: Chỉ nạp từ đĩa đúng 128 ô vừa được chọn (bỏ qua 256 ô bị loại!)
|
|
|
|
| 1524 |
)
|
| 1525 |
|
| 1526 |
del core_tensors, selected_expert_tensors, full_needed_tensors
|
| 1527 |
+
gc.collect()
|
| 1528 |
|
| 1529 |
# Bước C4: Truyền tín hiệu qua 128 ô đã cắt + Shared Experts để sinh states_out cho Tầng L+1
|
| 1530 |
+
if need_forward_next:
|
| 1531 |
pruned_gate_w = pruned_layer_state[gate_w_key].to(
|
| 1532 |
device, dtype=torch.float32
|
| 1533 |
)
|
|
|
|
| 1546 |
f"{shared_prefix}.w1.weight" in pruned_layer_state
|
| 1547 |
or f"{shared_prefix}.gate_proj.weight" in pruned_layer_state
|
| 1548 |
)
|
| 1549 |
+
num_new_experts = len(selected_old_indices)
|
| 1550 |
+
|
| 1551 |
+
# Chia thành các cửa sổ (window_size = 65 chunks ~ 2.9 GB RAM) để mỗi chuyên gia
|
| 1552 |
+
# 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
|
| 1553 |
+
window_size = 65
|
| 1554 |
+
for w_start in range(0, num_chunks, window_size):
|
| 1555 |
+
w_end = min(num_chunks, w_start + window_size)
|
| 1556 |
+
w_len = w_end - w_start
|
| 1557 |
+
|
| 1558 |
+
win_x_flat: List[torch.Tensor] = []
|
| 1559 |
+
win_shapes: List[Tuple[int, int, int]] = []
|
| 1560 |
+
win_topk_idx: List[torch.Tensor] = []
|
| 1561 |
+
win_topk_weights: List[torch.Tensor] = []
|
| 1562 |
+
win_moe_out_flat: List[torch.Tensor] = []
|
| 1563 |
+
expert_to_win_chunks: Dict[int, List[int]] = {
|
| 1564 |
+
eid: [] for eid in range(num_new_experts)
|
| 1565 |
+
}
|
| 1566 |
+
|
| 1567 |
+
for local_i, c_idx in enumerate(range(w_start, w_end)):
|
| 1568 |
+
s_i = c_idx * batch_size
|
| 1569 |
+
e_i = min(num_samples, (c_idx + 1) * batch_size)
|
| 1570 |
+
ids_batch = input_ids_all[s_i:e_i].to(device, dtype=torch.long)
|
| 1571 |
+
|
| 1572 |
+
q_norm_cpu, s_norm_cpu = mid_normed_q[c_idx] # type: ignore[misc]
|
| 1573 |
+
normed_ffn = dequantize_activation_int8(
|
| 1574 |
+
q_norm_cpu.to(device),
|
| 1575 |
+
s_norm_cpu.to(device),
|
| 1576 |
+
dtype=torch.bfloat16,
|
| 1577 |
+
)
|
| 1578 |
+
B, S, D = normed_ffn.shape
|
| 1579 |
+
win_shapes.append((B, S, D))
|
| 1580 |
+
|
| 1581 |
+
_, topk_idx, topk_weights = route_tokens_v4_or_v3(
|
| 1582 |
+
normed_hidden=normed_ffn,
|
| 1583 |
+
gate_weight=pruned_gate_w,
|
| 1584 |
+
correction_bias=pruned_gate_b,
|
| 1585 |
+
tid2eid=pruned_tid2eid,
|
| 1586 |
+
input_ids=ids_batch,
|
| 1587 |
+
scoring_func=scoring_func,
|
| 1588 |
+
n_group=n_group,
|
| 1589 |
+
topk_group=topk_group,
|
| 1590 |
+
top_k=top_k,
|
| 1591 |
+
routed_scaling_factor=routed_scaling,
|
| 1592 |
+
norm_topk_prob=norm_topk_prob,
|
| 1593 |
+
)
|
| 1594 |
|
| 1595 |
+
active_eids = torch.unique(topk_idx).tolist()
|
| 1596 |
+
for eid in active_eids:
|
| 1597 |
+
if 0 <= int(eid) < num_new_experts:
|
| 1598 |
+
expert_to_win_chunks[int(eid)].append(local_i)
|
| 1599 |
+
|
| 1600 |
+
x_flat_cpu = normed_ffn.view(-1, D).cpu()
|
| 1601 |
+
win_x_flat.append(x_flat_cpu)
|
| 1602 |
+
win_topk_idx.append(topk_idx.cpu())
|
| 1603 |
+
win_topk_weights.append(topk_weights.cpu())
|
| 1604 |
+
win_moe_out_flat.append(
|
| 1605 |
+
torch.zeros_like(x_flat_cpu, dtype=torch.bfloat16)
|
| 1606 |
+
)
|
| 1607 |
+
# Giải phóng bản nén của chunk này ngay sau khi đưa vào cửa sổ
|
| 1608 |
+
mid_normed_q[c_idx] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1609 |
|
| 1610 |
+
# Duyệt theo từng chuyên gia ở vòng ngoài: giải nén MXFP4 đúng 1 lần/cửa sổ!
|
| 1611 |
+
for new_eid in range(num_new_experts):
|
| 1612 |
+
active_local_chunks = expert_to_win_chunks[new_eid]
|
| 1613 |
+
if not active_local_chunks:
|
| 1614 |
continue
|
| 1615 |
exp_prefix = f"{layer_prefix}.{ffn_kind}.experts.{new_eid}"
|
| 1616 |
+
exp_dequant_cache: Dict[str, torch.Tensor] = {}
|
| 1617 |
+
|
| 1618 |
+
for local_i in active_local_chunks:
|
| 1619 |
+
t_idx = win_topk_idx[local_i]
|
| 1620 |
+
exp_mask = t_idx == new_eid
|
| 1621 |
+
token_mask = exp_mask.any(dim=-1)
|
| 1622 |
+
if not token_mask.any():
|
| 1623 |
+
continue
|
| 1624 |
+
tokens_for_e = win_x_flat[local_i][token_mask].to(
|
| 1625 |
+
device, dtype=torch.bfloat16
|
| 1626 |
+
)
|
| 1627 |
+
out_e = forward_swiglu_expert(
|
| 1628 |
+
tokens_for_e,
|
| 1629 |
+
pruned_layer_state,
|
| 1630 |
+
exp_prefix,
|
| 1631 |
+
device,
|
| 1632 |
+
swiglu_limit=swiglu_limit,
|
| 1633 |
+
dequant_cache=exp_dequant_cache,
|
| 1634 |
+
)
|
| 1635 |
+
t_weights = win_topk_weights[local_i][token_mask].to(
|
| 1636 |
+
device, dtype=torch.bfloat16
|
| 1637 |
+
)
|
| 1638 |
+
e_mask_sub = exp_mask[token_mask].to(
|
| 1639 |
+
device, dtype=torch.bfloat16
|
| 1640 |
+
)
|
| 1641 |
+
weights_for_e = (t_weights * e_mask_sub).sum(
|
| 1642 |
+
dim=-1, keepdim=True
|
| 1643 |
+
)
|
| 1644 |
+
weighted_out = (out_e * weights_for_e).cpu()
|
| 1645 |
+
win_moe_out_flat[local_i][token_mask] += weighted_out
|
| 1646 |
+
|
| 1647 |
+
del exp_dequant_cache
|
| 1648 |
+
|
| 1649 |
+
# Cộng Shared Experts (giải nén 1 lần) và kết hợp với `res_state` từ `write_dir`
|
| 1650 |
+
shared_dequant_cache: Dict[str, torch.Tensor] = {}
|
| 1651 |
+
for local_i, c_idx in enumerate(range(w_start, w_end)):
|
| 1652 |
+
B, S, D = win_shapes[local_i]
|
| 1653 |
+
moe_out = win_moe_out_flat[local_i].to(
|
| 1654 |
+
device, dtype=torch.bfloat16
|
| 1655 |
+
).view(B, S, D)
|
| 1656 |
+
|
| 1657 |
+
if has_shared:
|
| 1658 |
+
normed_ffn = win_x_flat[local_i].to(
|
| 1659 |
+
device, dtype=torch.bfloat16
|
| 1660 |
+
).view(B, S, D)
|
| 1661 |
+
shared_out = forward_swiglu_expert(
|
| 1662 |
+
normed_ffn,
|
| 1663 |
+
pruned_layer_state,
|
| 1664 |
+
shared_prefix,
|
| 1665 |
+
device,
|
| 1666 |
+
swiglu_limit=swiglu_limit,
|
| 1667 |
+
dequant_cache=shared_dequant_cache,
|
| 1668 |
+
)
|
| 1669 |
+
moe_out = moe_out + shared_out
|
| 1670 |
+
|
| 1671 |
+
res_state = buffer_mgr.load_chunk(
|
| 1672 |
+
write_dir, c_idx, device=device
|
| 1673 |
)
|
| 1674 |
+
hc_pair = mid_hc_post[c_idx]
|
| 1675 |
+
if hc_pair is not None:
|
| 1676 |
+
post_ffn = hc_pair[0].to(device, dtype=torch.float32)
|
| 1677 |
+
comb_ffn = hc_pair[1].to(device, dtype=torch.float32)
|
| 1678 |
+
hs_out = hc_post_step(
|
| 1679 |
+
moe_out, res_state, post_ffn, comb_ffn
|
| 1680 |
+
)
|
| 1681 |
+
else:
|
| 1682 |
+
hs_out = res_state + moe_out
|
| 1683 |
+
|
| 1684 |
+
buffer_mgr.save_chunk(write_dir, c_idx, hs_out)
|
| 1685 |
+
|
| 1686 |
+
del (
|
| 1687 |
+
shared_dequant_cache,
|
| 1688 |
+
win_x_flat,
|
| 1689 |
+
win_topk_idx,
|
| 1690 |
+
win_topk_weights,
|
| 1691 |
+
win_moe_out_flat,
|
| 1692 |
+
)
|
| 1693 |
+
if str(device).startswith("cuda") and torch.cuda.is_available():
|
| 1694 |
+
torch.cuda.empty_cache()
|
| 1695 |
+
print(
|
| 1696 |
+
f" [Pass 2 - Pruned MoE Forward] {st_name}: {w_end}/{num_chunks} chunks",
|
| 1697 |
+
flush=True,
|
| 1698 |
+
)
|
| 1699 |
|
| 1700 |
parity += 1
|
| 1701 |
|
| 1702 |
+
del mid_normed_q, mid_hc_post
|
| 1703 |
|
| 1704 |
# Bước C5: Lưu file .safetensors đã cắt của Tầng L
|
| 1705 |
out_shard_path = os.path.join(output_dir, out_shard_name)
|