Token Classification
lora
AI-Detector-35BA3B / gpu /block_fp8.py
matthewagi's picture matt's picture
Initial model release
86599c0
Raw History Blame Contribute Delete
1.65 kB
import torch
def pack_experts(weight):
# Match vLLM's per_block_cast_to_fp8 for the merged, training-rounded BF16 weights.
experts, rows, cols = weight.shape
if rows % 128 or cols % 128 or weight.dtype != torch.bfloat16:
raise ValueError(f"Unsupported MoE weight {weight.shape} {weight.dtype}")
packed = torch.empty_like(weight, dtype=torch.float8_e4m3fn)
scales = torch.empty(
(experts, rows // 128, cols // 128), dtype=torch.float32, device=weight.device
)
for start in range(0, experts, 8):
block = weight[start : start + 8].reshape(
-1, rows // 128, 128, cols // 128, 128
)
scale = block.abs().float().amax((2, 4), keepdim=True).clamp_min_(1e-4) / 448
scales[start : start + 8].copy_(scale[:, :, 0, :, 0])
packed[start : start + 8].copy_(
(block * scale.reciprocal()).reshape(-1, rows, cols)
)
return packed, scales
def configure_serialized_experts(config, ignored):
# vLLM may resolve either the original names or packed linear-module prefixes.
for layer in range(config["num_hidden_layers"]):
prefix = f"model.layers.{layer}"
ignored.update(
f"{prefix}.{name}"
for name in (
"linear_attn.in_proj_qkvz",
"linear_attn.in_proj_ba",
"self_attn.qkv_proj",
"mlp.shared_expert.gate_up_proj",
)
)
config["quantization_config"] = {
"quant_method": "fp8",
"activation_scheme": "dynamic",
"weight_block_size": [128, 128],
"ignored_layers": sorted(ignored),
}