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|
|
|
| 1 |
+
"""
|
| 2 |
+
Convert MTP expert weights from NVFP4 packed format to INT4 compressed-tensors.
|
| 3 |
+
|
| 4 |
+
FP4 E2M1 format: 2 values packed per U8 byte
|
| 5 |
+
weight: [out, in/2] U8 (2 FP4 per byte, block_size_fp4=16 fp4 values = 8 bytes)
|
| 6 |
+
weight_scale: [out, in/2/8] F8E4M3 (one scale per 8 bytes = per 16 fp4 values)
|
| 7 |
+
weight_scale_2: scalar F32 (global scale)
|
| 8 |
+
input_scale: scalar F32 (activation scale, ignored for weight loading)
|
| 9 |
+
"""
|
| 10 |
+
import torch
|
| 11 |
+
import numpy as np
|
| 12 |
+
from safetensors import safe_open
|
| 13 |
+
from safetensors.torch import save_file
|
| 14 |
+
from collections import OrderedDict
|
| 15 |
+
|
| 16 |
+
MTP_PATH = "/data/models/Kimi-K2.5-MTP/mtp_fp8_orig.safetensors"
|
| 17 |
+
OUTPUT_PATH = "/data/models/Kimi-K2.5-MTP/mtp.safetensors"
|
| 18 |
+
GROUP_SIZE = 32 # INT4 group size for compressed-tensors
|
| 19 |
+
PACK_FACTOR = 8 # 8 INT4 values per INT32 (GPTQ format, matches base model) # 4 INT4 values per INT32 (GPTQ format)
|
| 20 |
+
|
| 21 |
+
# NV FP4 E2M1 decode table (4-bit index → float value)
|
| 22 |
+
# E2M1: 1 sign bit, 2 exponent bits, 1 mantissa bit
|
| 23 |
+
FP4_TABLE = torch.tensor([
|
| 24 |
+
0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
|
| 25 |
+
-0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0
|
| 26 |
+
], dtype=torch.float32)
|
| 27 |
+
|
| 28 |
+
def dequant_fp4_block(weight_u8, weight_scale_fp8e4m3, weight_scale_2_f32):
|
| 29 |
+
"""Dequantize FP4-packed weight to BF16.
|
| 30 |
+
|
| 31 |
+
weight_u8: [out, in/2] — 2 FP4 values per U8 byte
|
| 32 |
+
weight_scale: [out, in/2/8] F8E4M3 — scale per 8 bytes (16 fp4 values)
|
| 33 |
+
weight_scale_2: scalar F32 — global scale
|
| 34 |
+
|
| 35 |
+
Returns: [out, in] BF16
|
| 36 |
+
"""
|
| 37 |
+
out_f, in_packed = weight_u8.shape
|
| 38 |
+
in_fp4 = in_packed * 2 # actual number of FP4 values per row
|
| 39 |
+
|
| 40 |
+
# Unpack FP4: low nibble first, then high nibble
|
| 41 |
+
w_u8 = weight_u8.to(torch.int32)
|
| 42 |
+
low_nibble = w_u8 & 0x0F # [out, in/2]
|
| 43 |
+
high_nibble = (w_u8 >> 4) & 0x0F # [out, in/2]
|
| 44 |
+
|
| 45 |
+
# Interleave: low nibble at even positions, high nibble at odd
|
| 46 |
+
unpacked = torch.stack([low_nibble, high_nibble], dim=-1) # [out, in/2, 2]
|
| 47 |
+
unpacked = unpacked.reshape(out_f, in_fp4) # [out, in]
|
| 48 |
+
|
| 49 |
+
# Decode FP4 values
|
| 50 |
+
decoded = FP4_TABLE[unpacked.cpu()].to(torch.float32) # [out, in]
|
| 51 |
+
|
| 52 |
+
# Apply per-block scale: each block = 16 fp4 values = 8 bytes
|
| 53 |
+
# weight_scale shape: [out, in/16] (in F8E4M3)
|
| 54 |
+
scale = weight_scale_fp8e4m3.to(torch.float32) # [out, in/16]
|
| 55 |
+
# Repeat scale for each 16-element block
|
| 56 |
+
scale_expanded = scale.repeat_interleave(16, dim=-1) # [out, in]
|
| 57 |
+
|
| 58 |
+
# Apply global scale
|
| 59 |
+
global_scale = weight_scale_2_f32.item() if weight_scale_2_f32.numel() == 1 else 1.0
|
| 60 |
+
|
| 61 |
+
result = decoded * scale_expanded * global_scale
|
| 62 |
+
return result.to(torch.bfloat16)
|
| 63 |
+
|
| 64 |
+
def quantize_int4_gptq(weight_bf16, group_size=32):
|
| 65 |
+
"""Quantize BF16 to INT4 GPTQ format (packed 4 values per INT32)."""
|
| 66 |
+
out_f, in_f = weight_bf16.shape
|
| 67 |
+
w = weight_bf16.to(torch.float32)
|
| 68 |
+
|
| 69 |
+
pad = (group_size - in_f % group_size) % group_size
|
| 70 |
+
if pad > 0:
|
| 71 |
+
w = torch.nn.functional.pad(w, (0, pad))
|
| 72 |
+
in_padded = w.shape[1]
|
| 73 |
+
|
| 74 |
+
w_grouped = w.reshape(out_f, -1, group_size)
|
| 75 |
+
scales = w_grouped.abs().amax(dim=-1) / 7.0
|
| 76 |
+
scales = scales.clamp(min=1e-10)
|
| 77 |
+
|
| 78 |
+
w_int = torch.round(w_grouped / scales.unsqueeze(-1)).clamp(-8, 7).to(torch.int8)
|
| 79 |
+
w_int = w_int.reshape(out_f, in_padded)
|
| 80 |
+
|
| 81 |
+
# Pack 4 INT4 values per INT32
|
| 82 |
+
w_unsigned = (w_int + 8).to(torch.int32)
|
| 83 |
+
w_r = w_unsigned.reshape(out_f, -1, PACK_FACTOR)
|
| 84 |
+
packed = torch.zeros(out_f, w_r.shape[1], dtype=torch.int32)
|
| 85 |
+
for i in range(PACK_FACTOR):
|
| 86 |
+
packed |= (w_r[:, :, i] & 0xF) << (i * 4)
|
| 87 |
+
|
| 88 |
+
shape = torch.tensor([out_f, in_f], dtype=torch.int32)
|
| 89 |
+
return packed, scales.to(torch.bfloat16), shape
|
| 90 |
+
|
| 91 |
+
print("Loading original FP4-packed MTP weights...")
|
| 92 |
+
new_tensors = OrderedDict()
|
| 93 |
+
converted_expert = 0
|
| 94 |
+
converted_shared = 0
|
| 95 |
+
passed = 0
|
| 96 |
+
|
| 97 |
+
with safe_open(MTP_PATH, framework="pt", device="cpu") as f:
|
| 98 |
+
all_keys = sorted(f.keys())
|
| 99 |
+
|
| 100 |
+
# Identify FP4-packed projections (have weight + weight_scale with U8 dtype)
|
| 101 |
+
fp4_bases = set()
|
| 102 |
+
for k in all_keys:
|
| 103 |
+
if k.endswith(".weight") and not k.endswith("_scale") and not k.endswith("_scale_2"):
|
| 104 |
+
t = f.get_tensor(k)
|
| 105 |
+
if t.dtype == torch.uint8:
|
| 106 |
+
base = k[:-7]
|
| 107 |
+
if f"{base}.weight_scale" in all_keys:
|
| 108 |
+
fp4_bases.add(base)
|
| 109 |
+
|
| 110 |
+
print(f"FP4-packed projections: {len(fp4_bases)}")
|
| 111 |
+
|
| 112 |
+
processed = set()
|
| 113 |
+
for k in all_keys:
|
| 114 |
+
if k in processed:
|
| 115 |
+
continue
|
| 116 |
+
|
| 117 |
+
base = None
|
| 118 |
+
for fb in fp4_bases:
|
| 119 |
+
if k.startswith(fb + "."):
|
| 120 |
+
base = fb
|
| 121 |
+
break
|
| 122 |
+
|
| 123 |
+
if base is not None:
|
| 124 |
+
if k == f"{base}.weight":
|
| 125 |
+
w_u8 = f.get_tensor(k)
|
| 126 |
+
w_scale = f.get_tensor(f"{base}.weight_scale")
|
| 127 |
+
w_scale2 = f.get_tensor(f"{base}.weight_scale_2")
|
| 128 |
+
|
| 129 |
+
w_bf16 = dequant_fp4_block(w_u8, w_scale, w_scale2)
|
| 130 |
+
|
| 131 |
+
if ".mlp.experts." in base:
|
| 132 |
+
packed, scales, shape = quantize_int4_gptq(w_bf16, GROUP_SIZE)
|
| 133 |
+
new_tensors[f"{base}.weight_packed"] = packed
|
| 134 |
+
new_tensors[f"{base}.weight_scale"] = scales
|
| 135 |
+
new_tensors[f"{base}.weight_shape"] = shape
|
| 136 |
+
converted_expert += 1
|
| 137 |
+
if converted_expert == 1:
|
| 138 |
+
print(f" Sample: {base}.weight_packed: {list(packed.shape)}, scale: {list(scales.shape)}")
|
| 139 |
+
else:
|
| 140 |
+
new_tensors[f"{base}.weight"] = w_bf16
|
| 141 |
+
converted_shared += 1
|
| 142 |
+
|
| 143 |
+
processed.update([k, f"{base}.weight_scale", f"{base}.weight_scale_2", f"{base}.input_scale"])
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
new_tensors[k] = f.get_tensor(k)
|
| 147 |
+
passed += 1
|
| 148 |
+
|
| 149 |
+
print(f"Expert→INT4: {converted_expert}, Shared→BF16: {converted_shared}, Passthrough: {passed}")
|
| 150 |
+
print(f"Total: {len(new_tensors)}")
|
| 151 |
+
print("Saving...")
|
| 152 |
+
save_file(new_tensors, OUTPUT_PATH)
|
| 153 |
+
import os
|
| 154 |
+
print(f"Saved: {os.path.getsize(OUTPUT_PATH)/1024/1024:.1f} MB")
|