epilogues.cuh 37.6 KB
Newer Older
sxtyzhangzk's avatar
sxtyzhangzk committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma once

#include "gemm_base.cuh"

namespace nunchaku::kernels {

template<typename Config>
class Epilogues;

#ifndef __INTELLISENSE__
template<typename Config>
class Epilogues : public GEMMBase<Config> {
#else
template<>
class Epilogues<GEMMConfig_W4A4_FP16> : public GEMMBase<GEMMConfig_W4A4_FP16> {
    using Config = GEMMConfig_W4A4_FP16;
#endif
public:
    IMPORT_GEMM_BASE(Config);

public:
    struct EpilogueGelu {
Muyang Li's avatar
Muyang Li committed
23
24
25
        struct Arguments {
            size_t unused;
        };
sxtyzhangzk's avatar
sxtyzhangzk committed
26
27
28

        // static constexpr float SHIFT_VALUE = 0.171875f;

Muyang Li's avatar
Muyang Li committed
29
30
31
        __device__ __forceinline__ void
        operator()(const BlockInfo binfo, fpsum_warp &fpsum, int M, int N, int K, const Arguments &args) {
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
32
            for (int i = 0; i < WARP_M_TILES; i++) {
Muyang Li's avatar
Muyang Li committed
33
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
34
                for (int j = 0; j < WARP_N_TILES; j++) {
Muyang Li's avatar
Muyang Li committed
35
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
36
37
                    for (int k = 0; k < 4; k++) {
                        half2_t &data = fpsum[i * WARP_N_TILES + j].data[k];
Muyang Li's avatar
Muyang Li committed
38
                        data          = gelu_half2(data);
sxtyzhangzk's avatar
sxtyzhangzk committed
39
40
41
42
43
44
45
46
47
48
49
50
51
                        // data = __hadd2(data, half2_t(SHIFT_VALUE, SHIFT_VALUE));
                    }
                }
            }
        }
    };

    // template<int PoolSize = 128>
    struct EpilogueQKVProj {
        struct Arguments {
            half_t *out;
            int actualM, actualN;

Muyang Li's avatar
Muyang Li committed
52
            half_t *pool_out;               // [M / PoolSize, N]
sxtyzhangzk's avatar
sxtyzhangzk committed
53
54
55
56
57
58
            const float *rotary_emb;        // [M, HEAD_DIM / 2, ROTARY_EMB_NUM_ELEMENTS]
            const half_t *rmsnorm_weight_q; // [HEAD_DIM]
            const half_t *rmsnorm_weight_k; // [HEAD_DIM]
            float epsilon;
        };

Muyang Li's avatar
Muyang Li committed
59
        static constexpr int HEAD_DIM           = 128;
sxtyzhangzk's avatar
sxtyzhangzk committed
60
61
        static constexpr int NUM_HEADS_PER_WARP = WARP_N / HEAD_DIM;

Muyang Li's avatar
Muyang Li committed
62
63
        static constexpr int PoolSize            = 128;
        static constexpr int NUM_WARPS_PER_POOL  = PoolSize / WARP_M;
sxtyzhangzk's avatar
sxtyzhangzk committed
64
65
        static constexpr int NUM_POOLS_PER_BLOCK = BLOCK_M / PoolSize;

Muyang Li's avatar
Muyang Li committed
66
67
68
69
70
71
72
73
74
75
76
77
        static constexpr int ROTARY_EMB_NUM_ELEMENTS = 2; // 1 for theta, 2 for {sin, cos} pair

        __device__ __forceinline__ static void apply(fpsum_warp fpsum,
                                                     half_t *out,
                                                     int M,
                                                     int N,
                                                     int K,
                                                     half_t *pool_out,
                                                     const float *rotary_emb,
                                                     const half_t *rmsnorm_weight,
                                                     float epsilon,
                                                     int maxRows) {
sxtyzhangzk's avatar
sxtyzhangzk committed
78
79
80
            const int laneId = threadIdx.x % WARP_SIZE;
            const int warpId = threadIdx.x / WARP_SIZE;

limm's avatar
limm committed
81
82
            // __shared__ alignas(128) uint8_t shmem[NUM_WARPS][ceilDiv(unpack_fpsum::SHMEM_SIZE, 128) * 128];
	    __shared__ uint8_t shmem[NUM_WARPS][ceilDiv(unpack_fpsum::SHMEM_SIZE, 128) * 128] __attribute__((aligned(128)));
sxtyzhangzk's avatar
sxtyzhangzk committed
83
84

            constexpr int PACK_SIZE = unpack_fpsum::PACK_SIZE;
Muyang Li's avatar
Muyang Li committed
85
            using pack_t            = unpack_fpsum::pack_t;
sxtyzhangzk's avatar
sxtyzhangzk committed
86

Muyang Li's avatar
Muyang Li committed
87
            using pack_rope_t            = std::array<float, PACK_SIZE / 2 * ROTARY_EMB_NUM_ELEMENTS>;
sxtyzhangzk's avatar
sxtyzhangzk committed
88
89
90
            constexpr int LANES_PER_HEAD = HEAD_DIM / PACK_SIZE;

            pack_t reduce_tmp;
limm's avatar
limm committed
91
92
            // __shared__ alignas(128) pack_t pool[NUM_WARPS];
	    __shared__ pack_t pool[NUM_WARPS] __attribute__((aligned(128)));
sxtyzhangzk's avatar
sxtyzhangzk committed
93
94
95
96
97
98
99
100
101
102
103
104

            // load rmsnorm scales
            pack_t rms;
            if (laneId < LANES_PER_HEAD) {
                rms = load(reinterpret_cast<const pack_t *>(&rmsnorm_weight[laneId * PACK_SIZE]));
            }
            if constexpr (LANES_PER_HEAD < WARP_SIZE) {
                for (int i = 0; i < PACK_SIZE; i++) {
                    rms[i] = __shfl_sync(~0, rms[i], laneId % LANES_PER_HEAD);
                }
            }

Muyang Li's avatar
Muyang Li committed
105
106
            const float *rotary_emb_base_addr = &rotary_emb[(warpId * WARP_M) * HEAD_DIM / 2 * ROTARY_EMB_NUM_ELEMENTS +
                                                            laneId * PACK_SIZE / 2 * ROTARY_EMB_NUM_ELEMENTS];
sxtyzhangzk's avatar
sxtyzhangzk committed
107
108
109

            CHECK_NAN(fpsum, "fpsum");

Muyang Li's avatar
Muyang Li committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
            unpack_fpsum()(fpsum,
                           out + warpId * WARP_M * N,
                           N,
                           maxRows - warpId * WARP_M,
                           INT_MAX,
                           shmem[warpId],
                           [&](int rowId, pack_t &pack) ALWAYSINLINE {
                               // load rope
                               pack_rope_t rope;
                               if (laneId < LANES_PER_HEAD) {
                                   // freq = load(reinterpret_cast<pack_freq_t *>(&freqs_cis[(warpId * WARP_M + rowId) *
                                   // HEAD_DIM * 2 + laneId * PACK_SIZE * 2]));
                                   rope = load(reinterpret_cast<const pack_rope_t *>(
                                       &rotary_emb_base_addr[rowId * HEAD_DIM / 2 * ROTARY_EMB_NUM_ELEMENTS]));
                               }
                               if constexpr (LANES_PER_HEAD < WARP_SIZE) {
                                   for (int i = 0; i < rope.size(); i++) {
                                       rope[i] = __shfl_sync(~0, rope[i], laneId % LANES_PER_HEAD);
                                   }
                               }

                               // rmsnorm
                               float sqrsum = 0.0f;
                               for (int i = 0; i < PACK_SIZE; i++) {
                                   sqrsum += float(pack[i]) * float(pack[i]);
                                   CHECK_NAN(sqrsum, "sqrsum");
                               }
#pragma unroll
                               for (int mask = LANES_PER_HEAD / 2; mask > 0; mask /= 2) {
limm's avatar
limm committed
139
                                   sqrsum += __shfl_xor(sqrsum, mask);
Muyang Li's avatar
Muyang Li committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
                               }
                               sqrsum /= HEAD_DIM;
                               float coef = cuda_frsqrt(sqrsum + epsilon);
                               CHECK_NAN(coef, "coef");

                               for (int i = 0; i < PACK_SIZE; i++) {
                                   pack[i] *= coef * float(rms[i]);

                                   CHECK_NAN(rms[i], "rms.wgt");
                                   CHECK_NAN(pack[i], "rms.out");
                               }

#if 1
                               // rope
                               for (int i = 0; i < PACK_SIZE; i += 2) {
                                   float2 pack2 = half22float2(half2_t(pack[i], pack[i + 1]));

                                   CHECK_NAN(freq[i].x, "rope.freq");
                                   CHECK_NAN(freq[i].y, "rope.freq");
                                   CHECK_NAN(freq[i + 1].x, "rope.freq");
                                   CHECK_NAN(freq[i + 1].y, "rope.freq");

                                   // half2_t tmp = __hmul2(freq[i], pack2);
                                   // tmp = __hfma2(freq[i+1], pack2, tmp);
                                   // pack[i] = tmp.x;
                                   // pack[i+1] = tmp.y;

                                   // printf("block.x=%d block.y=%d warpId=%d rowId=%d (%d) freqs = %f %f %f %f\n",
                                   //     blockIdx.x, blockIdx.y, warpId, rowId,
                                   //     blockIdx.x * BLOCK_M + warpId * WARP_M + rowId,
                                   //     (float)freq[i].x, (float)freq[i].y, (float)freq[i+1].x, (float)freq[i+1].y
                                   // );
                                   // __trap();

                                   // half2_t tmp = __hmul2(half2_t(pack2.x, pack2.x), freq[i]);
                                   // tmp = __hfma2(half2_t(pack2.y, pack2.y), freq[i+1], tmp);
                                   // pack[i] = tmp.x;
                                   // pack[i+1] = tmp.y;

                                   float sin, cos;

                                   if constexpr (ROTARY_EMB_NUM_ELEMENTS == 1) {
                                       sin = cuda_sin(rope[i / 2]);
                                       cos = cuda_cos(rope[i / 2]);
                                   }
                                   if constexpr (ROTARY_EMB_NUM_ELEMENTS == 2) {
                                       sin = rope[i];
                                       cos = rope[i + 1];
                                   }

                                   // pack[i]   = pack2.x * freq[i].x   + pack2.y * freq[i].y;
                                   // pack[i+1] = pack2.x * freq[i+1].x + pack2.y * freq[i+1].y;

                                   pack[i]     = half_t(pack2.x * cos - pack2.y * sin);
                                   pack[i + 1] = half_t(pack2.x * sin + pack2.y * cos);

                                   CHECK_NAN(pack[i], "rope.out");
                                   CHECK_NAN(pack[i + 1], "rope.out");
                               }
#endif
sxtyzhangzk's avatar
sxtyzhangzk committed
200

Muyang Li's avatar
Muyang Li committed
201
202
203
204
205
                               // mean pool
                               for (int i = 0; i < PACK_SIZE; i++) {
                                   reduce_tmp[i] += pack[i];
                               }
                           });
sxtyzhangzk's avatar
sxtyzhangzk committed
206
207
208
209
210
211
212
213
214
215

            if (!pool_out) {
                return;
            }

            store<true>(&pool[warpId], reduce_tmp);
            __syncthreads();

            if (warpId < NUM_POOLS_PER_BLOCK) {
                const int row = warpId * NUM_WARPS_PER_POOL;
Muyang Li's avatar
Muyang Li committed
216
                reduce_tmp    = load<true>(&pool[row]);
sxtyzhangzk's avatar
sxtyzhangzk committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

                for (int i = 1; i < NUM_WARPS_PER_POOL; i++) {
                    pack_t pack = load<true>(&pool[row + i]);
                    for (int j = 0; j < PACK_SIZE; j++) {
                        reduce_tmp[j] += pack[j];
                    }
                }
                for (int j = 0; j < PACK_SIZE; j++) {
                    reduce_tmp[j] /= PoolSize;
                }

                store(reinterpret_cast<pack_t *>(pool_out + warpId * N), reduce_tmp);
            }
            __syncthreads();
        }

Muyang Li's avatar
Muyang Li committed
233
234
        __device__ __forceinline__ void
        operator()(const BlockInfo binfo, fpsum_warp fpsum, int M, int N, int K, const Arguments &args) {
sxtyzhangzk's avatar
sxtyzhangzk committed
235
236
237
238
239
240
241
242
243
244
245
            const int bm = binfo.bm;
            const int bn = binfo.bn;

            assert(binfo.numBlocksN % 3 == 0);
            const bool is_q = bn < binfo.numBlocksN / 3;
            const bool is_k = !is_q && bn < binfo.numBlocksN / 3 * 2;

            assert(!args.pool_out || args.actualM == M);
            assert(args.actualN == N);

            if (is_q || is_k) {
Muyang Li's avatar
Muyang Li committed
246
247
248
249
250
251
252
253
254
255
                apply(fpsum,
                      args.out + bm * BLOCK_M * args.actualN + bn * BLOCK_N,
                      M,
                      N,
                      K,
                      args.pool_out ? args.pool_out + bm * BLOCK_M / PoolSize * N : nullptr,
                      args.rotary_emb + bm * BLOCK_M * (HEAD_DIM / 2 * ROTARY_EMB_NUM_ELEMENTS),
                      is_q ? args.rmsnorm_weight_q : args.rmsnorm_weight_k,
                      args.epsilon,
                      args.actualM - bm * BLOCK_M);
sxtyzhangzk's avatar
sxtyzhangzk committed
256
            } else {
Muyang Li's avatar
Muyang Li committed
257
258
259
260
261
262
263
264
265
266
                EpilogueDefault()(binfo,
                                  fpsum,
                                  M,
                                  N,
                                  K,
                                  typename EpilogueDefault::Arguments{
                                      .out     = args.out,
                                      .actualM = args.actualM,
                                      .actualN = args.actualN,
                                  });
sxtyzhangzk's avatar
sxtyzhangzk committed
267
268
269
270
271
            }
        }
    };

    struct EpilogueRMSNormRope {
Muyang Li's avatar
Muyang Li committed
272
273
        static constexpr int HEAD_DIM              = 128;
        static constexpr int NUM_HEADS_PER_WARP    = WARP_N / HEAD_DIM;
sxtyzhangzk's avatar
sxtyzhangzk committed
274
275
276
277
        static constexpr int WARP_N_TILES_PER_HEAD = WARP_N_TILES / NUM_HEADS_PER_WARP;

        static constexpr int ROTARY_EMB_NUM_ELEMENTS = 2;

Muyang Li's avatar
Muyang Li committed
278
        using packed_rotemb_t                    = float4;
sxtyzhangzk's avatar
sxtyzhangzk committed
279
280
281
282
283
284
285
286
287
288
289
290
        static constexpr int WARP_N_ROTEMB_TILES = WARP_N_TILES / NUM_HEADS_PER_WARP * 2;
        using rotemb_warp = std::array<packed_rotemb_t, WARP_M_TILES * WARP_N_ROTEMB_TILES>; // 128 regs

        struct Arguments {
            // **packed** [M, HEAD_DIM] float => [M // 16, HEAD_DIM // 8, WARP_SIZE] of packed_rotemb_t
            // aka [M // BLOCK_M, NUM_WARPS, WARP_M_TILES, WARP_N_TILES // NUM_HEADS_PER_WARP * 2, WARP_SIZE]
            const packed_rotemb_t *rotary_emb;
            const half_t *rmsnorm_weight_q; // [HEAD_DIM]
            const half_t *rmsnorm_weight_k; // [HEAD_DIM]
            float epsilon;
        };

Muyang Li's avatar
Muyang Li committed
291
        __device__ __forceinline__ static rotemb_warp load_rotemb(const packed_rotemb_t *ptr_rotemb) {
sxtyzhangzk's avatar
sxtyzhangzk committed
292
293
294
295
            const int laneId = threadIdx.x % WARP_SIZE;
            const int warpId = threadIdx.x / WARP_SIZE;

            rotemb_warp rotemb;
Muyang Li's avatar
Muyang Li committed
296
297
            const packed_rotemb_t *ptrlane =
                &ptr_rotemb[warpId * WARP_M_TILES * WARP_N_ROTEMB_TILES * WARP_SIZE + laneId];
sxtyzhangzk's avatar
sxtyzhangzk committed
298
299
300

            unrolled_loop<WARP_M_TILES>([&]<int i>() {
                unrolled_loop<WARP_N_ROTEMB_TILES>([&]<int j>() {
Muyang Li's avatar
Muyang Li committed
301
                    constexpr int offset                = (i * WARP_N_ROTEMB_TILES + j) * WARP_SIZE;
sxtyzhangzk's avatar
sxtyzhangzk committed
302
303
304
305
306
307
308
                    rotemb[i * WARP_N_ROTEMB_TILES + j] = load(&ptrlane[offset]);
                });
            });

            return rotemb;
        }

Muyang Li's avatar
Muyang Li committed
309
        __device__ __forceinline__ static void load_rmsnorm(const half_t *ptr_rmsnorm_weight, half_t *shmem) {
sxtyzhangzk's avatar
sxtyzhangzk committed
310
311
312
            const int laneId = threadIdx.x % WARP_SIZE;

            static constexpr int PACK_SIZE = HEAD_DIM / WARP_SIZE;
Muyang Li's avatar
Muyang Li committed
313
            using packed_t                 = std::array<half_t, PACK_SIZE>;
sxtyzhangzk's avatar
sxtyzhangzk committed
314
315
316
317
318

            packed_t pack = load(reinterpret_cast<const packed_t *>(ptr_rmsnorm_weight + laneId * PACK_SIZE));
            store<true>(reinterpret_cast<packed_t *>(shmem + laneId * PACK_SIZE), pack);
        }

Muyang Li's avatar
Muyang Li committed
319
        __device__ __forceinline__ static packed_fpsum_t load_rmsnorm_from_shmem(half_t *shmem, int n) {
sxtyzhangzk's avatar
sxtyzhangzk committed
320
            const int laneId = threadIdx.x % WARP_SIZE;
Muyang Li's avatar
Muyang Li committed
321
            const int col    = n * INSN_N + laneId / 16 * 8; // lane 0-15: n*16+0, lane 16-31: n*16+8
sxtyzhangzk's avatar
sxtyzhangzk committed
322
323
324
325
326
            uint4 tmp;
            ldmatrix(shmem + col, tmp);
            return kernels::bit_cast<packed_fpsum_t>(tmp);
        }

Muyang Li's avatar
Muyang Li committed
327
328
        __device__ __forceinline__ static void
        apply(fpsum_warp &fpsum, const packed_rotemb_t *ptr_rotemb, const half_t *ptr_rmsnorm_weight, float epsilon) {
sxtyzhangzk's avatar
sxtyzhangzk committed
329
330
331
332
333
            const int laneId = threadIdx.x % WARP_SIZE;
            const int warpId = threadIdx.x / WARP_SIZE;

            __shared__ half_t shmem_rmsnorm[NUM_WARPS][HEAD_DIM];
            load_rmsnorm(ptr_rmsnorm_weight, &shmem_rmsnorm[warpId][0]);
limm's avatar
limm committed
334
335
            // __syncwarp();
	    __builtin_amdgcn_wave_barrier();
sxtyzhangzk's avatar
sxtyzhangzk committed
336
337
338
339
340
341
342
343
344
345

            rotemb_warp rotemb = load_rotemb(ptr_rotemb);

            float rmsnorm_coef[NUM_HEADS_PER_WARP][WARP_M_TILES][2];

            auto sqr = [](half2_t val) ALWAYSINLINE {
                float2 fval = half22float2(val);
                return fval.x * fval.x + fval.y * fval.y;
            };

Muyang Li's avatar
Muyang Li committed
346
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
347
348
349
            for (int head = 0; head < NUM_HEADS_PER_WARP; head++) {
                const int n_offset = head * WARP_N_TILES_PER_HEAD;

Muyang Li's avatar
Muyang Li committed
350
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
351
352
                for (int m = 0; m < WARP_M_TILES; m++) {
                    float sqrsum[2] = {0.0f, 0.0f};
Muyang Li's avatar
Muyang Li committed
353
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
354
355
356
357
358
359
                    for (int n = 0; n < WARP_N_TILES_PER_HEAD; n++) {
                        sqrsum[0] += sqr(fpsum[m * WARP_N_TILES + n + n_offset].data[0]);
                        sqrsum[1] += sqr(fpsum[m * WARP_N_TILES + n + n_offset].data[1]);
                        sqrsum[0] += sqr(fpsum[m * WARP_N_TILES + n + n_offset].data[2]);
                        sqrsum[1] += sqr(fpsum[m * WARP_N_TILES + n + n_offset].data[3]);
                    }
Muyang Li's avatar
Muyang Li committed
360
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
361
                    for (int mask = 1; mask <= 2; mask *= 2) {
limm's avatar
limm committed
362
363
                        sqrsum[0] += __shfl_xor(sqrsum[0], mask);
                        sqrsum[1] += __shfl_xor(sqrsum[1], mask);
sxtyzhangzk's avatar
sxtyzhangzk committed
364
365
366
367
368
369
                    }
                    rmsnorm_coef[head][m][0] = cuda_frsqrt(sqrsum[0] / HEAD_DIM + epsilon);
                    rmsnorm_coef[head][m][1] = cuda_frsqrt(sqrsum[1] / HEAD_DIM + epsilon);
                }
            }

Muyang Li's avatar
Muyang Li committed
370
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
371
372
373
            for (int head = 0; head < NUM_HEADS_PER_WARP; head++) {
                const int n_offset = head * WARP_N_TILES_PER_HEAD;

Muyang Li's avatar
Muyang Li committed
374
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
375
376
                for (int n = 0; n < WARP_N_TILES_PER_HEAD; n++) {
                    packed_f32psum_t rms = packed_fp16_to_fp32(load_rmsnorm_from_shmem(&shmem_rmsnorm[warpId][0], n));
Muyang Li's avatar
Muyang Li committed
377
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
                    for (int m = 0; m < WARP_M_TILES; m++) {
                        packed_f32psum_t pack = packed_fp16_to_fp32(fpsum[m * WARP_N_TILES + n + n_offset]);
                        pack.data[0] *= rmsnorm_coef[head][m][0] * rms.data[0];
                        pack.data[1] *= rmsnorm_coef[head][m][0] * rms.data[1];
                        pack.data[2] *= rmsnorm_coef[head][m][1] * rms.data[2];
                        pack.data[3] *= rmsnorm_coef[head][m][1] * rms.data[3];
                        pack.data[4] *= rmsnorm_coef[head][m][0] * rms.data[4];
                        pack.data[5] *= rmsnorm_coef[head][m][0] * rms.data[5];
                        pack.data[6] *= rmsnorm_coef[head][m][1] * rms.data[6];
                        pack.data[7] *= rmsnorm_coef[head][m][1] * rms.data[7];

                        auto rope = [](float &x, float &y, float sin, float cos) ALWAYSINLINE {
                            float ix = x, iy = y;
                            x = ix * cos - iy * sin;
                            y = ix * sin + iy * cos;
                        };

                        {
                            packed_rotemb_t sincos = rotemb[m * WARP_N_ROTEMB_TILES + n * 2];
                            rope(pack.data[0], pack.data[1], sincos.x, sincos.y);
                            rope(pack.data[2], pack.data[3], sincos.z, sincos.w);
                        }
                        {
                            packed_rotemb_t sincos = rotemb[m * WARP_N_ROTEMB_TILES + n * 2 + 1];
                            rope(pack.data[4], pack.data[5], sincos.x, sincos.y);
                            rope(pack.data[6], pack.data[7], sincos.z, sincos.w);
                        }

                        fpsum[m * WARP_N_TILES + n + n_offset] = packed_fp32_to_fp16(pack);
                    }
                }
            }
        }

Muyang Li's avatar
Muyang Li committed
412
413
        __device__ __forceinline__ void
        operator()(const BlockInfo binfo, fpsum_warp &fpsum, int M, int N, int K, const Arguments &args) {
sxtyzhangzk's avatar
sxtyzhangzk committed
414
415
416
417
418
419
420
421
            const int bm = binfo.bm;
            const int bn = binfo.bn;

            assert(binfo.numBlocksN % 3 == 0);
            const bool is_q = bn < binfo.numBlocksN / 3;
            const bool is_k = !is_q && bn < binfo.numBlocksN / 3 * 2;

            if (is_q || is_k) {
Muyang Li's avatar
Muyang Li committed
422
423
424
425
                apply(fpsum,
                      args.rotary_emb + bm * NUM_WARPS * WARP_M_TILES * WARP_N_ROTEMB_TILES * WARP_SIZE,
                      is_q ? args.rmsnorm_weight_q : args.rmsnorm_weight_k,
                      args.epsilon);
sxtyzhangzk's avatar
sxtyzhangzk committed
426
427
428
429
430
            }
        }
    };

    struct EpiloguePackQKV {
Muyang Li's avatar
Muyang Li committed
431
        using attn_half_t  = half;
sxtyzhangzk's avatar
sxtyzhangzk committed
432
433
434
        using attn_half2_t = half2;
        using packed_qkv_t = uint4;

Muyang Li's avatar
Muyang Li committed
435
        static constexpr int HEAD_DIM  = 128;
sxtyzhangzk's avatar
sxtyzhangzk committed
436
437
438
439
440
441
442
443
444
445
446
447
448
        static constexpr int INSN_K_QK = 16;
        static constexpr int INSN_K_PV = 16;

        struct Arguments {
            packed_qkv_t *out_q, *out_k, *out_v;
            int actualM;

            // !!! stride in number of packed_qkv_t !!!
            int strideHead_q;
            int strideHead_k;
            int strideHead_v;
        };

Muyang Li's avatar
Muyang Li committed
449
        __device__ __forceinline__ static attn_half2_t convert_half2(half2_t input) {
sxtyzhangzk's avatar
sxtyzhangzk committed
450
451
452
453
454
455
456
457
            if constexpr (std::is_same_v<half2_t, attn_half2_t>) {
                return input;
            } else {
                float2 fval = half22float2(input);
                return float22half2<attn_half2_t>(fval);
            }
        }

Muyang Li's avatar
Muyang Li committed
458
        __device__ __forceinline__ static packed_qkv_t pack_q(packed_fpsum_t input) {
sxtyzhangzk's avatar
sxtyzhangzk committed
459
460
461
462
463
464
465
466
            packed_qkv_t output;
            output.x = kernels::bit_cast<int>(convert_half2(input.data[0]));
            output.y = kernels::bit_cast<int>(convert_half2(input.data[1]));
            output.z = kernels::bit_cast<int>(convert_half2(input.data[2]));
            output.w = kernels::bit_cast<int>(convert_half2(input.data[3]));
            return output;
        }

Muyang Li's avatar
Muyang Li committed
467
        __device__ __forceinline__ static packed_qkv_t pack_k(packed_fpsum_t input) {
sxtyzhangzk's avatar
sxtyzhangzk committed
468
469
470
471
472
473
474
475
            packed_qkv_t output;
            output.x = kernels::bit_cast<int>(convert_half2(input.data[0]));
            output.y = kernels::bit_cast<int>(convert_half2(input.data[2]));
            output.z = kernels::bit_cast<int>(convert_half2(input.data[1]));
            output.w = kernels::bit_cast<int>(convert_half2(input.data[3]));
            return output;
        }

Muyang Li's avatar
Muyang Li committed
476
        __device__ __forceinline__ static packed_qkv_t pack_v(packed_fpsum_t input) {
sxtyzhangzk's avatar
sxtyzhangzk committed
477
478
479
480
481
482
483
484
            packed_qkv_t output;
            output.x = kernels::bit_cast<int>(convert_half2(movmatrix(input.data[0])));
            output.y = kernels::bit_cast<int>(convert_half2(movmatrix(input.data[1])));
            output.z = kernels::bit_cast<int>(convert_half2(movmatrix(input.data[2])));
            output.w = kernels::bit_cast<int>(convert_half2(movmatrix(input.data[3])));
            return output;
        }

Muyang Li's avatar
Muyang Li committed
485
        __device__ __forceinline__ static void mask(packed_qkv_t &pack, uint32_t maskVal, int m, int maxRows) {
sxtyzhangzk's avatar
sxtyzhangzk committed
486
487
488
489
490
491
492
493
494
495
496
497
498
            const int laneId = threadIdx.x % WARP_SIZE;
            if (m * INSN_M + laneId / 4 >= maxRows) {
                pack.x = maskVal;
                pack.z = maskVal;
            }
            if (m * INSN_M + laneId / 4 + 8 >= maxRows) {
                pack.y = maskVal;
                pack.w = maskVal;
            }
        }

        // qkv: [batch, head, bm, NUM_WARPS, WARP_M_TILES, WARP_N_TILES, WARP_SIZE] of packed_qkv_t
        template<typename F>
Muyang Li's avatar
Muyang Li committed
499
500
        __device__ __forceinline__ static void
        apply(fpsum_warp &fpsum, packed_qkv_t *ptr_output, int maxRows, F &&funcPack, attn_half2_t maskVal) {
sxtyzhangzk's avatar
sxtyzhangzk committed
501
502
503
504
505
506
            const int laneId = threadIdx.x % WARP_SIZE;
            const int warpId = threadIdx.x / WARP_SIZE;

            static_assert(HEAD_DIM == WARP_N);

            packed_qkv_t *ptrlane = &ptr_output[((warpId * WARP_M_TILES + 0) * WARP_N_TILES + 0) * WARP_SIZE + laneId];
Muyang Li's avatar
Muyang Li committed
507

sxtyzhangzk's avatar
sxtyzhangzk committed
508
509
510
511
512
513
514
515
516
            unrolled_loop<WARP_M_TILES>([&]<int m>() ALWAYSINLINE {
                unrolled_loop<WARP_N_TILES>([&]<int n>() ALWAYSINLINE {
                    packed_qkv_t pack = funcPack(fpsum[m * WARP_N_TILES + n]);
                    mask(pack, kernels::bit_cast<uint32_t>(maskVal), m, maxRows - warpId * WARP_M);
                    store(&ptrlane[(m * WARP_N_TILES + n) * WARP_SIZE], pack);
                });
            });
        }

Muyang Li's avatar
Muyang Li committed
517
518
        __device__ __forceinline__ void
        operator()(const BlockInfo binfo, fpsum_warp fpsum, int M, int N, int K, const Arguments &args) {
sxtyzhangzk's avatar
sxtyzhangzk committed
519
520
521
522
523
            const int bm = binfo.bm;
            const int bn = binfo.bn;

            assert(binfo.numBlocksN % 3 == 0);
            const int numBlocksQ = binfo.numBlocksN / 3;
Muyang Li's avatar
Muyang Li committed
524
525
            const bool is_q      = bn < numBlocksQ;
            const bool is_k      = !is_q && bn < numBlocksQ * 2;
sxtyzhangzk's avatar
sxtyzhangzk committed
526
527
528
529

            // bn is head_id (assume HEAD_DIM == WARP_N)
            int head_id, strideHead;
            if (is_q) {
Muyang Li's avatar
Muyang Li committed
530
                head_id    = bn;
sxtyzhangzk's avatar
sxtyzhangzk committed
531
532
                strideHead = args.strideHead_q;
            } else if (is_k) {
Muyang Li's avatar
Muyang Li committed
533
                head_id    = bn - numBlocksQ;
sxtyzhangzk's avatar
sxtyzhangzk committed
534
535
                strideHead = args.strideHead_k;
            } else {
Muyang Li's avatar
Muyang Li committed
536
                head_id    = bn - numBlocksQ * 2;
sxtyzhangzk's avatar
sxtyzhangzk committed
537
538
539
540
                strideHead = args.strideHead_v;
            }

            int block_offset = head_id * strideHead + bm * NUM_WARPS * WARP_M_TILES * WARP_N_TILES * WARP_SIZE;
Muyang Li's avatar
Muyang Li committed
541
            int maxRows      = args.actualM - bm * BLOCK_M;
sxtyzhangzk's avatar
sxtyzhangzk committed
542
543
544
545
546
547
548
549
550
551
552
553
554
555

            // static constexpr float neginf = -std::numeric_limits<float>::infinity();

            if (is_q) {
                apply(fpsum, args.out_q + block_offset, maxRows, pack_q, attn_half2_t(0.0f, 0.0f));
            } else if (is_k) {
                apply(fpsum, args.out_k + block_offset, maxRows, pack_k, attn_half2_t(NAN, NAN));
            } else {
                apply(fpsum, args.out_v + block_offset, maxRows, pack_v, attn_half2_t(0.0f, 0.0f));
            }
        }
    };

    struct EpilogueLiteLA {
Muyang Li's avatar
Muyang Li committed
556
557
558

        __device__ __forceinline__ static packed_f32psum_t
        mma_litela(packed_fpsum_t k, packed_fpsum_t v, packed_f32psum_t psum) {
sxtyzhangzk's avatar
sxtyzhangzk committed
559
560
561
562
563
564
565
566
567
            for (int i = 0; i < 4; i++) {
                k.data[i] = movmatrix(k.data[i]);
                v.data[i] = movmatrix(v.data[i]);
            }
            std::swap(v.data[1], v.data[2]);
            return mma_f16xf16_f32(v, k, psum);
        }

        static constexpr int LITELA_HEAD_DIM = 32;
Muyang Li's avatar
Muyang Li committed
568
569
        static constexpr int LITELA_K_TILES  = LITELA_HEAD_DIM / 16;
        static constexpr int LITELA_V_TILES  = LITELA_HEAD_DIM / 16;
sxtyzhangzk's avatar
sxtyzhangzk committed
570
571
572
573

        static constexpr int SHMEM_SIZE = NUM_WARPS * (LITELA_HEAD_DIM + 1) * (LITELA_HEAD_DIM + 8) * sizeof(float);

        // out_vk: [batch_size, num_heads, head_dim + 1, head_dim]
Muyang Li's avatar
Muyang Li committed
574
575
        __device__ __forceinline__ static void
        apply_litela(const BlockInfo binfo, fpsum_warp fpsum, float *out_vk, int num_blocks_per_batch) {
sxtyzhangzk's avatar
sxtyzhangzk committed
576
577
578
579
580
            const int laneId = threadIdx.x % WARP_SIZE;
            const int warpId = threadIdx.x / WARP_SIZE;

            using vk_t = float[NUM_WARPS][LITELA_HEAD_DIM + 1][LITELA_HEAD_DIM + 8];
            extern __shared__ uint8_t shmem[];
Muyang Li's avatar
Muyang Li committed
581

sxtyzhangzk's avatar
sxtyzhangzk committed
582
583
584
585
586
587
588
            vk_t &shmem_vk = *reinterpret_cast<vk_t *>(shmem);

            static_assert(sizeof(vk_t) == SHMEM_SIZE);
            static_assert(WARP_N == BLOCK_N);
            assert(binfo.numBlocksN % 3 == 0);

            const int num_heads = binfo.numBlocksN / 3 * 2 * (WARP_N / (LITELA_HEAD_DIM * 2));
Muyang Li's avatar
Muyang Li committed
589
            const int batch_id  = binfo.bm / num_blocks_per_batch;
sxtyzhangzk's avatar
sxtyzhangzk committed
590
591

            for (int head_id = 0; head_id < WARP_N / (LITELA_HEAD_DIM * 2); head_id++) {
Muyang Li's avatar
Muyang Li committed
592
593
594
595
                const int global_head_id =
                    (binfo.bn - binfo.numBlocksN / 3) * (WARP_N / (LITELA_HEAD_DIM * 2)) + head_id;
                float *out_vk_current_head =
                    out_vk + (batch_id * num_heads + global_head_id) * (LITELA_HEAD_DIM + 1) * LITELA_HEAD_DIM;
sxtyzhangzk's avatar
sxtyzhangzk committed
596
597
598
599

                for (int i = laneId; i < sizeof(shmem_vk) / sizeof(float) / NUM_WARPS; i += WARP_SIZE) {
                    *((&shmem_vk[warpId][0][0]) + i) = 0;
                }
limm's avatar
limm committed
600
601
                // __syncwarp();
		__builtin_amdgcn_wave_barrier();
sxtyzhangzk's avatar
sxtyzhangzk committed
602
603
604

                for (int tile_v = 0; tile_v < LITELA_V_TILES; tile_v++) {
                    for (int tile_k = 0; tile_k < LITELA_K_TILES; tile_k++) {
Muyang Li's avatar
Muyang Li committed
605
                        packed_f32psum_t attn_sum = {0};
sxtyzhangzk's avatar
sxtyzhangzk committed
606
607
                        for (int i = 0; i < WARP_M_TILES; i++) {
                            packed_fpsum_t k = fpsum[i * WARP_N_TILES + head_id * (LITELA_HEAD_DIM * 2) / 16 + tile_k];
Muyang Li's avatar
Muyang Li committed
608
609
                            packed_fpsum_t v = fpsum[i * WARP_N_TILES + head_id * (LITELA_HEAD_DIM * 2) / 16 +
                                                     LITELA_HEAD_DIM / 16 + tile_v];
sxtyzhangzk's avatar
sxtyzhangzk committed
610
                            for (int j = 0; j < 4; j++) {
fengzch's avatar
fengzch committed
611
612
613
614
615
616
617
618
619
620
                                __hip_bfloat162 first;
                                first.x = float(k.data[j].x);
                                first.y = float(k.data[j].y);
                                auto temp = half2_t(0, 0);
                                __hip_bfloat162 sec;
                                sec.x = float(temp.x);
                                sec.y = float(temp.y);
                                auto relu_result = __hmax2(first, sec); // relu
                                k.data[j].x = float(relu_result.x);
                                k.data[j].y = float(relu_result.y);
sxtyzhangzk's avatar
sxtyzhangzk committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
                            }
                            attn_sum = mma_litela(k, v, attn_sum);
                        }

                        const int row = tile_v * 16 + laneId / 4;
                        const int col = tile_k * 16 + laneId % 4 * 2;

                        shmem_vk[warpId][row + 0][col + 0] = attn_sum.data[0];
                        shmem_vk[warpId][row + 0][col + 1] = attn_sum.data[1];
                        shmem_vk[warpId][row + 8][col + 0] = attn_sum.data[2];
                        shmem_vk[warpId][row + 8][col + 1] = attn_sum.data[3];
                        shmem_vk[warpId][row + 0][col + 8] = attn_sum.data[4];
                        shmem_vk[warpId][row + 0][col + 9] = attn_sum.data[5];
                        shmem_vk[warpId][row + 8][col + 8] = attn_sum.data[6];
                        shmem_vk[warpId][row + 8][col + 9] = attn_sum.data[7];
                    }
                }
                for (int tile_k = 0; tile_k < LITELA_K_TILES; tile_k++) {
Muyang Li's avatar
Muyang Li committed
639
                    packed_f32psum_t attn_sum = {0};
sxtyzhangzk's avatar
sxtyzhangzk committed
640
641
642
643
                    for (int i = 0; i < WARP_M_TILES; i++) {
                        packed_fpsum_t k = fpsum[i * WARP_N_TILES + head_id * (LITELA_HEAD_DIM * 2) / 16 + tile_k];
                        packed_fpsum_t v = {};
                        for (int j = 0; j < 4; j++) {
fengzch's avatar
fengzch committed
644
645
646
647
648
649
650
651
652
653
                            __hip_bfloat162 first;
                            first.x = float(k.data[j].x);
                            first.y = float(k.data[j].y);
                            auto temp = half2_t(0, 0);
                            __hip_bfloat162 sec;
                            sec.x = float(temp.x);
                            sec.y = float(temp.y);
                            auto relu_result = __hmax2(first, sec); // relu
                            k.data[j].x = float(relu_result.x);
                            k.data[j].y = float(relu_result.y);
sxtyzhangzk's avatar
sxtyzhangzk committed
654
                        }
Muyang Li's avatar
Muyang Li committed
655
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
                        for (int i = 0; i < 4; i++) {
                            v.data[i] = half2_t(1, 1);
                        }
                        // if (laneId < 4) {
                        //     v.data[0] = half2_t(1, 1);
                        //     v.data[2] = half2_t(1, 1);
                        // }
                        // if (laneId % 4 == 0) {
                        //     v.data[0] = half2_t(1, 0);
                        //     v.data[1] = half2_t(1, 0);
                        // }
                        attn_sum = mma_litela(k, v, attn_sum);
                    }
                    const int row = LITELA_HEAD_DIM + laneId / 4;
                    const int col = tile_k * 16 + laneId % 4 * 2;

                    if (laneId < 4) {
                        shmem_vk[warpId][row + 0][col + 0] = attn_sum.data[0];
                        shmem_vk[warpId][row + 0][col + 1] = attn_sum.data[1];
                        shmem_vk[warpId][row + 0][col + 8] = attn_sum.data[4];
                        shmem_vk[warpId][row + 0][col + 9] = attn_sum.data[5];
                    }
                }
                __syncthreads();

                for (int i = warpId; i < LITELA_HEAD_DIM + 1; i += NUM_WARPS) {
                    for (int j = laneId; j < LITELA_HEAD_DIM; j += WARP_SIZE) {
                        float sum = 0;
                        for (int k = 0; k < NUM_WARPS; k++) {
                            sum += shmem_vk[k][i][j];
                        }
                        reduce_add(&out_vk_current_head[i * LITELA_HEAD_DIM + j], sum);
                    }
                }
                __syncthreads();
            }
        }

        struct Arguments {
            half_t *out_q;
            float *out_vk;
            int num_blocks_per_batch;
            int actualM;
        };

Muyang Li's avatar
Muyang Li committed
701
702
        __device__ __forceinline__ void
        operator()(const BlockInfo binfo, fpsum_warp fpsum, int M, int N, int K, const Arguments &args) {
sxtyzhangzk's avatar
sxtyzhangzk committed
703
704
705
706
            const int bm = binfo.bm;
            const int bn = binfo.bn;

            if (bn < binfo.numBlocksN / 3) {
Muyang Li's avatar
Muyang Li committed
707
708
709
710
711
712
713
714
715
716
717
                fpsum = apply_act(fpsum, [](half_t x) { return __hmax(x, 0); }); // relu
                return EpilogueDefault()(binfo,
                                         fpsum,
                                         M,
                                         N / 3,
                                         K,
                                         typename EpilogueDefault::Arguments{
                                             .out     = args.out_q,
                                             .actualM = args.actualM,
                                             .actualN = N / 3,
                                         });
sxtyzhangzk's avatar
sxtyzhangzk committed
718
719
720
721
722
723
724
725
726
            }

            return apply_litela(binfo, fpsum, args.out_vk, args.num_blocks_per_batch);
        }

        // each thread block mults BlockSize*HEAD_DIM q and (HEAD_DIM+1)*HEAD_DIM vk, in-place writes back to q
        // q:   [batch_size, #blocks, block_size, #heads, HEAD_DIM]
        // vk:  [batch_size, #heads, HEAD_DIM+1, HEAD_DIM]
        struct vk_mul_q_kernel {
fengzch-das's avatar
fengzch-das committed
727
            static constexpr int MIN_ARCH = std::is_same_v<half_t, __nv_bfloat16> ? 800 : 750;
sxtyzhangzk's avatar
sxtyzhangzk committed
728
            // FIXME FIXME FIXME
Muyang Li's avatar
Muyang Li committed
729
            __device__ void operator()(half_t *q, const float *vk, float eps, int num_tokens) {
sxtyzhangzk's avatar
sxtyzhangzk committed
730
731
732
733
734
                const int block_id = blockIdx.x;
                const int head_id  = blockIdx.y;
                const int batch_id = blockIdx.z;

                const int num_blocks = gridDim.x;
Muyang Li's avatar
Muyang Li committed
735
                const int num_heads  = gridDim.y;
sxtyzhangzk's avatar
sxtyzhangzk committed
736
737
738
739
                const int block_size = blockDim.x;

                bool pred = block_id * block_size + threadIdx.x < num_tokens;

Muyang Li's avatar
Muyang Li committed
740
741
742
                half_t *localq =
                    &q[(((batch_id * num_blocks + block_id) * block_size + threadIdx.x) * num_heads + head_id) *
                       LITELA_HEAD_DIM];
sxtyzhangzk's avatar
sxtyzhangzk committed
743
                const float *localvk = &vk[(batch_id * num_heads + head_id) * (LITELA_HEAD_DIM + 1) * LITELA_HEAD_DIM];
Muyang Li's avatar
Muyang Li committed
744
745
                // half_t *localout = &out[(((batch_id * num_blocks + block_id) * block_size + threadIdx.x) * num_heads
                // + head_id) * LITELA_HEAD_DIM];
sxtyzhangzk's avatar
sxtyzhangzk committed
746

Muyang Li's avatar
Muyang Li committed
747
                using packed_q  = std::array<half_t, 8>;
sxtyzhangzk's avatar
sxtyzhangzk committed
748
749
750
751
752
                using packed_vk = std::array<float, 4>;

                half_t qblock[LITELA_HEAD_DIM];
                for (int i = 0; i < LITELA_HEAD_DIM; i += sizeof(packed_q) / sizeof(half_t)) {
                    if (pred) {
Muyang Li's avatar
Muyang Li committed
753
754
                        *reinterpret_cast<packed_q *>(&qblock[i]) =
                            load(reinterpret_cast<const packed_q *>(&localq[i]));
sxtyzhangzk's avatar
sxtyzhangzk committed
755
756
757
758
                    }
                }

                float outblock[LITELA_HEAD_DIM + 1];
Muyang Li's avatar
Muyang Li committed
759
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
760
761
                for (int j = 0; j < LITELA_HEAD_DIM + 1; j++) {
                    outblock[j] = 0;
Muyang Li's avatar
Muyang Li committed
762
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
763
764
                    for (int i = 0; i < LITELA_HEAD_DIM; i += sizeof(packed_vk) / sizeof(float)) {
                        packed_vk vkpack = load(reinterpret_cast<const packed_vk *>(&localvk[j * LITELA_HEAD_DIM + i]));
Muyang Li's avatar
Muyang Li committed
765
#pragma unroll
sxtyzhangzk's avatar
sxtyzhangzk committed
766
767
768
769
770
                        for (int k = 0; k < vkpack.size(); k++) {
                            outblock[j] += (float)qblock[i + k] * vkpack[k];
                        }
                    }
                }
Muyang Li's avatar
Muyang Li committed
771

sxtyzhangzk's avatar
sxtyzhangzk committed
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
                for (int i = 0; i < LITELA_HEAD_DIM; i += sizeof(packed_q) / sizeof(half_t)) {
                    packed_q opack;
                    for (int k = 0; k < opack.size(); k++) {
                        opack[k] = __fdividef(outblock[i + k], outblock[LITELA_HEAD_DIM] + eps);
                    }
                    if (pred) {
                        store(reinterpret_cast<packed_q *>(&localq[i]), opack);
                    }
                }
            }
        };
    };

    template<typename Epilogue>
    struct test_epilogue_kernel {
fengzch-das's avatar
fengzch-das committed
787
        static constexpr int MIN_ARCH = std::is_same_v<half_t, __nv_bfloat16> ? 800 : 750;
Muyang Li's avatar
Muyang Li committed
788
789
        static constexpr size_t SHMEM_PER_WARP =
            ceilDiv<size_t>(Base::template load_act_to_fpsum<false>::SHMEM_SIZE, 128) * 128;
sxtyzhangzk's avatar
sxtyzhangzk committed
790
791
792
793
794
795
796
797
798
799
800
801
802
        static constexpr size_t SHMEM_SIZE = SHMEM_PER_WARP * NUM_WARPS;

        struct Arguments {
            const half_t *input;
            half_t *output;

            // aligned to BLOCK_M and BLOCK_N
            int M, N;
            int actualM, actualN;

            typename Epilogue::Arguments argsEpilogue;
        };

Muyang Li's avatar
Muyang Li committed
803
        __device__ __forceinline__ void operator()(Arguments args) {
sxtyzhangzk's avatar
sxtyzhangzk committed
804
            const BlockInfo binfo = {
Muyang Li's avatar
Muyang Li committed
805
806
                .bm         = (int)blockIdx.x,
                .bn         = (int)blockIdx.y,
sxtyzhangzk's avatar
sxtyzhangzk committed
807
808
809
810
                .numBlocksM = (int)gridDim.x,
                .numBlocksN = (int)gridDim.y,
            };

Muyang Li's avatar
Muyang Li committed
811
812
            const int bm     = binfo.bm;
            const int bn     = binfo.bn;
sxtyzhangzk's avatar
sxtyzhangzk committed
813
814
815
816
817
818
819
820
821
            const int warpId = threadIdx.x / WARP_SIZE;

            const int m_offset = bm * BLOCK_M + warpId * WARP_M;
            const int n_offset = bn * BLOCK_N;

            extern __shared__ uint8_t shmem[];

            fpsum_warp fpsum;

fengzch's avatar
fengzch committed
822
            typename Base::template load_act_to_fpsum<false>()(args.input + m_offset * args.actualN + n_offset,
Muyang Li's avatar
Muyang Li committed
823
824
825
826
827
                                                      args.actualN,
                                                      args.actualM - m_offset,
                                                      args.actualN - n_offset,
                                                      fpsum,
                                                      shmem + warpId * SHMEM_PER_WARP);
sxtyzhangzk's avatar
sxtyzhangzk committed
828
829
830

            Epilogue()(binfo, fpsum, args.M, args.N, 0, args.argsEpilogue);

Muyang Li's avatar
Muyang Li committed
831
832
833
834
835
836
837
838
839
840
            EpilogueDefault()(binfo,
                              fpsum,
                              args.M,
                              args.N,
                              0,
                              typename EpilogueDefault::Arguments{
                                  .out     = args.output,
                                  .actualM = args.actualM,
                                  .actualN = args.actualN,
                              });
sxtyzhangzk's avatar
sxtyzhangzk committed
841
842
843
844
        }
    };
};

Muyang Li's avatar
Muyang Li committed
845
}; // namespace nunchaku::kernels