okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Trial2 merge f-0291-pr-amd (82eaeb422): verify.cpp head keeps both: pr-nv2's chunked head (h0/HT, up to 8 columns a launch) and pr-amd's fused q8_1 image (q8_head, image at the chunk's own xq_ offset)62db0bf10

main
27.3 KiB512 linesraw
1// src/kernels/cuda/shared_expert.cu - P2.S2: the shared expert.
2//
3// `ref/moe.py::shared_expert`, transcribed:
4//
5//     h = silu(x @ gate_shexp.T) * (x @ up_shexp.T)      <- SILU GOES ON GATE, not on up
6//     h = h @ down_shexp.T                                (nt, n_embd)
7//     g = sigmoid(x @ gate_inp_shexp)                     (nt,) ONE SCALAR PER TOKEN
8//     return h * g[:, None]
9//
10// TWO THINGS HERE WERE BELIEVED WRONG FOR MANY ROUNDS and `docs/semantics.md` records both.  SILU GOES ON THE
11// GATE TENSOR: the opposite reading is plausible, produces the right shapes, and is wrong.  And
12// `ffn_gate_inp_shexp` is `(n_embd,)` whose output is "one value per token" - a SCALAR gate obtained by dotting
13// that vector with the hidden state, NOT a per-expert gate and NOT a per-dimension elementwise one.  Both were
14// live readings of the same shapes until the source comment settled them.
15//
16// The result is ADDED to the routed output - not router-weighted, not renormalised against it.
17//
18// The legacy canonical projections use their explicit Q8_0/Q8_K activation images. The optional native
19// BF16 path affects only the scalar gate: it reads the original F32 input and uses pinned CUDA MMVF plus
20// an FP32 sigmoid. Native projection overrides independently select CUDA Q8_1 MMVQ and FP32 SwiGLU.
21#include "strata/kernels/shared_expert.hpp"
22#include "strata/kernels/fuse_decode.hpp"
23#include "strata/kernels/bf16_gemv.hpp"
24#include "strata/kernels/bf16_bits.hpp"
25#include "strata/kernels/f16_bits.hpp"
26#include "strata/kernels/quantize_act.hpp"
27#include "strata/kernels/s2_gemv_q8.hpp"
28#include "strata/kernels/s_gemv.hpp"
29#include "strata/kernels/native_mmvq.hpp"
30#include "strata/kernels/verify_kernels.hpp"
31
32#include <cuda_fp16.h>
33#include <cuda_runtime.h>
34
35#include <cmath>
36#include <climits>
37#include <cstdio>
38#include <string>
39#include <cstdlib>
40#include <cstring>
41#include <stdexcept>
42
43namespace strata::kernels {
44namespace {
45
46constexpr int THREADS = 128;
47bool native_bf16 = false;
48
49// `f32_to_f16` used to live here as a private copy.  Round 198 found it - and the identical one in
50// `quantize_act.cu` - returning a NaN for every FINITE value that overflows fp16 (1e30, 65536, 1e45) instead
51// of saturating to inf, because `exp >= 31` conflates an f32 inf/NaN with an out-of-range finite exponent.
52// This file's fixture is all O(1), so it could not see it.  The conversion now lives in one place, with the
53// regimes spelled out.
54
55// silu(x) = x / (1 + exp(-x)), written as `ref/moe.py` writes it, in DOUBLE then cast - the reference works in
56// float64 and a float32 exp differs in the last bits.  The multiplication by `up` is the reference's order.
57__global__ void swiglu_kernel(const float* __restrict__ gate, const float* __restrict__ up,
58                              float* __restrict__ out, int n) {
59    const int i = blockIdx.x * blockDim.x + threadIdx.x;
60    if (i >= n) return;
61    const double x = (double) gate[i];
62    out[i] = (float) (x / (1.0 + exp(-x))) * up[i];
63}
64
65__global__ void native_swiglu_kernel(const float* gate, const float* up, float* out, int n) {
66    const int i = blockIdx.x * blockDim.x + threadIdx.x;
67    if (i >= n) return;
68    // Pinned CUDA unary.cuh op_silu, then unary_gated_op_kernel's multiply.
69    // Explicit intrinsics reproduce its --use_fast_math operations without
70    // changing compilation of the default legacy arithmetic in this file.
71    out[i] = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i];
72}
73
74
75__global__ void to_f16_kernel(const float* __restrict__ in, uint16_t* __restrict__ out, int n) {
76    const int i = blockIdx.x * blockDim.x + threadIdx.x;
77    if (i < n) out[i] = f16_from_f32(in[i]);
78}
79
80// The per-token scalar gate: sigmoid(dot(x, w)) with w = `ffn_gate_inp_shexp` (n_embd,).
81//
82// **ONE THREAD WAS THE LARGEST SINGLE KERNEL IN THE MODEL, AND THE COMMENT DEFENDING IT SAID WHY IT SHOULD
83// NOT BE.**  It read: "n_embd is 2560, so this is a short serial loop and the parallelism is elsewhere."
84// 2560 iterations is not short when each one is a DOUBLE multiply-add.  This card's double rate is **1/64** of
85// its float rate, so the loop is a 2560-long dependency chain through a 1/64-rate unit - tens of microseconds
86// from the chain alone, before counting 2560 sequential global loads issued by one thread with no coalescing.
87//
88// MEASURED, and this is what the number looks like from outside: `shared_expert` is **0.2374 ms of a
89// 0.8883 ms block - 26.7% of the whole block, 11.4 ms per token** - for three projections that read 5.5 MB and
90// whose memory floor is 0.009 ms.  It is seven kernels, and six of them are GEMVs or elementwise passes over
91// 640-2560 elements.  This is the one that cannot be explained by bandwidth.
92//
93// THE DOUBLE ACCUMULATOR IS KEPT.  `ref/gr.py` reduces in float64 and `block_sum` in `gr.cu` exists for the
94// same reason - the summation order of a tree is not the reference's, so the defence is enough precision that
95// the order stops mattering.  What changes is the CHAIN: ten terms per thread instead of 2560, then a
96// tree-reduce.  Through a sigmoid, a 1e-16 relative difference in the dot is not a difference.
97//
98// **BOTH OPERANDS ARE BF16, AND THAT IS THE REFERENCE'S CONTRACT, NOT A STORAGE DETAIL.**  `gate_inp_shexp` is a
99// BF16 weight, so ggml converts the activation to its `vec_dot_type` - BF16 - exactly as it does for the router
100// (`docs/activation-contract.md`).  This kernel used to take `const float* w` while the LOADER had already
101// re-rounded the tensor to 2 B/elem, so it read 2560 floats out of a 5120-byte buffer: 5120 B past the end of
102// the tensor, inside the 4.5 GiB arena, where nothing faults.  The dot came out astronomically large, sigmoid
103// saturated to 1.0, and `scale_kernel` multiplied the shared expert's output by it - which is why the FIRST
104// symptom was 2560 non-finite outputs rather than a wrong scalar.
105//
106// A wrong scalar here is the quiet failure mode: sigmoid bounds the damage to [0,1], so a gate that should be
107// 0.5 and reads 1.0 scales the shared expert by 2x and produces perfectly finite, perfectly plausible logits.
108__device__ __forceinline__ double warp_sum_d(double v) {
109    for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
110    return __shfl_sync(0xFFFFFFFFu, v, 0);
111}
112
113__global__ void scalar_gate_kernel(const uint16_t* __restrict__ x_bf16, const uint16_t* __restrict__ w_bf16,
114                                   float* __restrict__ out, int n_embd) {
115    __shared__ double scratch[8];   // 8 warps: the launch is <<<1, 256>>>
116    double acc = 0.0;
117    for (int i = threadIdx.x; i < n_embd; i += blockDim.x)
118        acc += (double) f32_from_bf16(x_bf16[i]) * (double) f32_from_bf16(w_bf16[i]);
119    __syncthreads();
120    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
121    acc = warp_sum_d(acc);
122    if (lane == 0) scratch[warp] = acc;
123    __syncthreads();
124    const int nw = ((int) blockDim.x + 31) >> 5;
125    if (warp == 0) {
126        acc = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0;
127        acc = warp_sum_d(acc);
128        if (threadIdx.x == 0) out[0] = (float) (1.0 / (1.0 + exp(-acc)));
129    }
130}
131
132__global__ void scale_kernel(float* __restrict__ out, const float* __restrict__ g, int n) {
133    const int i = blockIdx.x * blockDim.x + threadIdx.x;
134    if (i < n) out[i] *= g[0];
135}
136
137__global__ void native_scalar_sigmoid_kernel(float* gate) {
138    // Match the single-token CUDA sigmoid's FP32 fast-math operations without changing legacy kernels'
139    // compilation flags. The dot product was already reduced by the pinned native MMVF implementation.
140    gate[0] = __fdividef(1.0f, 1.0f + __expf(-gate[0]));
141}
142__global__ void native_scalar_sigmoid_multi_kernel(float* gate) {   // thread t = token t, same expression
143    gate[threadIdx.x] = __fdividef(1.0f, 1.0f + __expf(-gate[threadIdx.x]));
144}
145
146/// The MoE block's final combination.  See the header for the two readings it exists to pin.
147__global__ void moe_combine_kernel(const float* __restrict__ parts, const float* __restrict__ weights,
148                                   const float* __restrict__ shared, float* __restrict__ y, int n_embd,
149                                   int k, int has_shared) {
150    const int j = blockIdx.x * blockDim.x + threadIdx.x;
151    if (j >= n_embd) return;
152    // Accumulate in DOUBLE, in the reference's own order (`for i in range(k): out[t] += w[t,i] * g[0]`).
153    // f32 would be defensible for ten terms, but the reference is float64 and this is one line.
154    double acc = 0.0;
155    for (int e = 0; e < k; ++e) acc += (double) weights[e] * (double) parts[(size_t) e * n_embd + j];
156    // The SHARED output is added PLAIN - not router-weighted, not renormalised against the routed sum.
157    if (has_shared) acc += (double) shared[j];
158    y[j] = (float) acc;
159}
160
161}  // namespace
162
163void shared_expert_set_native_bf16(bool enabled) { native_bf16 = enabled; }
164bool shared_expert_native_bf16_enabled() { return native_bf16; }
165
166namespace {
167__global__ void scale_rows_kernel(float* __restrict__ out, const float* __restrict__ g, int n) {
168    const int t = blockIdx.y;
169    const int i = blockIdx.x * blockDim.x + threadIdx.x;
170    if (i < n) out[(size_t) t * n + i] *= g[t];
171}
172
173__global__ void sigmoid_scale_rows_kernel(float* __restrict__ out, const float* __restrict__ g, int n) {
174    const int t = blockIdx.y;
175    const int i = blockIdx.x * blockDim.x + threadIdx.x;
176    if (i < n) {
177        const float gt = __fdividef(1.0f, 1.0f + __expf(-g[t]));
178        out[(size_t) t * n + i] *= gt;
179    }
180}
181
182__global__ void sigmoid_scale_rows_vec4_kernel(float4* __restrict__ out4, const float* __restrict__ g, int n4) {
183    const int t = blockIdx.y;
184    const int i = blockIdx.x * blockDim.x + threadIdx.x;
185    if (i < n4) {
186        const float gt = __fdividef(1.0f, 1.0f + __expf(-__ldg(g + t)));
187        float4 v = out4[(size_t) t * n4 + i];
188        v.x *= gt;
189        v.y *= gt;
190        v.z *= gt;
191        v.w *= gt;
192        out4[(size_t) t * n4 + i] = v;
193    }
194}
195
196void launch_sigmoid_scale_rows(float* out, const float* g, int n_embd, int n_tok, cudaStream_t cs) {
197    if ((n_embd & 3) == 0 && ((uintptr_t) out & 15u) == 0) {
198        const int n4 = n_embd >> 2;
199        sigmoid_scale_rows_vec4_kernel<<<dim3((unsigned) ((n4 + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(
200            reinterpret_cast<float4*>(out), g, n4);
201    } else {
202        sigmoid_scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(
203            out, g, n_embd);
204    }
205}
206
207bool fused_swiglu_q81_enabled() {
208    static const bool on = [] {
209        const char* v = std::getenv("STRATA_FUSED_SWIGLU_Q81");
210        return v == nullptr || std::atoi(v) != 0;
211    }();
212    return on;
213}
214}  // namespace
215
216void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw,
217                         const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd,
218                         int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse) {
219    const bool gate_deferred = (lfuse & 1) != 0, pair = (lfuse & 2) != 0;
220    if (n_tok < 1 || n_tok > kVerifyMaxT || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream)
221        throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens (16 in a wide build), native weights, scratch and a stream");
222    cudaStream_t cs = (cudaStream_t) stream;
223    // the activation's q8_1: the caller's (STRATA_VERIFY_QDEDUP, x_q8_1_ready) or the descriptor's, else quantized here
224    const void* x_q8_1 = x_q8_1_ready ? x_q8_1_ready : nw.x_q8_1;
225    if (!x_q8_1) {
226        native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream);
227        x_q8_1 = nw.q8_1;
228    }
229    // S26 STRATA_LFUSE (gate_deferred): gate and up in one launch where the pair applies (bitwise the two calls)
230    if (!(pair && nw.gate_type == nw.up_type &&
231          native_mmvq_pair(nw.gate_type, nw.gate_data, nw.up_data, x_q8_1, gate, up, (int) n_embd, (int) n_ff, n_tok, stream))) {
232        native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream);
233        native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream);
234    }
235    const int n = (int) (n_ff * n_tok);
236    if (fused_swiglu_q81_enabled()) {
237        native_swiglu_quantize_q8_1(gate, up, nw.q8_1, (int) n_ff, n_tok, stream);
238    } else {
239        native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n);
240        native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream);
241    }
242    native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream);
243    if (gate_deferred) {   // the caller computed g (raw) with the router and scales `out` in the combine
244        const cudaError_t e = cudaGetLastError();
245        if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e));
246        return;
247    }
248    static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
249    if (native_bf16 && batch && n_tok > 1) {   // one gemv for all rows (outputs identical), fused sigmoid+scale
250        bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream);
251        launch_sigmoid_scale_rows(out, g, (int) n_embd, n_tok, cs);
252    } else if (native_bf16 && n_tok == 1) {
253        bf16_gemv_fp32_mmvf(x, gate_inp_bf16, g, n_embd, 1, stream);
254        launch_sigmoid_scale_rows(out, g, (int) n_embd, 1, cs);
255    } else {
256        for (int t = 0; t < n_tok; ++t) {
257            if (native_bf16) {
258                bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream);
259                native_scalar_sigmoid_kernel<<<1, 1, 0, cs>>>(g + t);
260            } else {
261                scalar_gate_kernel<<<1, 256, 0, cs>>>(x_bf16 + (size_t) t * n_embd, gate_inp_bf16, g + t, (int) n_embd);
262            }
263        }
264        scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(
265            out, g, (int) n_embd);
266    }
267    const cudaError_t e = cudaGetLastError();
268    if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e));
269}
270
271uint64_t shared_expert_scratch_bytes(int64_t n_ff) {
272    // gate (n_ff f32) | up (n_ff f32) | q8_0 (n_ff/32*34) | q8k (n_ff/256*292) | g (1 f32), 16-byte aligned
273    const uint64_t a = ((uint64_t) n_ff * 4 + 15) & ~15ull;
274    const uint64_t q0 = ((uint64_t) (n_ff / 32) * 34 + 15) & ~15ull;
275    const uint64_t qk = ((uint64_t) (n_ff / 256) * 292 + 15) & ~15ull;
276    return a * 2 + q0 + qk + 32;
277}
278
279void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* x_bf16, const SForm& gate_form,
280                   const uint8_t* gate_codes, const float* gate_scales, const float* gate_off,
281                   const SForm& up_form, const uint8_t* up_codes, const float* up_scales, const float* up_off,
282                   const SForm& down_form, const uint8_t* down_codes, const float* down_scales,
283                   const float* down_off, const uint16_t* gate_inp_bf16, float* scratch, float* out,
284                   int64_t n_embd, int64_t n_ff, int tpr, void* stream, const float* x_f32,
285                   const NativeSharedWeights* native) {
286    if (n_embd <= 0 || n_ff <= 0) return;
287    const bool use_native = native_bf16;
288    const bool native_gate = native && native->gate_data && native_mmvq_supported(native->gate_type);
289    const bool native_up = native && native->up_data && native_mmvq_supported(native->up_type);
290    const bool native_down = native && native->down_data && native_mmvq_supported(native->down_type);
291    const bool native_projection = native_gate || native_up || native_down;
292    if ((use_native || native_gate || native_up) && !x_f32)
293        throw std::invalid_argument("shared_expert native input projection requires unrounded x_f32");
294    if (native_projection) {
295        if (!native->q8_1 || !stream || n_embd > INT_MAX || n_ff > INT_MAX)
296            throw std::invalid_argument("shared_expert native projections require scratch, stream and int32 dimensions");
297        // Validate every active shape before any kernel is enqueued.
298        if (native_gate) native_mmvq_weight_bytes(native->gate_type, (int) n_embd, (int) n_ff);
299        if (native_up) native_mmvq_weight_bytes(native->up_type, (int) n_embd, (int) n_ff);
300        if (native_down) native_mmvq_weight_bytes(native->down_type, (int) n_ff, (int) n_embd);
301    }
302    if (scratch == nullptr) {
303        std::fprintf(stderr, "shared_expert: scratch is null; the caller owns it "
304                             "(see shared_expert_scratch_bytes)\n");
305        std::exit(1);
306    }
307    // CARVED FROM THE CALLER'S SCRATCH.  This used to be four `cudaMalloc`s and four `cudaFree`s per call, which
308    // is illegal during stream capture AND a token-path allocation - P2.T10 forbids both.
309    uint8_t* p = (uint8_t*) scratch;
310    const uint64_t a = ((uint64_t) n_ff * 4 + 15) & ~15ull;
311    const uint64_t q0 = ((uint64_t) (n_ff / 32) * 34 + 15) & ~15ull;
312    const uint64_t qk = ((uint64_t) (n_ff / 256) * 292 + 15) & ~15ull;
313    float* gate = (float*) p;
314    float* up = (float*) (p + a);
315    uint8_t* h_q8_0 = (uint8_t*) (p + a * 2);
316    uint8_t* h_q8k = (uint8_t*) (p + a * 2 + q0);
317    float* g = (float*) (p + a * 2 + q0 + qk);
318
319    // WHICH ACTIVATION THIS PROJECTION WANTS, READ FROM ITS OWN FORM.  See `SForm::act_kind`: the three
320    // families cannot be told apart by the other fields, so the kind is carried rather than derived.
321    auto gemv = [&](const SForm& f, const uint8_t* codes, const float* scales, const float* off,
322                    const uint8_t* act80, const uint8_t* actq8k, float* y, int64_t nin, int64_t nout) {
323        if (f.code_bits == 2) {
324            s2_gemv_q8(act80, codes, scales, y, nin, nout, tpr, stream);
325        } else if (f.act_kind == 1) {
326            s_gemv_q8k_split(actq8k, codes, scales, off, y, nin, nout, f, stream);
327        } else {
328            s_gemv_q8_0_split(act80, codes, scales, off, y, nin, nout, f, stream);
329        }
330    };
331
332    const unsigned g_ff = (unsigned) ((n_ff + THREADS - 1) / THREADS);
333    const unsigned g_embd = (unsigned) ((n_embd + THREADS - 1) / THREADS);
334
335#if defined(STRATA_EXPERIMENTAL_SM60)
336        if (strata::kernels::fuse_decode()) {
337    // V100 (experimental sm_70 build): gate and up projections, then silu(gate) * up - ONE kernel when both
338    // projections are S-family (`s_gemv_pair_silu`: one read of x, SwiGLU in the epilogue, `up` never
339    // materialised).  The pair kernel is bit-exact vs the three-kernel sequence (shared row math, shared
340    // SwiGLU expression).  The ready-made engine's path below is untouched.
341    bool paired = false;
342    if (!native_gate && !native_up) {
343        paired = s_gemv_pair_silu(x_q8_0, x_q8k, gate_form, gate_codes, gate_scales, gate_off,
344                                  up_form, up_codes, up_scales, up_off, gate, n_embd, n_ff, 32,
345                                  native_projection ? 2 : 0, stream);
346    }
347    if (paired) {
348        // `gate` already holds the products
349    } else {
350        const void* x_q8_1 = (native && native->x_q8_1) ? native->x_q8_1 : nullptr;
351        if ((native_gate || native_up) && !x_q8_1) {
352            native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream);
353            x_q8_1 = native->q8_1;
354        }
355        if (native_gate)
356            native_mmvq(native->gate_type, native->gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, 1, stream);
357        else
358            gemv(gate_form, gate_codes, gate_scales, gate_off, x_q8_0, x_q8k, gate, n_embd, n_ff);
359        if (native_up)
360            native_mmvq(native->up_type, native->up_data, x_q8_1, up, (int) n_embd, (int) n_ff, 1, stream);
361        else
362            gemv(up_form, up_codes, up_scales, up_off, x_q8_0, x_q8k, up, n_embd, n_ff);
363    }
364
365    // down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is
366    // what `ggml_mul_mat` does for every matmul in the model.  It used to be rounded to fp16 with no
367    // justification beyond "the kernel takes fp16".
368    //
369    // When the pair kernel ran, `gate` already holds the products and only the quantizer is left.  Otherwise
370    // silu(gate) * up AND the quantization are ONE kernel (was: swiglu pass, then quantize); the products
371    // land in `gate` exactly as `swiglu_kernel` left them and the blocks are the same bytes the standalone
372    // quantizers produced.  The legacy silu is the double-precision `ref/moe.py` form (`swilu_kind` 0).
373    if (paired) {
374        if (native_down) {
375            native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);
376        } else if (down_form.act_kind == 1) {
377            if (n_ff % 256 != 0) {
378                std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "
379                                     "of 256; Q8_K is structurally impossible here\n", (long long) n_ff);
380                std::exit(1);
381            }
382            quantize_q8_K(gate, h_q8k, n_ff, stream);
383        } else {
384            quantize_q8_0(gate, h_q8_0, n_ff, stream);
385        }
386    } else if (native_projection) {
387        native_swiglu_kernel<<<g_ff, THREADS, 0, (cudaStream_t) stream>>>(gate, up, gate, (int) n_ff);
388        if (native_down) {
389            native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);
390        } else if (down_form.act_kind == 1) {
391            if (n_ff % 256 != 0) {
392                std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "
393                                     "of 256; Q8_K is structurally impossible here\n", (long long) n_ff);
394                std::exit(1);
395            }
396            quantize_q8_K(gate, h_q8k, n_ff, stream);
397        } else {
398            quantize_q8_0(gate, h_q8_0, n_ff, stream);
399        }
400    } else if (native_down) {
401        // no fused entry for the Q8_1 contract; the swilu pass and the q8_1 quantizer stay separate
402        swiglu_kernel<<<g_ff, THREADS, 0, (cudaStream_t) stream>>>(gate, up, gate, (int) n_ff);
403        native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);
404    } else if (down_form.act_kind == 1) {
405        if (n_ff % 256 != 0) {
406            std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "
407                                 "of 256; Q8_K is structurally impossible here\n", (long long) n_ff);
408            std::exit(1);
409        }
410        swilu_quantize_q8_K(gate, up, gate, n_ff, 0, h_q8k, stream);
411    } else {
412        swilu_quantize_q8_0(gate, up, gate, n_ff, 0, h_q8_0, stream);
413    }
414    if (native_down) {
415        native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream);
416    } else {
417        gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);
418    }
419        } else
420#endif
421        {
422    // gate and up projections, then silu(gate) * up in place in `gate`
423    const void* x_q8_1 = (native && native->x_q8_1) ? native->x_q8_1 : nullptr;
424    if ((native_gate || native_up) && !x_q8_1) {
425        native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream);
426        x_q8_1 = native->q8_1;
427    }
428    if (native_gate)
429        native_mmvq(native->gate_type, native->gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, 1, stream);
430    else
431        gemv(gate_form, gate_codes, gate_scales, gate_off, x_q8_0, x_q8k, gate, n_embd, n_ff);
432    if (native_up)
433        native_mmvq(native->up_type, native->up_data, x_q8_1, up, (int) n_embd, (int) n_ff, 1, stream);
434    else
435        gemv(up_form, up_codes, up_scales, up_off, x_q8_0, x_q8k, up, n_embd, n_ff);
436    if (native_projection && native_down && fused_swiglu_q81_enabled()) {
437        native_swiglu_quantize_q8_1(gate, up, native->q8_1, (int) n_ff, 1, stream);
438        native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream);
439    } else {
440        if (native_projection)
441            native_swiglu_kernel<<<g_ff, THREADS, 0, (cudaStream_t) stream>>>(gate, up, gate, (int) n_ff);
442        else
443            swiglu_kernel<<<g_ff, THREADS, 0, (cudaStream_t) stream>>>(gate, up, gate, (int) n_ff);
444
445        // down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is
446        // what `ggml_mul_mat` does for every matmul in the model.  It used to be rounded to fp16 with no
447        // justification beyond "the kernel takes fp16".
448        if (native_down) {
449            native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);
450            native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream);
451        } else if (down_form.act_kind == 1) {
452            if (n_ff % 256 != 0) {
453                std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "
454                                     "of 256; Q8_K is structurally impossible here\n", (long long) n_ff);
455                std::exit(1);
456            }
457            quantize_q8_K(gate, h_q8k, n_ff, stream);
458            gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);
459        } else if (down_form.code_bits == 2) {
460            quantize_q8_0(gate, h_q8_0, n_ff, stream);
461            gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);
462        } else {
463            quantize_q8_0(gate, h_q8_0, n_ff, stream);
464            gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);
465        }
466    }
467        }
468
469    // the per-token scalar gate, then the multiply.  Note the gate is computed from `x`, the ORIGINAL hidden
470    // state, not from anything the expert produced. The historical branch uses BF16-rounded inputs; the
471    // native branch uses the pinned CUDA FP32 activation contract.
472    // `<<<1, 256>>>`: one block, because the output is ONE scalar and a second block would only add a global
473    // round trip.  256 threads is the reduction's width, not the problem's size.
474    if (use_native) {
475        bf16_gemv_fp32_mmvf(x_f32, gate_inp_bf16, g, n_embd, 1, stream);
476        launch_sigmoid_scale_rows(out, g, (int) n_embd, 1, (cudaStream_t) stream);
477    } else {
478        scalar_gate_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(x_bf16, gate_inp_bf16, g, (int) n_embd);
479        scale_kernel<<<g_embd, THREADS, 0, (cudaStream_t) stream>>>(out, g, (int) n_embd);
480    }
481
482    if (stream == nullptr) {
483        const cudaError_t e = cudaDeviceSynchronize();
484        if (e != cudaSuccess) {
485            std::fprintf(stderr, "shared_expert: %s\n", cudaGetErrorString(e));
486            std::exit(1);
487        }
488    }
489}
490
491void moe_combine(const float* parts, const float* weights, const float* shared, float* y, int64_t n_embd,
492                 int64_t k, void* stream) {
493    if (n_embd <= 0 || k <= 0) return;
494    // k > 64 is refused rather than truncated: silently summing the first 64 of a longer list would be a
495    // wrong answer that looks like a right one, and no geometry in this artifact comes close to it.
496    if (k > 64) {
497        std::fprintf(stderr, "moe_combine: k = %lld exceeds 64\n", (long long) k);
498        std::exit(1);
499    }
500    const unsigned grid = (unsigned) ((n_embd + THREADS - 1) / THREADS);
501    moe_combine_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(parts, weights, shared, y, (int) n_embd,
502                                                                   (int) k, shared != nullptr);
503    if (stream == nullptr) {
504        const cudaError_t e = cudaDeviceSynchronize();
505        if (e != cudaSuccess) {
506            std::fprintf(stderr, "moe_combine: %s\n", cudaGetErrorString(e));
507            std::exit(1);
508        }
509    }
510}
511
512}  // namespace strata::kernels