Token Classification
lora
matthewagi's picture matt's picture
Initial model release
86599c0
Raw History Blame Contribute Delete
5.41 kB
"""Swap in Hopper expert kernels while keeping the BF16 attribution path."""
import torch
@torch.no_grad()
def convert(backbone, config, precision, *, encoder_backend=None, encoder_layers=0):
if precision == "bf16":
return {"expert_layers": 40, "expert_weights": "BF16", "activations": "BF16"}
from vllm.config import set_current_vllm_config
from vllm.model_executor.layers.fused_moe import RoutedExperts
from vllm.model_executor.layers.quantization.online.fp8 import (
Fp8PerBlockOnlineMoEMethod,
)
method_class = Fp8PerBlockOnlineMoEMethod
backend = "triton"
kernels = set()
with set_current_vllm_config(config):
for number, layer in enumerate(backbone.layers, 1):
(expert,) = [
module
for module in layer.modules()
if isinstance(module, RoutedExperts)
]
selected = (
encoder_backend
if encoder_backend and number <= encoder_layers
else backend
)
if expert.w13_weight.dtype == torch.float8_e4m3fn:
# The portable FP8 checkpoint is loaded as canonical Triton block weights.
if (
type(expert.quant_method.moe_kernel.fused_experts).__name__
!= "TritonExperts"
):
raise ValueError(
"Expected canonical Triton FP8 weights before backend selection"
)
if selected in ("auto", "triton"):
kernels.add("TritonExperts")
continue
expert.moe_config.moe_backend = selected
method = method_class(moe=expert.moe_config)
method._setup_kernel(
expert,
expert.w13_weight,
expert.w2_weight,
expert.w13_weight_scale_inv,
expert.w2_weight_scale_inv,
None,
None,
)
expert._replace_quant_method(method)
kernels.add(type(method.moe_kernel.fused_experts).__name__)
continue
expert.moe_config.moe_backend = selected
method = method_class(moe=expert.moe_config)
if "quant_method" in expert._modules:
del expert.quant_method
expert._replace_quant_method(method)
expert.w13_input_scale = expert.w2_input_scale = None
method.process_weights_after_loading(expert)
if method.moe_kernel is None or expert.w13_weight.dtype == torch.bfloat16:
raise RuntimeError(
f"No quantized kernel for {precision} expert layer {number}"
)
kernels.add(type(method.moe_kernel.fused_experts).__name__)
if number % 10 == 0:
print("CONVERTED", precision, number, sorted(kernels), flush=True)
torch.cuda.empty_cache()
return {
"expert_layers": number,
"kernels": sorted(kernels),
"expert_weights": "FP8 E4M3 block 128x128"
if precision.startswith("fp8")
else "MXFP4 group 32",
"activations": "dynamic FP8 for expert GEMMs"
if precision.startswith("fp8")
else "16-bit for expert GEMMs",
}
@torch.no_grad()
def convert_dense_projections(roots, gates):
"""Apply CUTLASS FP8 to eligible projections, excluding the routed expert gates."""
from types import MethodType
from torch import nn
from torch.nn import functional as F
from vllm import _custom_ops as ops
from vllm.model_executor.layers.linear import LinearBase
def dense_forward(self, x):
flat = x.reshape(-1, x.shape[-1]).to(torch.bfloat16).contiguous()
activation, scale = ops.scaled_fp8_quant(flat, use_per_token_if_dynamic=True)
output = ops.cutlass_scaled_mm(
activation, self.weight.T, scale, self.weight_scale, torch.bfloat16
)
output = output[:, : self.original_width].reshape(
*x.shape[:-1], self.original_width
)
bias = getattr(self, "bias", None)
skip = getattr(self, "skip_bias_add", False)
if bias is not None and not skip:
output = output + bias.to(output.dtype)
return (
(output, bias if skip else None)
if getattr(self, "return_bias", False)
else output
)
seen = set()
for root in roots:
for mod in root.modules():
if not isinstance(mod, (nn.Linear, LinearBase)) or id(mod) in gates | seen:
continue
if mod.weight.ndim != 2 or mod.weight.shape[1] % 16:
continue
seen.add(id(mod))
weight = mod.weight.detach().float()
mod.original_width = weight.shape[0]
weight = F.pad(weight, (0, 0, 0, (-weight.shape[0]) % 16))
scale = weight.abs().amax(dim=1, keepdim=True).clamp_min(1e-12) / 448
mod.weight = nn.Parameter(
(weight / scale).clamp(-448, 448).to(torch.float8_e4m3fn),
requires_grad=False,
)
mod.register_buffer("weight_scale", scale.contiguous())
mod.forward = MethodType(dense_forward, mod)
torch.cuda.empty_cache()
return len(seen)