from __future__ import annotations import math import torch from torch import nn from torch.nn import functional as F def quantize_experts(weight, storage="fp8"): # Tensorwise per expert: transpose can reuse the exact same quantized storage and scale. if storage not in ("fp8", "int8"): raise ValueError(f"Unsupported frozen expert storage: {storage}") limit = 448. if storage == "fp8" else 127. scales = weight.float().abs().amax(dim=(1, 2)).clamp_min(1.e-12)/limit q = (weight.float()/scales[:, None, None]).clamp(-limit, limit) q = q.to(torch.float8_e4m3fn) if storage == "fp8" else q.round().to(torch.int8) return q.contiguous(), scales.float() def reference_grouped(x, weight, offsets, mapping=None, transpose=False): """CPU mathematical reference; never selected for CUDA execution.""" output = [] start = 0 for expert, end in enumerate(offsets.tolist()): wi = expert if mapping is None else int(mapping[expert]) n = weight.shape[2] if transpose else weight.shape[1] if wi < 0: output.append(x[start:end].sum(-1, keepdim=True).expand(-1, n)*0) else: w = weight[wi].T if transpose else weight[wi] output.append(F.linear(x[start:end], w.to(x.dtype))) start = end return torch.cat(output) class FrozenFP8Linear(torch.autograd.Function): @staticmethod def forward(ctx, x, weight, scales, offsets): from .kernels import grouped ctx.save_for_backward(weight, scales, offsets) return grouped(x, weight, offsets, scales=scales) @staticmethod def backward(ctx, dy): from .kernels import grouped weight, scales, offsets = ctx.saved_tensors return grouped(dy, weight, offsets, transpose=True, scales=scales, backward=True), None, None, None class AdapterLinear(torch.autograd.Function): @staticmethod def forward(ctx, x, weight, offsets, mapping, selected): from .kernels import grouped ctx.save_for_backward(x, weight, offsets, mapping, selected) return grouped(x, weight, offsets, mapping=mapping) @staticmethod def backward(ctx, dy): from .kernels import grouped, weight_gradient x, w, off, mapping, selected = ctx.saved_tensors dx = grouped(dy, w, off, mapping=mapping, transpose=True) if ctx.needs_input_grad[0] else None dw = weight_gradient(x, dy, w, off, selected) return dx, dw, None, None, None class SelectedLoRA(nn.Module): def __init__(self, experts, selected, in_features, out_features, rank, alpha, device): super().__init__() self.register_buffer("selected", torch.tensor(selected, device=device, dtype=torch.int32)) mapping = torch.full((experts,), -1, device=device, dtype=torch.int32) mapping[self.selected.long()] = torch.arange(len(selected), device=device, dtype=torch.int32) self.register_buffer("mapping", mapping) self.a = nn.Parameter(torch.empty(len(selected), rank, in_features, device=device, dtype=torch.float32)) self.b = nn.Parameter(torch.zeros(len(selected), out_features, rank, device=device, dtype=torch.float32)) # Each expert gets an independent fan-in initialization, not the 3D tensor's aggregate fan-in. nn.init.uniform_(self.a, -1/math.sqrt(in_features), 1/math.sqrt(in_features)) self.scale = alpha/rank def forward(self, x, offsets): if x.is_cuda: low = AdapterLinear.apply(x, self.a, offsets, self.mapping, self.selected) return AdapterLinear.apply(low, self.b, offsets, self.mapping, self.selected)*self.scale low = reference_grouped(x, self.a, offsets, self.mapping) return reference_grouped(low, self.b, offsets, self.mapping)*self.scale class FrozenFP8Experts(nn.Module): """Frozen byte-weight experts: Hopper FP8 or Ampere INT8-storage/BF16-compute. The historical class/buffer names stay stable for existing adapters. INT8 weights are dequantized inside GEMM tiles, never into a second full copy. """ def __init__(self, gate_up, down, storage="fp8"): super().__init__() self.experts, twice_intermediate, self.hidden = gate_up.shape self.intermediate = twice_intermediate//2 for name, weight in (("gate_up", gate_up), ("down", down)): q, scales = quantize_experts(weight, storage) if storage == "fp8" and q.is_cuda and torch.cuda.get_device_capability(q.device)[0] == 8: q = q.view(torch.uint8) self.register_buffer(name+"_q8", q) self.register_buffer(name+"_scale", scales) self.gate_up_lora = self.down_lora = None self.profile = False self.profile_mask = None self.register_buffer("routing_counts", torch.zeros(self.experts, dtype=torch.int64, device=gate_up.device)) def install_adapters(self, selected, rank, alpha): if len(set(selected)) != len(selected) or any(not 0 <= i < self.experts for i in selected): raise ValueError("Invalid expert selection") device = self.gate_up_q8.device self.gate_up_lora = SelectedLoRA(self.experts, selected, self.hidden, 2*self.intermediate, rank, alpha, device) self.down_lora = SelectedLoRA(self.experts, selected, self.intermediate, self.hidden, rank, alpha, device) def _linear(self, x, name, offsets): w, scale = getattr(self, name+"_q8"), getattr(self, name+"_scale") if x.is_cuda: return FrozenFP8Linear.apply(x, w, scale, offsets) return reference_grouped(x, w.float()*scale[:, None, None], offsets) def forward(self, hidden_states, top_k_index, top_k_weights): if self.profile: routes = top_k_index if self.profile_mask is None else top_k_index[self.profile_mask] self.routing_counts.add_(torch.bincount(routes.reshape(-1), minlength=self.experts)) tokens, dim = hidden_states.shape routes = top_k_index.reshape(-1) order = torch.argsort(routes, stable=True) source = torch.arange(tokens, device=routes.device).repeat_interleave(top_k_index.shape[-1])[order] offsets = torch.bincount(routes, minlength=self.experts).cumsum(0).to(torch.int32) # Repeated input gathers accumulate their backward contributions in # FP32, rather than through BF16 atomics on the residual stream. x = hidden_states.float()[source].to(hidden_states.dtype) gate_up = self._linear(x, "gate_up", offsets) if self.gate_up_lora is not None: gate_up = gate_up + self.gate_up_lora(x, offsets) gate, up = gate_up.chunk(2, -1) active = F.silu(gate)*up y = self._linear(active, "down", offsets) if self.down_lora is not None: y = y + self.down_lora(active, offsets) y = y * top_k_weights.reshape(-1)[order, None].to(y.dtype) # Restore token/top-k order before summing. Each inverse index is unique; # this avoids unordered BF16 atomic reductions of the routed outputs. inverse = torch.empty_like(order) inverse[order] = torch.arange(order.numel(), device=order.device) return y[inverse].float().reshape(tokens, top_k_index.shape[-1], dim).sum(1).to(hidden_states.dtype) class SharedLoRALinear(nn.Module): def __init__(self, base, rank, alpha): super().__init__() self.base = base.requires_grad_(False) self.a = nn.Parameter(torch.empty(rank, base.in_features, device=base.weight.device, dtype=torch.float32)) self.b = nn.Parameter(torch.zeros(base.out_features, rank, device=base.weight.device, dtype=torch.float32)) nn.init.kaiming_uniform_(self.a, a=math.sqrt(5)) self.scale = alpha/rank def forward(self, x): return self.base(x) + F.linear(F.linear(x, self.a.to(x.dtype)), self.b.to(x.dtype))*self.scale def select_experts(counts, count): # Stable ties; this selection is saved with the checkpoint and never recomputed on resume. return sorted(range(len(counts)), key=lambda i: (-counts[i], i))[:count]