okami.mom/strata

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

Niko1221Trial2 merge f-0291-mac-q (8e7ed6818)01f804ea1

main
11.2 KiB201 linesraw
1// metal/kernels/gdn.metal - one GDN (gated delta-net) layer's recurrence for a window of tokens, fused end to end:
2//
3//   conv (4 taps, history [channels][3] oldest first) -> SiLU, on q (16 heads), k (16), v (48 heads) of 128
4//   q, k: L2 norm as native_gdn_l2_norm (rsqrt(sum/128 + eps/128), then x 1/sqrt(128), two roundings)
5//   gate = exp(softplus(alpha + dt) * a)  (softplus = v > 20 ? v : log1p(exp(v))),  beta = sigmoid(beta)
6//   kv_j = sum_i S[i][j] k[i];  delta_j = (v_j - gate * kv_j) * beta;  S = gate * S + k[i] delta_j
7//   o_j = (sum_i S[i][j] q[i]) / sqrt(128);  y_j = o_j * rsqrt(mean(o^2) + eps) * gamma_j * sigmoid(z_j)
8//
9// State layout as Strata's: S[(i * h_v + h) * 128 + j].  Value head h reads q/k head h % h_k.
10// One threadgroup per value head, 512 threads = 16 simdgroups: simdgroup s holds columns j = 32 (s % 4) + lane and
11// rows i = 32 (s / 4) .. + 32 of the head's 128 x 128 state in registers.  GDN_NTOK tokens run in order; with
12// `commit` the state and the conv history are written back after the last one (a verify window runs without commit,
13// the fold of m accepted tokens is the same kernel with GDN_NTOK = m and commit).  The conv history is read from
14// `hist` and the committed one written to `hist_out` (ping-pong: the q/k channels are shared by three threadgroups).
15
16#ifndef STRATA_XH16_DECL
17#define STRATA_XH16_DECL
18// STRATA_METAL_F16 (function constant 25): the window's x also as half planes, after the float planes and S16:
19// [3][plane] halves - raw (IQ4_XS), x * 4^-(i % 4) (Q2_0), x * 2^-8 at odd i (the K-quants); idx = t * n + d, jj = d % 16
20constant bool XH16 [[function_constant(25)]];
21constant bool xh16 = is_function_constant_defined(XH16) && XH16;
22static inline void put_x16(device float* xp, uint plane, uint idx, uint jj, float v) {
23    device half* xh = (device half*)(xp + 4 * plane + plane / 16);
24    const float q2b[4] = {1.0f, 0.25f, 0.0625f, 0.015625f};
25    xh[idx] = half(v);
26    xh[plane + idx] = half(v * q2b[jj & 3]);
27    xh[2 * plane + idx] = half((jj & 1) ? v * 0.00390625f : v);
28}
29#endif
30
31constant int GDN_NTOK [[function_constant(2)]];
32// GDN_ROWS (function constant 31, with GDN_NTOK = 1): the grid is (h_v, rows) and row y is a DIFFERENT sequence (a batch slot) with its own
33// state and conv history; rinfo as in qsa.metal (header [5] state stride, [6] history stride per slot and parity; row y at [8 + 4 y] =
34// {slot, cell, history parity, 0}).  hist / hist_out are then one buffer (hist), the parities side by side per slot.  The inputs and the
35// output are row y of the window's arrays.  Off: exactly the plain kernel.
36constant bool GDN_ROWS_C [[function_constant(31)]];
37constant bool gdn_rows = is_function_constant_defined(GDN_ROWS_C) && GDN_ROWS_C;
38
39struct GdnArgs {
40    uint h_k;        // 16
41    uint h_v;        // 48
42    uint channels;   // 10240 = (2 h_k + h_v) * 128
43    uint commit;     // 0: verify (no write); 1: commit after the last token; 0x100 | k (1 <= k <= GDN_NTOK): commit
44                     // the state and the conv history after the first k tokens, in place, while every token's y is
45                     // still computed (a window whose first k rows are kept) - bitwise the commit of a k-token step
46    float eps;       // 1e-6
47    uint plane;      // 0: y only; else y is the raw plane of prepared activations (xprep layout, n = h_v * 128,
48                     // `plane` floats between planes) and the other planes and the per-16 sums are written too
49};
50
51// The kernel is launched with IB * 128 threads (512 for gdn_step, 1024 for gdn_step8).  Without the attribute the compiler
52// is free to use as many registers as the 128-row state needs and a pipeline can end up with
53// maxTotalThreadsPerThreadgroup below the launch size: an M2 Max gave 448 for the GDN_NTOK >= 2 specializations, and
54// Metal then skips the dispatch without an error (#2323).  The attribute makes the compiler fit the launch size.
55template <int IB>
56[[max_total_threads_per_threadgroup(IB * 128)]]
57kernel void gdn_step_t(device float* state [[buffer(0)]], device float* hist [[buffer(1)]],
58                     device const float* qkv [[buffer(2)]], device const float* alpha [[buffer(3)]],
59                     device const float* beta [[buffer(4)]], device const float* z [[buffer(5)]],
60                     device const float* conv_w [[buffer(6)]], device const float* dt [[buffer(7)]],
61                     device const float* ssm_a [[buffer(8)]], device const float* gamma [[buffer(9)]],
62                     device float* y [[buffer(10)]], constant GdnArgs& a [[buffer(11)]],
63                     device float* hist_out [[buffer(12)]],
64                     device const uint* rinfo [[buffer(13), function_constant(gdn_rows)]],
65                     uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
66                     ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
67    constexpr int S = 128;
68    threadgroup float qs[S], ks[S], vs[S];
69    constexpr int RPT = S / IB;   // state rows per thread
70    threadgroup float red[IB][S];
71    threadgroup float part[32];
72    threadgroup float gb[2];
73    threadgroup float ys[S];
74    const int h = int(tg.x), hk = h % int(a.h_k), hv = int(a.h_v);
75    const int cb = sg & 3, ib = sg >> 2;
76    const int j = 32 * cb + lane, i0 = RPT * ib;
77    const float scale = 1.0f / sqrt(float(S));
78    const int row0 = gdn_rows ? int(tg.y) : 0;
79    if (gdn_rows) {
80        const ulong sl = rinfo[8 + 4 * row0], par = rinfo[8 + 4 * row0 + 2];
81        state += sl * rinfo[5];
82        hist_out = hist + (sl * 2 + (1 - par)) * rinfo[6];
83        hist += (sl * 2 + par) * rinfo[6];
84    }
85
86    // the channel this thread convolves: 0..127 q of head hk, 128..255 k of head hk, 256..383 v of head h
87    int ch = -1;
88    if (tid < 128) ch = hk * S + tid;
89    else if (tid < 256) ch = int(a.h_k) * S + hk * S + (tid - 128);
90    else if (tid < 384) ch = 2 * int(a.h_k) * S + h * S + (tid - 256);
91    float hst[3] = {0.0f, 0.0f, 0.0f}, cw[4] = {0.0f, 0.0f, 0.0f, 0.0f};
92    if (ch >= 0) {
93        for (int k = 0; k < 3; ++k) hst[k] = hist[ch * 3 + k];
94        for (int k = 0; k < 4; ++k) cw[k] = conv_w[ch * 4 + k];
95    }
96    float st[RPT];
97    for (int r = 0; r < RPT; ++r) st[r] = state[((i0 + r) * hv + h) * S + j];
98
99    const int commit_at = a.commit == 1u ? GDN_NTOK : (a.commit >> 8) ? int(a.commit & 0xFFu) : 0;
100    for (int t = 0; t < GDN_NTOK; ++t) {
101        // conv + SiLU
102        const int tr = t + row0;
103        float cv = 0.0f;
104        if (ch >= 0) {
105            const float in = qkv[tr * int(a.channels) + ch];
106            const float vals[4] = {hst[0], hst[1], hst[2], in};
107            float s = 0.0f;
108            for (int k = 0; k < 4; ++k) s = fma(vals[k], cw[k], s);
109            s = s + 0.0f;
110            cv = s / (1.0f + exp(-s));
111            hst[0] = hst[1];
112            hst[1] = hst[2];
113            hst[2] = in;
114        }
115        // L2 norms of q (threads 0..127 = simdgroups 0..3) and k (128..255 = 4..7)
116        const float ssq = simd_sum(cv * cv);
117        if (lane == 0) part[sg] = ssq;
118        if (tid == 0) {
119            const float v = alpha[tr * hv + h] + dt[h];
120            // log1p(e^v) (Kahan: log(u) * e / (u - 1), u = 1 + e; exact where 1 + e rounds to 1)
121            const float e = exp(v), u = 1.0f + e;
122            const float sp = v > 20.0f ? v : (u == 1.0f ? e : log(u) * e / (u - 1.0f));
123            gb[0] = exp(sp * ssm_a[h]);
124            gb[1] = 1.0f / (1.0f + exp(-beta[tr * hv + h]));
125        }
126        threadgroup_barrier(mem_flags::mem_threadgroup);
127        if (tid < 256) {
128            const int base = tid < 128 ? 0 : 4;
129            const float tot = (part[base] + part[base + 1]) + (part[base + 2] + part[base + 3]);
130            const float rs = rsqrt(tot / float(S) + a.eps / float(S));
131            const float nv = (rs * cv) * scale;
132            if (tid < 128) qs[tid] = nv;
133            else ks[tid - 128] = nv;
134        } else if (tid < 384) {
135            vs[tid - 256] = cv;
136        }
137        threadgroup_barrier(mem_flags::mem_threadgroup);
138        const float g = gb[0], be = gb[1];
139        // kv_j
140        float kv = 0.0f;
141        for (int r = 0; r < RPT; ++r) kv = fma(st[r], ks[i0 + r], kv);
142        red[ib][j] = kv;
143        threadgroup_barrier(mem_flags::mem_threadgroup);
144        kv = 0.0f;
145        for (int k = 0; k < IB; ++k) kv += red[k][j];
146        const float delta = (vs[j] - g * kv) * be;
147        float o = 0.0f;
148        for (int r = 0; r < RPT; ++r) {
149            st[r] = fma(g, st[r], ks[i0 + r] * delta);
150            o = fma(st[r], qs[i0 + r], o);
151        }
152        threadgroup_barrier(mem_flags::mem_threadgroup);
153        red[ib][j] = o;
154        threadgroup_barrier(mem_flags::mem_threadgroup);
155        // the readout and the output norm: column j's o (every i-block thread of the column holds the same value)
156        o = 0.0f;
157        for (int k = 0; k < IB; ++k) o += red[k][j];
158        o = o * scale;
159        const float osq = ib == 0 ? simd_sum(o * o) : 0.0f;
160        if (ib == 0 && lane == 0) part[cb] = osq;
161        threadgroup_barrier(mem_flags::mem_threadgroup);
162        if (ib == 0) {
163            const float tot = (part[0] + part[1]) + (part[2] + part[3]);
164            const float rs = rsqrt(tot / float(S) + a.eps);
165            const float zz = z[tr * hv * S + h * S + j];
166            const float yv = ((rs * o) * gamma[j]) * (1.0f / (1.0f + exp(-zz)));
167            y[tr * hv * S + h * S + j] = yv;
168            if (a.plane) {
169                const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f,
170                                      0.00006103515625f};
171                const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f};
172                device float* raw = y + tr * hv * S + h * S + j;
173                const int jj = j & 15;
174                raw[a.plane] = yv * q2s[jj & 7];
175                raw[2 * a.plane] = yv * p4s[jj & 3];
176                raw[3 * a.plane] = (jj & 1) ? yv * 0.00390625f : yv;
177                if (xh16) put_x16(y, a.plane, t * hv * S + h * S + j, jj, yv);
178                ys[j] = yv;
179            }
180        }
181        if (t + 1 == commit_at) {
182            // the state and the conv history after token t (registers: st after this token's update, hst after its
183            // shift); the state is read only before the loop, so in place is safe.  q/k history: the threadgroups
184            // h < h_k own their q/k head (h == hk); v history: every head its own - to hist_out, NOT in place: a q/k
185            // channel is read by the three threadgroups h % h_k at their start, and a threadgroup may start after its
186            // owner has finished (seen on the 10-core M4); the caller swaps the two
187            for (int r = 0; r < RPT; ++r) state[((i0 + r) * hv + h) * S + j] = st[r];
188            if (ch >= 0 && (tid >= 256 || h < int(a.h_k)))
189                for (int k = 0; k < 3; ++k) hist_out[ch * 3 + k] = hst[k];
190        }
191        threadgroup_barrier(mem_flags::mem_threadgroup);
192        if (a.plane && ib == 0 && (j & 15) == 0) {
193            float s0 = 0.0f, s1 = 0.0f;
194            for (int k = 0; k < 16; k += 2) { s0 += ys[j + k]; s1 += ys[j + k + 1]; }
195            y[4 * a.plane + tr * (hv * S / 16) + (h * S + j) / 16] = s0 + s1;
196        }
197    }
198}
199
200template [[host_name("gdn_step")]] kernel decltype(gdn_step_t<4>) gdn_step_t<4>;
201template [[host_name("gdn_step8")]] kernel decltype(gdn_step_t<8>) gdn_step_t<8>;