okami.mom/strata

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

Niko1221Merge f-029-gdn-amd01ef87656

main
16.5 KiB324 linesraw
1// Included by kernels.cu right after the gfx11 chunked-GDN kernels (it uses their constants, types and helpers).
2//
3// STRATA_GDN_CHUNKED=1 on gfx12 (RDNA4: R9700 / 9070 / 9060): the same chunked algorithm as the gfx11 kernels above, on
4// the gfx12 matrix cores.  The fragment layout differs from gfx11 (wave32, v_wmma_f32_16x16x16_f16; checked on an R9700 by
5// results/gdn/GDN-A/micro/wmma12.cpp): A and B take 8 halves a lane, lane l holding row (A) or column (B) l & 15 and
6// k = 8 * (l >> 4) + 0..7; the accumulator lane l holds column l & 15 and rows 8 * (l >> 4) + 0..7.  So an accumulator IS the
7// next product's B operand (an FP16 conversion only: no permlane / byte permute as on gfx11), and the row of accumulator
8// element v is 8 * hi + v (gfx11: 2 * v + hi).  Everything else (chunk of 16, FP16 operands, FP32 accumulate and state, the
9// norm fused, T and P from a prep kernel) is the gfx11 design, so the numerics are the same class (FP16 operands).
10#if defined(__gfx1200__) || defined(__gfx1201__)
11#define STRATA_GDN_WMMA12 1
12#endif
13__device__ __forceinline__ gw_f8 gw_mma12(gw_h8 a, gw_h8 b, gw_f8 c) {
14#if defined(STRATA_GDN_WMMA12)
15    return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
16#else
17    (void) a; (void) b; (void) c;
18    __builtin_trap();   // not a gfx12 device pass: the runtime gate never launches it
19#endif
20}
21__device__ __forceinline__ gw_h8 gw_acc_to_b12(gw_f8 x) {
22    gw_h8 r;
23#pragma unroll
24    for (int i = 0; i < 8; ++i) r[i] = (_Float16) x[i];
25    return r;
26}
27// A barrier over LDS only (LB): __syncthreads() is a workgroup fence over all memory, which also waits for the global loads of the
28// next chunk that the scan keeps in flight (the same reason gfx11 has gw_lds_barrier).  gfx12: wait for this wave's LDS accesses
29// (DScnt), then the barrier; the compiler still waits for each load before its first use.
30template<bool LB> __device__ __forceinline__ void gw12_barrier() {
31#if defined(STRATA_GDN_WMMA12)
32    if (LB) {
33        __asm__ volatile("s_wait_dscnt 0x0" ::: "memory");
34        __builtin_amdgcn_s_barrier();
35        __asm__ volatile("" ::: "memory");
36    } else {
37        __syncthreads();
38    }
39#else
40    __syncthreads();
41#endif
42}
43__device__ __forceinline__ gw_h8 gw_ld8(const _Float16* p) { return *reinterpret_cast<const gw_h8*>(p); }   // 16 bytes of LDS
44
45// The causal conv + SiLU + q/k L2 norm (gdn_conv_l2_kernel's arithmetic) with the result written as FP16: half the traffic of
46// the FP32 h in the conv and in both chunked kernels.  One block per (head of 128 channels, tile of 64 tokens).
47__global__ void __launch_bounds__(128) gdn_conv_l2_h16_kernel(const float* __restrict__ hist, const float* __restrict__ qkv,
48                                                              const float* __restrict__ w, _Float16* __restrict__ h, int64_t T,
49                                                              float eps) {
50    const int c = blockIdx.x * blockDim.x + threadIdx.x;
51    const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE;
52    if (t0 >= T) return;
53    const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T;
54    auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; };
55    float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1);
56    const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];
57    const bool norm = blockIdx.x < 2 * HK;   // q and k heads; v channels are not normalised
58    __shared__ float part[16][4];
59    for (int64_t tb = t0; tb < t1; tb += 16) {
60        const int n = (int) (t1 - tb < 16 ? t1 - tb : 16);
61        float val[16];
62#pragma unroll
63        for (int j = 0; j < 16; ++j) {
64            val[j] = 0.0f;
65            if (j < n) {
66                const float x = qkv[(tb + j) * C + c];
67                const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;
68                val[j] = s / (1.0f + __expf(-s));
69                v0 = v1; v1 = v2; v2 = x;
70            }
71        }
72        if (norm) {
73#pragma unroll
74            for (int j = 0; j < 16; ++j) {
75                float sq = val[j] * val[j];
76#pragma unroll
77                for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor(sq, o);
78                if ((threadIdx.x & 31) == 0) part[j][threadIdx.x >> 5] = sq;
79            }
80            __syncthreads();
81#pragma unroll
82            for (int j = 0; j < 16; ++j) val[j] *= rsqrtf(part[j][0] + part[j][1] + part[j][2] + part[j][3] + eps);
83            __syncthreads();
84        }
85#pragma unroll
86        for (int j = 0; j < 16; ++j)
87            if (j < n) h[(tb + j) * C + c] = (_Float16) val[j];
88    }
89}
90
91// H16: h is the FP16 conv output of gdn_conv_l2_h16_kernel (the matrix-core operands are FP16 anyway; v keeps 11 bits, the
92// same rounding the y operand takes a step later), else the FP32 h of gdn_conv.
93template<bool H16>
94__global__ void __launch_bounds__(32 * GW_VPK) gdn_w12_prep_kernel(const float* __restrict__ hf, const _Float16* __restrict__ hh,
95                                                                const float* __restrict__ gate,
96                                                                const float* __restrict__ beta, _Float16* __restrict__ tp,
97                                                                int64_t T) {
98    __shared__ float sa[GW_VPK][GW_CK * GW_CK], sg[GW_VPK][GW_CK], sb[GW_VPK][GW_CK];
99    const int qh = blockIdx.x, ch = blockIdx.y, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4;
100    const int vh = qh + w * HK;
101    const int64_t t0 = (int64_t) ch * GW_CK;
102    gw_f8 kk = {}, qk = {};   // k_t.k_i and q_t.k_i (lane: column i = c, rows t = 8 * hi + v)
103    {
104        const bool ok = t0 + c < T;   // past the end: zero rows
105        const float* ht = hf + (ok ? t0 + c : 0) * C;
106        const _Float16* hth = hh + (ok ? t0 + c : 0) * C;
107#pragma unroll
108        for (int j = 0; j < S / 16; ++j) {
109            gw_h8 ka, qa;
110            if (H16) {
111                ka = *reinterpret_cast<const gw_h8*>(hth + HK * S + qh * S + 16 * j + 8 * hi);
112                qa = *reinterpret_cast<const gw_h8*>(hth + qh * S + 16 * j + 8 * hi);
113                if (!ok) { ka = gw_h8{}; qa = gw_h8{}; }
114            } else {
115#pragma unroll
116                for (int i = 0; i < 2; ++i) {
117                    const gw_f4 k4 = *reinterpret_cast<const gw_f4*>(ht + HK * S + qh * S + 16 * j + 8 * hi + 4 * i);
118                    const gw_f4 q4 = *reinterpret_cast<const gw_f4*>(ht + qh * S + 16 * j + 8 * hi + 4 * i);
119#pragma unroll
120                    for (int e = 0; e < 4; ++e) {
121                        ka[4 * i + e] = (_Float16) (ok ? k4[e] : 0.0f);
122                        qa[4 * i + e] = (_Float16) (ok ? q4[e] : 0.0f);
123                    }
124                }
125            }
126            kk = gw_mma12(ka, ka, kk);   // B = K^T: lane i holds column i of K^T = row i of K, the A operand itself
127            qk = gw_mma12(qa, ka, qk);
128        }
129    }
130    if (l < GW_CK) {   // past the end: gate 0, beta 0
131        const bool ok = t0 + l < T;
132        float g = ok ? gate[(t0 + l) * HV + vh] : 0.0f;
133#pragma unroll
134        for (int o = 1; o < GW_CK; o <<= 1) {
135            const float u = __shfl_up(g, o, GW_CK);
136            if (l >= o) g += u;
137        }
138        sg[w][l] = g;
139        sb[w][l] = ok ? beta[(t0 + l) * HV + vh] : 0.0f;
140    }
141    __syncthreads();
142    _Float16* out = tp + ((int64_t) ch * HV + vh) * (2 * GW_CK * GW_CK);
143#pragma unroll
144    for (int v = 0; v < 8; ++v) {
145        const int t = 8 * hi + v;
146        sa[w][t * GW_CK + c] = c < t ? sb[w][t] * __expf(sg[w][t] - sg[w][c]) * kk[v] : 0.0f;
147        out[GW_CK * GW_CK + t * GW_CK + c] = (_Float16) (c <= t ? __expf(sg[w][t] - sg[w][c]) * qk[v] : 0.0f);
148    }
149    __syncthreads();
150    if (l < GW_CK) {   // lane c: column c of T = (I + A)^-1 by forward substitution
151        float tc[GW_CK];
152#pragma unroll
153        for (int t = 0; t < GW_CK; ++t) {
154            float v = t == c ? 1.0f : 0.0f;
155#pragma unroll
156            for (int k = 0; k < t; ++k) v = fmaf(-sa[w][t * GW_CK + k], tc[k], v);
157            tc[t] = v;
158            out[t * GW_CK + c] = (_Float16) v;
159        }
160    }
161}
162
163// gw_load / gw_touch for the FP16 h (a thread's 8 channels of k, q, v are one 16-byte load each)
164__device__ __forceinline__ void gw12_load16(GwChunk& in, const _Float16* __restrict__ hh, const float* __restrict__ gate,
165                                            const float* __restrict__ beta, const unsigned* __restrict__ tp, int64_t t0, int64_t T,
166                                            int vh, int qh) {
167    const int t = threadIdx.x >> 4, r = (threadIdx.x & 15) * 8;
168    const _Float16* ht = hh + std::min<int64_t>(t0 + t, T - 1) * C;
169    in.tp = tp[((t0 / GW_CK) * HV + vh) * (GW_CK * GW_CK) + threadIdx.x];
170    const gw_h8 k = *reinterpret_cast<const gw_h8*>(ht + HK * S + qh * S + r);
171    const gw_h8 q = *reinterpret_cast<const gw_h8*>(ht + qh * S + r);
172    const gw_h8 v = *reinterpret_cast<const gw_h8*>(ht + 2 * HK * S + vh * S + r);
173    in.k0 = gw_f4{(float) k[0], (float) k[1], (float) k[2], (float) k[3]};
174    in.k1 = gw_f4{(float) k[4], (float) k[5], (float) k[6], (float) k[7]};
175    in.q0 = gw_f4{(float) q[0], (float) q[1], (float) q[2], (float) q[3]};
176    in.q1 = gw_f4{(float) q[4], (float) q[5], (float) q[6], (float) q[7]};
177    in.v0 = gw_f4{(float) v[0], (float) v[1], (float) v[2], (float) v[3]};
178    in.v1 = gw_f4{(float) v[4], (float) v[5], (float) v[6], (float) v[7]};
179    if (threadIdx.x < GW_CK) {
180        const int64_t tl = std::min<int64_t>(t0 + threadIdx.x, T - 1);
181        in.g = gate[tl * HV + vh];
182        in.b = beta[tl * HV + vh];
183    }
184}
185__device__ __forceinline__ unsigned gw12_touch16(const _Float16* __restrict__ hh, const float* __restrict__ z, int64_t t0, int64_t T,
186                                                 int vh, int qh) {
187    const int t = threadIdx.x >> 4, part = threadIdx.x & 15, kind = part >> 2;
188    if (t0 + t >= T) return 0u;
189    if (kind == 3) return __float_as_uint((z + (t0 + t) * HV * S + vh * S)[32 * (part & 3)]);
190    const _Float16* p = kind == 0 ? hh + (t0 + t) * C + HK * S + qh * S
191                      : kind == 1 ? hh + (t0 + t) * C + qh * S
192                                  : hh + (t0 + t) * C + 2 * HK * S + vh * S;
193    return *reinterpret_cast<const unsigned*>(p + 64 * (part & 1));   // 256 bytes of FP16: two lines
194}
195
196template<bool LB, bool H16>
197__global__ void __launch_bounds__(GW_NW * 32) gdn_w12_scan_kernel(float* __restrict__ state, const float* __restrict__ hf,
198                                                                  const _Float16* __restrict__ hh,
199                                                                  const float* __restrict__ gate, const float* __restrict__ beta,
200                                                                  const float* __restrict__ z, const float* __restrict__ gamma,
201                                                                  const unsigned* __restrict__ tp, float eps,
202                                                                  uint16_t* __restrict__ y16, int64_t T, int64_t ld16) {
203    __shared__ __attribute__((aligned(16))) _Float16 sk[GW_CK * GW_KP], sq[GW_CK * GW_KP], skt[S * GW_CK],
204        stp[2 * GW_CK * GW_CK];
205    __shared__ __attribute__((aligned(16))) float sv[GW_CK * S], so[GW_CK * S], sn[GW_CK * GW_NW];
206    __shared__ float sg[GW_CK], sb[GW_CK], sgam[S];
207    const _Float16 *st_ = stp, *sp_ = stp + GW_CK * GW_CK;   // T, P
208    const int vh = blockIdx.x, qh = vh % HK, w = threadIdx.x >> 5, l = threadIdx.x & 31, c = l & 15, hi = l >> 4;
209    const int col = 16 * w + c;
210    const int st = threadIdx.x >> 4, sr = (threadIdx.x & 15) * 8;
211    const size_t rs = (size_t) HV * S;
212    gw_f8 s[S / 16];   // the state: rows 16j + 8 * hi + v, column col
213#pragma unroll
214    for (int j = 0; j < S / 16; ++j)
215#pragma unroll
216        for (int v = 0; v < 8; ++v) s[j][v] = state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col];
217    if (threadIdx.x < S) sgam[threadIdx.x] = gamma[threadIdx.x];
218    const float out_scale = rsqrtf((float) S);
219    GwChunk cur;
220    if (H16) gw12_load16(cur, hh, gate, beta, tp, 0, T, vh, qh); else gw_load(cur, hf, gate, beta, tp, 0, T, vh, qh);
221    unsigned touched = 0;
222    gw_f4 z0 = {}, z1 = {};
223    auto store_rows = [&](int64_t c0) {
224        if (c0 + st >= T) return;
225        const float* o = &so[st * S + sr];
226        gw_h8 r;
227#pragma unroll
228        for (int i = 0; i < 8; ++i) r[i] = (_Float16) (o[i] * sigm(i < 4 ? z0[i] : z1[i - 4]));
229        *reinterpret_cast<uint4*>(y16 + (c0 + st) * ld16 + vh * S + sr) = __builtin_bit_cast(uint4, r);
230    };
231    for (int64_t t0 = 0; t0 < T; t0 += GW_CK) {
232        {   // stage this chunk
233            gw_h8 kh, qq;
234#pragma unroll
235            for (int i = 0; i < 8; ++i) {
236                kh[i] = (_Float16) (i < 4 ? cur.k0[i] : cur.k1[i - 4]);
237                qq[i] = (_Float16) (i < 4 ? cur.q0[i] : cur.q1[i - 4]);
238                skt[(sr + i) * GW_CK + st] = kh[i];
239            }
240            *reinterpret_cast<uint4*>(&sk[st * GW_KP + sr]) = __builtin_bit_cast(uint4, kh);
241            *reinterpret_cast<uint4*>(&sq[st * GW_KP + sr]) = __builtin_bit_cast(uint4, qq);
242            *reinterpret_cast<gw_f4*>(&sv[st * S + sr]) = cur.v0;
243            *reinterpret_cast<gw_f4*>(&sv[st * S + sr + 4]) = cur.v1;
244            reinterpret_cast<unsigned*>(stp)[threadIdx.x] = cur.tp;
245            if (threadIdx.x < GW_CK) {   // past the end: gate 0, beta 0
246                const bool ok = t0 + l < T;
247                float g = ok ? cur.g : 0.0f;
248#pragma unroll
249                for (int o = 1; o < GW_CK; o <<= 1) {
250                    const float u = __shfl_up(g, o, GW_CK);
251                    if (l >= o) g += u;
252                }
253                sg[l] = g;
254                sb[l] = ok ? cur.b : 0.0f;
255            }
256        }
257        if (t0 + GW_CK < T) {
258            if (H16) gw12_load16(cur, hh, gate, beta, tp, t0 + GW_CK, T, vh, qh);
259            else gw_load(cur, hf, gate, beta, tp, t0 + GW_CK, T, vh, qh);
260        }
261        const unsigned touch_now = H16 ? gw12_touch16(hh, z, t0 + GW_AHEAD * GW_CK, T, vh, qh)
262                                       : gw_touch(hf, z, t0 + GW_AHEAD * GW_CK, T, vh, qh);
263        gw12_barrier<LB>();   // (1) this chunk staged; the previous chunk's norm in so
264        if (t0 > 0) store_rows(t0 - GW_CK);
265        __asm__ volatile("" ::"v"(touched));
266        touched = touch_now;
267        {
268            const int64_t tz = std::min<int64_t>(t0 + st, T - 1);
269            z0 = *reinterpret_cast<const gw_f4*>(z + tz * HV * S + vh * S + sr);
270            z1 = *reinterpret_cast<const gw_f4*>(z + tz * HV * S + vh * S + sr + 4);
271        }
272        gw_f8 x = {}, qs = {};   // K S0 and Q S0, this wave's columns
273#pragma unroll
274        for (int j = 0; j < S / 16; ++j) {
275            const gw_h8 b = gw_acc_to_b12(s[j]);
276            x = gw_mma12(gw_ld8(sk + c * GW_KP + 16 * j + 8 * hi), b, x);
277            qs = gw_mma12(gw_ld8(sq + c * GW_KP + 16 * j + 8 * hi), b, qs);
278        }
279        gw_f8 y;
280#pragma unroll
281        for (int v = 0; v < 8; ++v) {
282            const int t = 8 * hi + v;
283            y[v] = sb[t] * (sv[t * S + col] - __expf(sg[t]) * x[v]);
284        }
285        const gw_f8 d = gw_mma12(gw_ld8(st_ + c * GW_CK + 8 * hi), gw_acc_to_b12(y), gw_f8{});
286        gw_f8 o;
287#pragma unroll
288        for (int v = 0; v < 8; ++v) o[v] = __expf(sg[8 * hi + v]) * qs[v];
289        o = gw_mma12(gw_ld8(sp_ + c * GW_CK + 8 * hi), gw_acc_to_b12(d), o);
290#pragma unroll
291        for (int v = 0; v < 8; ++v) {
292            o[v] *= out_scale;
293            float p = o[v] * o[v];
294#pragma unroll
295            for (int m = 1; m < 16; m <<= 1) p += __shfl_xor(p, m);
296            if (c == 0) sn[(8 * hi + v) * GW_NW + w] = p;
297        }
298        const float gl = sg[GW_CK - 1];
299        gw_f8 dd;
300#pragma unroll
301        for (int v = 0; v < 8; ++v) dd[v] = __expf(gl - sg[8 * hi + v]) * d[v];
302        const gw_h8 db = gw_acc_to_b12(dd);
303        const float eg = __expf(gl);
304#pragma unroll
305        for (int j = 0; j < S / 16; ++j) s[j] = gw_mma12(gw_ld8(skt + (16 * j + c) * GW_CK + 8 * hi), db, s[j] * eg);
306        gw12_barrier<LB>();   // (2) the sums of o^2
307        const float g_col = sgam[col];
308#pragma unroll
309        for (int v = 0; v < 8; ++v) {
310            const int t = 8 * hi + v;
311            const gw_f4 n0 = *reinterpret_cast<const gw_f4*>(&sn[t * GW_NW]), n1 = *reinterpret_cast<const gw_f4*>(&sn[t * GW_NW + 4]);
312            const float ss = n0[0] + n0[1] + n0[2] + n0[3] + n1[0] + n1[1] + n1[2] + n1[3];
313            so[t * S + col] = o[v] * rsqrtf(ss * (1.0f / S) + eps) * g_col;
314        }
315    }
316    __asm__ volatile("" ::"v"(touched));
317    gw12_barrier<LB>();
318    store_rows((T - 1) / GW_CK * GW_CK);
319    __asm__ volatile("" : "+s"(state));
320#pragma unroll
321    for (int j = 0; j < S / 16; ++j)
322#pragma unroll
323        for (int v = 0; v < 8; ++v) state[(size_t) (16 * j + 8 * hi + v) * rs + (size_t) vh * S + col] = s[j][v];
324}