okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
10.0 KiB208 linesraw
1// metal/kernels/hcf.metal - the hyper-connection read's gr_norm folded into the kernel that makes the sublayer output
2// (decode windows; after gemv.metal, gr.metal and glue.metal).
3//
4// gr_norm did, per stream c and token t:   R'[c][d] = fma(bo[d], g_c, R[c][d])   (written back in place)
5//                                          xn[c][d] = (R'[c][d] * w_norm[c][d]) * rsqrt(mean(R'[c]^2) + eps)
6// with g_c = 2 / (1 + exp(-inj[c] / hc)).  Here the producer of bo (the mixer's output GEMV, the MoE combine) does the
7// first line itself for the outputs it computes (4 streams a value), and the LAST threadgroup of its dispatch to finish
8// (the router_route pattern: a device counter, reset by the last) does the second line for every stream and token.  The
9// reduction is gr_norm's: thread (tid mod 256) sums its 10 elements d = tid + 256 j with fma in j order, simd_sum over
10// the 32 lanes, the 8 simdgroup partials added in order.  A producer threadgroup of 128 threads runs two of gr_norm's
11// virtual simdgroups a real one.  All values are bitwise gr_norm's after the producer's own dispatch; one dispatch (a
12// barrier, ~7 us in the decode chain) is gone per read.  n_embd 2560, hc 4.
13
14struct HcfArgs {
15    uint n_embd;
16    uint hc;
17    float eps;
18    uint pad;
19};
20
21static inline void hcf_apply(device float* R, device const float* inj, constant HcfArgs& h, int t, int row, float v) {
22#ifdef HCF_NO_APPLY
23    return;
24#endif
25    const int n = int(h.n_embd), hc = int(h.hc);
26    for (int c = 0; c < hc; ++c) {
27        const float g = 2.0f / (1.0f + exp(-inj[t * hc + c] / float(hc)));
28        device float* r = R + (t * hc + c) * n + row;
29        *r = fma(v, g, *r);
30    }
31}
32
33// R' (every stream, token) -> xn.  NTH threads (128 or 256); part: 4 * 8 floats of threadgroup memory
34template <int NTH>
35static inline void hcf_norm(device const float* R, device const float* w_norm, device float* xn, constant HcfArgs& h, int ntok,
36                            ushort tid, ushort sg, ushort lane, threadgroup float* part) {
37    constexpr int NV = 256 / NTH, NJ = 10;
38    const int n = int(h.n_embd);
39    for (int t = 0; t < ntok; ++t) {
40        float v[4][NV][NJ];
41        for (int c = 0; c < 4; ++c) {
42            device const float* r = R + (t * 4 + c) * n;
43            for (int m = 0; m < NV; ++m) {
44                const int vt = int(tid) + NTH * m;
45                float ss = 0.0f;
46                for (int j = 0; j < NJ; ++j) {
47                    const float x = r[vt + 256 * j];
48                    v[c][m][j] = x;
49                    ss = fma(x, x, ss);
50                }
51                ss = simd_sum(ss);
52                if (lane == 0) part[c * 8 + int(sg) + (NTH / 32) * m] = ss;
53            }
54        }
55        threadgroup_barrier(mem_flags::mem_threadgroup);
56        for (int c = 0; c < 4; ++c) {
57            float tot = 0.0f;
58            for (int i = 0; i < 8; ++i) tot += part[c * 8 + i];
59            const float rs = rsqrt(tot / float(n) + h.eps);
60            device float* o = xn + (t * 4 + c) * n;
61            device const float* w = w_norm + c * n;
62            for (int m = 0; m < NV; ++m) {
63                const int vt = int(tid) + NTH * m;
64                for (int j = 0; j < NJ; ++j) {
65                    const int d = vt + 256 * j;
66                    o[d] = v[c][m][j] * w[d] * rs;
67                }
68            }
69        }
70        threadgroup_barrier(mem_flags::mem_threadgroup);
71    }
72}
73
74// the last-arrival protocol (router_route's): true in the one threadgroup that runs the follow-on work
75static inline bool hcf_last(device atomic_uint* counter, uint ngx, ushort tid, threadgroup uint* last) {
76#if !defined(HCF_NOFENCE1) && !defined(HCF_T0FENCE1)
77    atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device);
78#endif
79    threadgroup_barrier(mem_flags::mem_device);
80#ifdef HCF_T0FENCE1
81    if (tid == 0) atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device);
82#endif
83    if (tid == 0) *last = atomic_fetch_add_explicit(counter, 1u, memory_order_relaxed) == ngx - 1 ? 1u : 0u;
84    threadgroup_barrier(mem_flags::mem_threadgroup);
85    const bool l = *last != 0;
86#ifndef HCF_NOFENCE2
87    if (l) atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device);
88#endif
89    return l;
90}
91
92// gemv (gemv.metal's arithmetic and tile, written as the original) with bo = y applied to R and the last threadgroup forming xn.
93// Buffers 0..4 as gemv; R, inj, w_norm, xn, counter, HcfArgs.
94template <int F, int LPR, int NR, int SG, int KS>
95kernel void gemv_hcf(device const uchar* W [[buffer(0)]], device const float* xp [[buffer(1)]],
96                     device const float* s16 [[buffer(2)]], device float* y [[buffer(3)]], constant GemvArgs& a [[buffer(4)]],
97                     device float* R [[buffer(5)]], device const float* inj [[buffer(6)]],
98                     device const float* w_norm [[buffer(7)]], device float* xn [[buffer(8)]],
99                     device atomic_uint* counter [[buffer(9)]], constant HcfArgs& h [[buffer(10)]],
100                     uint3 tg [[threadgroup_position_in_grid]], uint3 ngv [[threadgroups_per_grid]],
101                     ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]],
102                     ushort tid [[thread_index_in_threadgroup]]) {
103    constexpr int UNIT = fmt<F>::UNIT, RS = SG / KS, RG = 32 / LPR;
104    threadgroup uint tab[fmt<F>::TAB];
105    threadgroup float red[KS > 1 ? KS * RS * RG * NR * 8 : 1];
106    threadgroup float part[32];
107    threadgroup uint last;
108    load_tab<F>(tab, tid, SG * 32);
109    threadgroup_barrier(mem_flags::mem_threadgroup);
110    const int ks = sg / RS, rs = sg % RS;
111    const int li = lane % LPR;
112    const int lrow0 = (rs * RG + lane / LPR) * NR;
113    const int row0 = int(tg.x) * RS * RG * NR + lrow0;
114    const int U = int(a.n_in) / UNIT;
115    const int u0 = ks * U / KS, u1 = (ks + 1) * U / KS;
116    float acc[NR][8];
117    for (int r = 0; r < NR; ++r)
118        for (int t = 0; t < NTOK; ++t) acc[r][t] = 0.0f;
119    device const uchar* rp[NR];
120    for (int r = 0; r < NR; ++r) rp[r] = W + (ulong)min(row0 + r, int(a.n_out) - 1) * a.row_bytes;
121    const int s16n = int(a.n_in) / 16;
122    for (int u = u0 + li; u < u1; u += LPR) {
123        float q[NR][UNIT];
124        float4 sc[NR];
125        for (int r = 0; r < NR; ++r) Dec<F>::run(rp[r], u, q[r], sc[r], tab);
126        float xs[UNIT], xsum[2];
127        for (int t = 0; t < NTOK; ++t) {
128            X<F>::load(xp + t * int(a.x_stride), s16 + t * s16n, u, xs, xsum);
129            for (int r = 0; r < NR; ++r) acc[r][t] += unit_combine<UNIT>(q[r], sc[r], xs, xsum);
130        }
131    }
132    constexpr int RPT = RS * RG * NR;
133    for (int r = 0; r < NR; ++r)
134        for (int t = 0; t < NTOK; ++t) {
135            const float v = lane_sum<LPR>(acc[r][t]);
136            if (KS == 1) {
137                if (li == 0 && row0 + r < int(a.n_out)) {
138                    y[t * int(a.y_stride) + row0 + r] = v;
139                    hcf_apply(R, inj, h, t, row0 + r, v);
140                }
141            } else if (li == 0) {
142                red[(ks * RPT + lrow0 + r) * 8 + t] = v;
143            }
144        }
145    if (KS > 1) {
146        threadgroup_barrier(mem_flags::mem_threadgroup);
147        if (ks == 0 && li == 0)
148            for (int r = 0; r < NR; ++r)
149                for (int t = 0; t < NTOK; ++t) {
150                    float v = 0.0f;
151                    for (int k = 0; k < KS; ++k) v += red[(k * RPT + lrow0 + r) * 8 + t];
152                    if (row0 + r < int(a.n_out)) {
153                        y[t * int(a.y_stride) + row0 + r] = v;
154                        hcf_apply(R, inj, h, t, row0 + r, v);
155                    }
156                }
157    }
158#ifdef HCF_NO_LAST
159    return;
160#endif
161    if (!hcf_last(counter, ngv.x, tid, &last)) return;
162#ifndef HCF_NO_NORM
163    hcf_norm<SG * 32>(R, w_norm, xn, h, int(a.n_tok), tid, sg, lane, part);
164#endif
165    if (tid == 0) atomic_store_explicit(counter, 0u, memory_order_relaxed);
166}
167
168// moe_combine_sh (glue.metal) with the same follow-on.  One thread an output; threadgroups of 256.
169kernel void moe_combine_hcf(device const float* ye [[buffer(0)]], device const int* plan [[buffer(1)]],
170                            device const float* ysh [[buffer(2)]], device const float* sg [[buffer(3)]],
171                            device float* bo [[buffer(4)]], constant GlueArgs& a [[buffer(5)]],
172                            device float* R [[buffer(6)]], device const float* inj [[buffer(7)]],
173                            device const float* w_norm [[buffer(8)]], device float* xn [[buffer(9)]],
174                            device atomic_uint* counter [[buffer(10)]], constant HcfArgs& h [[buffer(11)]],
175                            uint3 tg [[threadgroup_position_in_grid]], uint3 ngv [[threadgroups_per_grid]],
176                            ushort sgi [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]],
177                            ushort tid [[thread_index_in_threadgroup]]) {
178    threadgroup float part[32];
179    threadgroup uint last;
180    const uint gid = tg.x * 256 + tid;
181    const uint t = gid / a.n_embd, k = gid % a.n_embd;
182    if (t < a.n_tok) {
183        float s = 0.0f;
184        for (uint j = 0; j < a.topk; ++j) s += ye[plan[P_TOKENT + t * a.topk + j] * int(a.n_embd) + k];
185        const float gs = 1.0f / (1.0f + exp(-sg[t]));
186        const float v = fma(gs, ysh[gid], s);
187        bo[gid] = v;
188        hcf_apply(R, inj, h, int(t), int(k), v);
189    }
190#ifdef HCF_NO_LAST
191    return;
192#endif
193    if (!hcf_last(counter, ngv.x, tid, &last)) return;
194#ifndef HCF_NO_NORM
195    hcf_norm<256>(R, w_norm, xn, h, int(a.n_tok), tid, sgi, lane, part);
196#endif
197    if (tid == 0) atomic_store_explicit(counter, 0u, memory_order_relaxed);
198}
199
200#define GVH_(F) template [[host_name("gemvh_" #F)]] kernel decltype(gemv_hcf<F, 32, 1, 8, 2>) gemv_hcf<F, 32, 1, 8, 2>;
201#define GVH(F) GVH_(F)
202GVH(T_F32) GVH(T_BF16) GVH(T_Q8_0) GVH(T_Q4_0) GVH(T_Q5_0) GVH(T_IQ4_NL) GVH(T_IQ4_XS) GVH(T_Q2_0) GVH(T_IQ3_S) GVH(T_Q3_K)
203GVH(T_Q4_K) GVH(T_Q5_K) GVH(T_Q6_K)
204
205// timing probe: an empty kernel (the cost of one dependent dispatch)
206kernel void noop_k(device float* x [[buffer(0)]], uint t [[thread_position_in_grid]]) {
207    if (x[0] == 12345.678f) x[t + 1] = 1.0f;
208}