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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
from __future__ import annotations
from typing_extensions import override
import torch
import torch.nn.functional as F
from torch import nn
from ..model.config import Config
from ..util.tensor import to2
from . import Module, Linear
from ..ext import exllamav3_ext as ext
from .. import ext as _ext_mod
def _rocm_silu_lim() -> bool:
# ext.silu_mul on ROCm runs fused_silu_mul with the clamp (GLM swiglu_limit) while this knob is on (ext.py ROCM_KNOBS)
return bool(getattr(_ext_mod, "ROCM_KNOBS", {}).get("silu_lim"))
from ..constants import MAX_MLP_INTERMEDIATE
from ..model.model_tp_alloc import TPAllocation
from .multilinear import MultiLinear
from ..util.tensor import g_tensor_cache
from .quant.exl3 import VERIFY_FUSE, MAX_BSZN_GEMV_R, dec_workspace
from .quant.exl3 import row_pad_pitch as _row_pad_pitch
import os
MAX_BSZN = 8 # must match MAX_BSZN in exllamav3_ext/libtorch/mlp.h and block_sparse_mlp.py
class MLP(Module):
def __init__(
self,
config: Config | None,
key: str,
hidden_size: int,
intermediate_size: int,
out_size: int | None = None,
key_up: str | None = None,
key_down: str | None = None,
key_alpha_p: str | None = None,
key_alpha_n: str | None = None,
alpha_p: float | None = None,
alpha_n: float | None = None,
qmap: str | None = None,
out_dtype: torch.dtype = None,
activation_fn: str = "silu",
intermediate_split_size: int | None = MAX_MLP_INTERMEDIATE,
interm_dtype: torch.dtype = None,
pad_to = 128,
ups: list[Linear | Module] = None,
downs: list[Linear | Module] = None,
select_hq_bits: int = 0,
qbits_key: str = "bits"
):
super().__init__(config, key, None)
self.q_priority = 1 + select_hq_bits
self.hidden_size = hidden_size
self.pad_to = pad_to
self.out_dtype = out_dtype
self.interm_dtype = interm_dtype
self.activation_fn = activation_fn
self.intermediate_size = intermediate_size
self.intermediate_split_size = intermediate_split_size
self.out_size = out_size or hidden_size
fkey, frange_up = None, None
if ups is not None:
assert downs is not None and len(downs) == len(ups)
self.num_slices = len(ups)
self.ups = ups
self.downs = downs
else:
if intermediate_split_size and intermediate_size > intermediate_split_size:
num_slices = (intermediate_size + intermediate_split_size - 1) // intermediate_split_size
interm_slice = intermediate_size // num_slices // 128 * 128
interm_split = [interm_slice for _ in range(num_slices)]
interm_split[-1] += intermediate_size - sum(interm_split)
self.num_slices = num_slices
else:
interm_split = [intermediate_size]
self.num_slices = 1
self.ups = []
self.downs = []
a = 0
for idx, sp in enumerate(interm_split):
b = a + sp
if self.num_slices > 1:
s_key_u = f"{key}.{key_up}.slice.{idx}"
s_key_d = f"{key}.{key_down}.slice.{idx}"
a_key_u = f"{key}.{key_up}"
a_key_d = f"{key}.{key_down}"
else:
s_key_u = f"{key}.{key_up}"
s_key_d = f"{key}.{key_down}"
a_key_u = None
a_key_d = None
up = Linear(
config = config,
key = s_key_u,
in_features = hidden_size,
out_features = b - a,
full_in_features = hidden_size,
full_out_features = intermediate_size,
first_in_feature = 0,
first_out_feature = a,
qmap = qmap + ".input" if qmap is not None else None,
fkey = fkey,
frange = frange_up,
alt_key = a_key_u,
out_dtype = self.interm_dtype,
pad_to = pad_to,
select_hq_bits = select_hq_bits,
qgroup = key + ".u",
qbits_key = qbits_key,
)
down = Linear(
config = config,
key = s_key_d,
in_features = b - a,
out_features = self.out_size,
full_in_features = intermediate_size,
full_out_features = self.out_size,
first_in_feature = a,
first_out_feature = 0,
qmap = qmap + ".down" if qmap is not None else None,
alt_key = a_key_d,
out_dtype = self.out_dtype,
allow_input_padding = True,
pad_to = pad_to,
trim_padded_out = True,
select_hq_bits = select_hq_bits,
qgroup = key + ".d",
qbits_key = qbits_key,
)
self.ups.append(up)
self.downs.append(down)
self.register_submodule(up)
self.register_submodule(down)
a = b
self.activation_fn = activation_fn
self.key_alpha_p = key_alpha_p
self.key_alpha_n = key_alpha_n
self.alpha_p = alpha_p
self.alpha_n = alpha_n
match activation_fn:
case "silu": self.activation_fn_call = F.silu
case "gelu": self.activation_fn_call = lambda x: F.gelu(x, approximate = "tanh")
case "gelu_exact": self.activation_fn_call = F.gelu
case "quick_gelu": self.activation_fn_call = lambda x: x * torch.sigmoid(1.702 * x)
case "relu2": self.activation_fn_call = lambda x: torch.square(F.relu(x))
case "xielu": self.activation_fn_call = self.act_xielu
self.tp_reduce = False
self.bc = None
self.bsz1_pa_args = []
@override
def optimizer_targets(self):
u, d = [], []
for m in self.ups: u += m.optimizer_targets()
for m in self.downs: d += m.optimizer_targets()
return [[u, d]]
@override
def can_defer_load(self):
if self.num_slices > 1: return False
return super().can_defer_load()
@override
def load(self, device: torch.Device, load_slice: int | None = None, **kwargs):
if load_slice is None:
super().load(device, **kwargs)
else:
self.ups[load_slice].load(device, **kwargs)
self.downs[load_slice].load(device, **kwargs)
if self.key_alpha_p:
self.alpha_p = self.config.stc.get_tensor(self.key_alpha_p, None, optional = False, allow_bf16 = True)
if self.key_alpha_n:
self.alpha_n = self.config.stc.get_tensor(self.key_alpha_n, None, optional = False, allow_bf16 = True)
self.load_local(device, **kwargs)
def load_local(self, device: torch.Device, **kwargs):
# Graphed bsz-1 path (up -> act -> down in one C++ call)
self.bc = None
if (
device != torch.device("cpu") and
self.num_slices == 1 and
self.activation_fn in ("silu", "gelu", "relu2") and
self.interm_dtype in (None, torch.half) and
self.ups[0].quant_type == "exl3" and self.ups[0].inner.bc is not None and
self.downs[0].quant_type == "exl3" and self.downs[0].inner.bc is not None
):
up0, down0 = self.ups[0], self.downs[0]
self.bsz1_pa_args = [
(device, (1, 1, up0.out_features), torch.half, "mlp_u"),
(device, (1, 1, up0.out_features), torch.half, "mlp_ones"),
]
u, ones = (g_tensor_cache.get(*arg) for arg in self.bsz1_pa_args)
ones.fill_(1.0)
# Zero-padded staging statics for padded projection dims (hidden % 128 != 0)
xp = None
if up0.in_features != self.hidden_size:
xp = g_tensor_cache.get(device, (1, up0.in_features), torch.half, "mlp_xp")
xp.zero_()
yp = None
if down0.out_features != self.out_size:
yp = g_tensor_cache.get(device, (1, down0.out_features), self.out_dtype or torch.half, "mlp_yp")
self.bc = ext.BC_MLP(
xp = xp,
u = u,
ones = ones,
yp = yp,
act_silu = self.activation_fn == "silu",
act_gelu = self.activation_fn == "gelu",
act_relu2 = self.activation_fn == "relu2",
up = up0.inner.bc,
down = down0.inner.bc,
act_limit = 0.0,
hidden_size = self.hidden_size,
out_size = self.out_size,
)
@override
def unload(self):
super().unload()
self.alpha_p = None
self.alpha_n = None
self.bc = None
self.bsz1_pa_args = []
@override
def pin_linears(self):
# Pinning swaps the children's native linear handles; the graphed bsz-1 path built by
# load_local captured the old ones and, through them, the original VRAM trellis. Rebuild
# it against the pinned linears so the moved weights are actually released
super().pin_linears()
if self.device is not None:
self.load_local(self.device)
def act_xielu_torch(self, x):
alpha_p = nn.functional.softplus(self.alpha_p.float()).item()
alpha_n = nn.functional.softplus(self.alpha_n.float()).item() + 0.5
eps = torch.tensor([-9.9838e-07], device = x.device)
return torch.where(
x > 0,
alpha_p * x * x + 0.5 * x,
(torch.expm1(torch.min(x, eps)) - x) * alpha_n + 0.5 * x,
).half()
def act_xielu(self, x):
y = torch.empty_like(x, dtype = torch.half)
ext.xielu(x, y, self.alpha_p, self.alpha_n)
return y
@override
def forward(
self,
x: torch.Tensor,
params: dict,
out_dtype: torch.dtype | None = None
) -> torch.Tensor:
# Fused C++ path for single-token decode, replayed through an internal CUDA graph from
# the third invocation on
bsz, q_len, _ = x.shape
if (
self.bc is not None and bsz == 1 and q_len == 1 and
x.dtype == torch.float16 and x.is_contiguous()
):
d = torch.empty_like(x, dtype = out_dtype or self.out_dtype)
self.bc.run_bsz1(x, d)
if self.tp_reduce:
params["backend"].all_reduce(d)
return to2(d, out_dtype, self.out_dtype)
qs = params.get("q_mlp_slice")
r = [qs] if qs is not None else range(0, self.num_slices)
d = None
for s in r:
u = self.ups[s].forward(x, params)
# TODO: mixed precision activation kernel?
a = self.activation_fn_call(u)
if self.interm_dtype == torch.float:
a = a.half()
d_ = self.downs[s].forward(a, params)
if d is None: d = d_
else: d += d_
del d_
if self.tp_reduce:
params["backend"].all_reduce(d)
return to2(d, out_dtype, self.out_dtype)
@override
def get_tensors(self):
t = super().get_tensors()
if self.alpha_p is not None:
t[self.key_alpha_p] = self.alpha_p
if self.alpha_n is not None:
t[self.key_alpha_n] = self.alpha_n
return t
def make_tp_allocation(self, options: dict) -> list[TPAllocation]:
storage = 0
ims = min(self.intermediate_size, self.intermediate_split_size)
for u in self.ups: storage += u.storage_size()
for d in self.downs: storage += d.storage_size()
overhead_d = self.hidden_size * (self.out_dtype or torch.half).itemsize
overhead_s = 2 * ims * (self.interm_dtype or torch.half).itemsize
if self.interm_dtype != torch.half:
overhead_s += ims * torch.half.itemsize
recons = max(
self.ups[0].recons_size(),
self.downs[0].recons_size()
)
slice = self.num_slices > 1
tpa = TPAllocation(
key = self.key,
channel_width = 1 if slice else 128,
channel_unit = "slices" if slice else "channels",
storage_per_device = 0,
storage_to_split = storage,
overhead_per_device = overhead_d,
overhead_to_split = overhead_s,
recons_temp = recons,
channels_to_split = self.num_slices if slice else self.ups[0].out_features // 128,
limit_key = "mlp"
)
return [tpa]
def tp_export(self, plan, producer):
assert self.device is not None, "Cannot export module for TP before loading."
assert self.pad_to == 128, "Cannot export module for TP unless pad_to == 128."
def _export(child):
nonlocal producer
return child.tp_export(plan, producer) if child is not None else None
return {
"cls": MLP,
"kwargs": {
"key": self.key,
"hidden_size": self.hidden_size,
"intermediate_size": self.intermediate_size,
"activation_fn": self.activation_fn,
"out_dtype": self.out_dtype,
"interm_dtype": self.interm_dtype,
"intermediate_split_size": self.intermediate_split_size,
},
"alpha_p": producer.send(self.alpha_p),
"alpha_n": producer.send(self.alpha_n),
"ups": [_export(self.ups[i]) for i in range(self.num_slices)],
"downs": [_export(self.downs[i]) for i in range(self.num_slices)],
"device": self.device,
}
@staticmethod
def tp_import(local_context, exported, plan, **kwargs):
consumer = local_context["consumer"]
key = exported["kwargs"]["key"]
device = local_context["device"]
first, last, unit = plan[key]
num_slices = len(exported["ups"])
if first >= last:
num_slices = 0
def _import_i_split(name, i, split):
nonlocal exported, plan
return exported[name][i]["cls"].tp_import_split(local_context, exported[name][i], plan, split) \
if exported.get(name) else None
def _import_i(name, i):
nonlocal exported, plan
return exported[name][i]["cls"].tp_import(local_context, exported[name][i], plan) \
if exported.get(name) else None
if num_slices == 1:
assert unit == "channels"
u_split = (True, first, last)
d_split = (False, first, last)
module = MLP(
config = None,
**exported["kwargs"],
ups = [_import_i_split("ups", 0, u_split)],
downs = [_import_i_split("downs", 0, d_split)],
)
elif num_slices > 1:
assert unit == "slices"
module = MLP(
config = None,
**exported["kwargs"],
ups = [_import_i("ups", i) for i in range(first, last)],
downs = [_import_i("downs", i) for i in range(first, last)],
)
else:
module = MLP(
config = None,
**exported["kwargs"],
ups = [],
downs = [],
)
module.device = device
module.alpha_p = consumer.recv(exported["alpha_p"], cuda = False)
module.alpha_n = consumer.recv(exported["alpha_n"], cuda = False)
if not kwargs.get("skip_reduction"):
module.tp_reduce = True
if module.num_slices == 1:
module.load_local(device)
torch.cuda.synchronize()
return module
def _vf_plain_exl3(l, dim: int) -> bool:
"""a Linear whose forward is exactly inner.forward (no pad/trim/lora/scales/bias)
and whose inner LinearEXL3 can run exl3_dec_gemv_r."""
return (
getattr(l, "quant_type", None) == "exl3" and getattr(l.inner, "dec_ok", False) and
l.inner.bias is None and not l.lora_a_tensors and l.in_features == dim and
l.pre_scale == 1.0 and l.softcap == 0.0 and l.post_scale == 1.0 and
not (l.trim_padded_out and l.out_features != l.out_features_unpadded)
)
_FQ_GU_CAT = os.environ.get("EXL3_FQ_GU_CAT", "1") != "0"
# EXL3_MOE_Q8_REUSE (default 1): the MoE shared expert reuses the routed call's q8_1(x) (only with the q8q8 path, BOLT_FQ_Q8Q8)
_Q8_REUSE = os.environ.get("EXL3_MOE_Q8_REUSE", "1") != "0" and os.environ.get("BOLT_FQ_Q8Q8", "1") != "0"
_Q8_REUSE_SAID = [False]
def _fq_gu_cat(mlp, s, x, params = None):
"""Gate + up of a foreign Q8_0 slice in ONE fq_gemv_q8_0 at 1 row: the row-stacked [gate; up] weights cached once, one q8
quantization of x and one launch instead of two of each. Each output row is the same dot over the same quantized x, so g and u
are bit-identical to the two separate calls. Returns (g, u) views or None (any other case keeps the two calls)."""
if not _FQ_GU_CAT or not hasattr(ext, "fq_gemv_q8_0"):
return None
gm, um = mlp.gates[s], mlp.ups[s]
if getattr(gm, "format", None) != "q8_0" or getattr(um, "format", None) != "q8_0":
return None
if gm.packed is None or um.packed is None or gm.in_features != um.in_features or gm.out_features != um.out_features:
return None
if x.dtype != torch.half or not x.is_contiguous() or x.shape[-1] != gm.in_features or x.device != gm.packed.device:
return None
if (gm.out_dtype or torch.half) != torch.half or (um.out_dtype or torch.half) != torch.half:
return None
N, K = gm.out_features, gm.in_features
cache = mlp.__dict__.setdefault("_fq_gu_cat_w", {})
w = cache.get(s)
if w is None or w[0] != gm.packed.data_ptr():
w = (gm.packed.data_ptr(), torch.cat([gm.packed.reshape(N, -1), um.packed.reshape(N, -1)], 0).contiguous())
cache[s] = w
out = torch.empty((1, 2 * N), dtype = torch.half, device = x.device)
if _Q8_REUSE and params is not None and params.get("fq_q8_x") == x.data_ptr() and hasattr(ext, "fq_gemv_q8_0_q8"):
# q8_1(x) already in the cached scratch (written by the routed MoE call on the same x): same bytes fq_gemv_q8_0 would make
ext.fq_gemv_q8_0_q8(ext.fq_q8_scratch(x.device.index, 1, K), w[1].reshape(2 * N, -1, 34), out)
if not _Q8_REUSE_SAID[0]:
_Q8_REUSE_SAID[0] = True
print(" -- MoE shared expert reuses the routed q8_1(x)", flush = True)
else:
ext.fq_gemv_q8_0(x.reshape(1, K), w[1].reshape(2 * N, -1, 34), out)
shp = x.shape[:-1] + (N,)
return out[:, :N].view(shp), out[:, N:].view(shp)
class GatedMLP(Module):
def __init__(
self,
config: Config | None,
key: str,
hidden_size: int,
intermediate_size: int,
key_up: str | None = None,
key_gate: str | None = None,
key_down: str | None = None,
key_fused_gate_up: str | None = None,
qmap: str | None = None,
out_dtype: torch.dtype = None,
activation_fn: str = "silu",
intermediate_split_size: int | None = MAX_MLP_INTERMEDIATE,
interm_dtype: torch.dtype = None,
act_limit: float = 0.0,
pad_to = 128,
gates: list[Linear | Module] = None,
ups: list[Linear | Module] = None,
downs: list[Linear | Module] = None,
select_hq_bits: int = 0,
qbits_key: str = "bits"
):
super().__init__(config, key, None)
self.out_dtype = out_dtype
self.interm_dtype = interm_dtype
self.activation_fn = activation_fn
self.intermediate_size = intermediate_size
self.hidden_size = hidden_size
self.intermediate_split_size = intermediate_split_size
self.pad_to = pad_to
self.act_limit = act_limit
if key_fused_gate_up:
assert not intermediate_split_size or intermediate_size <= intermediate_split_size, \
"Cannot combine fused gate/up layers with MLP slicing"
fkey = f"{key}.{key_fused_gate_up}"
frange_gate = (0, intermediate_size)
frange_up = (intermediate_size, 2 * intermediate_size)
else:
fkey, frange_gate, frange_up = None, None, None
if gates is not None:
assert ups is not None and len(ups) == len(gates)
assert downs is not None and len(downs) == len(gates)
self.num_slices = len(gates)
self.gates = gates
self.ups = ups
self.downs = downs
else:
if intermediate_split_size and intermediate_size > intermediate_split_size:
num_slices = (intermediate_size + intermediate_split_size - 1) // intermediate_split_size
interm_slice = intermediate_size // num_slices // 128 * 128
interm_split = [interm_slice for _ in range(num_slices)]
interm_split[-1] += intermediate_size - sum(interm_split)
self.num_slices = num_slices
else:
interm_split = [intermediate_size]
self.num_slices = 1
self.gates = []
self.ups = []
self.downs = []
a = 0
for idx, sp in enumerate(interm_split):
b = a + sp
if self.num_slices > 1:
s_key_g = f"{key}.{key_gate}.slice.{idx}"
s_key_u = f"{key}.{key_up}.slice.{idx}"
s_key_d = f"{key}.{key_down}.slice.{idx}"
a_key_g = f"{key}.{key_gate}"
a_key_u = f"{key}.{key_up}"
a_key_d = f"{key}.{key_down}"
else:
s_key_g = f"{key}.{key_gate}"
s_key_u = f"{key}.{key_up}"
s_key_d = f"{key}.{key_down}"
a_key_g = None
a_key_u = None
a_key_d = None
gate = Linear(
config = config,
key = s_key_g,
in_features = hidden_size,
out_features = b - a,
full_in_features = hidden_size,
full_out_features = intermediate_size,
first_in_feature = 0,
first_out_feature = a,
qmap = qmap + ".input" if qmap is not None else None,
fkey = fkey,
frange = frange_gate,
alt_key = a_key_g,
out_dtype = self.interm_dtype,
pad_to = pad_to,
select_hq_bits = select_hq_bits,
qgroup = key + ".gu",
qbits_key = qbits_key,
)
up = Linear(
config = config,
key = s_key_u,
in_features = hidden_size,
out_features = b - a,
full_in_features = hidden_size,
full_out_features = intermediate_size,
first_in_feature = 0,
first_out_feature = a,
qmap = qmap + ".input" if qmap is not None else None,
fkey = fkey,
frange = frange_up,
alt_key = a_key_u,
out_dtype = self.interm_dtype,
pad_to = pad_to,
select_hq_bits = select_hq_bits,
qgroup = key + ".gu",
qbits_key = qbits_key,
)
down = Linear(
config = config,
key = s_key_d,
in_features = b - a,
out_features = hidden_size,
full_in_features = intermediate_size,
full_out_features = hidden_size,
first_in_feature = a,
first_out_feature = 0,
qmap = qmap + ".down" if qmap is not None else None,
alt_key = a_key_d,
out_dtype = self.out_dtype,
allow_input_padding = True,
pad_to = pad_to,
select_hq_bits = select_hq_bits,
qgroup = key + ".d",
qbits_key = qbits_key,
)
self.ups.append(up)
self.gates.append(gate)
self.downs.append(down)
self.register_submodule(up)
self.register_submodule(gate)
self.register_submodule(down)
a = b
match activation_fn:
case "silu": self.activation_fn_call = ext.silu_mul
case "relu2": self.activation_fn_call = ext.relu2_mul
case "gelu": self.activation_fn_call = ext.gelu_mul
self.tp_reduce = False
self.multi_gu: list[MultiLinear | None] = [None] * self.num_slices
self.bc = None
self.bsz1_pa_args = []
@override
def optimizer_targets(self):
g, u, d = [], [], []
for m in self.gates: g += m.optimizer_targets()
for m in self.ups: u += m.optimizer_targets()
for m in self.downs: d += m.optimizer_targets()
return [[g + u, d]]
@override
def can_defer_load(self):
if self.num_slices > 1: return False
return super().can_defer_load()
@override
def load(self, device: torch.Device, load_slice: int | None = None, **kwargs):
if load_slice is None:
super().load(device, **kwargs)
else:
self.gates[load_slice].load(device, **kwargs)
self.ups[load_slice].load(device, **kwargs)
self.downs[load_slice].load(device, **kwargs)
self.load_local(device, load_slice or 0, **kwargs)
def load_local(self, device: torch.Device, load_slice: int, **kwargs):
# Test if gate and up proj can be fused
if (
not self.config.infer_params.no_reconstruct and
device != torch.device("cpu") and
self.gates[load_slice].quant_type == "exl3" and
self.ups[load_slice].quant_type == "exl3" and
self.gates[load_slice].out_features == self.ups[load_slice].out_features and
self.gates[load_slice].inner.K == self.ups[load_slice].inner.K and
self.gates[load_slice].inner.bias is None and
self.ups[load_slice].inner.bias is None and
self.config.infer_params.use_mgemm(
self.gates[load_slice].inner.K,
self.gates[load_slice].out_features,
self.gates[load_slice].inner.mul1 and self.ups[load_slice].inner.mul1,
self.device,
)
):
self.multi_gu[load_slice] = MultiLinear(self.device, [self.gates[load_slice], self.ups[load_slice]])
# Graphed bsz-1 path: fused gate+up mgemm when available, otherwise two separate GEMV
# calls (the unfused configuration the int8-activation GEMV mode prefers)
self.bc = None
if self.num_slices == 1 and self.downs[0].inner.bc is not None:
mgu = self.multi_gu[0]
g0, u0 = self.gates[0], self.ups[0]
can_separate = (
mgu is None and
g0.quant_type == "exl3" and g0.inner.bc is not None and
u0.quant_type == "exl3" and u0.inner.bc is not None and
g0.out_features == u0.out_features
)
if mgu is not None or can_separate:
out_f = mgu.out_features if mgu is not None else g0.out_features
self.bsz1_pa_args = [
(device, (2, MAX_BSZN, self.hidden_size), self.interm_dtype, "gu"),
(device, (2, MAX_BSZN, out_f), self.interm_dtype, "a1"),
(device, (1, MAX_BSZN, out_f), torch.half, "a2"),
(device, (1, MAX_BSZN, out_f), torch.half, "down_xh"),
]
self.bc = ext.BC_GatedMLP(
*(g_tensor_cache.get(*arg) for arg in self.bsz1_pa_args),
mgu.ptrs_trellis if mgu is not None else None,
mgu.ptrs_suh if mgu is not None else None,
mgu.ptrs_svh if mgu is not None else None,
mgu.K if mgu is not None else 0,
bool(mgu.mcg) if mgu is not None else False,
bool(mgu.mul1) if mgu is not None else False,
self.activation_fn == "silu",
self.activation_fn == "gelu",
self.activation_fn == "relu2",
g0.inner.bc if mgu is None else None,
u0.inner.bc if mgu is None else None,
self.downs[0].inner.bc,
self.act_limit,
)
@override
def unload(self):
super().unload()
if self.bc is not None:
# for arg in self.bsz1_pa_args:
# g_tensor_cache.drop(*arg)
self.bc = None
self.bsz1_pa_args = []
for i in range(self.num_slices):
if self.multi_gu[i] is not None:
self.multi_gu[i].unload()
self.multi_gu[i] = None
@override
def pin_linears(self):
# As MLP.pin_linears, plus the fused gate/up MultiLinear: its pointer table holds raw
# device addresses of the pre-pin trellis tensors, which the prefill path would otherwise
# keep reading after those tensors are freed
super().pin_linears()
if self.device is None:
return
for i in range(self.num_slices):
if self.multi_gu[i] is not None:
self.multi_gu[i].unload()
self.multi_gu[i] = None
self.load_local(self.device, 0)
@override
def forward(
self,
x: torch.Tensor,
params: dict,
out_dtype: torch.dtype | None = None
) -> torch.Tensor:
bsz, q_len, dim = x.shape
# EXL3_NC2_SHARED_FUSE: the MoE reduce widens and adds the down GEMM's fp16 output itself
nc2_half = bool(params.get("nc2_down_half")) and self.num_slices == 1 and not self.tp_reduce
if self.num_slices == 0:
d = torch.zeros_like(x, dtype = self.out_dtype)
if self.tp_reduce:
params["backend"].all_reduce(d, False)
else:
qs = params.get("q_mlp_slice")
r = [qs] if qs is not None else range(0, self.num_slices)
d = None
for s in r:
# R-row verify, gate+up in ONE exl3_dec_gemv_r_multi launch (Hadamards
# inside) instead of 2 x (had_in + exl3_gemv + had_out); down goes to gemv_r via
# LinearEXL3.forward. Same activation call as the unfused branch below.
if (
VERIFY_FUSE["on"] and 1 < bsz * q_len <= MAX_BSZN_GEMV_R and
params.get("dflash_verify") and x.dtype == torch.half and x.is_contiguous() and
hasattr(ext, "exl3_dec_gemv_r_multi") and
_vf_plain_exl3(self.gates[s], dim) and _vf_plain_exl3(self.ups[s], dim) and
self.gates[s].inner.K == self.ups[s].inner.K and
self.gates[s].out_features == self.ups[s].out_features
):
gi, ui = self.gates[s].inner, self.ups[s].inner
rows = bsz * q_len
g = torch.empty((bsz, q_len, gi.out_features), dtype = gi.default_out_dtype, device = x.device)
u = torch.empty_like(g, dtype = ui.default_out_dtype)
scratch, counters = dec_workspace(x.device)
ext.exl3_dec_gemv_r_multi(
x.view(rows, dim), [gi.trellis, ui.trellis], [gi.suh, ui.suh], [gi.svh, ui.svh],
[g.view(rows, -1), u.view(rows, -1)], scratch, counters, [gi.K, ui.K], False)
a = torch.empty_like(u, dtype = torch.half) if self.interm_dtype != torch.half else u
self.activation_fn_call(g, u, a, self.act_limit)
d_ = self.downs[s].forward(a, params, torch.half if nc2_half else None)
if d is None: d = d_
else: d += d_
del d_
continue
if self.bc is not None and bsz * q_len <= MAX_BSZN:
d = torch.empty_like(x, dtype = out_dtype or self.out_dtype)
xv = x.view(1, bsz * q_len, dim) # local view: x itself feeds every slice
self.bc.run_bszN(xv, d.view(xv.shape))
elif self.multi_gu[s] is None or bsz * q_len > 32:
gu = _fq_gu_cat(self, s, x, params) if bsz * q_len == 1 else None
if gu is not None:
g, u = gu
else:
g = self.gates[s].forward(x, params)
u = self.ups[s].forward(x, params)
# nc2 S1-rest (EXL3_NC2_SILU_PAD, default off): silu_mul writes its rows at the down projection's
# padded pitch, so the down GEMM skips its pad_copy_in (same values, bit-exact)
a_pitch = 0
# (only where ext.silu_mul itself runs fused_silu_mul, the kernel the pitched variant shares: ext.py)
if os.environ.get("EXL3_NC2_SILU_PAD", "0") == "1" and self.activation_fn_call is ext.silu_mul and \
hasattr(ext, "silu_mul_pitched") and os.environ.get("EXL3_FUSE_SILU", "1") != "0" and \
(not self.act_limit or _rocm_silu_lim()) and g.dtype == u.dtype and g.dtype in (torch.half, torch.float) and \
g.shape == u.shape and g.is_contiguous() and u.is_contiguous():
ik = u.shape[-1]
a_pitch = _row_pad_pitch(self.downs[s], ik, u.numel() // ik, params)
if a_pitch:
rows_ = u.numel() // ik
a = torch.empty((rows_, a_pitch), dtype = torch.half, device = u.device)[:, :ik]
ext.silu_mul_pitched(g, u, a, float(self.act_limit or 0.0))
a = a.view(*u.shape)
else:
a = torch.empty_like(u, dtype = torch.half) if self.interm_dtype != torch.half else u
self.activation_fn_call(g, u, a, self.act_limit)
d_ = self.downs[s].forward(a, params, torch.half if nc2_half else None)
if d is None: d = d_
else: d += d_
del d_
else:
xv = x.view(1, bsz * q_len, dim) # local view: x itself feeds every slice
guh = torch.empty((2, bsz * q_len, dim), dtype = self.interm_dtype, device = x.device)
gu = torch.empty((2, bsz * q_len, self.multi_gu[s].out_features), dtype = self.interm_dtype, device = x.device)
ext.exl3_mgemm(
xv,
self.multi_gu[s].ptrs_trellis,
gu,
self.multi_gu[s].ptrs_suh,
guh,
self.multi_gu[s].ptrs_svh,
None,
None,
self.multi_gu[s].K,
-1,
self.multi_gu[s].mcg,
self.multi_gu[s].mul1,
-1,
-1,
0,
1, None, None)
g = gu[0].view(bsz, q_len, self.multi_gu[s].out_features)
u = gu[1].view(bsz, q_len, self.multi_gu[s].out_features)
a = torch.empty_like(u, dtype = torch.half) if self.interm_dtype != torch.half else u
self.activation_fn_call(g, u, a, self.act_limit)
d_ = self.downs[s].forward(a, params, torch.half if nc2_half else None)
if d is None: d = d_
else: d += d_
del d_
if self.tp_reduce:
params["backend"].all_reduce(d)
if nc2_half and d.dtype == torch.half:
return d
return to2(d, out_dtype, self.out_dtype)
def make_tp_allocation(self, options: dict) -> list[TPAllocation]:
storage = 0
ims = min(self.intermediate_size, self.intermediate_split_size)
for g in self.gates: storage += g.storage_size()
for u in self.ups: storage += u.storage_size()
for d in self.downs: storage += d.storage_size()
overhead_d = self.hidden_size * (self.out_dtype or torch.half).itemsize
overhead_s = 2 * ims * (self.interm_dtype or torch.half).itemsize
if self.interm_dtype != torch.half:
overhead_s += ims * torch.half.itemsize
recons = max(
self.gates[0].recons_size(),
self.ups[0].recons_size(),
self.downs[0].recons_size()
)
slice = self.num_slices > 1
tpa = TPAllocation(
key = self.key,
channel_width = 1 if slice else 128,
channel_unit = "slices" if slice else "channels",
storage_per_device = 0,
storage_to_split = storage,
overhead_per_device = overhead_d,
overhead_to_split = overhead_s,
recons_temp = recons,
channels_to_split = self.num_slices if slice else self.ups[0].out_features // 128,
limit_key = "mlp"
)
return [tpa]
def tp_export(self, plan, producer):
assert self.device is not None, "Cannot export module for TP before loading."
assert self.pad_to == 128, "Cannot export module for TP unless pad_to == 128."
def _export(child):
nonlocal producer
return child.tp_export(plan, producer) if child is not None else None
return {
"cls": GatedMLP,
"kwargs": {
"key": self.key,
"hidden_size": self.hidden_size,
"intermediate_size": self.intermediate_size,
"activation_fn": self.activation_fn,
"out_dtype": self.out_dtype,
"interm_dtype": self.interm_dtype,
"intermediate_split_size": self.intermediate_split_size,
"act_limit": self.act_limit
},
"gates": [_export(self.gates[i]) for i in range(self.num_slices)],
"ups": [_export(self.ups[i]) for i in range(self.num_slices)],
"downs": [_export(self.downs[i]) for i in range(self.num_slices)],
"device": self.device,
}
@staticmethod
def tp_import(local_context, exported, plan, **kwargs):
key = exported["kwargs"]["key"]
device = local_context["device"]
first, last, unit = plan[key]
num_slices = len(exported["gates"])
if first >= last:
num_slices = 0
def _import_i_split(name, i, split):
nonlocal exported, plan
return exported[name][i]["cls"].tp_import_split(local_context, exported[name][i], plan, split) \
if exported.get(name) else None
def _import_i(name, i):
nonlocal exported, plan
return exported[name][i]["cls"].tp_import(local_context, exported[name][i], plan) \
if exported.get(name) else None
if num_slices == 1:
assert unit == "channels"
gu_split = (True, first, last)
d_split = (False, first, last)
exported["kwargs"]["intermediate_size"] = last - first
module = GatedMLP(
config = None,
**exported["kwargs"],
gates = [_import_i_split("gates", 0, gu_split)],
ups = [_import_i_split("ups", 0, gu_split)],
downs = [_import_i_split("downs", 0, d_split)],
)
elif num_slices > 1:
assert unit == "slices"
module = GatedMLP(
config = None,
**exported["kwargs"],
gates = [_import_i("gates", i) for i in range(first, last)],
ups = [_import_i("ups", i) for i in range(first, last)],
downs = [_import_i("downs", i) for i in range(first, last)],
)
else:
module = GatedMLP(
config = None,
**exported["kwargs"],
gates = [],
ups = [],
downs = [],
)
module.device = device
if not kwargs.get("skip_reduction"):
module.tp_reduce = True
for i in range(module.num_slices):
module.load_local(device, i)
torch.cuda.synchronize()
return module