okami.mom/strata

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

Niko1221Merge f-029-gdn-mx3a76d5eaf

main
42.5 KiB789 linesraw
1// metal/kernels/gdn_prompt.metal - a GDN layer's recurrence for a PROMPT chunk of T tokens, in three passes: the work
2// that does not touch the state runs parallel over the tokens; only the state update is a scan, and the columns of a
3// head's state are independent in it (column j needs k, q, v_j, the gate and beta), so a lane owns one column.
4//
5//   gdn_pre    per (token, head): conv (4 taps; history oldest first) -> SiLU; q, k L2 norm * 1/sqrt(128) (the decode
6//              step's arithmetic); kq = k . q per key head; gate = exp(softplus(alpha + dt) * a), beta = sigmoid(beta);
7//              the chunk's last 3 conv inputs -> hist_out
8//   gdn_scan   per (value head, 32 columns x CB simdgroups): the state column in registers (128 floats a lane);
9//              per token a = S^T k, b = S^T q (old state), delta = (v - g a) beta, o = (g b + delta kq) / sqrt(128)
10//              (= S_new^T q / sqrt(128)), S = g S + k delta^T; q and k staged per TB tokens in threadgroup memory
11//   gdn_post   per (token, head): y = o * rsqrt(mean(o^2) + eps) * gamma * sigmoid(z) -> fp16 (the out GEMM's operand)
12//              and, with `f32`, fp32
13//
14// State layout as Strata's: S[(i * h_v + h) * 128 + j].  Value head h reads q/k head h % h_k.
15// The kernels are new entries (nothing of gdn.metal changes).
16
17struct GdnPArgs {
18    uint n_tok;
19    uint h_k;        // 16
20    uint h_v;        // 48
21    uint channels;   // 10240
22    float eps;       // 1e-6
23    uint f32;        // gdn_post: also write fp32 y
24};
25
26// function constant 7 (optional): the row stride in floats of ONE fused output [qkv | z | alpha | beta] of the four input
27// projections (16480).  gdn_pre then reads qkv / alpha / beta and gdn_post reads z at that stride (the buffers bound at offsets);
28// undefined (every other caller): the separate buffers of channels / h_v / h_v * 128 floats a row.
29constant int GDN_LD [[function_constant(7)]];
30constant bool gdn_ld_on = is_function_constant_defined(GDN_LD);
31
32static inline float gp_conv(device const float* qkv, device const float* hist, device const float* cw, int ch, int t,
33                            int channels) {
34    float s = 0.0f;
35    for (int k = 0; k < 4; ++k) {
36        const int src = t - 3 + k;
37        const float x = src >= 0 ? qkv[src * channels + ch] : hist[ch * 3 + (src + 3)];
38        s = fma(x, cw[ch * 4 + k], s);
39    }
40    s = s + 0.0f;
41    return s / (1.0f + exp(-s));
42}
43
44// grid (h_k + h_v / 2, T), 256 threads.  x < h_k: q (threads 0..127) and k (128..255) of key head x; else value heads
45// 2 (x - h_k) and + 1.
46kernel void gdn_pre(device const float* qkv [[buffer(0)]], device const float* hist [[buffer(1)]],
47                    device const float* conv_w [[buffer(2)]], device const float* alpha [[buffer(3)]],
48                    device const float* beta [[buffer(4)]], device const float* dt [[buffer(5)]],
49                    device const float* ssm_a [[buffer(6)]], device float* qn [[buffer(7)]], device float* kn [[buffer(8)]],
50                    device float* vc [[buffer(9)]], device float2* gb [[buffer(10)]], device float* kq [[buffer(11)]],
51                    device float* hist_out [[buffer(12)]], constant GdnPArgs& a [[buffer(13)]],
52                    uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
53                    ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
54    constexpr int S = 128;
55    threadgroup float part[8];
56    threadgroup float prod[S];
57    const int x = int(tg.x), t = int(tg.y), hk_n = int(a.h_k), hv = int(a.h_v), C = int(a.channels), T = int(a.n_tok);
58    int ch;
59    if (x < hk_n) ch = tid < 128 ? x * S + tid : hk_n * S + x * S + (tid - 128);
60    else ch = 2 * hk_n * S + (2 * (x - hk_n) + (tid >> 7)) * S + (tid & 127);
61    const int QL = gdn_ld_on ? GDN_LD : C;
62    const float cv = gp_conv(qkv, hist, conv_w, ch, t, QL);
63    if (t == T - 1)
64        for (int k = 0; k < 3; ++k) {
65            const int src = T - 3 + k;
66            hist_out[ch * 3 + k] = src >= 0 ? qkv[src * QL + ch] : hist[ch * 3 + (src + 3)];
67        }
68    if (x < hk_n) {
69        const float ssq = simd_sum(cv * cv);
70        if (lane == 0) part[sg] = ssq;
71        threadgroup_barrier(mem_flags::mem_threadgroup);
72        const int base = tid < 128 ? 0 : 4;
73        const float tot = (part[base] + part[base + 1]) + (part[base + 2] + part[base + 3]);
74        const float rs = rsqrt(tot / float(S) + a.eps / float(S));
75        const float nv = (rs * cv) * (1.0f / sqrt(float(S)));
76        if (tid < 128) {
77            qn[(t * hk_n + x) * S + tid] = nv;
78            prod[tid] = nv;
79        }
80        threadgroup_barrier(mem_flags::mem_threadgroup);
81        if (tid >= 128) {
82            kn[(t * hk_n + x) * S + tid - 128] = nv;
83            const float p = simd_sum(nv * prod[tid - 128]);
84            if (lane == 0) part[sg] = p;   // simdgroups 4..7 (q's slots 0..3 are read already)
85        }
86        threadgroup_barrier(mem_flags::mem_threadgroup);
87        if (tid == 0) kq[t * hk_n + x] = (part[4] + part[5]) + (part[6] + part[7]);
88    } else {
89        const int h = 2 * (x - hk_n) + (tid >> 7);
90        vc[(t * hv + h) * S + (tid & 127)] = cv;
91        if ((tid & 127) == 0) {
92            const int AL = gdn_ld_on ? GDN_LD : hv;
93            const float v = alpha[t * AL + h] + dt[h];
94            const float e = exp(v), u = 1.0f + e;
95            const float sp = v > 20.0f ? v : (u == 1.0f ? e : log(u) * e / (u - 1.0f));
96            gb[t * hv + h] = float2(exp(sp * ssm_a[h]), 1.0f / (1.0f + exp(-beta[t * AL + h])));
97        }
98    }
99}
100
101// grid (h_v * 4 / CB), CB * 32 threads; TB tokens of q and k staged at a time
102template <int CB, int TB>
103kernel void gdn_scan_t(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]],
104                       device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]],
105                       device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]],
106                       device float* o [[buffer(6)]], constant GdnPArgs& a [[buffer(7)]],
107                       uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
108                       ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
109    constexpr int S = 128, NB = 4 / CB;
110    threadgroup float4 qs[TB][32], ks[TB][32];
111    const int h = int(tg.x) / NB, hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k);
112    const int j = ((int(tg.x) % NB) * CB + sg) * 32 + lane;
113    const int T = int(a.n_tok);
114    const float scale = 1.0f / sqrt(float(S));
115    float st[S];
116#pragma clang loop unroll(full)
117    for (int i = 0; i < S; ++i) st[i] = state[(i * hv + h) * S + j];
118    for (int t0 = 0; t0 < T; t0 += TB) {
119        const int nb = min(TB, T - t0);
120        threadgroup_barrier(mem_flags::mem_threadgroup);
121        for (int idx = tid; idx < nb * 32; idx += CB * 32) {
122            const int tt = idx >> 5, w = idx & 31;
123            qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w];
124            ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w];
125        }
126        threadgroup_barrier(mem_flags::mem_threadgroup);
127        for (int tt = 0; tt < nb; ++tt) {
128            const int t = t0 + tt;
129            const float2 g_b = gb[t * hv + h];
130            const float kqv = kq[t * hkn + hk];
131            const float v = vc[(t * hv + h) * S + j];
132            float ka = 0.0f, kb = 0.0f, qa = 0.0f, qb = 0.0f;
133#pragma clang loop unroll(full)
134            for (int w = 0; w < 32; w += 2) {
135                const float4 k0 = ks[tt][w], k1 = ks[tt][w + 1], q0 = qs[tt][w], q1 = qs[tt][w + 1];
136                ka = fma(st[4 * w], k0.x, ka); ka = fma(st[4 * w + 1], k0.y, ka);
137                ka = fma(st[4 * w + 2], k0.z, ka); ka = fma(st[4 * w + 3], k0.w, ka);
138                kb = fma(st[4 * w + 4], k1.x, kb); kb = fma(st[4 * w + 5], k1.y, kb);
139                kb = fma(st[4 * w + 6], k1.z, kb); kb = fma(st[4 * w + 7], k1.w, kb);
140                qa = fma(st[4 * w], q0.x, qa); qa = fma(st[4 * w + 1], q0.y, qa);
141                qa = fma(st[4 * w + 2], q0.z, qa); qa = fma(st[4 * w + 3], q0.w, qa);
142                qb = fma(st[4 * w + 4], q1.x, qb); qb = fma(st[4 * w + 5], q1.y, qb);
143                qb = fma(st[4 * w + 6], q1.z, qb); qb = fma(st[4 * w + 7], q1.w, qb);
144            }
145            const float g = g_b.x, kv = ka + kb, qv = qa + qb;
146            const float delta = (v - g * kv) * g_b.y;
147            o[(t * hv + h) * S + j] = fma(g, qv, delta * kqv) * scale;
148#pragma clang loop unroll(full)
149            for (int w = 0; w < 32; ++w) {
150                const float4 k4 = ks[tt][w];
151                st[4 * w] = fma(g, st[4 * w], k4.x * delta);
152                st[4 * w + 1] = fma(g, st[4 * w + 1], k4.y * delta);
153                st[4 * w + 2] = fma(g, st[4 * w + 2], k4.z * delta);
154                st[4 * w + 3] = fma(g, st[4 * w + 3], k4.w * delta);
155            }
156        }
157    }
158#pragma clang loop unroll(full)
159    for (int i = 0; i < S; ++i) state[(i * hv + h) * S + j] = st[i];
160}
161
162// a probe for the bench (function constant 6): 1 = no per-token exchange (wrong results), 2 = no state update
163constant int GDN_PROBE [[function_constant(6)]];
164constant int gdn_probe = is_function_constant_defined(GDN_PROBE) ? GDN_PROBE : 0;
165
166// the rows of a column split over IB simdgroups (128 / IB rows a lane, fewer registers): grid (h_v * 4), IB * 32
167// threads; lane = column (32 columns a threadgroup); per token the IB partial dots are exchanged through threadgroup
168// memory (double-buffered: one barrier a token)
169template <int IB, int TB>
170kernel void gdn_scan_r(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]],
171                       device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]],
172                       device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]],
173                       device float* o [[buffer(6)]], constant GdnPArgs& a [[buffer(7)]],
174                       uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
175                       ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
176    constexpr int S = 128, R = S / IB, R4 = R / 4;
177    threadgroup float4 qs[TB][32], ks[TB][32];
178    threadgroup float2 red[2][IB][32];
179    threadgroup float vs[TB][32];
180    threadgroup float4 gk[TB];   // gate, beta, kq
181    const int h = int(tg.x) / 4, hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k);
182    const int j = (int(tg.x) % 4) * 32 + lane, i0 = sg * R;
183    const int T = int(a.n_tok);
184    const float scale = 1.0f / sqrt(float(S));
185    float st[R];
186#pragma clang loop unroll(full)
187    for (int i = 0; i < R; ++i) st[i] = state[((i0 + i) * hv + h) * S + j];
188    for (int t0 = 0; t0 < T; t0 += TB) {
189        const int nb = min(TB, T - t0);
190        threadgroup_barrier(mem_flags::mem_threadgroup);
191        for (int idx = tid; idx < nb * 32; idx += IB * 32) {
192            const int tt = idx >> 5, w = idx & 31;
193            qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w];
194            ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w];
195            vs[tt][w] = vc[((t0 + tt) * hv + h) * S + (j - lane) + w];
196            if (w == 0) {
197                const float2 g_b = gb[(t0 + tt) * hv + h];
198                gk[tt] = float4(g_b.x, g_b.y, kq[(t0 + tt) * hkn + hk], 0.0f);
199            }
200        }
201        threadgroup_barrier(mem_flags::mem_threadgroup);
202        for (int tt = 0; tt < nb; ++tt) {
203            const int t = t0 + tt, slot = t & 1;
204            float ka = 0.0f, qa = 0.0f;
205#pragma clang loop unroll(full)
206            for (int w = 0; w < R4; ++w) {
207                const float4 k4 = ks[tt][i0 / 4 + w], q4 = qs[tt][i0 / 4 + w];
208                ka = fma(st[4 * w], k4.x, ka); ka = fma(st[4 * w + 1], k4.y, ka);
209                ka = fma(st[4 * w + 2], k4.z, ka); ka = fma(st[4 * w + 3], k4.w, ka);
210                qa = fma(st[4 * w], q4.x, qa); qa = fma(st[4 * w + 1], q4.y, qa);
211                qa = fma(st[4 * w + 2], q4.z, qa); qa = fma(st[4 * w + 3], q4.w, qa);
212            }
213            const float4 g_b = gk[tt];
214            const float kqv = g_b.z;
215            const float v = vs[tt][lane];
216            float2 s = float2(ka, qa);
217            if (gdn_probe != 1) {
218                red[slot][sg][lane] = s;
219                threadgroup_barrier(mem_flags::mem_threadgroup);
220                s = red[slot][0][lane];
221#pragma clang loop unroll(full)
222                for (int b = 1; b < IB; ++b) s += red[slot][b][lane];
223            }
224            const float g = g_b.x;
225            const float delta = (v - g * s.x) * g_b.y;
226            if (sg == 0) o[(t * hv + h) * S + j] = fma(g, s.y, delta * kqv) * scale;
227            if (gdn_probe != 2)
228#pragma clang loop unroll(full)
229            for (int w = 0; w < R4; ++w) {
230                const float4 k4 = ks[tt][i0 / 4 + w];
231                st[4 * w] = fma(g, st[4 * w], k4.x * delta);
232                st[4 * w + 1] = fma(g, st[4 * w + 1], k4.y * delta);
233                st[4 * w + 2] = fma(g, st[4 * w + 2], k4.z * delta);
234                st[4 * w + 3] = fma(g, st[4 * w + 3], k4.w * delta);
235            }
236        }
237    }
238#pragma clang loop unroll(full)
239    for (int i = 0; i < R; ++i) state[((i0 + i) * hv + h) * S + j] = st[i];
240}
241
242// gdn_scan_r<8, 16> with the 16 state rows of a lane in four float4 variables (no array): a register-allocation check
243kernel void gdn_scan_v(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]],
244                       device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]],
245                       device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]],
246                       device float* o [[buffer(6)]], constant GdnPArgs& a [[buffer(7)]],
247                       uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
248                       ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
249    constexpr int S = 128, IB = 8, TB = 16;
250    threadgroup float4 qs[TB][32], ks[TB][32];
251    threadgroup float2 red[2][IB][32];
252    threadgroup float vs[TB][32];
253    threadgroup float4 gk[TB];
254    const int h = int(tg.x) / 4, hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k);
255    const int j = (int(tg.x) % 4) * 32 + lane, i0 = sg * 16, w0 = sg * 4;
256    const int T = int(a.n_tok);
257    const float scale = 1.0f / sqrt(float(S));
258    device float* sp = state + (i0 * hv + h) * S + j;
259    const int rs = hv * S;
260    float4 s0 = float4(sp[0], sp[rs], sp[2 * rs], sp[3 * rs]);
261    float4 s1 = float4(sp[4 * rs], sp[5 * rs], sp[6 * rs], sp[7 * rs]);
262    float4 s2 = float4(sp[8 * rs], sp[9 * rs], sp[10 * rs], sp[11 * rs]);
263    float4 s3 = float4(sp[12 * rs], sp[13 * rs], sp[14 * rs], sp[15 * rs]);
264    for (int t0 = 0; t0 < T; t0 += TB) {
265        const int nb = min(TB, T - t0);
266        threadgroup_barrier(mem_flags::mem_threadgroup);
267        for (int idx = tid; idx < nb * 32; idx += IB * 32) {
268            const int tt = idx >> 5, w = idx & 31;
269            qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w];
270            ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w];
271            vs[tt][w] = vc[((t0 + tt) * hv + h) * S + (j - lane) + w];
272            if (w == 0) {
273                const float2 g_b = gb[(t0 + tt) * hv + h];
274                gk[tt] = float4(g_b.x, g_b.y, kq[(t0 + tt) * hkn + hk], 0.0f);
275            }
276        }
277        threadgroup_barrier(mem_flags::mem_threadgroup);
278        for (int tt = 0; tt < nb; ++tt) {
279            const int t = t0 + tt, slot = t & 1;
280            const float4 k0 = ks[tt][w0], k1 = ks[tt][w0 + 1], k2 = ks[tt][w0 + 2], k3 = ks[tt][w0 + 3];
281            const float4 q0 = qs[tt][w0], q1 = qs[tt][w0 + 1], q2 = qs[tt][w0 + 2], q3 = qs[tt][w0 + 3];
282            const float ka = (dot(s0, k0) + dot(s1, k1)) + (dot(s2, k2) + dot(s3, k3));
283            const float qa = (dot(s0, q0) + dot(s1, q1)) + (dot(s2, q2) + dot(s3, q3));
284            red[slot][sg][lane] = float2(ka, qa);
285            const float4 g_b = gk[tt];
286            const float v = vs[tt][lane];
287            threadgroup_barrier(mem_flags::mem_threadgroup);
288            float2 r = red[slot][0][lane];
289            for (int b = 1; b < IB; ++b) r += red[slot][b][lane];
290            const float g = g_b.x;
291            const float delta = (v - g * r.x) * g_b.y;
292            if (sg == 0) o[(t * hv + h) * S + j] = fma(g, r.y, delta * g_b.z) * scale;
293            s0 = fma(float4(g), s0, k0 * delta);
294            s1 = fma(float4(g), s1, k1 * delta);
295            s2 = fma(float4(g), s2, k2 * delta);
296            s3 = fma(float4(g), s3, k3 * delta);
297        }
298    }
299    sp[0] = s0.x; sp[rs] = s0.y; sp[2 * rs] = s0.z; sp[3 * rs] = s0.w;
300    sp[4 * rs] = s1.x; sp[5 * rs] = s1.y; sp[6 * rs] = s1.z; sp[7 * rs] = s1.w;
301    sp[8 * rs] = s2.x; sp[9 * rs] = s2.y; sp[10 * rs] = s2.z; sp[11 * rs] = s2.w;
302    sp[12 * rs] = s3.x; sp[13 * rs] = s3.y; sp[14 * rs] = s3.z; sp[15 * rs] = s3.w;
303}
304
305// grid (h_v, T), 128 threads
306kernel void gdn_post(device const float* o [[buffer(0)]], device const float* z [[buffer(1)]],
307                     device const float* gamma [[buffer(2)]], device half* yh [[buffer(3)]], device float* y [[buffer(4)]],
308                     constant GdnPArgs& a [[buffer(5)]],
309                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
310                     ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
311    threadgroup float part[4];
312    const int h = int(tg.x), t = int(tg.y), hv = int(a.h_v);
313    const uint i = uint(t * hv + h) * 128 + tid;
314    const float ov = o[i];
315    const float ss = simd_sum(ov * ov);
316    if (lane == 0) part[sg] = ss;
317    threadgroup_barrier(mem_flags::mem_threadgroup);
318    const float tot = (part[0] + part[1]) + (part[2] + part[3]);
319    const float rs = rsqrt(tot / 128.0f + a.eps);
320    const float zv = gdn_ld_on ? z[uint(t) * uint(GDN_LD) + uint(h) * 128u + tid] : z[i];
321    const float yv = ((rs * ov) * gamma[tid]) * (1.0f / (1.0f + exp(-zv)));
322    yh[i] = half(yv);
323    if (a.f32) y[i] = yv;
324}
325
326template [[host_name("gdn_scan_1")]] kernel decltype(gdn_scan_t<1, 16>) gdn_scan_t<1, 16>;
327template [[host_name("gdn_scan_2")]] kernel decltype(gdn_scan_t<2, 16>) gdn_scan_t<2, 16>;
328template [[host_name("gdn_scan_4")]] kernel decltype(gdn_scan_t<4, 16>) gdn_scan_t<4, 16>;
329template [[host_name("gdn_scanr_2")]] kernel decltype(gdn_scan_r<2, 16>) gdn_scan_r<2, 16>;
330template [[host_name("gdn_scanr_4")]] kernel decltype(gdn_scan_r<4, 16>) gdn_scan_r<4, 16>;
331template [[host_name("gdn_scanr_8")]] kernel decltype(gdn_scan_r<8, 16>) gdn_scan_r<8, 16>;
332template [[host_name("gdn_scanr_4_8")]] kernel decltype(gdn_scan_r<4, 8>) gdn_scan_r<4, 8>;
333template [[host_name("gdn_scanr_4_4")]] kernel decltype(gdn_scan_r<4, 4>) gdn_scan_r<4, 4>;
334template [[host_name("gdn_scanr_4_2")]] kernel decltype(gdn_scan_r<4, 2>) gdn_scan_r<4, 2>;
335template [[host_name("gdn_scanr_8_8")]] kernel decltype(gdn_scan_r<8, 8>) gdn_scan_r<8, 8>;
336template [[host_name("gdn_scanr_8_4")]] kernel decltype(gdn_scan_r<8, 4>) gdn_scan_r<8, 4>;
337template [[host_name("gdn_scanr_2_8")]] kernel decltype(gdn_scan_r<2, 8>) gdn_scan_r<2, 8>;
338template [[host_name("gdn_scanr_2_4")]] kernel decltype(gdn_scan_r<2, 4>) gdn_scan_r<2, 4>;
339
340// ---- gdn_scanf: gdn_scan_r<4, TB> with gdn_post folded in.  One threadgroup a value head (grid h_v), 16 simdgroups =
341// 4 column blocks x 4 row blocks, 512 threads.  The scan is gdn_scan_r's, token for token (the same operations in the
342// same order, so o is the same bits); a column block's row-block-0 simdgroup holds o for its 32 columns, writes them and
343// their simd_sum of squares to threadgroup memory, and once every TB tokens the whole threadgroup runs gdn_post's
344// arithmetic on those tokens (the sum of the four partials in gdn_post's order: the same bits as gdn_post).  Outputs:
345// y (fp16) and, with `f32`, fp32 y; o itself never reaches device memory.
346template <int TB>
347kernel void gdn_scan_f(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]],
348                       device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]],
349                       device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]],
350                       device const float* z [[buffer(6)]], device const float* gamma [[buffer(7)]],
351                       device half* yh [[buffer(8)]], device float* y32 [[buffer(9)]], constant GdnPArgs& a [[buffer(10)]],
352                       uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
353                       ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
354    constexpr int S = 128, IB = 4, R = S / IB, R4 = R / 4;
355    threadgroup float4 qs[TB][32], ks[TB][32];
356    threadgroup float2 red[2][16][32];
357    threadgroup float vs[TB][128];
358    threadgroup float4 gk[TB];
359    threadgroup float ot[TB][128];
360    threadgroup float osq[TB][4];
361    const int h = int(tg.x), hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k);
362    const int cb = sg >> 2, ib = sg & 3;
363    const int j = cb * 32 + lane, i0 = ib * R;
364    const int T = int(a.n_tok);
365    const float scale = 1.0f / sqrt(float(S));
366    float st[R];
367#pragma clang loop unroll(full)
368    for (int i = 0; i < R; ++i) st[i] = state[((i0 + i) * hv + h) * S + j];
369    for (int t0 = 0; t0 < T; t0 += TB) {
370        const int nb = min(TB, T - t0);
371        threadgroup_barrier(mem_flags::mem_threadgroup);
372        for (int idx = tid; idx < nb * 32; idx += 512) {
373            const int tt = idx >> 5, w = idx & 31;
374            qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w];
375            ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w];
376        }
377        for (int idx = tid; idx < nb * 128; idx += 512) {
378            const int tt = idx >> 7, w = idx & 127;
379            vs[tt][w] = vc[((t0 + tt) * hv + h) * S + w];
380        }
381        for (int tt = tid; tt < nb; tt += 512) {
382            const float2 g_b = gb[(t0 + tt) * hv + h];
383            gk[tt] = float4(g_b.x, g_b.y, kq[(t0 + tt) * hkn + hk], 0.0f);
384        }
385        threadgroup_barrier(mem_flags::mem_threadgroup);
386        for (int tt = 0; tt < nb; ++tt) {
387            const int t = t0 + tt, slot = t & 1;
388            float ka = 0.0f, qa = 0.0f;
389#pragma clang loop unroll(full)
390            for (int w = 0; w < R4; ++w) {
391                const float4 k4 = ks[tt][i0 / 4 + w], q4 = qs[tt][i0 / 4 + w];
392                ka = fma(st[4 * w], k4.x, ka); ka = fma(st[4 * w + 1], k4.y, ka);
393                ka = fma(st[4 * w + 2], k4.z, ka); ka = fma(st[4 * w + 3], k4.w, ka);
394                qa = fma(st[4 * w], q4.x, qa); qa = fma(st[4 * w + 1], q4.y, qa);
395                qa = fma(st[4 * w + 2], q4.z, qa); qa = fma(st[4 * w + 3], q4.w, qa);
396            }
397            const float4 g_b = gk[tt];
398            const float v = vs[tt][j];
399            red[slot][sg][lane] = float2(ka, qa);
400            threadgroup_barrier(mem_flags::mem_threadgroup);
401            float2 s = red[slot][cb * 4][lane];
402#pragma clang loop unroll(full)
403            for (int b = 1; b < IB; ++b) s += red[slot][cb * 4 + b][lane];
404            const float g = g_b.x;
405            const float delta = (v - g * s.x) * g_b.y;
406            if (ib == 0) {
407                const float ov = fma(g, s.y, delta * g_b.z) * scale;
408                ot[tt][j] = ov;
409                const float ss = simd_sum(ov * ov);
410                if (lane == 0) osq[tt][cb] = ss;
411            }
412#pragma clang loop unroll(full)
413            for (int w = 0; w < R4; ++w) {
414                const float4 k4 = ks[tt][i0 / 4 + w];
415                st[4 * w] = fma(g, st[4 * w], k4.x * delta);
416                st[4 * w + 1] = fma(g, st[4 * w + 1], k4.y * delta);
417                st[4 * w + 2] = fma(g, st[4 * w + 2], k4.z * delta);
418                st[4 * w + 3] = fma(g, st[4 * w + 3], k4.w * delta);
419            }
420        }
421        threadgroup_barrier(mem_flags::mem_threadgroup);
422        // gdn_post for these tokens
423        for (int idx = tid; idx < nb * 128; idx += 512) {
424            const int tt = idx >> 7, c = idx & 127;
425            const float tot = (osq[tt][0] + osq[tt][1]) + (osq[tt][2] + osq[tt][3]);
426            const float rs = rsqrt(tot / 128.0f + a.eps);
427            const ulong i = ulong((t0 + tt) * hv + h) * 128 + c;
428            const float ov = ot[tt][c];
429            const float yv = ((rs * ov) * gamma[c]) * (1.0f / (1.0f + exp(-z[i])));
430            yh[i] = half(yv);
431            if (a.f32) y32[i] = yv;
432        }
433    }
434#pragma clang loop unroll(full)
435    for (int i = 0; i < R; ++i) state[((i0 + i) * hv + h) * S + j] = st[i];
436}
437template [[host_name("gdn_scanf_8")]] kernel decltype(gdn_scan_f<8>) gdn_scan_f<8>;
438template [[host_name("gdn_scanf_4")]] kernel decltype(gdn_scan_f<4>) gdn_scan_f<4>;
439template [[host_name("gdn_scanf_2")]] kernel decltype(gdn_scan_f<2>) gdn_scan_f<2>;
440
441// ---- the chunked form (chunks of GC = 32 tokens), the WY / UT form of the gated delta rule.  With G_t the product
442// of the chunk's gates up to t (log space: lg_t) and S0 the state entering the chunk:
443//   (I + A) D = B,  A_ts = beta_t (k_t . k_s) G_t / G_s (s < t),  B = [beta v | beta G k]   ->   D = [U | W]
444//   delta = U - W S0,   o_t = G_t S0^T q_t + sum_{s <= t} (q_t . k_s) G_t / G_s delta_s,
445//   S_L = G_L S0 + sum_s G_L / G_s k_s delta_s^T
446// (the sequential recurrence's algebra; the rounding differs).  Three kernels:
447//   gdn_cprep   per (head, chunk): lg, A, the forward substitution for U and W (a thread per column of B)
448//   gdn_cstate  per (head, 32 state columns): the chunks in order - delta, the inter-chunk output, the state update
449//   gdn_cout    per (head, chunk): o += the intra-chunk part, times 1/sqrt(128)
450constant constexpr int GC = 32;
451
452// grid (h_v, chunks), 256 threads.  U, W: [h][chunk][GC][128]; lgo: [h][chunk][GC]
453kernel void gdn_cprep(device const float* qn [[buffer(0)]], device const float* kn [[buffer(1)]],
454                      device const float* vc [[buffer(2)]], device const float2* gb [[buffer(3)]],
455                      device float* U [[buffer(4)]], device float* W [[buffer(5)]], device float* lgo [[buffer(6)]],
456                      constant GdnPArgs& a [[buffer(7)]],
457                      uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
458    constexpr int S = 128;
459    threadgroup float A[GC][GC];
460    threadgroup float lg[GC], bt[GC];
461    const int h = int(tg.x), c = int(tg.y), hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok);
462    const int NC = (T + GC - 1) / GC, t0 = c * GC, nb = min(GC, T - t0);
463    if (tid == 0) {
464        float s = 0.0f;
465        for (int t = 0; t < GC; ++t) {
466            if (t < nb) s += max(log(gb[(t0 + t) * hv + h].x), -80.0f);
467            lg[t] = s;
468            bt[t] = t < nb ? gb[(t0 + t) * hv + h].y : 0.0f;
469        }
470    }
471    threadgroup_barrier(mem_flags::mem_threadgroup);
472    for (int idx = tid; idx < GC * GC; idx += 256) {
473        const int t = idx / GC, s = idx % GC;
474        float v = 0.0f;
475        if (s < t && t < nb) {
476            device const float4* kt = (device const float4*)(kn + ((t0 + t) * hkn + hk) * S);
477            device const float4* ks = (device const float4*)(kn + ((t0 + s) * hkn + hk) * S);
478            float d = 0.0f;
479            for (int i = 0; i < S / 4; ++i) d += dot(kt[i], ks[i]);
480            v = bt[t] * d * exp(lg[t] - lg[s]);
481        }
482        A[t][s] = v;
483    }
484    threadgroup_barrier(mem_flags::mem_threadgroup);
485    // forward substitution, column j of B a thread (threads 0..127: beta v; 128..255: beta G k)
486    const int j = tid & 127;
487    const bool isw = tid >= 128;
488    float x[GC];
489    for (int t = 0; t < GC; ++t) {
490        float b = 0.0f;
491        if (t < nb) b = isw ? bt[t] * exp(lg[t]) * kn[((t0 + t) * hkn + hk) * S + j] : bt[t] * vc[((t0 + t) * hv + h) * S + j];
492        for (int s = 0; s < t; ++s) b = fma(-A[t][s], x[s], b);
493        x[t] = b;
494    }
495    device float* o = (isw ? W : U) + (ulong(h) * NC + c) * GC * S + j;
496    for (int t = 0; t < GC; ++t) o[t * S] = x[t];
497    if (tid < GC) lgo[(h * NC + c) * GC + tid] = lg[tid];
498}
499
500// grid (h_v * 4), 256 threads = 8 row blocks of 16 x 32 columns; the state's 128 x 32 block in registers (16 a thread)
501kernel void gdn_cstate(device float* state [[buffer(0)]], device const float* qn [[buffer(1)]],
502                       device const float* kn [[buffer(2)]], device const float* U [[buffer(3)]],
503                       device const float* W [[buffer(4)]], device const float* lgo [[buffer(5)]],
504                       device float* delta [[buffer(6)]], device float* o [[buffer(7)]], constant GdnPArgs& a [[buffer(8)]],
505                       uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
506                       ushort lane [[thread_index_in_simdgroup]]) {
507    constexpr int S = 128, RB = 16;
508    threadgroup float red[8][16][32];
509    threadgroup float dl[GC][32];
510    const int h = int(tg.x) / 4, hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok);
511    const int NC = (T + GC - 1) / GC;
512    const int j = (int(tg.x) % 4) * 32 + lane, i0 = sg * RB;
513    float st[RB];
514    for (int r = 0; r < RB; ++r) st[r] = state[((i0 + r) * hv + h) * S + j];
515    for (int c = 0; c < NC; ++c) {
516        const int t0 = c * GC, nb = min(GC, T - t0);
517        device const float* Uc = U + (ulong(h) * NC + c) * GC * S;
518        device const float* Wc = W + (ulong(h) * NC + c) * GC * S;
519        device const float* lg = lgo + (h * NC + c) * GC;
520        // pass 0: delta = U - W S0;  pass 1: o_inter = G_t S0^T q_t;  16 tokens at a time
521        for (int pass = 0; pass < 2; ++pass) {
522            for (int hf = 0; hf < 2; ++hf) {
523                float p[16];
524                for (int u = 0; u < 16; ++u) {
525                    const int t = hf * 16 + u;
526                    float s = 0.0f;
527                    if (t < nb) {
528                        device const float* v = pass == 0 ? Wc + t * S + i0 : qn + ((t0 + t) * hkn + hk) * S + i0;
529                        for (int r = 0; r < RB; ++r) s = fma(v[r], st[r], s);
530                    }
531                    p[u] = s;
532                }
533                threadgroup_barrier(mem_flags::mem_threadgroup);
534                for (int u = 0; u < 16; ++u) red[sg][u][lane] = p[u];
535                threadgroup_barrier(mem_flags::mem_threadgroup);
536                for (int u = sg * 2; u < sg * 2 + 2; ++u) {
537                    const int t = hf * 16 + u;
538                    float s = 0.0f;
539                    for (int b = 0; b < 8; ++b) s += red[b][u][lane];
540                    if (t < nb) {
541                        if (pass == 0) {
542                            const float d = Uc[t * S + j] - s;
543                            dl[t][lane] = d;
544                            delta[((ulong(h) * NC + c) * GC + t) * S + j] = d;
545                        } else {
546                            o[((t0 + t) * hv + h) * S + j] = exp(lg[t]) * s;
547                        }
548                    } else if (pass == 0) {
549                        dl[t][lane] = 0.0f;
550                    }
551                }
552            }
553        }
554        threadgroup_barrier(mem_flags::mem_threadgroup);
555        // S = G_L S0 + sum_s G_L / G_s k_s delta_s^T
556        const float lgl = lg[nb - 1], gl = exp(lgl);
557        for (int r = 0; r < RB; ++r) st[r] *= gl;
558        for (int s = 0; s < nb; ++s) {
559            const float f = exp(lgl - lg[s]) * dl[s][lane];
560            device const float* ks = kn + ((t0 + s) * hkn + hk) * S + i0;
561            for (int r = 0; r < RB; ++r) st[r] = fma(ks[r], f, st[r]);
562        }
563        threadgroup_barrier(mem_flags::mem_threadgroup);
564    }
565    for (int r = 0; r < RB; ++r) state[((i0 + r) * hv + h) * S + j] = st[r];
566}
567
568// grid (h_v, chunks), 128 threads (column j): o_t = (o_inter_t + sum_{s <= t} (q_t . k_s) G_t / G_s delta_s) / sqrt(128)
569kernel void gdn_cout(device const float* qn [[buffer(0)]], device const float* kn [[buffer(1)]],
570                     device const float* delta [[buffer(2)]], device const float* lgo [[buffer(3)]],
571                     device float* o [[buffer(4)]], constant GdnPArgs& a [[buffer(5)]],
572                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
573    constexpr int S = 128;
574    threadgroup float M[GC][GC];
575    const int h = int(tg.x), c = int(tg.y), hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok);
576    const int NC = (T + GC - 1) / GC, t0 = c * GC, nb = min(GC, T - t0);
577    device const float* lg = lgo + (h * NC + c) * GC;
578    for (int idx = tid; idx < GC * GC; idx += 128) {
579        const int t = idx / GC, s = idx % GC;
580        float v = 0.0f;
581        if (s <= t && t < nb) {
582            device const float4* qt = (device const float4*)(qn + ((t0 + t) * hkn + hk) * S);
583            device const float4* ks = (device const float4*)(kn + ((t0 + s) * hkn + hk) * S);
584            float d = 0.0f;
585            for (int i = 0; i < S / 4; ++i) d += dot(qt[i], ks[i]);
586            v = d * exp(lg[t] - lg[s]);
587        }
588        M[t][s] = v;
589    }
590    threadgroup_barrier(mem_flags::mem_threadgroup);
591    const int j = tid;
592    device const float* dc = delta + (ulong(h) * NC + c) * GC * S + j;
593    float dv[GC];
594    for (int s = 0; s < GC; ++s) dv[s] = s < nb ? dc[s * S] : 0.0f;
595    const float scale = 1.0f / sqrt(float(S));
596    for (int t = 0; t < nb; ++t) {
597        float s = o[((t0 + t) * hv + h) * S + j];
598        for (int u = 0; u <= t; ++u) s = fma(M[t][u], dv[u], s);
599        o[((t0 + t) * hv + h) * S + j] = s * scale;
600    }
601}
602
603// ---- the chunked form v2: the same algebra as gdn_cprep / gdn_cstate / gdn_cout (WY / UT, chunks of GC = 32), organised for the
604// GPU.  Staging the chunk's k in threadgroup memory removes the redundant device loads of gdn_cprep, the state update, the
605// inter-chunk and the intra-chunk products run as 8x8 simdgroup_matrix products (fp32), and the intra-chunk part is folded into
606// the state kernel (no gdn_cout, no delta buffer).  The chunk's q.k matrix M (with the decay factors) comes from the prep.
607//   gdn_cprep2   per (head, chunk): lg, A, the forward substitution for U and W, and M_ts = (q_t . k_s) G_t / G_s (s <= t)
608//   gdn_cstate2  per (head, 32 state columns): the chunks in order - delta = U - W S, o = (G q S + M delta) / sqrt(128),
609//                S = G_L S + sum_s (G_L / G_s) k_s delta_s^T.  The q and k rows of the last chunk's 32 tokens are read in
610//                full (rows past n_tok are read and multiplied by zero): the caller's buffers hold a multiple of 32 rows.
611kernel void gdn_cprep2(device const float* qn [[buffer(0)]], device const float* kn [[buffer(1)]],
612                       device const float* vc [[buffer(2)]], device const float2* gb [[buffer(3)]],
613                       device float* U [[buffer(4)]], device float* W [[buffer(5)]], device float* lgo [[buffer(6)]],
614                       device float* Mo [[buffer(7)]], constant GdnPArgs& a [[buffer(8)]],
615                       uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
616    constexpr int S = 128;
617    threadgroup float4 Ks[GC * 32];
618    threadgroup float4 A4[GC * 8];
619    threadgroup float* A = (threadgroup float*)A4;
620    threadgroup float lg[GC], bt[GC];
621    const int h = int(tg.x), c = int(tg.y), hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok);
622    const int NC = (T + GC - 1) / GC, t0 = c * GC, nb = min(GC, T - t0);
623    if (tid == 0) {
624        float s = 0.0f;
625        for (int t = 0; t < GC; ++t) {
626            if (t < nb) s += max(log(gb[(t0 + t) * hv + h].x), -80.0f);
627            lg[t] = s;
628            bt[t] = t < nb ? gb[(t0 + t) * hv + h].y : 0.0f;
629        }
630    }
631    device const float4* kn4 = (device const float4*)kn;
632    for (int idx = tid; idx < GC * 32; idx += 256) {
633        const int t = idx >> 5, w = idx & 31;
634        Ks[idx] = t < nb ? kn4[((t0 + t) * hkn + hk) * 32 + w] : float4(0.0f);
635    }
636    threadgroup_barrier(mem_flags::mem_threadgroup);
637    for (int idx = tid; idx < GC * GC; idx += 256) {
638        const int t = idx / GC, s = idx % GC;
639        float av = 0.0f, mv = 0.0f;
640        if (t < nb && s <= t && gdn_probe != 1) {
641            device const float4* qt = (device const float4*)(qn + ((t0 + t) * hkn + hk) * S);
642            float dm = 0.0f, da = 0.0f;
643            for (int i = 0; i < S / 4; ++i) {
644                const float4 ks = Ks[s * 32 + i];
645                dm += dot(qt[i], ks);
646                da += dot(Ks[t * 32 + i], ks);
647            }
648            const float f = exp(lg[t] - lg[s]);
649            mv = dm * f;
650            if (s < t) av = bt[t] * da * f;
651        }
652        A[t * GC + s] = av;
653        Mo[((ulong(h) * NC + c) * GC + t) * GC + s] = mv;
654    }
655    threadgroup_barrier(mem_flags::mem_threadgroup);
656    const int j = tid & 127;
657    const bool isw = tid >= 128;
658    threadgroup const float* Kf = (threadgroup const float*)Ks;
659    float x[GC];
660#pragma clang loop unroll(full)
661    for (int t = 0; t < GC; ++t) x[t] = 0.0f;
662#pragma clang loop unroll(full)
663    for (int t = 0; t < GC; ++t) {
664        float b = 0.0f;
665        if (t < nb) b = isw ? bt[t] * exp(lg[t]) * Kf[t * S + j] : bt[t] * vc[((t0 + t) * hv + h) * S + j];
666#pragma clang loop unroll(full)
667        for (int s4 = 0; s4 < (t + 3) / 4; ++s4) {
668            const float4 ar = A4[t * 8 + s4];
669            b = fma(-ar.x, x[4 * s4], b);
670            b = fma(-ar.y, x[4 * s4 + 1], b);
671            b = fma(-ar.z, x[4 * s4 + 2], b);
672            b = fma(-ar.w, x[4 * s4 + 3], b);
673        }
674        x[t] = b;
675    }
676    device float* o = (isw ? W : U) + (ulong(h) * NC + c) * GC * S + j;
677#pragma clang loop unroll(full)
678    for (int t = 0; t < GC; ++t) o[t * S] = x[t];
679    if (tid < GC) lgo[(h * NC + c) * GC + tid] = lg[tid];
680}
681
682
683// grid (h_v * 4), 128 threads = 4 simdgroups.  A simdgroup owns rows 32 sg .. 32 sg + 31 of the 128 x 32 state block as 4 x 4
684// simdgroup matrices that stay in registers for the whole call; each chunk the block is stored to threadgroup memory (Sm) once,
685// where the two products that need all 128 rows (W S and Q S, sharing the S tiles) read it.
686kernel void gdn_cstate2(device float* state [[buffer(0)]], device const float* qn [[buffer(1)]],
687                        device const float* kn [[buffer(2)]], device const float* U [[buffer(3)]],
688                        device const float* W [[buffer(4)]], device const float* lgo [[buffer(5)]],
689                        device const float* Mo [[buffer(6)]], device float* o [[buffer(7)]], constant GdnPArgs& a [[buffer(8)]],
690                        uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
691                        ushort sg [[simdgroup_index_in_threadgroup]]) {
692    constexpr int S = 128;
693    threadgroup float Sm[S][32];
694    threadgroup float Dl[GC][32];
695    threadgroup float X[GC][32];
696    threadgroup float Y[GC][32];
697    const int h = int(tg.x) / 4, hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok);
698    const int NC = (T + GC - 1) / GC, j0 = (int(tg.x) % 4) * 32;
699    const float scale = 1.0f / sqrt(float(S));
700    simdgroup_float8x8 st[4][4];
701    for (int rt = 0; rt < 4; ++rt)
702        for (int jt = 0; jt < 4; ++jt)
703            simdgroup_load(st[rt][jt], state + ((32 * sg + 8 * rt) * hv + h) * S + j0 + 8 * jt, hv * S);
704    for (int c = 0; c < NC; ++c) {
705        const int t0 = c * GC, nb = min(GC, T - t0);
706        device const float* Uc = U + (ulong(h) * NC + c) * GC * S;
707        device const float* Wc = W + (ulong(h) * NC + c) * GC * S;
708        device const float* Mc = Mo + (ulong(h) * NC + c) * GC * GC;
709        device const float* lg = lgo + (h * NC + c) * GC;
710        for (int rt = 0; rt < 4; ++rt)
711            for (int jt = 0; jt < 4; ++jt) simdgroup_store(st[rt][jt], &Sm[32 * sg + 8 * rt][8 * jt], 32);
712        threadgroup_barrier(mem_flags::mem_threadgroup);
713        // P1 = W S0 (into X) and P2 = Q S0 (into Y), the S tiles read once for both
714        simdgroup_float8x8 acc1[4], acc2[4];
715        for (int jt = 0; jt < 4; ++jt) {
716            acc1[jt] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
717            acc2[jt] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
718        }
719        device const float* qrow = qn + ((t0 + 8 * sg) * hkn + hk) * S;
720        if (gdn_probe != 1)
721#pragma clang loop unroll(full)
722        for (int kb = 0; kb < 16; ++kb) {
723            simdgroup_float8x8 aw, aq, bs;
724            simdgroup_load(aw, Wc + (8 * sg) * S + 8 * kb, S);
725            simdgroup_load(aq, qrow + 8 * kb, hkn * S);
726            for (int jt = 0; jt < 4; ++jt) {
727                simdgroup_load(bs, &Sm[8 * kb][8 * jt], 32);
728                simdgroup_multiply_accumulate(acc1[jt], aw, bs, acc1[jt]);
729                simdgroup_multiply_accumulate(acc2[jt], aq, bs, acc2[jt]);
730            }
731        }
732        for (int jt = 0; jt < 4; ++jt) {
733            simdgroup_store(acc1[jt], &X[8 * sg][8 * jt], 32);
734            simdgroup_store(acc2[jt], &Y[8 * sg][8 * jt], 32);
735        }
736        threadgroup_barrier(mem_flags::mem_threadgroup);
737        for (int idx = tid; idx < GC * 32; idx += 128) {
738            const int t = idx >> 5, j = idx & 31;
739            Dl[t][j] = t < nb ? Uc[t * S + j0 + j] - X[t][j] : 0.0f;
740        }
741        threadgroup_barrier(mem_flags::mem_threadgroup);
742        // intra = M delta (into X)
743        for (int jt = 0; jt < 4; ++jt) acc1[jt] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
744        if (gdn_probe != 2)
745#pragma clang loop unroll(full)
746        for (int kb = 0; kb < 4; ++kb) {
747            simdgroup_float8x8 am, bd;
748            simdgroup_load(am, Mc + (8 * sg) * GC + 8 * kb, GC);
749            for (int jt = 0; jt < 4; ++jt) {
750                simdgroup_load(bd, &Dl[8 * kb][8 * jt], 32);
751                simdgroup_multiply_accumulate(acc1[jt], am, bd, acc1[jt]);
752            }
753        }
754        for (int jt = 0; jt < 4; ++jt) simdgroup_store(acc1[jt], &X[8 * sg][8 * jt], 32);
755        threadgroup_barrier(mem_flags::mem_threadgroup);
756        const float lgl = lg[nb - 1], gl = exp(lgl);
757        if (gdn_probe != 4)
758        for (int idx = tid; idx < GC * 32; idx += 128) {
759            const int t = idx >> 5, j = idx & 31;
760            if (t < nb) {
761                o[((t0 + t) * hv + h) * S + j0 + j] = fma(exp(lg[t]), Y[t][j], X[t][j]) * scale;
762                Dl[t][j] *= exp(lgl - lg[t]);
763            } else {
764                Dl[t][j] = 0.0f;
765            }
766        }
767        threadgroup_barrier(mem_flags::mem_threadgroup);
768        // S = G_L S + K^T delta'
769        for (int rt = 0; rt < 4; ++rt)
770            for (int jt = 0; jt < 4; ++jt) {
771                st[rt][jt].thread_elements()[0] *= gl;
772                st[rt][jt].thread_elements()[1] *= gl;
773            }
774        if (gdn_probe != 3)
775#pragma clang loop unroll(full)
776        for (int kb = 0; kb < 4; ++kb) {
777            simdgroup_float8x8 bd[4];
778            for (int jt = 0; jt < 4; ++jt) simdgroup_load(bd[jt], &Dl[8 * kb][8 * jt], 32);
779            for (int rt = 0; rt < 4; ++rt) {
780                simdgroup_float8x8 ak;
781                simdgroup_load(ak, kn + ((t0 + 8 * kb) * hkn + hk) * S + 32 * sg + 8 * rt, hkn * S, ulong2(0, 0), true);
782                for (int jt = 0; jt < 4; ++jt) simdgroup_multiply_accumulate(st[rt][jt], ak, bd[jt], st[rt][jt]);
783            }
784        }
785    }
786    for (int rt = 0; rt < 4; ++rt)
787        for (int jt = 0; jt < 4; ++jt)
788            simdgroup_store(st[rt][jt], state + ((32 * sg + 8 * rt) * hv + h) * S + j0 + 8 * jt, hv * S);
789}