drama-3-nvfp4 / runtime /disk_experts.py
Reza2kn's picture
Release owner-approved Drama 3 routed-expert NVFP4 checkpoint and validated runtime
fabc3df verified
Raw History Blame Contribute Delete
5.59 kB
"""On-demand Drama 3 experts with bounded GPU cache and native NVFP4 GEMMs."""
import json
import os
import re
from functools import lru_cache
from pathlib import Path
import flashinfer
import torch
import torch.nn.functional as functional
from safetensors import safe_open
from sglang.srt.layers.moe.fused_moe_triton import FusedMoE
from sglang.srt.layers.moe.token_dispatcher.standard import StandardCombineInput
from sglang.srt.layers.quantization.base_config import FusedMoEMethodBase
from sglang.srt.layers.quantization.modelopt_quant import ModelOptFp4Config
from sglang_omni.models.fishaudio_drama3.quantization import ExpertFp8Config
IS_SOURCE = os.environ.get('DRAMA3_REFERENCE_SOURCE') == '1'
CHECKPOINT = Path(os.environ.get('DRAMA3_CHECKPOINT', Path(__file__).resolve().parents[1])).expanduser().resolve()
WEIGHT_MAP = json.loads((CHECKPOINT / 'model.safetensors.index.json').read_text())['weight_map']
SHARDS = {}
def read_tensor(name):
filename = WEIGHT_MAP[name]
if filename not in SHARDS:
SHARDS[filename] = safe_open(str(CHECKPOINT / filename), framework='pt')
return SHARDS[filename].get_tensor(name).to('cuda')
@lru_cache(maxsize=64)
def expert_weights(layer_index, expert_index):
matrices = []
for projection in ['gate_proj', 'up_proj', 'down_proj']:
prefix = f'model.language_model.layers.{layer_index}.mlp.experts.{expert_index}.{projection}'
weight = read_tensor(prefix + '.weight')
if IS_SOURCE:
scales = read_tensor(prefix + '.weight_scale_inv').float()
rows, columns = weight.shape
weight = (weight.float().reshape(rows // 128, 128, columns // 128, 128)
* scales[:, None, :, None]).reshape(rows, columns)
matrices.append(weight.to(torch.bfloat16))
else:
scales = read_tensor(prefix + '.weight_scale')
global_scale = read_tensor(prefix + '.weight_scale_2').reshape(1)
matrices.append((weight, scales, global_scale))
if IS_SOURCE:
return matrices
gate, up, down = matrices
fused = (torch.cat([gate[0], up[0]]), torch.cat([gate[1], up[1]]), gate[2])
result = []
for packed, scales, global_scale in [fused, down]:
swizzled = flashinfer.nvfp4_block_scale_interleave(scales.contiguous().view(torch.uint8))
result.append((packed.contiguous(), swizzled, global_scale))
return result
def nvfp4_linear(activations, weights):
packed_weight, weight_scales, global_weight_scale = weights
token_count = activations.shape[0]
padded_count = max(16, (token_count + 15) // 16 * 16)
padded = functional.pad(activations, (0, 0, 0, padded_count - token_count))
packed, scales, token_scales = flashinfer.nvfp4_quantize(
padded.contiguous(), 1 / 2688,
sfLayout=flashinfer.SfLayout.layout_128x4,
per_token_activation=True, backend='cute-dsl')
output = flashinfer.mm_fp4(packed, packed_weight.T, scales, weight_scales,
global_weight_scale, out_dtype=torch.bfloat16,
backend='cutlass')
return (output[:token_count].float() * token_scales[:token_count, None]).to(activations.dtype)
class DiskExpertMethod(FusedMoEMethodBase):
def __init__(self, prefix):
self.layer_index = int(re.search(r'layers\.(\d+)', prefix).group(1))
def create_weights(self, layer, **kwargs):
def ignore_loaded_expert(parameter, loaded_weight, *args, **kwargs):
pass
suffixes = ['weight', 'weight_scale_inv'] if IS_SOURCE else ['weight', 'weight_scale', 'weight_scale_2', 'input_scale']
for prefix in ['w13', 'w2']:
for suffix in suffixes:
parameter = torch.nn.Parameter(torch.zeros(1), requires_grad=False)
parameter.weight_loader = ignore_loaded_expert
layer.register_parameter(prefix + '_' + suffix, parameter)
def create_moe_runner(self, layer, moe_runner_config):
self.runner = None
def apply(self, layer, dispatch_output):
hidden_states = dispatch_output.hidden_states
topk = dispatch_output.topk_output
expert_ids = topk.topk_ids
result = torch.zeros_like(hidden_states, dtype=torch.float32)
for expert_index in torch.unique(expert_ids).tolist():
if expert_index < 0:
continue
rows, slots = torch.where(expert_ids == expert_index)
selected = hidden_states[rows]
weights = expert_weights(self.layer_index, expert_index)
if IS_SOURCE:
gate, up, down = weights
intermediate = functional.silu(functional.linear(selected, gate)) * functional.linear(selected, up)
output = functional.linear(intermediate, down)
else:
gate_up, down = weights
gate, up = nvfp4_linear(selected, gate_up).chunk(2, dim=-1)
output = nvfp4_linear(functional.silu(gate) * up, down)
weighted = output.float() * topk.topk_weights[rows, slots].float().unsqueeze(-1)
result.index_add_(0, rows, weighted)
return StandardCombineInput(result.to(hidden_states.dtype))
def install():
config_class = ExpertFp8Config if IS_SOURCE else ModelOptFp4Config
original = config_class.get_quant_method
def disk_method(self, layer, prefix):
if isinstance(layer, FusedMoE):
return DiskExpertMethod(prefix)
return original(self, layer, prefix)
config_class.get_quant_method = disk_method