File size: 15,553 Bytes
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
31ffdfe
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
7b01b36
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
31ffdfe
7b01b36
 
 
31ffdfe
 
 
 
 
 
 
 
7b01b36
 
 
31ffdfe
7b01b36
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
31ffdfe
 
 
 
7b01b36
 
 
31ffdfe
7b01b36
 
 
31ffdfe
 
 
7b01b36
31ffdfe
 
7b01b36
 
 
31ffdfe
7b01b36
31ffdfe
7b01b36
 
 
31ffdfe
 
 
 
 
 
 
7b01b36
 
 
 
31ffdfe
 
7b01b36
 
 
31ffdfe
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
7b01b36
 
 
 
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
 
 
31ffdfe
7b01b36
 
 
 
 
 
 
 
31ffdfe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
139
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// SPDX-License-Identifier: Apache-2.0
// msda_k (tt/msda_k.py), compute. Per work item (32 queries x one head block; see msda_k_reader.cpp):
//   1. for each half h (the points of RISC h): DEST0..2 <- cb_geo_h (fx, fy, attn; fp32, UnpackToDestFp32); SFPU:
//      W_c = a * wx * wy for the 4 corners (fp32) -> cb_w pages 4h .. 4h + 3 (fp32).
//   2. for each step (point p, corner c): DEST0 = W_{h,c} @ E_p (broadcast of column p over the 32 channels, exact),
//      DEST0 *= V (the gathered bf16 value tile; DEST -> SrcB reuse), packer L1 accumulation into cb_acc (fp32).
//   3. cb_acc (fp32, UnpackToDestFp32) -> bf16 -> cb_out.
// CBs: cb_geo_h 3 pages / item (6 total), cb_in_h 2P pages / item (4P total), cb_w 8 (once per item), cb_acc 1,
// cb_e P (waited once), cb_out 1 per item (2 total).
#include <cstdint>

#include "api/compute/common.h"
#include "api/compute/compute_kernel_api.h"
#include "api/compute/compute_kernel_hw_startup.h"
#include "api/compute/eltwise_binary.h"
#include "api/compute/matmul.h"
#include "api/compute/pack.h"
#include "api/compute/reconfig_data_format.h"
#include "api/compute/tile_move_copy.h"
#include "api/compute/tilize.h"
#include "api/compute/bcast.h"
#include "api/compute/reduce.h"
#include "api/compute/softmax.h"
#include "ttnn/cpp/ttnn/kernel_lib/reduce_helpers_compute.hpp"
#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/chain.hpp"
#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/convenience.hpp"
#include "ttnn/cpp/ttnn/kernel_lib/eltwise/unary/math.hpp"
#ifdef MSDA_K_TIMING
#include "tools/profiler/kernel_profiler.hpp"
#define TNOW() reg_read(RISCV_DEBUG_REG_WALL_CLOCK_L)
#endif

#if defined(TRISC_MATH)
#include "llk_math_eltwise_unary_sfpu_macros.h"
#include "sfpi.h"

namespace ckernel::sfpu {
// DEST tiles 0, 1, 2 = fx, fy, attn -> tiles 0..3 = the NW, NE, SW, SE weights (one face per call)
// fx / fy arrive as the fp32 2^23 + q (q the 16-bit fraction, msda_k_reader.cpp): (f - 2^23) * 2^-16 is exact
inline void msda_k_w_face() {
#pragma GCC unroll 2
    for (int d = 0; d < 8; d++) {
        sfpi::vFloat fx = (sfpi::dst_reg[0] - 8388608.0f) * 0.0000152587890625f;
        sfpi::vFloat fy = (sfpi::dst_reg[32] - 8388608.0f) * 0.0000152587890625f;
        sfpi::vFloat a = sfpi::dst_reg[64];
        sfpi::vFloat gx = 1.0f - fx;
        sfpi::vFloat ay0 = a * (1.0f - fy);
        sfpi::vFloat ay1 = a * fy;
        sfpi::dst_reg[0] = gx * ay0;
        sfpi::dst_reg[32] = fx * ay0;
        sfpi::dst_reg[64] = gx * ay1;
        sfpi::dst_reg[96] = fx * ay1;
        sfpi::dst_reg++;
    }
}
// SM: DEST 0, 1, 2, 3 = fx, fy, softmax, half mask -> attn = softmax * mask (exact: x 1 or x 0), then as above
inline void msda_k_w_face_sm() {
#pragma GCC unroll 2
    for (int d = 0; d < 8; d++) {
        sfpi::vFloat fx = (sfpi::dst_reg[0] - 8388608.0f) * 0.0000152587890625f;
        sfpi::vFloat fy = (sfpi::dst_reg[32] - 8388608.0f) * 0.0000152587890625f;
        sfpi::vFloat a = sfpi::dst_reg[64] * sfpi::dst_reg[96];
        sfpi::vFloat gx = 1.0f - fx;
        sfpi::vFloat ay0 = a * (1.0f - fy);
        sfpi::vFloat ay1 = a * fy;
        sfpi::dst_reg[0] = gx * ay0;
        sfpi::dst_reg[32] = fx * ay0;
        sfpi::dst_reg[64] = gx * ay1;
        sfpi::dst_reg[96] = fx * ay1;
        sfpi::dst_reg++;
    }
}
}  // namespace ckernel::sfpu
#endif

#if defined(TRISC_UNPACK)
// llk_unpack_AB<COL> with srcB read ofs16 x 16 bytes past the tile (see msda_cm_compute.cpp)
inline void unpack_ab_col_ofs(uint32_t cba, uint32_t cbb, uint32_t ta, uint32_t tb, uint32_t ofs16) {
    const uint32_t ida = get_operand_id(cba);
    const uint32_t idb = get_operand_id(cbb);
    const uint32_t aa = get_local_cb_interface(ida).fifo_rd_ptr - 1 + get_local_cb_interface(ida).fifo_page_size * ta;
    const uint32_t ab =
        get_local_cb_interface(idb).fifo_rd_ptr - 1 + get_local_cb_interface(idb).fifo_page_size * tb + ofs16;
    llk_unpack_AB_impl<BroadcastType::COL>(aa, ab, 0, unpack_src_format[idb]);
}
#endif

namespace ckl = compute_kernel_lib;

constexpr uint32_t P = get_compile_time_arg_val(1);
constexpr uint32_t NWORK = get_compile_time_arg_val(2);
constexpr uint32_t NC = get_compile_time_arg_val(3);
constexpr uint32_t GX = get_compile_time_arg_val(4);
constexpr uint32_t SKIP = get_compile_time_arg_val(5);   // strided items (msda_k_reader.cpp)
// SM (BEVFORMER_MSDA_SOFTMAX=kernel): the softmax of the head's logit tile (cb_lg, from the reader) runs here, the
// same LLK sequence (and CB formats / unpack modes) as ttnn.softmax(numeric_stable) on one fp32 tile (attention
// softmax.cpp, Wt = 1, block 1): row max -> x - max, exp -> row sum, 1 / sum -> x * (1 / sum)
constexpr uint32_t SM = get_compile_time_arg_val(6);
// PAIRS (VSRC 2): the readers deliver each point's corners as two [32 x 64] row-major blocks (NW | NE, SW | SE);
// they are tilized (exact) into cb_tl0 / cb_tl1 in the step order (point, corner) before the steps
constexpr uint32_t PAIRS = get_compile_time_arg_val(7);
constexpr uint32_t cb_tl0 = 19, cb_tl1 = 20;
constexpr uint32_t cb_in0 = 0, cb_in1 = 1, cb_geo0 = 2, cb_geo1 = 3, cb_e = 4, cb_w = 5, cb_acc = 6, cb_out = 16;
constexpr uint32_t cb_lg = 9, cb_scmax = 10, cb_scsum = 11, cb_msk = 12, cb_sm = 13, cb_max = 14, cb_exps = 15,
                   cb_rsum = 17;

static inline void softmax_tile() {
    reconfig_data_format(cb_lg, cb_lg);
    pack_reconfig_data_format(cb_exps);
    copy_init(cb_lg);
    compute_kernel_lib::reduce<PoolType::MAX, ReduceDim::REDUCE_ROW, cb_lg, cb_scmax, cb_max,
                               compute_kernel_lib::ReduceInputPolicy::WaitUpfrontNoPop,
                               compute_kernel_lib::ReduceDataFormatReconfigMode::INPUT>(
        compute_kernel_lib::ReduceInputBlockShape::row(1));
    ckl::eltwise_chain(
        ckl::IterationShape::tiles(1).block_size(1),
        ckl::BinaryFpu<ckl::BinaryFpuOp::Sub,
                       ckl::input(cb_lg, ckl::WaitPolicy::Upfront, ckl::PopPolicy::AtEnd, ckl::InputTileMapping::Block,
                                  ckl::DataFormatReconfig::Disabled),
                       ckl::input(cb_max, ckl::BroadcastDim::Col, ckl::WaitPolicy::Upfront, ckl::PopPolicy::AtEnd)>{},
        ckl::Exp<static_cast<ckl::Approx>(0), ckl::Dst::D0>{},
        ckl::PackTile<ckl::output(cb_exps, ckl::ReservePolicy::PerBlockSize, ckl::PushPolicy::PerBlockSize,
                                  ckl::DataFormatReconfig::Disabled)>{});
    cb_wait_front(cb_exps, 1);
    compute_kernel_lib::reduce<PoolType::SUM, ReduceDim::REDUCE_ROW, cb_exps, cb_scsum, cb_rsum,
                               compute_kernel_lib::ReduceInputPolicy::WaitUpfrontNoPop>(
        compute_kernel_lib::ReduceInputBlockShape::row(1), compute_kernel_lib::ReduceInputMemoryLayout::contiguous(),
        compute_kernel_lib::NoAccumulation{}, [](uint32_t) {
            recip_tile_init<ReciprocalDestAcc::FP32, ReciprocalApproxMode::Precise>();
            recip_tile<ReciprocalDestAcc::FP32, ReciprocalApproxMode::Precise>(0);
        });
    ckl::mul<ckl::input(cb_exps, ckl::WaitPolicy::Upfront, ckl::PopPolicy::AtEnd, ckl::InputTileMapping::Block),
             ckl::input(cb_rsum, ckl::BroadcastDim::Col, ckl::WaitPolicy::Upfront, ckl::PopPolicy::AtEnd),
             ckl::output(cb_sm, ckl::ReservePolicy::PerBlockSize, ckl::PushPolicy::PerBlockSize)>(
        ckl::IterationShape::tiles(1).block_size(1));
}
constexpr uint32_t PH = P / 2;
constexpr uint32_t NS = PH * 4;

void kernel_main() {
    const uint32_t ci = get_absolute_logical_y() * GX + get_absolute_logical_x();
    if (ci >= NC) {
        return;
    }
    const uint32_t w0 = SKIP ? ci : ci * NWORK / NC;
    const uint32_t w1 = SKIP ? NWORK : (ci + 1) * NWORK / NC;
    const uint32_t wstep = SKIP ? NC : 1;
    if (w0 >= w1) {
        return;
    }
    if constexpr (SM) {
        compute_kernel_hw_startup(cb_lg, cb_scmax, cb_exps);
        cb_wait_front(cb_scmax, 1);
        cb_wait_front(cb_scsum, 1);
        cb_wait_front(cb_msk, 2);
    } else {
        compute_kernel_hw_startup(cb_geo0, cb_geo0, cb_w);
    }
    cb_wait_front(cb_e, P);
#ifdef MSDA_K_TIMING
    uint32_t t_geo = 0, t_in = 0, t_w = 0, t_tl = 0, t_st = 0, t_fin = 0, t0, t1;
#endif
    for (uint32_t w = w0; w < w1; w += wstep) {
#ifdef MSDA_K_TIMING
        t1 = TNOW();
#endif
        if constexpr (SM) {
            softmax_tile();
            cb_wait_front(cb_sm, 1);
        }
        // ---- 1. corner weights
        cb_reserve_back(cb_w, 8);
        for (uint32_t h = 0; h < 2; ++h) {
            const uint32_t cg = h ? cb_geo1 : cb_geo0;
#ifdef MSDA_K_TIMING
            t0 = TNOW();
#endif
            cb_wait_front(cg, 3);
#ifdef MSDA_K_TIMING
            t_geo += TNOW() - t0;
#endif
            tile_regs_acquire();
            reconfig_data_format_srca(cg);
            copy_init(cg);
            copy_tile(cg, 0, 0);
            copy_tile(cg, 1, 1);
            if constexpr (SM) {
                reconfig_data_format_srca(cb_sm);
                copy_init(cb_sm);
                copy_tile(cb_sm, 0, 2);
                reconfig_data_format_srca(cb_msk);
                copy_init(cb_msk);
                copy_tile(cb_msk, h, 3);
                MATH((SFPU_UNARY_INIT(unused)));
                MATH((SFPU_UNARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, msda_k_w_face_sm, 0,
                                                      SM == 2 ? VectorMode::RC : VectorMode::C)));
            } else {
                copy_tile(cg, 2, 2);
                MATH((SFPU_UNARY_INIT(unused)));
                MATH((SFPU_UNARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, msda_k_w_face, 0,
                                                      VectorMode::C)));   // point columns < 16 (no joint mode here)
            }
            tile_regs_commit();
            tile_regs_wait();
            pack_reconfig_data_format(cb_w);
            for (uint32_t c = 0; c < 4; ++c) {
                pack_tile<true>(c, cb_w, h * 4 + c);
            }
            tile_regs_release();
            cb_pop_front(cg, 3);
        }
        cb_push_back(cb_w, 8);
        if constexpr (SM) {
            cb_pop_front(cb_sm, 1);
        }
        cb_wait_front(cb_w, 8);
#ifdef MSDA_K_TIMING
        t0 = TNOW();
        t_w += t0 - t1;
#endif
        if constexpr (PAIRS) {
            for (uint32_t h = 0; h < 2; ++h) {
                const uint32_t cin = h ? cb_in1 : cb_in0;
                const uint32_t ct = h ? cb_tl1 : cb_tl0;
#ifdef MSDA_K_TIMING
                t1 = TNOW();
#endif
                cb_wait_front(cin, NS);
#ifdef MSDA_K_TIMING
                t_in += TNOW() - t1;
#endif
                cb_reserve_back(ct, NS);
                reconfig_data_format_srca(cin);
                pack_reconfig_data_format(ct);
                constexpr uint32_t BW = 2 * PAIRS;   // tiles per staging block: 2 (pair rows), 4 (quad rows)
#ifdef MSDA_K_FAST_TILIZE
                // BEVFORMER_MSDA_TILIZE=fast: the BH fast tilize (a lossless bf16 reorder)
                fast_tilize_init(cin, BW, ct);
                for (uint32_t bk = 0; bk < NS / BW; ++bk) {
                    fast_tilize_block(cin, BW, ct, BW * bk, BW * bk);
                }
                fast_tilize_uninit(cin, ct, BW);
#else
                tilize_init(cin, BW, ct);
                for (uint32_t bk = 0; bk < NS / BW; ++bk) {
                    tilize_block(cin, BW, ct, BW * bk, BW * bk);
                }
                tilize_uninit(cin, ct);
#endif
                cb_push_back(ct, NS);
                cb_pop_front(cin, NS);
            }
        }
#ifdef MSDA_K_TIMING
        t1 = TNOW();
        t_tl += t1 - t0;
#endif
        // ---- 2. the 4P (point, corner) steps
        cb_reserve_back(cb_acc, 1);
#ifdef MSDA_K_COLB
        reconfig_data_format(cb_tl0, cb_w);
#else
        reconfig_data_format_srca(cb_e);
        reconfig_data_format_srcb(cb_w);
#endif
        pack_reconfig_data_format(cb_acc);
        for (uint32_t h = 0; h < 2; ++h) {
            const uint32_t ci_ = PAIRS ? (h ? cb_tl1 : cb_tl0) : (h ? cb_in1 : cb_in0);
            cb_wait_front(ci_, NS);
#ifdef MSDA_K_NOSTEPS
            for (uint32_t k = 0; k < 4; k += 4) {
#else
            for (uint32_t k = 0; k < NS; k += 4) {
#endif
                // AutoE2E: the 4 corners of point p in one DEST acquire (4 fp32 tiles in half-sync): one matmul
                // init + 4 broadcasts, one mul init + 4 products, 4 packs with L1 accumulation (the same products and
                // the same fp32 sum order as one step per acquire; 2 inits and 1 sync per 4 steps instead of 8 / 4)
                const uint32_t p = h * PH + (k >> 2);
                tile_regs_acquire();
#ifdef MSDA_K_COLB
                // DEST[c] = V_{p, c} * (column 4 p of W_{h, c} broadcast over the 32 channels)
                if (k == 0) {
                    mul_bcast_cols_init(ci_, cb_w);
                }
                for (uint32_t c = 0; c < 4; ++c) {
                    MATH((llk_math_eltwise_binary<EltwiseBinaryType::ELWMUL, BroadcastType::COL, DST_ACCUM_MODE,
                                                  MATH_FIDELITY, EltwiseBinaryReuseDestType::NONE>(ci_, cb_w, c, true)));
                    UNPACK((unpack_ab_col_ofs(ci_, cb_w, k + c, h * 4 + c, p)));
                }
                tile_regs_commit();
                tile_regs_wait();
                // L1 accumulation switched only where its state changes (each switch stalls the packer)
                uint32_t c0 = 0;
                if (h == 0 && k == 0) {
                    pack_tile<true>(0, cb_acc, 0);
                    pack_reconfig_l1_acc(1);
                    c0 = 1;
                }
                for (uint32_t c = c0; c < 4; ++c) {
                    pack_tile<true>(c, cb_acc, 0);
                }
#else
                matmul_init(cb_w, cb_e);
                for (uint32_t c = 0; c < 4; ++c) {
                    matmul_tiles(cb_w, cb_e, h * 4 + c, p, c);
                }
                mul_reuse_dest_init<EltwiseBinaryReuseDestType::DEST_TO_SRCB>(ci_);
                for (uint32_t c = 0; c < 4; ++c) {
                    mul_reuse_dest_tiles<EltwiseBinaryReuseDestType::DEST_TO_SRCB>(ci_, k + c, c);
                }
                tile_regs_commit();
                tile_regs_wait();
                for (uint32_t c = 0; c < 4; ++c) {
                    pack_reconfig_l1_acc((h == 0 && k == 0 && c == 0) ? 0 : 1);
                    pack_tile<true>(c, cb_acc, 0);
                }
#endif
                tile_regs_release();
            }
            cb_pop_front(ci_, NS);
        }
        pack_reconfig_l1_acc(0);
        cb_push_back(cb_acc, 1);
        cb_pop_front(cb_w, 8);
#ifdef MSDA_K_TIMING
        t0 = TNOW();
        t_st += t0 - t1;
#endif
        // ---- 3. fp32 sum -> bf16 output tile
        cb_wait_front(cb_acc, 1);
        cb_reserve_back(cb_out, 1);
        tile_regs_acquire();
        reconfig_data_format_srca(cb_acc);
        copy_init(cb_acc);
        copy_tile(cb_acc, 0, 0);
        tile_regs_commit();
        tile_regs_wait();
        pack_reconfig_data_format(cb_out);
        pack_tile(0, cb_out);
        tile_regs_release();
        cb_push_back(cb_out, 1);
        cb_pop_front(cb_acc, 1);
#ifdef MSDA_K_TIMING
        t_fin += TNOW() - t0;
#endif
    }
#ifdef MSDA_K_TIMING
    DeviceTimestampedData("geo", t_geo);
    DeviceTimestampedData("in", t_in);
    DeviceTimestampedData("w", t_w);
    DeviceTimestampedData("tl", t_tl);
    DeviceTimestampedData("st", t_st);
    DeviceTimestampedData("fin", t_fin);
#endif
}