okami.mom/strata

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

Niko1221Merge f-mac-rel (Mac Metal support) into f-144-rel6a74320ca

main
17.0 KiB341 linesraw
1// metal/kernels/gr2.metal - the hyper-connection read in TWO dispatches (after quant/units/gr.metal), for BF16 HC
2// weights (the exact path) or a Q8_0 copy of them (the STRATA_HC_Q8 option):
3//
4//   gr_down3  grid (row blocks, hc streams).  The RMSNorm is per stream, so a threadgroup owns one stream c: it forms
5//             R'_c = R_c + bo * 2 sigmoid(inj_prev_c / hc) (10 KB a token), its sum of squares and rs_c itself,
6//             stages xn_c = (R'_c * w_norm_c) * rs_c in threadgroup memory once, and every simdgroup dots its rows'
7//             stream-c quarter with it: D[t][row][c].  Row block 0 also writes R'_c to R_out (ping-pong, never in
8//             place) and rs_c.  Rows 0..hc_lr-1 are w_down, hc_lr.. the inject rows.
9//   gr_up3    lo[k] = silu(sum_c D[t][k][c] / hc) formed in threadgroup memory, then as gr_up with xn = R' * w_norm
10//             * rs on the fly, writing the prepared activations.
11//   inj_prev of the NEXT read = sum_c D[t][hc_lr + c'][c] of this one (gr_down3 sums it, in c order).
12//
13// Per element the arithmetic is gr_norm's (fma(bo, g, R), then (R' * w) * rs); the K order differs (per stream, then
14// the 4 streams in order).
15
16#ifndef P_TOKENT
17#define P_TOKENT 532   // moe.metal's plan layout
18#endif
19
20struct GrArgs3 {
21    uint n_embd;
22    uint hc;
23    uint hc_lr;
24    uint n_tok;      // the prepared planes' row count (the plane stride)
25    uint apply;
26    float eps;
27    uint rb_down;    // bytes per row of w_down / w_inject
28    uint rb_up;      // bytes per row of w_up
29    uint comb;       // 1: bo is not given; it is the MoE combine (moe_combine_sh's arithmetic) of buffers 10..13
30    uint topk;
31};
32
33// bo[t][d], given or the MoE combine: sum_k ye[entry(t, k)][d] (k in order) + sigmoid(sg[t]) * ysh[t][d]
34static inline float bo_at(device const float* bo, device const int* plan, device const float* ye,
35                          device const float* ysh, device const float* sg, constant GrArgs3& a, int t, int d) {
36    const int n = int(a.n_embd);
37    if (!a.comb) return bo[t * n + d];
38    float s = 0.0f;
39    for (uint j = 0; j < a.topk; ++j) s += ye[plan[P_TOKENT + t * int(a.topk) + j] * n + d];
40    const float gs = 1.0f / (1.0f + exp(-sg[t]));
41    return fma(gs, ysh[t * n + d], s);
42}
43
44template <int F, int TT, int RPS>
45kernel void gr_down3(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]],
46                     device const float* Rin [[buffer(2)]], device float* Rout [[buffer(3)]],
47                     device const float* bo [[buffer(4)]], device const float* Dprev [[buffer(5)]],
48                     device const float* wn [[buffer(6)]], device float* D [[buffer(7)]],
49                     device float* rs_out [[buffer(8)]], constant GrArgs3& a [[buffer(9)]],
50                     device const int* plan [[buffer(10)]], device const float* ye [[buffer(11)]],
51                     device const float* ysh [[buffer(12)]], device const float* sgv [[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 UNIT = fmt<F>::UNIT;
55    threadgroup float xs_tg[TT][2560];
56    threadgroup float part[8][TT];
57    threadgroup float g_tg[TT], rs_tg[TT];
58    threadgroup uint tab[fmt<F>::TAB];
59    load_tab<F>(tab, tid, 256);
60    const int n = int(a.n_embd), hc = int(a.hc), NIN = hc * n, c = int(tg.y);
61    const int nrows = int(a.hc_lr) + hc;
62    for (int t0 = 0; t0 < GR_NTOK; t0 += TT) {
63        const int T = min(TT, GR_NTOK - t0);
64        if (tid < T) {
65            float g = 0.0f;
66            if (a.apply) {
67                device const float* dp = Dprev + ((t0 + tid) * nrows + int(a.hc_lr) + c) * hc;
68                const float ip = ((dp[0] + dp[1]) + dp[2]) + dp[3];
69                g = 2.0f / (1.0f + exp(-ip / float(hc)));
70            }
71            g_tg[tid] = g;
72        }
73        threadgroup_barrier(mem_flags::mem_threadgroup);
74        for (int t = 0; t < T; ++t) {
75            device const float* rt = Rin + (t0 + t) * NIN + c * n;
76            float ss = 0.0f;
77            for (int d = tid; d < n; d += 256) {
78                float v = rt[d];
79                if (a.apply) v = fma(bo_at(bo, plan, ye, ysh, sgv, a, t0 + t, d), g_tg[t], v);
80                xs_tg[t][d] = v;
81                ss = fma(v, v, ss);
82                if (tg.x == 0) Rout[(t0 + t) * NIN + c * n + d] = v;
83            }
84            ss = simd_sum(ss);
85            if (lane == 0) part[sg][t] = ss;
86        }
87        threadgroup_barrier(mem_flags::mem_threadgroup);
88        if (tid < T) {
89            float tot = 0.0f;
90            for (int k = 0; k < 8; ++k) tot += part[k][tid];
91            const float rsv = rsqrt(tot / float(n) + a.eps);
92            rs_tg[tid] = rsv;
93            if (tg.x == 0) rs_out[(t0 + tid) * hc + c] = rsv;
94        }
95        threadgroup_barrier(mem_flags::mem_threadgroup);
96        for (int t = 0; t < T; ++t)
97            for (int d = tid; d < n; d += 256) xs_tg[t][d] = xs_tg[t][d] * wn[c * n + d] * rs_tg[t];
98        threadgroup_barrier(mem_flags::mem_threadgroup);
99        // the rows: simdgroup sg holds RPS rows; lanes split the stream's units
100        int rows[RPS];
101        device const uchar* wr[RPS];
102        for (int k = 0; k < RPS; ++k) {
103            rows[k] = (int(tg.x) * 8 + sg) * RPS + k;
104            const int rr = min(rows[k], nrows - 1);
105            wr[k] = rr < int(a.hc_lr) ? w_down + ulong(rr) * a.rb_down : w_inject + ulong(rr - int(a.hc_lr)) * a.rb_down;
106        }
107        float acc[RPS][TT];
108        for (int k = 0; k < RPS; ++k)
109            for (int t = 0; t < TT; ++t) acc[k][t] = 0.0f;
110        const int U = n / UNIT, u0 = c * U;
111        for (int u = lane; u < U; u += 32) {
112            float q[RPS][UNIT];
113            float4 sc[RPS];
114            for (int k = 0; k < RPS; ++k) Dec<F>::run(wr[k], u0 + u, q[k], sc[k], tab);
115            for (int t = 0; t < T; ++t) {
116                float xs[UNIT], xsum[2] = {0.0f, 0.0f};
117                for (int e = 0; e < UNIT; ++e) xs[e] = xs_tg[t][u * UNIT + e];
118                for (int k = 0; k < RPS; ++k) acc[k][t] += unit_combine<UNIT>(q[k], sc[k], xs, xsum);
119            }
120        }
121        for (int k = 0; k < RPS; ++k)
122            for (int t = 0; t < T; ++t) {
123                const float v = simd_sum(acc[k][t]);
124                if (lane == 0 && rows[k] < nrows) D[((t0 + t) * nrows + rows[k]) * hc + c] = v;
125            }
126        threadgroup_barrier(mem_flags::mem_threadgroup);
127    }
128}
129
130// grid (n_embd / 16), 256 threads.
131template <int F>
132kernel void gr_up3(device const uchar* w_up [[buffer(0)]], device const float* D [[buffer(1)]],
133                   device const float* Rn [[buffer(2)]], device float* xp [[buffer(3)]],
134                   constant GrArgs3& a [[buffer(4)]], device const float* wn [[buffer(5)]],
135                   device const float* rs [[buffer(6)]],
136                   uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
137                   ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
138    constexpr int UNIT = fmt<F>::UNIT;
139    threadgroup float lo_tg[8][320];
140    threadgroup float gate[8][4][16];
141    threadgroup float msum[8][16];
142    threadgroup uint tab[fmt<F>::TAB];
143    load_tab<F>(tab, tid, 256);
144    const int n = int(a.n_embd), hc = int(a.hc), lr = int(a.hc_lr), nrows = lr + hc;
145    for (int e = tid; e < GR_NTOK * lr; e += 256) {
146        const int t = e / lr, k = e - t * lr;
147        device const float* dp = D + (t * nrows + k) * hc;
148        const float z = (((dp[0] + dp[1]) + dp[2]) + dp[3]) / float(hc);
149        lo_tg[t][k] = z / (1.0f + exp(-z));
150    }
151    threadgroup_barrier(mem_flags::mem_threadgroup);
152    const int c = sg >> 1, dl = 8 * (sg & 1) + lane / 4, li = lane & 3;
153    const int d = int(tg.x) * 16 + dl;
154    device const uchar* w = w_up + ulong(c * n + d) * a.rb_up;
155    const int U = lr / UNIT;
156    float acc[8];
157    for (int t = 0; t < 8; ++t) acc[t] = 0.0f;
158    for (int u = li; u < U; u += 4) {
159        float q[UNIT];
160        float4 sc;
161        Dec<F>::run(w, u, q, sc, tab);
162        for (int t = 0; t < GR_NTOK; ++t) {
163            float xs[UNIT], xsum[2] = {0.0f, 0.0f};
164            for (int e = 0; e < UNIT; ++e) xs[e] = lo_tg[t][UNIT * u + e];
165            acc[t] += unit_combine<UNIT>(q, sc, xs, xsum);
166        }
167    }
168    for (int t = 0; t < GR_NTOK; ++t) {
169        const float v = lane_sum<4>(acc[t]);
170        if (li == 0) gate[t][c][dl] = 1.0f / (1.0f + exp(-v));
171    }
172    threadgroup_barrier(mem_flags::mem_threadgroup);
173    const int t = tid / 16, j = tid & 15;
174    if (t < GR_NTOK) {
175        const int dd = int(tg.x) * 16 + j;
176        float m = 0.0f;
177        for (int cc = 0; cc < hc; ++cc) {
178            const float xn = Rn[(t * hc + cc) * n + dd] * wn[cc * n + dd] * rs[t * hc + cc];
179            m = fma(xn, gate[t][cc][j], m);
180        }
181        m = m / float(hc);
182        const uint plane = a.n_tok * uint(n);
183        device float* raw = xp + t * n + dd;
184        const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f,
185                              0.00006103515625f};
186        const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f};
187        raw[0] = m;
188        raw[plane] = m * q2s[j & 7];
189        raw[2 * plane] = m * p4s[j & 3];
190        raw[3 * plane] = (j & 1) ? m * 0.00390625f : m;
191        msum[t][j] = m;
192    }
193    threadgroup_barrier(mem_flags::mem_threadgroup);
194    if (t < GR_NTOK && j == 0) {
195        float s0 = 0.0f, s1 = 0.0f;
196        for (int k = 0; k < 16; k += 2) { s0 += msum[t][k]; s1 += msum[t][k + 1]; }
197        xp[4 * a.n_tok * uint(n) + t * (n / 16) + tg.x] = s0 + s1;
198    }
199}
200
201#define GD3(F, T, R) template [[host_name("gr_down3_" #F "_" #T "_" #R)]] kernel decltype(gr_down3<F, T, R>) gr_down3<F, T, R>;
202GD3(30, 1, 1) GD3(30, 2, 1) GD3(30, 3, 1) GD3(30, 1, 2) GD3(30, 2, 2) GD3(30, 3, 2)
203GD3(8, 1, 1) GD3(8, 2, 1) GD3(8, 3, 1) GD3(8, 1, 2) GD3(8, 2, 2) GD3(8, 3, 2)
204template [[host_name("gr_up3_30")]] kernel decltype(gr_up3<T_BF16>) gr_up3<T_BF16>;
205template [[host_name("gr_up3_8")]] kernel decltype(gr_up3<T_Q8_0>) gr_up3<T_Q8_0>;
206
207// BF16 only: as gr_down3, but each lane loads its rows' weights (5 units of 16 per row and lane: 2560 = 160 units)
208// into registers before the norm phase, so the weight stream is in flight while the threadgroup forms xn.
209template <int TT, int RPS>
210kernel void gr_down3b(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]],
211                      device const float* Rin [[buffer(2)]], device float* Rout [[buffer(3)]],
212                      device const float* bo [[buffer(4)]], device const float* Dprev [[buffer(5)]],
213                      device const float* wn [[buffer(6)]], device float* D [[buffer(7)]],
214                      device float* rs_out [[buffer(8)]], constant GrArgs3& a [[buffer(9)]],
215                      device const int* plan [[buffer(10)]], device const float* ye [[buffer(11)]],
216                      device const float* ysh [[buffer(12)]], device const float* sgv [[buffer(13)]],
217                      uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
218                      ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
219    threadgroup float xs_tg[TT][2560];
220    threadgroup float part[8][TT];
221    threadgroup float g_tg[TT], rs_tg[TT];
222    const int n = int(a.n_embd), hc = int(a.hc), NIN = hc * n, c = int(tg.y);
223    const int nrows = int(a.hc_lr) + hc;
224    int rows[RPS];
225    uint4 wr[RPS][5][2];
226    for (int k = 0; k < RPS; ++k) {
227        rows[k] = (int(tg.x) * 8 + sg) * RPS + k;
228        const int rr = min(rows[k], nrows - 1);
229        device const uchar* w = rr < int(a.hc_lr) ? w_down + ulong(rr) * a.rb_down : w_inject + ulong(rr - int(a.hc_lr)) * a.rb_down;
230        device const uint4* p = (device const uint4*)(w + 2 * (c * n));
231        for (int i = 0; i < 5; ++i) {
232            wr[k][i][0] = p[2 * (lane + 32 * i)];
233            wr[k][i][1] = p[2 * (lane + 32 * i) + 1];
234        }
235    }
236    for (int t0 = 0; t0 < GR_NTOK; t0 += TT) {
237        const int T = min(TT, GR_NTOK - t0);
238        if (tid < T) {
239            float g = 0.0f;
240            if (a.apply) {
241                device const float* dp = Dprev + ((t0 + tid) * nrows + int(a.hc_lr) + c) * hc;
242                const float ip = ((dp[0] + dp[1]) + dp[2]) + dp[3];
243                g = 2.0f / (1.0f + exp(-ip / float(hc)));
244            }
245            g_tg[tid] = g;
246        }
247        threadgroup_barrier(mem_flags::mem_threadgroup);
248        for (int t = 0; t < T; ++t) {
249            device const float* rt = Rin + (t0 + t) * NIN + c * n;
250            float ss = 0.0f;
251            for (int d = tid; d < n; d += 256) {
252                float v = rt[d];
253                if (a.apply) v = fma(bo_at(bo, plan, ye, ysh, sgv, a, t0 + t, d), g_tg[t], v);
254                xs_tg[t][d] = v;
255                ss = fma(v, v, ss);
256                if (tg.x == 0) Rout[(t0 + t) * NIN + c * n + d] = v;
257            }
258            ss = simd_sum(ss);
259            if (lane == 0) part[sg][t] = ss;
260        }
261        threadgroup_barrier(mem_flags::mem_threadgroup);
262        if (tid < T) {
263            float tot = 0.0f;
264            for (int k = 0; k < 8; ++k) tot += part[k][tid];
265            const float rsv = rsqrt(tot / float(n) + a.eps);
266            rs_tg[tid] = rsv;
267            if (tg.x == 0) rs_out[(t0 + tid) * hc + c] = rsv;
268        }
269        threadgroup_barrier(mem_flags::mem_threadgroup);
270        for (int t = 0; t < T; ++t)
271            for (int d = tid; d < n; d += 256) xs_tg[t][d] = xs_tg[t][d] * wn[c * n + d] * rs_tg[t];
272        threadgroup_barrier(mem_flags::mem_threadgroup);
273        float acc[RPS][TT];
274        for (int k = 0; k < RPS; ++k)
275            for (int t = 0; t < TT; ++t) acc[k][t] = 0.0f;
276        for (int i = 0; i < 5; ++i) {
277            const int u = lane + 32 * i;
278            for (int k = 0; k < RPS; ++k) {
279                const uint v[8] = {wr[k][i][0].x, wr[k][i][0].y, wr[k][i][0].z, wr[k][i][0].w,
280                                   wr[k][i][1].x, wr[k][i][1].y, wr[k][i][1].z, wr[k][i][1].w};
281                float q[16];
282                for (int e = 0; e < 8; ++e) {
283                    q[2 * e] = as_type<float>(v[e] << 16);
284                    q[2 * e + 1] = as_type<float>(v[e] & 0xFFFF0000u);
285                }
286                const float4 sc = float4(1.0f, 1.0f, 0.0f, 0.0f);
287                for (int t = 0; t < T; ++t) {
288                    float xs[16], xsum[2] = {0.0f, 0.0f};
289                    for (int e = 0; e < 16; ++e) xs[e] = xs_tg[t][u * 16 + e];
290                    acc[k][t] += unit_combine<16>(q, sc, xs, xsum);
291                }
292            }
293        }
294        for (int k = 0; k < RPS; ++k)
295            for (int t = 0; t < T; ++t) {
296                const float v = simd_sum(acc[k][t]);
297                if (lane == 0 && rows[k] < nrows) D[((t0 + t) * nrows + rows[k]) * hc + c] = v;
298            }
299        threadgroup_barrier(mem_flags::mem_threadgroup);
300    }
301}
302#define GD3B(T, R) template [[host_name("gr_down3b_" #T "_" #R)]] kernel decltype(gr_down3b<T, R>) gr_down3b<T, R>;
303GD3B(1, 1) GD3B(2, 1) GD3B(3, 1) GD3B(1, 2) GD3B(2, 2) GD3B(3, 2)
304
305// gr_norm_comb: gr_norm (gr.metal) with the sublayer output bo formed on the fly as the MoE combine - bo[t][d] =
306// sum_k ye[entry(t, k)][d] (k in order) + sigmoid(sg[t]) * ysh[t][d], moe_combine_sh's arithmetic - so the combine's
307// dispatch goes away; R', xn bitwise gr_norm's after moe_combine_sh.  One threadgroup per (stream c, token t).
308kernel void gr_norm_comb(device float* R [[buffer(0)]], device const float* ye [[buffer(1)]],
309                         device const float* inj [[buffer(2)]], device const float* w_norm [[buffer(3)]],
310                         device float* xn [[buffer(4)]], constant GrArgs& a [[buffer(5)]],
311                         device const int* plan [[buffer(6)]], device const float* ysh [[buffer(7)]],
312                         device const float* sgv [[buffer(8)]], constant uint& topk [[buffer(9)]],
313                         uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
314                         ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
315    threadgroup float part[8];
316    const uint c = tg.x, t = tg.y, n = a.n_embd;
317    device float* r = R + (t * a.hc + c) * n;
318    const float g = a.apply ? 2.0f / (1.0f + exp(-inj[t * a.hc + c] / float(a.hc))) : 0.0f;
319    const float gs = 1.0f / (1.0f + exp(-sgv[t]));
320    float ss = 0.0f;
321    for (uint d = tid; d < n; d += 256) {
322        float v = r[d];
323        if (a.apply) {
324            float s = 0.0f;
325            for (uint j = 0; j < topk; ++j) s += ye[plan[P_TOKENT + t * topk + j] * int(n) + d];
326            const float bo = fma(gs, ysh[t * n + d], s);
327            v = fma(bo, g, v);
328            r[d] = v;
329        }
330        ss = fma(v, v, ss);
331    }
332    ss = simd_sum(ss);
333    if (lane == 0) part[sg] = ss;
334    threadgroup_barrier(mem_flags::mem_threadgroup);
335    float tot = 0.0f;
336    for (int i = 0; i < 8; ++i) tot += part[i];
337    const float rs = rsqrt(tot / float(n) + a.eps);
338    device float* o = xn + (t * a.hc + c) * n;
339    device const float* w = w_norm + c * n;
340    for (uint d = tid; d < n; d += 256) o[d] = r[d] * w[d] * rs;
341}