Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

8.3 KB
Raw Blame
from __future__ import annotations
from typing_extensions import override
import os
import torch
import torch.nn.functional as F
from torch import nn
from ..model.config import Config
from . import Module
from ..ext import exllamav3_ext as ext
from ..model.model_tp_alloc import TPAllocation

_hip = torch.version.hip is not None

class GatedRMSNorm(Module):

    def __init__(
        self,
        config: Config | None,
        key: str,
        rms_norm_eps: float,
        out_dtype: torch.dtype | None = None,
        qmap: str | None = None,
        constant_bias: float = 0.0,
        groups: int = 1,
        gate_first: bool = False,
        gate_activation: str = "silu",
    ):
        super().__init__(config, key, None)
        assert qmap is None, "No quant scheme for RMSNorm"
        self.module_name = "RMSNorm"

        self.weight = None
        self.rms_norm_eps = rms_norm_eps
        self.out_dtype = out_dtype
        self._numel = None
        self.constant_bias = constant_bias
        # Mamba2 group norm: input viewed as rows of (weight.numel() / groups) channels, weight
        # row selected per group, and the gate applied before the norm: y = norm(x * silu(g)) * w
        self.groups = groups
        self.gate_first = gate_first
        # "silu" (GDN/Mamba2) or "sigmoid" (KDA); sigmoid takes the fp32 torch path (norm,
        # weight and gate all fp32, gate applied after the weighted norm, per the KDA reference)
        self.gate_activation = gate_activation
        assert gate_activation in ("silu", "sigmoid")
        self.bc = None

    @override
    def optimizer_targets(self):
        return []

    @override
    def load(self, device: torch.device, **kwargs):
        self.device = device
        weight = self.config.stc.get_tensor(f"{self.key}.weight", self.device, allow_bf16 = True)
        self._numel = weight.numel()
        self.weight = nn.Parameter(weight, requires_grad = False)

        self.bc = ext.BC_GatedRMSNorm(
            self.weight,
            self.rms_norm_eps,
            self.constant_bias,
            self.groups,
            self.gate_first,
            1 if self.gate_activation == "sigmoid" else 0,
        )

    @override
    def unload(self):
        self.bc = None
        self.device = None
        self.weight = None

    @override
    def get_tensors(self):
        return {
            f"{self.key}.weight": self.weight.data
        }

    def forward_torch(
        self,
        x: torch.Tensor,
        params,
        out_dtype: torch.dtype | None = None,
        gate: torch.Tensor = None,
    ) -> torch.Tensor:
        input_dtype = x.dtype
        if self.gate_first:
            hidden_states = x.to(torch.float32) * F.silu(gate.to(torch.float32))
            variance = hidden_states.pow(2).mean(-1, keepdim = True)
            hidden_states = hidden_states * torch.rsqrt(variance + self.rms_norm_eps)
            w = self.weight.view(self.groups, -1) if self.groups > 1 else self.weight
            hidden_states = w.to(torch.float32) * hidden_states
        else:
            hidden_states = x.to(torch.float32)
            variance = hidden_states.pow(2).mean(-1, keepdim=True)
            hidden_states = hidden_states * torch.rsqrt(variance + self.rms_norm_eps)
            hidden_states = self.weight * hidden_states.to(input_dtype)
            hidden_states = hidden_states * F.silu(gate.to(torch.float32))
        x = hidden_states.to(out_dtype or self.out_dtype)
        return x

    @override
    def weights_numel(self):
        return self._numel

    @override
    def forward(
        self,
        x: torch.Tensor,
        params,
        out_dtype: torch.dtype | None = None,
        gate: torch.Tensor = None,
        out_pitch: int = 0,
    ) -> torch.Tensor:
        gate_act = 1 if self.gate_activation == "sigmoid" else 0
        if gate_act and not (x.dtype == torch.bfloat16 and x.is_contiguous() and gate.is_contiguous()):
            # KDA torch fallback: strict-fp32 norm and weight, sigmoid gate after the norm
            h = x.to(torch.float32)
            h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim = True) + self.rms_norm_eps)
            h = self.weight.to(torch.float32) * h
            h = h * torch.sigmoid(gate.to(torch.float32))
            return h.to(out_dtype or self.out_dtype or x.dtype)
        if out_pitch:
            # write y with a padded token-row pitch (see exl3.row_pad_pitch); the caller checked eligibility.
            # y is a (bsz, seqlen, heads, dim) view of a (tokens, out_pitch) buffer
            assert _hip and x.dim() >= 3 and (out_dtype or self.out_dtype) == torch.half
            hd = x.shape[-2] * x.shape[-1]
            y = torch.empty((x.numel() // hd, out_pitch), dtype = torch.half, device = x.device)[:, :hd].view(x.shape)
            ext.gated_rms_norm(x, self.weight, y, gate, self.rms_norm_eps, self.constant_bias, self.groups, self.gate_first, gate_act, out_pitch)
            return y
        y = torch.empty_like(x, dtype = out_dtype or self.out_dtype)
        # EXL3_KDA_NORM_FUSED: norm.cu is not built on ROCm, so ext.gated_rms_norm is a ~12-kernel torch
        # fallback with fp32 intermediates. One Triton pass instead (gated_delta_net_fn/kda_norm.py)
        if (
            _hip and self.groups == 1 and not self.gate_first
            and x.dtype == torch.bfloat16 and x.is_contiguous() and gate.is_contiguous()
            and os.environ.get("EXL3_KDA_NORM_FUSED", "0") == "1"
        ):
            from .gated_delta_net_fn.kda_norm import kda_norm
            kda_norm(x, self.weight, y, gate, self.rms_norm_eps, self.constant_bias, silu = not gate_act)
            return y
        ext.gated_rms_norm(x, self.weight, y, gate, self.rms_norm_eps, self.constant_bias, self.groups, self.gate_first, gate_act)
        return y

    def make_tp_allocation(self, options: dict) -> list[TPAllocation]:
        stc = self.config.stc
        storage = sum(stc.get_tensor_sizes(self.key))
        overhead = storage // 2 * (self.out_dtype or torch.half).itemsize
        tpa = TPAllocation(
            key = self.key,
            storage_per_device = storage,
            overhead_per_device = overhead,
        )
        return [tpa]

    def tp_export(self, plan, producer):
        assert self.device is not None, "Cannot export module for TP before loading."
        return {
            "cls": GatedRMSNorm,
            "kwargs": {
                "key": self.key,
                "rms_norm_eps": self.rms_norm_eps,
                "out_dtype": self.out_dtype,
                "constant_bias": self.constant_bias,
                "groups": self.groups,
                "gate_first": self.gate_first,
            },
            "weight": producer.send(self.weight),
            "device": self.device,
        }

    @staticmethod
    def tp_import(local_context, exported, plan):
        consumer = local_context["consumer"]
        device = local_context["device"]
        module = GatedRMSNorm(
            config = None,
            **exported["kwargs"],
        )
        module.device = device
        w = consumer.recv(exported["weight"], cuda = True)
        module.weight = nn.Parameter(w)
        # load() builds the BC alongside the weight; the TP import must too, or graphed consumers
        # (BC_GatedDeltaNetSplit holds norm.bc) get a null pointer
        module.bc = ext.BC_GatedRMSNorm(module.weight, module.rms_norm_eps, module.constant_bias,
                                        module.groups, module.gate_first)
        torch.cuda.synchronize()
        return module

    @staticmethod
    def tp_import_split(local_context, exported, plan, split):
        consumer = local_context["consumer"]
        device = local_context["device"]
        first, last = split
        module = GatedRMSNorm(
            config = None,
            **exported["kwargs"],
        )
        module.device = device

        w = consumer.recv(exported["weight"], cuda = True)
        if w.dim() == 2:
            w = w[first : last, :]
        elif w.dim() == 1 and (last - first) < w.shape[0]:
            # Per-channel weight (Mamba2 group norm): element range; the caller fixes up
            # module.groups to the local group count
            w = w[first : last]
        module.weight = nn.Parameter(w.to(module.device).contiguous())
        module.bc = ext.BC_GatedRMSNorm(module.weight, module.rms_norm_eps, module.constant_bias,
                                        module.groups, module.gate_first)

        return module