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.

nc2 S1-rest: silu_mul writes the down input at the padded pitch (EXL3_NC2_SILU_PAD); MLA unfold writes the o_proj input padded (EXL3_NC2_MLA_OPAD); attention keeps o_proj fp16 output when the block asked for it (EXL3_NC2_ATTN_F16)

YanissAmza7787696d369
diff --git a/exllamav3/exllamav3_ext/activation.cu b/exllamav3/exllamav3_ext/activation.cu
index 9b4cd19..b5eda93 100644
--- a/exllamav3/exllamav3_ext/activation.cu
+++ b/exllamav3/exllamav3_ext/activation.cu
@@ -97,6 +97,41 @@ void silu_mul
silu_mul_gr(x, y, z, act_limit, nullptr);
}
+// nc2 S1-rest: silu_mul into z = (rows, cols) view of a (rows, pitch) buffer; x, y contiguous (rows, cols)
+void silu_mul_pitched
+(
+ const at::Tensor& x,
+ const at::Tensor& y,
+ at::Tensor& z,
+ const float act_limit
+)
+{
+ const at::cuda::OptionalCUDAGuard device_guard(x.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+
+ bool float_input = x.dtype() == at::kFloat;
+ if (float_input) { TORCH_CHECK_DTYPE(y, kFloat); }
+ else { TORCH_CHECK_DTYPE(x, kHalf); TORCH_CHECK_DTYPE(y, kHalf); }
+ TORCH_CHECK_DTYPE(z, kHalf);
+ TORCH_CHECK(x.is_contiguous() && y.is_contiguous(), "silu_mul_pitched: x, y must be contiguous");
+ TORCH_CHECK(z.dim() == 2 && z.stride(1) == 1, "silu_mul_pitched: z must be a 2D row view");
+ int64_t rows = z.size(0), cols = z.size(1), pitch = z.stride(0);
+ TORCH_CHECK(x.numel() == rows * cols && y.numel() == rows * cols, "silu_mul_pitched: shape mismatch");
+ TORCH_CHECK(cols % 2 == 0 && pitch % 2 == 0 && pitch >= cols, "silu_mul_pitched: cols, pitch must be even, pitch >= cols");
+ TORCH_CHECK(((uintptr_t) z.data_ptr()) % 4 == 0, "silu_mul_pitched: z misaligned");
+ TORCH_CHECK((z.storage_offset() + (rows - 1) * pitch + cols) * 2 <= (int64_t) z.storage().nbytes(), "silu_mul_pitched: z overruns storage");
+
+ size_t numel = x.numel();
+ size_t blocks = CEIL_DIVIDE(numel, 2 * NUM_THREADS);
+ if (float_input)
+ silu_mul_pitched_kernel_f<<<blocks, NUM_THREADS, 0, stream>>>
+ ((const float*) x.data_ptr(), (const float*) y.data_ptr(), (half*) z.data_ptr(), act_limit, numel, (int) (cols / 2), (int) (pitch / 2));
+ else
+ silu_mul_pitched_kernel_h<<<blocks, NUM_THREADS, 0, stream>>>
+ ((const half*) x.data_ptr(), (const half*) y.data_ptr(), (half*) z.data_ptr(), act_limit, numel, (int) (cols / 2), (int) (pitch / 2));
+ cuda_check(cudaPeekAtLastError());
+}
+
// gpt-oss clamped swiglu: (clamp(y, -limit, limit) + 1) * g * sigmoid(1.702 * g),
// g = min(x, limit) -> z, in-place if z == x or z == y
diff --git a/exllamav3/exllamav3_ext/activation.cuh b/exllamav3/exllamav3_ext/activation.cuh
index 68c81f6..c87cbc8 100644
--- a/exllamav3/exllamav3_ext/activation.cuh
+++ b/exllamav3/exllamav3_ext/activation.cuh
@@ -20,6 +20,14 @@ void silu_mul
const float act_limit
);
+void silu_mul_pitched
+(
+ const at::Tensor& x,
+ const at::Tensor& y,
+ at::Tensor& z,
+ const float act_limit
+);
+
void silu_oai_mul_gr
(
const at::Tensor& x,
diff --git a/exllamav3/exllamav3_ext/activation_kernels.cuh b/exllamav3/exllamav3_ext/activation_kernels.cuh
index a6df688..ee6611e 100644
--- a/exllamav3/exllamav3_ext/activation_kernels.cuh
+++ b/exllamav3/exllamav3_ext/activation_kernels.cuh
@@ -252,6 +252,81 @@ void act_mul_kernel_f
}
+// nc2 S1-rest (EXL3_NC2_SILU_PAD): silu_mul whose output rows sit at a padded pitch, so the down projection
+// reads it without a pad copy. Inputs contiguous (rows, cols); same per-element math as act_mul_kernel_h/f<ACT_SILU>,
+// only the store address differs. cols and pitch are even (half2 units: cols2, pitch2)
+__global__ __launch_bounds__(NUM_THREADS)
+void silu_mul_pitched_kernel_h
+(
+ const half* __restrict__ x,
+ const half* __restrict__ y,
+ half* __restrict__ z,
+ const float act_limit,
+ const size_t numel,
+ const int cols2,
+ const int pitch2
+)
+{
+ size_t idx = (blockIdx.x * NUM_THREADS + threadIdx.x);
+ if (idx >= numel / 2) return;
+ size_t r = idx / cols2;
+ size_t zi = r * pitch2 + (idx - r * cols2);
+
+ half2 x2 = ((const half2*) x)[idx];
+ half2 y2 = ((const half2*) y)[idx];
+
+ x2 = _silu(x2);
+
+ if (act_limit != 0.0f)
+ {
+ y2 = __hmax2(y2, __float2half2_rn(-act_limit));
+ y2 = __hmin2(y2, __float2half2_rn(act_limit));
+ x2 = __hmin2(x2, __float2half2_rn(act_limit));
+ }
+
+ ((half2*) z)[zi] = __hmul2(x2, y2);
+}
+
+__global__ __launch_bounds__(NUM_THREADS)
+void silu_mul_pitched_kernel_f
+(
+ const float* __restrict__ x,
+ const float* __restrict__ y,
+ half* __restrict__ z,
+ const float act_limit,
+ const size_t numel,
+ const int cols2,
+ const int pitch2
+)
+{
+ size_t idx = (blockIdx.x * NUM_THREADS + threadIdx.x);
+ if (idx >= numel / 2) return;
+ size_t r = idx / cols2;
+ size_t zi = r * pitch2 + (idx - r * cols2);
+
+ float2 x2 = ((const float2*) x)[idx];
+ float2 y2 = ((const float2*) y)[idx];
+
+ x2.x = _silu(x2.x);
+ x2.y = _silu(x2.y);
+
+ if (act_limit != 0.0f)
+ {
+ if (y2.x < -act_limit) y2.x = -act_limit;
+ if (y2.y < -act_limit) y2.y = -act_limit;
+ if (y2.x > act_limit) y2.x = act_limit;
+ if (y2.y > act_limit) y2.y = act_limit;
+ if (x2.x > act_limit) x2.x = act_limit;
+ if (x2.y > act_limit) x2.y = act_limit;
+ }
+
+ x2.x *= y2.x;
+ x2.y *= y2.y;
+ half2 r2 = __float22half2_rn(x2);
+ r2 = clamp_half2_to_finite(r2);
+ ((half2*) z)[zi] = r2;
+}
+
__global__ __launch_bounds__(NUM_THREADS)
void xielu_kernel_f
(
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 5e0accc..248e7f2 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -252,6 +252,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("rope", &rope, "rope");
m.def("gen_mrope_pos_ids", &gen_mrope_pos_ids, "gen_mrope_pos_ids");
m.def("silu_mul", &silu_mul, "silu_mul");
+ m.def("silu_mul_pitched", &silu_mul_pitched, "silu_mul_pitched");
m.def("silu_oai_mul", &silu_oai_mul, "silu_oai_mul");
m.def("gelu_mul", &gelu_mul, "gelu_mul");
m.def("relu2_mul", &relu2_mul, "relu2_mul");
diff --git a/exllamav3/modules/attention_fn/mla_triton.py b/exllamav3/modules/attention_fn/mla_triton.py
index 5ad2b69..3ecc2b8 100644
--- a/exllamav3/modules/attention_fn/mla_triton.py
+++ b/exllamav3/modules/attention_fn/mla_triton.py
@@ -657,6 +657,7 @@ def _mla_unfold_kernel(
BLOCK_M: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_N: tl.constexpr, # D_v tile (grid axis 2); D_v itself = one tile per head
+ OUT_PITCH: tl.constexpr = 0, # nc2 S1-rest: row pitch of out in elements (0 = dense H * D_v)
):
"""Per-head unfold o_h = o_lat_h @ W_UV_h from the flat layout, emitting token-major
output so o_proj consumes it without a permute. The V columns are split over grid axis 2
@@ -676,8 +677,12 @@ def _mla_unfold_kernel(
mask = valid_m[:, None], other = 0.0)
w_t = tl.load(w_uv_flat + offs_k[:, None] * (n_q_heads * D_v) + head * D_v + offs_v[None, :])
acc = tl.dot(o_t, w_t, acc = acc)
- tl.store(out + (offs_m[:, None] * n_q_heads + head) * D_v + offs_v[None, :],
- acc.to(tl.float16), mask = valid_m[:, None])
+ if OUT_PITCH:
+ tl.store(out + offs_m[:, None] * OUT_PITCH + head * D_v + offs_v[None, :],
+ acc.to(tl.float16), mask = valid_m[:, None])
+ else:
+ tl.store(out + (offs_m[:, None] * n_q_heads + head) * D_v + offs_v[None, :],
+ acc.to(tl.float16), mask = valid_m[:, None])
@triton.jit
@@ -1361,11 +1366,18 @@ def _unfold_cfg(R: int, v_head_dim: int):
return block_m, 128, v_head_dim, 2, 4
-def mla_unfold(o_lat: torch.Tensor, w_uv_flat: torch.Tensor, v_head_dim: int):
- """(H, R, kv_lora_rank) head-major latent output -> (R, H, v_head_dim) token-major."""
+def mla_unfold(o_lat: torch.Tensor, w_uv_flat: torch.Tensor, v_head_dim: int, out: torch.Tensor = None):
+ """(H, R, kv_lora_rank) head-major latent output -> (R, H, v_head_dim) token-major.
+ out (nc2 S1-rest): optional (R, H * v_head_dim) fp16 row view with unit column stride and any row pitch."""
H, R, D_c = o_lat.shape
- out = torch.empty((R, H, v_head_dim), dtype = torch.half, device = o_lat.device)
- if _dec_valu_unfold_ok(R, o_lat, w_uv_flat, H, v_head_dim):
+ out_pitch = 0
+ if out is not None:
+ assert out.dtype == torch.half and out.dim() == 2 and out.shape == (R, H * v_head_dim) and out.stride(1) == 1 \
+ and out.stride(0) >= H * v_head_dim
+ out_pitch = out.stride(0) if out.stride(0) != H * v_head_dim else 0
+ else:
+ out = torch.empty((R, H, v_head_dim), dtype = torch.half, device = o_lat.device)
+ if out_pitch == 0 and _dec_valu_unfold_ok(R, o_lat, w_uv_flat, H, v_head_dim):
_mla_ext().mla_unfold_dec(o_lat, w_uv_flat, out) # see mla_absorb_dec
return out
block_m, block_k, block_n, stages, warps = _unfold_cfg(R, v_head_dim)
@@ -1380,7 +1392,7 @@ def mla_unfold(o_lat: torch.Tensor, w_uv_flat: torch.Tensor, v_head_dim: int):
_mla_unfold_kernel[grid](
o_lat, w_uv_flat, out, R,
H, D_c, v_head_dim,
- block_m, block_k, block_n,
+ block_m, block_k, block_n, out_pitch,
num_warps = warps, num_stages = stages,
)
_unfold_block_k[fb_key] = block_k
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index f8c3aa1..ee29571 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -1729,6 +1729,10 @@ class GatedDeltaNet(Module):
if self.tp_reduce:
params["backend"].all_reduce(x)
+ # EXL3_NC2_ATTN_F16 (default off): keep o_proj's fp16 output when the block asked for it (see MLAttention)
+ if out_dtype is None and x.dtype == torch.half and params.get("pfe_y_half") and \
+ os.environ.get("EXL3_NC2_ATTN_F16", "0") == "1":
+ return x
return to2(x, out_dtype, self.out_dtype)
diff --git a/exllamav3/modules/mla_attn.py b/exllamav3/modules/mla_attn.py
index 5cffa4e..8b290b8 100644
--- a/exllamav3/modules/mla_attn.py
+++ b/exllamav3/modules/mla_attn.py
@@ -550,6 +550,11 @@ class MLAttention(Module):
raise ValueError(f"Unknown attn_mode: {attn_mode}")
if x is None:
return None # EXL3_PF_SKIP: kv_only, see _attend
+ # EXL3_NC2_ATTN_F16 (default off): the block asked for fp16 y (pfe_y_half) and o_proj returned it; keep it
+ # instead of the fp32 widen to self.out_dtype (the residual apply / ablit project_widen widen in-kernel)
+ if out_dtype is None and x.dtype == torch.half and params.get("pfe_y_half") and \
+ os.environ.get("EXL3_NC2_ATTN_F16", "0") == "1":
+ return x
return to2(x, out_dtype, self.out_dtype)
@@ -1296,10 +1301,24 @@ class MLAttention(Module):
"""Unfold W_UV per head from the flat layout (the kernel emits token-major output, so it
feeds o_proj without a permute), then o_proj. Context-length independent; the piecewise
block graph captures it with the MLP half."""
+ k = self.num_q_heads * self.v_head_dim
+ pitch = self._nc2_o_pitch(o_lat.shape[1], params)
+ if pitch:
+ buf = torch.empty((o_lat.shape[1], pitch), dtype = torch.half, device = o_lat.device)[:, :k]
+ mla_unfold(o_lat, self.w_uv_flat, self.v_head_dim, out = buf)
+ return self._dec_proj(self.o_proj, buf.view(bsz, seqlen, k), params)
o = mla_unfold(o_lat, self.w_uv_flat, self.v_head_dim)
- o = o.reshape(bsz, seqlen, self.num_q_heads * self.v_head_dim)
+ o = o.reshape(bsz, seqlen, k)
return self._dec_proj(self.o_proj, o, params)
+ def _nc2_o_pitch(self, rows: int, params: dict) -> int:
+ """EXL3_NC2_MLA_OPAD (default off): row pitch for the o_proj input so the unfold writes it padded and o_proj
+ skips its pad_copy_in (same values, bit-exact). 0 = dense."""
+ if os.environ.get("EXL3_NC2_MLA_OPAD", "0") != "1" or self.o_proj is None:
+ return 0
+ from .quant.exl3 import row_pad_pitch
+ return row_pad_pitch(self.o_proj, self.num_q_heads * self.v_head_dim, rows, params)
+
def _attend_split(self, q, q_pe, q_lat, head, seqlen, params, ckv_cache, kpe_cache,
block_table, host_seqlens, indices, qc):
@@ -1315,7 +1334,12 @@ class MLAttention(Module):
q_pe = q_pe.reshape(R, H, D_r)
qh = q[:head]
qh[:, :, self.qk_nope_head_dim:] = q_pe[:head]
- o = torch.empty((R, H, self.v_head_dim), dtype = torch.half, device = q.device)
+ pitch = self._nc2_o_pitch(R, params)
+ if pitch:
+ o2 = torch.empty((R, pitch), dtype = torch.half, device = q.device)[:, :H * self.v_head_dim]
+ o = o2.view(R, H, self.v_head_dim)
+ else:
+ o = torch.empty((R, H, self.v_head_dim), dtype = torch.half, device = q.device)
o[:head] = mla_attn_triton_prefill_mha(
qh,
self.w_uk_flat, self.w_uv_flat,
@@ -1332,6 +1356,9 @@ class MLAttention(Module):
qc = qc,
pool_len = int(host_seqlens[0]) + seqlen,
)
+ if pitch:
+ mla_unfold(o_lat, self.w_uv_flat, self.v_head_dim, out = o2[head:])
+ return self._dec_proj(self.o_proj, o2.view(1, seqlen, H * self.v_head_dim), params)
o[head:] = mla_unfold(o_lat, self.w_uv_flat, self.v_head_dim).view(tail, H, self.v_head_dim)
o = o.view(1, seqlen, H * self.v_head_dim)
return self._dec_proj(self.o_proj, o, params)
diff --git a/exllamav3/modules/mlp.py b/exllamav3/modules/mlp.py
index e04c29b..57a8b5d 100644
--- a/exllamav3/modules/mlp.py
+++ b/exllamav3/modules/mlp.py
@@ -12,6 +12,8 @@ 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
@@ -786,8 +788,20 @@ class GatedMLP(Module):
elif self.multi_gu[s] is None or bsz * q_len > 32:
g = self.gates[s].forward(x, params)
u = self.ups[s].forward(x, params)
- 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)
+ # 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
+ if os.environ.get("EXL3_NC2_SILU_PAD", "0") == "1" and self.activation_fn_call is ext.silu_mul 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, self.act_limit)
+ 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_