okami.mom/strata

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

Niko1221Merge f-strix-hcq8: Strix Halo 8-bit hyper-connection weights by default (gfx1151), sm_86 start-up adaptation default, gfx1151 expert layout mode 8, env-gated DFlash2/spec instrumentation and the opt-in cost-aware MTP windowa539e12c9

main
29.4 KiB552 linesraw
1// src/kernels/cuda/gr.cu - P2.S2: the gated residual / hyper-connection, `gr_read` and `gr_write`.
2//
3// See include/strata/kernels/gr.hpp for the semantics, for why the weights are bf16, and for the history of
4// this kernel's 134x-off-the-floor first version.  The short form: it was launched `<<<1, 256>>>` so that
5// `xn`/`xq` fit in shared memory, which used ONE of 48 SMs and cost 262 ms/token.
6//
7// THE SHAPE OF THE FIX is that each projection is an ordinary GEMV and is now mapped the way the shapes want:
8//
9//     norm    hc blocks, one per residual stream            (each needs its own reduction)
10//     down    ONE WARP PER OUTPUT ROW, lanes stride the 10240 reduction axis
11//     gate    ONE WARP PER OUTPUT ROW, lanes stride the 320 reduction axis
12//     mean    a flat elementwise pass over n_embd
13//
14// WARP-PER-ROW RATHER THAN THREAD-PER-ROW, and that is the whole difference.  A thread walking one row is
15// coalesced with ITSELF and 32 transactions away from its warp neighbours: `w_down[k*hc_dim + i]` for fixed k
16// is contiguous, but two threads on rows k and k+1 are hc_dim*2 bytes apart.  With the warp on one row, lanes
17// i, i+1, i+2 touch consecutive addresses in EITHER orientation - which is why this version needs no
18// transposed copies and takes both matrices exactly as the manifest stores them.
19//
20// Layouts are the MANIFEST's: `hc_attn_down.weight` is [10240, 320] with ne0 = hc*n_embd fast, so it holds
21// `w_down[k][i]` with i contiguous - `ref/gr.py`'s (hc_lr, hc*n_embd) row-major.  `hc_attn_up.weight` is
22// [320, 10240] so it holds `w_up[i][k]` with k contiguous - `ref/gr.py`'s (hc*n_embd, hc_lr) row-major.  Both
23// index with no permutation at all.
24#include "strata/kernels/gr.hpp"
25#include "strata/kernels/bf16_bits.hpp"
26#include "strata/kernels/bf16_gemv.hpp"
27#include "strata/kernels/native_gr_norm.hpp"
28#include "strata/kernels/native_gr_postops.hpp"
29
30#include <cuda_runtime.h>
31
32#include <cmath>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <stdexcept>
37
38namespace strata::kernels {
39namespace {
40
41constexpr int THREADS = 256;
42constexpr int WARPS = THREADS / 32;
43bool fp32_activations = false;
44bool native_mmvf = false;
45
46/// The bf16 conversions live in `strata/kernels/bf16_bits.hpp`, and this file used to carry its own copies.
47/// Two files with a private copy of a conversion whose failure mode is silent wrong bits is one too many -
48/// and the reason the shared header exists is that `bf16` and `fp16` are NOT two spellings of one idea, so a
49/// routine written for one and reused for the other is wrong in a way that still produces numbers.
50///
51/// The local names are kept as thin wrappers so the body below is untouched by the swap.
52__device__ __forceinline__ uint16_t f32_to_bf16_bits(float f) { return bf16_from_f32(f); }
53__device__ __forceinline__ float bf16_bits_to_f32(uint16_t h) { return f32_from_bf16(h); }
54__device__ __forceinline__ float activation_f32(float x) { return x; }
55__device__ __forceinline__ float activation_f32(uint16_t x) { return bf16_bits_to_f32(x); }
56__device__ __forceinline__ void store_activation(float* dst, int i, float x) { dst[i] = x; }
57__device__ __forceinline__ void store_activation(uint16_t* dst, int i, float x) {
58    dst[i] = f32_to_bf16_bits(x);
59}
60
61/// silu and sigmoid exactly as `ref/gr.py` writes them - in FLOAT, not double.
62///
63/// This is the opposite of `shared_expert.cu`, which uses double, and the difference is not stylistic:
64/// `ref/gr.py`'s arrays are float32, so `x / (1.0 + np.exp(-x))` evaluates in float32 under NEP 50, while
65/// `ref/moe.py` works in float64.  Matching the reference's PRECISION is part of transcribing it.
66__device__ __forceinline__ float silu_f(float x) { return x / (1.0f + expf(-x)); }
67__device__ __forceinline__ float sigmoid_f(float x) { return 1.0f / (1.0f + expf(-x)); }
68
69__device__ __forceinline__ double warp_sum(double v) {
70    for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
71    return __shfl_sync(0xFFFFFFFFu, v, 0);
72}
73
74__device__ __forceinline__ float warp_sumf(float v) {
75    for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
76    return __shfl_sync(0xFFFFFFFFu, v, 0);
77}
78
79/// The FP32 block-wide sum, for the reason the review's G5 states: this is a GeForce part and FP64 runs at a
80/// small fraction of FP32, so a `double` reduction turns a bandwidth kernel into a latency kernel.
81///
82/// The scratch is taken as `double*` and reinterpreted as `float*` rather than changing the callers' shared
83/// arrays, because `double scratch[8]` is 64 bytes and so is at least as large as the `float[8]` this needs -
84/// the cast cannot overrun, and it keeps the change to one function instead of one per caller.
85__device__ float block_sumf(float v, double* scratch_raw) {
86    float* scratch = (float*) scratch_raw;
87    // The leading barrier is not decoration - see the note on `block_sum` above: the result is read straight out
88    // of `scratch[0]` by every thread and a later call reuses the array, so without it a fast thread can
89    // overwrite `scratch[0]` before a slow one has read the previous result.
90    __syncthreads();
91    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
92    v = warp_sumf(v);
93    if (lane == 0) scratch[warp] = v;
94    __syncthreads();
95    const int nw = ((int) blockDim.x + 31) >> 5;
96    v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0f;
97    if (warp == 0) v = warp_sumf(v);
98    if (threadIdx.x == 0) scratch[0] = v;
99    __syncthreads();
100    return scratch[0];
101}
102
103/// Block-wide sum in DOUBLE, broadcast to every thread.
104///
105/// Double because `ref/gr.py` reduces in float64 for the norm and the bottleneck, and because a block-wide
106/// f32 sum of 2560 squares is a different number from the reference's; the shuffle tree here also reorders
107/// the additions, so the only defence is enough precision that the order stops mattering.
108///
109/// The leading `__syncthreads()` is not decoration: the result is read straight out of `scratch[0]` by every
110/// thread, and a later call reuses the same array.  Without a barrier on entry a fast thread can overwrite
111/// `scratch[0]` before a slow one has read the previous result - a race that is invisible in most runs.
112__device__ double block_sum(double v, double* scratch) {
113    __syncthreads();
114    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
115    v = warp_sum(v);
116    if (lane == 0) scratch[warp] = v;
117    __syncthreads();
118    const int nw = ((int) blockDim.x + 31) >> 5;
119    v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0;
120    if (warp == 0) v = warp_sum(v);
121    if (threadIdx.x == 0) scratch[0] = v;
122    __syncthreads();
123    return scratch[0];
124}
125
126/// `hc` blocks, one per residual stream: per-stream RMSNorm, then the activated stream in both forms.
127///
128/// ggml_rms_norm reduces over ne[0], and ne[0] is n_embd, so the reduction is PER STREAM.  The `[n_embd, hc]`
129/// gamma then scales each stream individually.
130///
131/// A per-thread accumulator is only a sum when the block is narrower than the row, which is why this is a
132/// block reduction: with `n_embd` equal to the thread count every thread would hold exactly one element and
133/// normalise by its own square.  That mistake is silent - it produces a plausible vector of the right shape -
134/// and it is what `gr_parity`'s `mixed vs reference` caught at 2.0e+01 in round 196.
135template <bool FP32_ACT>
136__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w_norm, float eps,
137                               int n_embd, float* __restrict__ xn, uint16_t* __restrict__ xq) {
138    __shared__ double scratch[8];
139    const int c = blockIdx.x;
140    const float* Rc = R + (size_t) c * n_embd;
141    float* xnc = xn + (size_t) c * n_embd;
142    uint16_t* xqc = xq + (size_t) c * n_embd;
143
144    // FP32, for the same reason as `gr_down_kernel` and `gr_inject_kernel`: this is a GeForce part, FP64 runs
145    // at a small fraction of FP32, and the sum of squares is a pure reduction.  It was the last `double` on the
146    // `gr_read` path.  `gr_norm` is only 0.80 ms/token, so this is hygiene rather than a headline - but it is
147    // 12 of the FP64 sites the review's G5 counted in this file, and the rule it states ("no FP64 on any decode
148    // or prefill path") is worth being able to check mechanically rather than case by case.
149    float ss = 0.0f;
150    for (int d = threadIdx.x; d < n_embd; d += blockDim.x) {
151        const float v = Rc[d];
152        ss += v * v;
153    }
154    const float ms = block_sumf(ss, scratch) / (float) n_embd;
155    const float rs = rsqrtf(ms + eps);
156    for (int d = threadIdx.x; d < n_embd; d += blockDim.x) {
157        const float x = Rc[d] * rs * w_norm[(size_t) c * n_embd + d];
158        xnc[d] = x;
159        if constexpr (!FP32_ACT) xqc[d] = f32_to_bf16_bits(x);
160    }
161}
162
163/// `lo = silu((bf16(xn) @ w_down.T) / hc)`, ONE BLOCK PER OUTPUT ROW with its warps splitting the reduction.
164template <typename Activation>
165__global__ void gr_down_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_down, int hc_dim,
166                               int hc_lr, int hc, Activation* __restrict__ lq,
167                               const uint16_t* __restrict__ w_inject, float* __restrict__ inject, bool do_inject) {
168    const int k = blockIdx.x;
169    if (do_inject && k == hc_lr) {
170        // Track F: the inject projection is the down grid's last block.  One warp per stream, the same
171        // lane stride and warp_sumf as `gr_inject_kernel`, so the four values are bitwise the old kernel's.
172        const int c = threadIdx.x >> 5;
173        if (c >= hc) return;
174        const int lane = threadIdx.x & 31;
175        const uint16_t* row = w_inject + (size_t) c * hc_dim;
176        float acc = 0.0f;
177        for (int i = lane; i < hc_dim; i += 32)
178            acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]);
179        acc = warp_sumf(acc);
180        if (lane == 0) inject[c] = acc;
181        return;
182    }
183    if (k >= hc_lr) return;
184    const int lane = threadIdx.x & 31;
185    const int warp = threadIdx.x >> 5;
186    const int nw = (int) (blockDim.x >> 5);          // warps per row == warps per block
187    const uint16_t* row = w_down + (size_t) k * hc_dim;
188    // **THE OCCUPANCY HERE IS 10% AND IT IS REAL, BUT FIXING IT DOES NOT PAY.**  `hc_lr` is 320, one warp per
189    // row, 8 warps per block, so this launches 40 blocks = 320 warps: **6.7 warps per SM out of the 64 a
190    // Blackwell SM holds**, each lane walking 10,240 elements in 320 dependent steps.
191    //
192    // Four independent accumulators were tried to break the dependency chain and put four loads in flight per
193    // lane.  **Measured: 39.86 ms/token of pure GPU against 39.80, i.e. no change**, with `gr_parity` green
194    // either way.  Removed, on the rule this file already states about `#pragma unroll 4`: a hint that does not
195    // change the timing is a claim that is not true.
196    //
197    // The reason is that `gr_read`'s cost is not here.  Its four kernels are the norm (4 blocks), this (40),
198    // `gr_gate_kernel` (1,280) and the mean (10), and the 1,280-block gate kernel reads 6.55 MB of weights with
199    // good occupancy - so `gr_read`'s ~93 us is mostly the gate kernel at its own memory rate, and the ~165 GB/s
200    // whole-call figure is an average over kernels that do not share a rate.
201    // **FP32, AND THE FP64 THAT WAS HERE COST MORE THAN EVERYTHING ELSE IN `gr_read`.**
202    //
203    // This accumulated in `double`.  GeForce Blackwell executes FP64 at a small fraction of FP32 - 1/64 on
204    // recent parts - so a 320-step dependent FP64 chain per lane turned a memory-bound reduction into a
205    // latency-bound one.  The `nsys` per-kernel table (round 2) measured it at **5.07 ms/token, 15.3% of all
206    // GPU time**, against `gr_gate_kernel`'s 1.23 ms - which REFUTES the comment that used to sit here, that
207    // "gr_read's ~93 us is mostly the gate kernel at its own memory rate".  It was not: down + inject were
208    // 8.77 of gr_read's 10.8 ms, and the gate was 1.23.
209    //
210    // The justification for `double` was matching `ref/gr.py`'s float64 transcription.  **The ground truth is
211    // llama.cpp, and llama.cpp accumulates in FP32** - so this does not move away from the oracle, it moves
212    // toward it, and the review's G1 lists it first.
213    //
214    // Four independent accumulators were tried here BEFORE, against the FP64 version, and measured no change
215    // (39.86 vs 39.80 ms/token) - because FP64 throughput was the limit, not the dependency chain.  With FP32
216    // the kernel becomes memory-bound: it reads ~13 MB per call across xq and w_down, which at the measured
217    // 641 GB/s is ~20 us against the 52 us this took.
218    // **THE OCCUPANCY CONCLUSION ABOVE IS STALE, AND THIS IS THE RETEST IT ASKED FOR.**
219    //
220    // "Fixing it does not pay" was measured against the FP64 version, where FP64 THROUGHPUT was the limit and
221    // more parallelism could not help.  The kernel is FP32 now (round 282: 5.07 -> 2.38 ms/token) and the limit
222    // moved to memory - which is the regime where occupancy does pay, because at 6.7 warps/SM there are not
223    // enough bytes in flight to cover DRAM latency.  The old result is not wrong; it is about a different kernel.
224    //
225    // One BLOCK per row, its 8 warps splitting the 10,240-element reduction: 320 blocks x 8 = **2,560 warps =
226    // 53 warps/SM instead of 6.7**, with no second kernel and no partial buffer - the eight partials meet in
227    // shared memory.  Lanes within a warp still read consecutive addresses, because warp `w` starts at
228    // `w * 32` and strides by `nw * 32`.
229    float acc = 0.0f;
230    for (int i = warp * 32 + lane; i < hc_dim; i += nw * 32)
231        acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]);
232    acc = warp_sumf(acc);
233
234    __shared__ float part[WARPS];
235    if (lane == 0) part[warp] = acc;
236    __syncthreads();
237    if (warp == 0) {
238        float t = (lane < nw) ? part[lane] : 0.0f;
239        t = warp_sumf(t);
240        // NOTE: the reduction order differs from the one-warp version, so this is a NUMERICS CHANGE.  C1 is the
241        // gate that judges it - not this comment, and not `gr_parity`, which compares against the reference on
242        // a fixture that a changed summation order can still pass.
243        if (lane == 0) store_activation(lq, k, silu_f(t / (float) hc));
244    }
245}
246
247/// `gated[i] = xn[i] * sigmoid(bf16(lo) @ w_up.T)`, one warp per output row, lanes striding hc_lr.
248template <typename Activation>
249__global__ void gr_gate_kernel(const Activation* __restrict__ lq, const uint16_t* __restrict__ w_up,
250                               const float* __restrict__ xn, int hc_dim, int hc_lr, float* __restrict__ gated) {
251    const int i = blockIdx.x * WARPS + (threadIdx.x >> 5);
252    if (i >= hc_dim) return;
253    const int lane = threadIdx.x & 31;
254    const uint16_t* row = w_up + (size_t) i * hc_lr;
255    float acc = 0.0f;
256    for (int k = lane; k < hc_lr; k += 32)
257        acc += activation_f32(lq[k]) * bf16_bits_to_f32(row[k]);
258    acc = warp_sumf(acc);
259    // Every lane computes the sigmoid (the shuffle broadcasts acc), so there is no second sync point and no
260    // branch; lane 0 stores.
261    if (lane == 0) gated[i] = xn[i] * sigmoid_f(acc);
262}
263
264/// `mixed[d] = mean over c of gated[c][d]`.  Flat elementwise: the mean is over the streams, which are
265/// strided by n_embd, so no cross-thread reduction is needed at all.
266__global__ void gr_mean_kernel(const float* __restrict__ gated, int n_embd, int hc, float* __restrict__ mixed) {
267    const int d = blockIdx.x * blockDim.x + threadIdx.x;
268    if (d >= n_embd) return;
269    float m = 0.0f;
270    for (int c = 0; c < hc; ++c) m += gated[(size_t) c * n_embd + d];
271    mixed[d] = m / (float) hc;
272}
273
274/// Track F: `gr_gate_kernel` and `gr_mean_kernel` in one launch.  One block owns WARPS columns for every
275/// stream; a warp computes one column's dot per stream (the same lane stride and warp_sumf as the old gate),
276/// the per-stream values meet in shared, and the mean adds them in the same c order as the old kernel.
277template <typename Activation>
278__global__ void gr_gate_mean_kernel(const Activation* __restrict__ lq, const uint16_t* __restrict__ w_up,
279                                    const float* __restrict__ xn, int hc_lr, int n_embd, int hc,
280                                    float* __restrict__ mixed) {
281    const int lane = threadIdx.x & 31;
282    const int warp = threadIdx.x >> 5;
283    const int d = blockIdx.x * WARPS + warp;
284    __shared__ float g[4][WARPS];
285    if (d < n_embd) {
286        for (int c = 0; c < hc; ++c) {
287            const int i = c * n_embd + d;
288            const uint16_t* row = w_up + (size_t) i * hc_lr;
289            float acc = 0.0f;
290            for (int k = lane; k < hc_lr; k += 32)
291                acc += activation_f32(lq[k]) * bf16_bits_to_f32(row[k]);
292            acc = warp_sumf(acc);
293            if (lane == 0) g[c][warp] = xn[i] * sigmoid_f(acc);
294        }
295    }
296    __syncthreads();
297    if (threadIdx.x < WARPS) {
298        const int dd = blockIdx.x * WARPS + threadIdx.x;
299        if (dd < n_embd) {
300            float m = 0.0f;
301            for (int c = 0; c < hc; ++c) m += g[c][threadIdx.x];
302            mixed[dd] = m / (float) hc;
303        }
304    }
305}
306
307/// `inject[c] = bf16(xn) @ w_inject[c]`, one value per stream: ONE WARP PER STREAM, lanes striding hc_dim.
308///
309/// This mirrors `gr_down_kernel` rather than using a block-wide reduction.  `hc` is 4 at the real geometry,
310/// so a block per stream would put 256 threads on a 10240-element dot and leave the reduction to do all the
311/// work; a warp per stream is the same shape as the down projection and reuses its pattern exactly.  The
312/// whole kernel is one block of `32*hc` threads, which is small - and it is a 4-value output, so it is.
313template <typename Activation>
314__global__ void gr_inject_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_inject,
315                                 int hc_dim, int hc, float* __restrict__ inject) {
316    const int c = threadIdx.x >> 5;
317    if (c >= hc) return;
318    const int lane = threadIdx.x & 31;
319    const uint16_t* row = w_inject + (size_t) c * hc_dim;
320    // FP32, for the same reason as `gr_down_kernel` - and this one is worse.  A ONE-BLOCK kernel doing four
321    // 10,240-element FP64 reductions measured **3.70 ms/token, 11.1% of all GPU time, from a single SM out of
322    // 48.**  It is the fourth largest consumer of GPU time in the engine and it cannot use more than 1/48th of
323    // the machine.  In FP32 the same reduction is a few microseconds and the block size stops mattering.
324    float acc = 0.0f;
325    for (int i = lane; i < hc_dim; i += 32)
326        acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]);
327    acc = warp_sumf(acc);
328    if (lane == 0) inject[c] = acc;
329}
330
331__global__ void gr_write_kernel(const float* __restrict__ R, const float* __restrict__ block_out,
332                                const float* __restrict__ inject, int n_embd, int hc, float* __restrict__ out) {
333    // w = 2*sigmoid(inject/hc), computed once per stream in shared rather than per element.
334    extern __shared__ unsigned char smem_raw[];
335    float* w = (float*) smem_raw;
336    if ((int) threadIdx.x < hc) w[threadIdx.x] = 2.0f * sigmoid_f(inject[threadIdx.x] / (float) hc);
337    __syncthreads();
338    const long long n = (long long) hc * n_embd;
339    for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n;
340         i += (long long) gridDim.x * blockDim.x) {
341        const int c = (int) (i / n_embd), d = (int) (i % n_embd);
342        // every stream adds the SAME block output; only the weight differs per stream
343        out[i] = R[i] + block_out[d] * w[c];
344    }
345}
346
347}  // namespace
348
349void gr_set_fp32_activations(bool enabled) { fp32_activations = enabled; }
350void gr_set_native_mmvf(bool enabled) { native_mmvf = enabled; }
351bool gr_native_mmvf_enabled() { return native_mmvf; }
352
353size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out) {
354    const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;
355    // ONE table, indexed by the same `k` that assigns the pointers below.  The first version of this function
356    // sized three locals named `xn`, `xq`, `lq` in a DIFFERENT order from the pointer assignments - `xq` got
357    // hc_lr*2 while `lq` got hc_dim*4 - so for the real geometry xq was given 640 bytes where it needed
358    // 20,480 and every region overlapped its neighbour.
359    //
360    // What that looked like is worth recording: `inject` came out ~20% wrong, and rewriting its reduction
361    // from block-wide to warp-wide produced BYTE-IDENTICAL wrong answers.  Two different reductions agreeing
362    // exactly is not a coincidence to investigate - it means the reduction is not where the bug is, and the
363    // inputs are.  Chasing the reduction instead cost most of a round.
364    const size_t sz[5] = {
365        hc_dim * sizeof(float),                // 0: xn
366        hc_dim * sizeof(uint16_t),             // 1: xq
367        (size_t) s.hc_lr * sizeof(uint16_t),   // 2: lq
368        hc_dim * sizeof(float),                // 3: gated
369        (size_t) s.hc_lr * sizeof(float),        // 4: lo (FP32 activation experiment)
370    };
371    size_t al[5], bytes = 0;
372    for (int k = 0; k < 5; ++k) {
373        al[k] = (sz[k] + 15) & ~(size_t) 15;
374        bytes += al[k];
375    }
376    out.bytes = bytes;
377    if (base != nullptr) {
378        unsigned char* p = (unsigned char*) base;
379        void* ptr[5];
380        for (int k = 0; k < 5; ++k) {
381            ptr[k] = p;
382            p += al[k];
383        }
384        out.xn = (float*) ptr[0];
385        out.xq = (uint16_t*) ptr[1];
386        out.lq = (uint16_t*) ptr[2];
387        out.gated = (float*) ptr[3];
388        out.lo = (float*) ptr[4];
389    }
390    return bytes;
391}
392
393void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
394             const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed,
395             float* inject, void* stream) {
396    if (s.n_embd <= 0 || s.hc <= 0 || s.hc_lr <= 0) return;
397    if (ws.xn == nullptr || ws.xq == nullptr || ws.lq == nullptr || ws.gated == nullptr || ws.lo == nullptr) {
398        std::fprintf(stderr, "gr_read: GrWorkspace is not initialised (see gr_workspace_init)\n");
399        std::exit(1);
400    }
401    if (ws.bytes < gr_workspace_bytes(s)) {
402        std::fprintf(stderr, "gr_read: GrWorkspace is %zu bytes but this geometry needs %zu\n",
403                     ws.bytes, gr_workspace_bytes(s));
404        std::exit(1);
405    }
406    const int n_embd = (int) s.n_embd, hc = (int) s.hc, hc_lr = (int) s.hc_lr;
407    const int hc_dim = (int) (s.hc * s.n_embd);
408    cudaStream_t st = (cudaStream_t) stream;
409
410    // One setting selects every projection in this call. Captured graphs retain these kernel variants.
411    const bool use_native = native_mmvf;
412    const bool use_fp32 = fp32_activations || use_native;
413    const bool fused_gm = hc <= 4;   // gr_gate_mean_kernel's shared array holds hc <= 4 streams
414    if (use_native) {
415        if ((hc_dim & 1) != 0 || (hc_lr & 1) != 0)
416            throw std::invalid_argument("gr_read native MMVF requires even hc*n_embd and hc_lr");
417        native_gr_rms_norm_weighted(R, w_norm, ws.xn, n_embd, hc, eps, stream);
418        bf16_gemv_fp32_mmvf(ws.xn, w_down, ws.lo, hc_dim, hc_lr, stream);
419        native_gr_down_silu(ws.lo, hc_lr, hc, stream);
420        bf16_gemv_fp32_mmvf(ws.lo, w_up, ws.gated, hc_lr, hc_dim, stream);
421        // The existing null-injection contract identifies the final mixer.
422        // Pinned qwen4exp uses fused HC pre for layers and the unfused graph for il=-1.
423        native_gr_pre_gated(ws.xn, ws.gated, mixed, n_embd, hc, w_inject != nullptr, stream);
424    } else if (use_fp32) {
425        gr_norm_kernel<true><<<hc, THREADS, 0, st>>>(R, w_norm, eps, n_embd, ws.xn, ws.xq);
426        gr_down_kernel<float><<<hc_lr + (w_inject != nullptr ? 1 : 0), THREADS, 0, st>>>(
427            ws.xn, w_down, hc_dim, hc_lr, hc, ws.lo, w_inject, inject, w_inject != nullptr);
428        if (fused_gm)
429            gr_gate_mean_kernel<float><<<(n_embd + WARPS - 1) / WARPS, THREADS, 0, st>>>(
430                ws.lo, w_up, ws.xn, hc_lr, n_embd, hc, mixed);
431        else
432            gr_gate_kernel<float><<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>(
433                ws.lo, w_up, ws.xn, hc_dim, hc_lr, ws.gated);
434    } else {
435        gr_norm_kernel<false><<<hc, THREADS, 0, st>>>(R, w_norm, eps, n_embd, ws.xn, ws.xq);
436        gr_down_kernel<uint16_t><<<hc_lr + (w_inject != nullptr ? 1 : 0), THREADS, 0, st>>>(
437            ws.xq, w_down, hc_dim, hc_lr, hc, ws.lq, w_inject, inject, w_inject != nullptr);
438        if (fused_gm)
439            gr_gate_mean_kernel<uint16_t><<<(n_embd + WARPS - 1) / WARPS, THREADS, 0, st>>>(
440                ws.lq, w_up, ws.xn, hc_lr, n_embd, hc, mixed);
441        else
442            gr_gate_kernel<uint16_t><<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>(
443                ws.lq, w_up, ws.xn, hc_dim, hc_lr, ws.gated);
444    }
445    if (!use_native && !fused_gm)
446        gr_mean_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(ws.gated, n_embd, hc, mixed);
447    // Absent for the final mixer, and then nothing is written - computing an injection nobody reads would be
448    // a claim, not a convenience.  The non-native calls compute it in the down grid's last block (Track F).
449    if (w_inject != nullptr && use_native)
450        bf16_gemv_fp32_mmvf(ws.xn, w_inject, inject, hc_dim, hc, stream);
451
452    const cudaError_t e = cudaGetLastError();
453    if (e != cudaSuccess) {
454        std::fprintf(stderr, "gr_read launch: %s\n", cudaGetErrorString(e));
455        std::exit(1);
456    }
457    if (stream == nullptr) {
458        const cudaError_t se = cudaDeviceSynchronize();
459        if (se != cudaSuccess) {
460            std::fprintf(stderr, "gr_read: %s\n", cudaGetErrorString(se));
461            std::exit(1);
462        }
463    }
464}
465
466static bool no_multi_gr() {
467    static const bool off = [] {
468        const char* v = std::getenv("STRATA_NO_MULTI_GR");
469        return v != nullptr && v[0] != '\0' && v[0] != '0';
470    }();
471    return off;
472}
473
474void gr_read_multi(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up,
475                   const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws,
476                   float* xn_multi, float* lo_multi, float* gated_multi, float* mixed, float* inject,
477                   int n_tok, void* stream) {
478    if (n_tok <= 0 || s.n_embd <= 0 || s.hc <= 0 || s.hc_lr <= 0) return;
479    if (!no_multi_gr() && native_mmvf && n_tok > 1 && xn_multi != nullptr && lo_multi != nullptr && gated_multi != nullptr) {
480        const int n_embd = (int) s.n_embd, hc = (int) s.hc, hc_lr = (int) s.hc_lr;
481        const int hc_dim = (int) (s.hc * s.n_embd);
482        if ((hc_dim & 1) != 0 || (hc_lr & 1) != 0)
483            throw std::invalid_argument("gr_read native MMVF requires even hc*n_embd and hc_lr");
484        native_gr_rms_norm_weighted_multi(R, w_norm, xn_multi, n_embd, hc, n_tok, eps, stream);
485        bf16_gemv_fp32_mmvf_multi(xn_multi, hc_dim, w_down, lo_multi, hc_lr, hc_dim, hc_lr, n_tok, stream);
486        native_gr_down_silu(lo_multi, hc_lr * n_tok, hc, stream);
487        bf16_gemv_fp32_mmvf_multi(lo_multi, hc_lr, w_up, gated_multi, hc_dim, hc_lr, hc_dim, n_tok, stream);
488        native_gr_pre_gated_multi(xn_multi, gated_multi, mixed, n_embd, hc, n_tok, w_inject != nullptr, stream);
489        if (w_inject != nullptr)
490            bf16_gemv_fp32_mmvf_multi(xn_multi, hc_dim, w_inject, inject, hc, hc_dim, hc, n_tok, stream);
491        const cudaError_t e = cudaGetLastError();
492        if (e != cudaSuccess) {
493            std::fprintf(stderr, "gr_read_multi launch: %s\n", cudaGetErrorString(e));
494            std::exit(1);
495        }
496        if (stream == nullptr) {
497            const cudaError_t se = cudaDeviceSynchronize();
498            if (se != cudaSuccess) {
499                std::fprintf(stderr, "gr_read_multi: %s\n", cudaGetErrorString(se));
500                std::exit(1);
501            }
502        }
503        return;
504    }
505    const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;
506    for (int t = 0; t < n_tok; ++t) {
507        gr_read(R + (size_t) t * hc_dim, w_norm, w_down, w_up, w_inject, eps, s, ws,
508                mixed + (size_t) t * s.n_embd, inject ? inject + (size_t) t * s.hc : nullptr, stream);
509    }
510}
511
512void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
513              void* stream) {
514    if (s.n_embd <= 0 || s.hc <= 0) return;
515    const long long n = (long long) s.hc * s.n_embd;
516    const int blocks = (int) ((n + THREADS - 1) / THREADS);
517    if (native_mmvf)
518        native_gr_post(R, block_out, inject, R_out, (int) s.n_embd, (int) s.hc, stream);
519    else
520        gr_write_kernel<<<blocks, THREADS, (size_t) s.hc * sizeof(float), (cudaStream_t) stream>>>(
521            R, block_out, inject, (int) s.n_embd, (int) s.hc, R_out);
522    if (stream == nullptr) {
523        const cudaError_t e = cudaDeviceSynchronize();
524        if (e != cudaSuccess) {
525            std::fprintf(stderr, "gr_write: %s\n", cudaGetErrorString(e));
526            std::exit(1);
527        }
528    }
529}
530
531void gr_write_multi(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out,
532                    int n_tok, void* stream) {
533    if (n_tok <= 0 || s.n_embd <= 0 || s.hc <= 0) return;
534    if (!no_multi_gr() && native_mmvf && n_tok > 1) {
535        native_gr_post_multi(R, block_out, inject, R_out, (int) s.n_embd, (int) s.hc, n_tok, stream);
536        if (stream == nullptr) {
537            const cudaError_t e = cudaDeviceSynchronize();
538            if (e != cudaSuccess) {
539                std::fprintf(stderr, "gr_write_multi: %s\n", cudaGetErrorString(e));
540                std::exit(1);
541            }
542        }
543        return;
544    }
545    const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;
546    for (int t = 0; t < n_tok; ++t) {
547        gr_write(R + (size_t) t * hc_dim, block_out + (size_t) t * s.n_embd, inject + (size_t) t * s.hc, s,
548                 R_out + (size_t) t * hc_dim, stream);
549    }
550}
551
552}  // namespace strata::kernels