File size: 17,005 Bytes
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: Apache-2.0
// msda_cm (tt/msda_cm.py): the AutoE2E spatial cross-attention as ONE kernel per layer, cell-major. Derived from
// msda_k_reader.cpp (quad maps, lean reads, head-minor strided items, fractions as 2^23 + q); this file is the data
// movement half and runs on both data-movement RISC-Vs: PART 0 (NCRISC) owns the points [0, 4) of each level,
// PART 1 (BRISC) the points [4, 8) and also writes the output tiles.
//
// Rows are the BEV cells (NQ, NB blocks of 32). Per cell up to K = 2 camera slots; the attention offsets / weights are
// the cell's own (the same for every camera that sees it: upstream gathers the same query per camera), the anchors
// per camera. Work item w (strided over the cores: w = core, core + NC, ..): b = w / H (block), j = w % H (head).
// Per item each RISC reads its header (the next item's while this item's chunks run):
//   T    int32 TILE [1, 1, NQ, 32], tile b: per row, columns 8 k + 2 a + (x, y) = the anchor a of slot k as
//        round(uv * 2^(16 + SMAX)) (level l: >> l, - 2^15 -> Q16.16 pixels of that level), column 16 + k = the
//        slot's camera (or -1), column 18 = the cell's camera count (0 .. K);
// and hands the compute kernel its raw projection tiles two items ahead (the compute kernel converts them and hands
// them back before the item's chunks):
//   off  fp32 TILE [1, 1, NQ, H * 64] (the sampling projection, 2^16-scaled), own tile b * 2 H + 2 j + PART: column
//        l * 8 + 2 q + (x, y) = the offset of point 4 PART + q of level l (tt/encoder.py orders the columns so)
//        -> back as int32 (Q16.16) in cb_off;
//   lg   fp32 TILE [1, 1, NQ, H * 32] (the attention projection), tile b * H + j (PART 0 only): column
//        16 h + 4 l + q = the logit of point 4 h + q of level l -> back as the softmax over the head's 32 columns
//        in cb_sm (one copy per RISC), whose own two faces PART, 2 + PART this RISC halves once per item on
//        2-camera rows (upstream's mean over the cameras; exact for normal numbers);
// and then runs the chunks (slot k, level l) for k < nslot (the block's largest camera count; one empty chunk when
// no camera sees the block): per chunk cb_geo <- fx, fy, attn (fp32) of own point q in column 4 q (the compute kernel
// broadcasts columns 0, 4, 8, 12 of its weight tiles) and cb_in <- per own point one [32 x 128] row-major staging
// block (one 256-byte quad page read per point and row: NW | NE | SW | SE). PART 0 pushes the chunk count to cb_ctl.
// value: quad maps per level l, [H * NCAM, HV_l + 1, WV_l + 1, 128] bf16 ROW_MAJOR, L1 interleaved; map j * NCAM + cam.
#include <stdint.h>

#include "api/dataflow/dataflow_api.h"
#include "ttnn/cpp/ttnn/kernel_lib/reduce_helpers_dataflow.hpp"
#ifdef MSDA_K_TIMING
#include "tools/profiler/kernel_profiler.hpp"
#define TNOW() reg_read(RISCV_DEBUG_REG_WALL_CLOCK_L)
#endif

constexpr uint32_t PART = get_compile_time_arg_val(0);
constexpr uint32_t cb_in = get_compile_time_arg_val(1);
constexpr uint32_t cb_geo = get_compile_time_arg_val(2);
constexpr uint32_t cb_t = get_compile_time_arg_val(3);     // own scratch: 2 T pages
constexpr uint32_t cb_out = get_compile_time_arg_val(5);
constexpr uint32_t cb_ctl = get_compile_time_arg_val(6);
constexpr uint32_t NB = get_compile_time_arg_val(7);
constexpr uint32_t NQ = get_compile_time_arg_val(8);
constexpr uint32_t H = get_compile_time_arg_val(9);
constexpr uint32_t NC = get_compile_time_arg_val(10);
constexpr uint32_t GX = get_compile_time_arg_val(11);
constexpr uint32_t WRITES_OUT = get_compile_time_arg_val(12);
constexpr uint32_t PUSHES_CTL = get_compile_time_arg_val(13);
constexpr uint32_t NCAM = get_compile_time_arg_val(14);
constexpr uint32_t K = get_compile_time_arg_val(15);
constexpr int32_t HV[4] = {get_compile_time_arg_val(16), get_compile_time_arg_val(17), get_compile_time_arg_val(18),
                           get_compile_time_arg_val(19)};
constexpr int32_t WV[4] = {get_compile_time_arg_val(20), get_compile_time_arg_val(21), get_compile_time_arg_val(22),
                           get_compile_time_arg_val(23)};
// the projection tensors' tile geometry: row stride (tiles) and first column tile of the offsets / logits (separate
// tensors: 2 H / 0 and H / 0; one merged [Q, 96 H] projection: 3 H / 0 and 3 H / 2 H)
constexpr uint32_t OFF_TW = get_compile_time_arg_val(24);
constexpr uint32_t OFF_C0 = get_compile_time_arg_val(25);
constexpr uint32_t LG_TW = get_compile_time_arg_val(26);
constexpr uint32_t LG_C0 = get_compile_time_arg_val(27);
constexpr auto t_args = TensorAccessorArgs<28>();
constexpr auto l_args = TensorAccessorArgs<t_args.next_compile_time_args_offset()>();
constexpr auto a_args = TensorAccessorArgs<l_args.next_compile_time_args_offset()>();
constexpr auto o_args = TensorAccessorArgs<a_args.next_compile_time_args_offset()>();

// the conversion CBs (the compute kernel's softmax scalers / logits; own raw off tiles, converted off, softmax)
constexpr uint32_t cb_scmax = 10, cb_scsum = 11, cb_lg = 12;
constexpr uint32_t cb_raw = PART ? 18 : 17, cb_off = PART ? 22 : 21, cb_sm = PART ? 24 : 23;

constexpr uint32_t P = 8;                 // points per level
constexpr uint32_t PH = P / 2;
constexpr uint32_t NS = PH * 4;           // staging tiles per chunk and RISC
constexpr uint32_t TB16 = 2048, TB32 = 4096, QPAGE = 256, FACE32 = 1024;
constexpr uint32_t NWORK = NB * H;
static_assert(K >= 1 && K <= 2, "msda_cm: 1 or 2 camera slots");

constexpr uint32_t FRAC0 = 0x4B000000u;   // fp32 2^23: the compute kernel takes (f - 2^23) * 2^-16
static inline uint32_t q16_frac(uint32_t q) { return FRAC0 | q; }
// x / 2 for an fp32 softmax weight (exact for normal numbers; the tiny denormal ones become 0)
static inline uint32_t half_bits(uint32_t v) { return ((v >> 23) & 0xFF) > 1 ? v - 0x800000u : 0u; }

static inline void zero_l1(uint32_t addr, uint32_t bytes) {
    const uint64_t z = get_noc_addr(MEM_ZEROS_BASE);
    for (uint32_t o = 0; o < bytes; o += MEM_ZEROS_SIZE) {
        noc_async_read(z, addr + o, MEM_ZEROS_SIZE);
    }
}
static inline void quad_read(uint32_t xy, uint32_t src, uint32_t dst) {
    while (!noc_cmd_buf_ready(noc_index, read_cmd_buf));
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_RET_ADDR_LO, dst);
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_LO, src);
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_COORDINATE, xy);
    NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_CMD_CTRL, NOC_CTRL_SEND_REQ);
}

// one chunk (slot k, level L) of own points: geo + reads; returns the number of reads issued
template <uint32_t L>
static inline uint32_t chunk(const int32_t* T, const int32_t* OFF, const uint32_t* SM, uint32_t* fx, uint32_t* fy,
                             uint32_t* at, uint32_t k, uint32_t nslot, uint32_t rows, uint32_t jcam, uint32_t mbase,
                             uint32_t in_base) {
    constexpr int32_t hv = HV[L], wv = WV[L];
    constexpr uint32_t wv1 = static_cast<uint32_t>(wv + 1);
    constexpr uint32_t plane = static_cast<uint32_t>((hv + 1) * (wv + 1));
    constexpr uint32_t OFFL = (L >> 1) * 256 + (L & 1) * 8;    // element of (row 0, level L) in the off tile
    constexpr uint32_t ATTL = L * 4;                            // column of level L in the own faces of cb_sm
    uint32_t nrd = 0;
    for (uint32_t r = 0; r < 32; ++r) {
        const uint32_t rb = ((r >> 4) << 9) + ((r & 15) << 4);      // element of (r, 0) in a full tile
        const int32_t cam = nslot ? T[rb + 256 + k] : -1;
        if (!(r < rows && cam >= 0)) {
#pragma GCC unroll 4
            for (uint32_t q = 0; q < PH; ++q) {
                at[rb + 4 * q] = 0;     // fx / fy keep earlier finite values: the weights are 0
            }
            continue;
        }
        const uint32_t pbase = (jcam + static_cast<uint32_t>(cam)) * plane + wv1 + 1;   // + (y0 * (wv + 1) + x0)
        const int32_t* tk = T + rb + 8 * k;
        const int32_t* orow = OFF + rb + OFFL;
        const uint32_t* arow = SM + ((((r >> 4) << 1) + PART) << 8) + ((r & 15) << 4) + ATTL;
        const uint32_t sbase = in_base + r * QPAGE;
#pragma GCC unroll 4
        for (uint32_t q = 0; q < PH; ++q) {
            const int32_t vx = ((tk[2 * q] >> L) - 32768) + orow[2 * q];
            const int32_t vy = ((tk[2 * q + 1] >> L) - 32768) + orow[2 * q + 1];
            const int32_t x0 = vx >> 16;
            const int32_t y0 = vy >> 16;
            // all four corners outside <=> x0 + 1 not in [0, wv] or y0 + 1 not in [0, hv]
            if (static_cast<uint32_t>(x0 + 1) > static_cast<uint32_t>(wv) ||
                static_cast<uint32_t>(y0 + 1) > static_cast<uint32_t>(hv)) {
                at[rb + 4 * q] = 0;
                continue;
            }
            fx[rb + 4 * q] = q16_frac(static_cast<uint32_t>(vx) & 0xFFFF);
            fy[rb + 4 * q] = q16_frac(static_cast<uint32_t>(vy) & 0xFFFF);
            at[rb + 4 * q] = arow[q];
#ifdef MSDA_K_NOREAD
            continue;
#endif
            const uint32_t pg = pbase + static_cast<uint32_t>(y0) * wv1 + static_cast<uint32_t>(x0);
            const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg);
            const uint32_t bank = pg - row * NUM_L1_BANKS;
            quad_read(l1_bank_to_noc_xy[noc_index][bank], mbase + row * QPAGE + bank_to_l1_offset[bank],
                      sbase + q * 4 * TB16);
            nrd += 1;
        }
    }
    return nrd;
}

void kernel_main() {
    const uint32_t ci = get_absolute_logical_y() * GX + get_absolute_logical_x();
    if (ci >= NC || ci >= NWORK) {
        return;
    }
    const auto t_acc = TensorAccessor(t_args, get_common_arg_val<uint32_t>(0), TB32);
    const auto l_acc = TensorAccessor(l_args, get_common_arg_val<uint32_t>(1), TB32);
    const auto a_acc = TensorAccessor(a_args, get_common_arg_val<uint32_t>(2), TB32);
    const auto o_acc = TensorAccessor(o_args, get_common_arg_val<uint32_t>(3), TB16);
    const uint32_t maddr[4] = {get_common_arg_val<uint32_t>(4), get_common_arg_val<uint32_t>(5),
                               get_common_arg_val<uint32_t>(6), get_common_arg_val<uint32_t>(7)};

    // the geo pages and the staging blocks: zero once (unwritten columns stay 0 / finite)
    cb_reserve_back(cb_geo, 6);
    zero_l1(get_write_ptr(cb_geo), 6 * TB32);
    cb_reserve_back(cb_in, 2 * NS);
    zero_l1(get_write_ptr(cb_in), 2 * NS * TB16);
    if constexpr (PUSHES_CTL) {
        // the softmax's reduce scalers, as ttnn's softmax reader makes them
        dataflow_kernel_lib::calculate_and_prepare_reduce_scaler<cb_scmax, ckernel::PoolType::MAX,
                                                                 ckernel::ReduceDim::REDUCE_ROW>();
        dataflow_kernel_lib::calculate_and_prepare_reduce_scaler<cb_scsum, ckernel::PoolType::SUM,
                                                                 ckernel::ReduceDim::REDUCE_ROW>();
    }
    // two T sets: the next item's T is read while this item's chunks run
    cb_reserve_back(cb_t, 2);
    const uint32_t sbuf = get_write_ptr(cb_t);
    noc_async_read_barrier();
    // the raw projection tiles of item w into the next free page of cb_raw (and cb_lg)
    auto raw = [&](uint32_t w) {
        const uint32_t b = w / H;
        const uint32_t j = w - b * H;
        cb_reserve_back(cb_raw, 1);
        noc_async_read(l_acc.get_noc_addr(b * OFF_TW + OFF_C0 + 2 * j + PART), get_write_ptr(cb_raw), TB32);
        if constexpr (PUSHES_CTL) {
            cb_reserve_back(cb_lg, 1);
            noc_async_read(a_acc.get_noc_addr(b * LG_TW + LG_C0 + j), get_write_ptr(cb_lg), TB32);
        }
    };
    auto raw_push = [&]() {
        cb_push_back(cb_raw, 1);
        if constexpr (PUSHES_CTL) {
            cb_push_back(cb_lg, 1);
        }
    };
#ifdef MSDA_K_TIMING
    uint32_t t_res = 0, t_loop = 0, t_bar = 0, t_out = 0, t_hdr = 0, t0, t1;
#endif

    uint32_t prev = 0xFFFFFFFF;
    uint32_t set = 0;
    // item ci's raw tiles and T, then item ci + NC's raw tiles in flight (the compute kernel converts item w + NC
    // before it takes item w's chunks)
    noc_async_read(t_acc.get_noc_addr(ci / H), sbuf, TB32);
    raw(ci);
    noc_async_read_barrier();
    raw_push();
    if (ci + NC < NWORK) {
        raw(ci + NC);
    }
    for (uint32_t w = ci; w < NWORK; w += NC) {
        const uint32_t b = w / H;
        const uint32_t j = w - b * H;
#ifdef MSDA_K_TIMING
        t0 = TNOW();
#endif
        noc_async_read_barrier();
        const uint32_t tbase = sbuf + set * TB32;
        if (w + NC < NWORK) {
            raw_push();
            noc_async_read(t_acc.get_noc_addr((w + NC) / H), sbuf + (set ^ 1) * TB32, TB32);
            if (w + 2 * NC < NWORK) {
                raw(w + 2 * NC);
            }
        }
        set ^= 1;
        int32_t* T = reinterpret_cast<int32_t*>(tbase);
        cb_wait_front(cb_off, 1);
        cb_wait_front(cb_sm, 1);
        const int32_t* OFF = reinterpret_cast<const int32_t*>(get_read_ptr(cb_off));
        uint32_t* const SM = reinterpret_cast<uint32_t*>(get_read_ptr(cb_sm));
        const uint32_t rows = NQ - b * 32 < 32 ? NQ - b * 32 : 32;
        uint32_t nslot = 0;
        for (uint32_t r = 0; r < rows; ++r) {
            const uint32_t c = static_cast<uint32_t>(T[((r >> 4) << 9) + ((r & 15) << 4) + 256 + 2]);
            nslot = c > nslot ? c : nslot;
            if (c >= 2) {
                // upstream's mean over the 2 cameras: the row's 16 own weights halved once per item
                uint32_t* arow = SM + ((((r >> 4) << 1) + PART) << 8) + ((r & 15) << 4);
#pragma GCC unroll 16
                for (uint32_t i = 0; i < 16; ++i) {
                    arow[i] = half_bits(arow[i]);
                }
            }
        }
        nslot = nslot > K ? K : nslot;
        const uint32_t nch = nslot ? nslot * 4 : 1;
        if constexpr (PUSHES_CTL) {
            cb_reserve_back(cb_ctl, 1);
            reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_ctl))[0] = nch;
            cb_push_back(cb_ctl, 1);
        }
#ifdef MSDA_K_TIMING
        t1 = TNOW();
        t_hdr += t1 - t0;
#endif
        const uint32_t jcam = j * NCAM;
        for (uint32_t ch = 0; ch < nch; ++ch) {
            const uint32_t k = ch >> 2;
            const uint32_t l = ch & 3;
#ifdef MSDA_K_TIMING
            t0 = TNOW();
#endif
            cb_reserve_back(cb_geo, 3);
            cb_reserve_back(cb_in, NS);
#ifdef MSDA_K_TIMING
            t1 = TNOW();
            t_res += t1 - t0;
#endif
#ifdef MSDA_K_RDNONE
            // probe: hand the compute kernel the chunk's pages without any reader work
            cb_push_back(cb_geo, 3);
            cb_push_back(cb_in, NS);
            continue;
#endif
            const uint32_t g_addr = get_write_ptr(cb_geo);
            const uint32_t in_base = get_write_ptr(cb_in);
            uint32_t* fx = reinterpret_cast<uint32_t*>(g_addr);
            uint32_t* fy = reinterpret_cast<uint32_t*>(g_addr + TB32);
            uint32_t* at = reinterpret_cast<uint32_t*>(g_addr + 2 * TB32);
            noc_async_read_one_packet_set_state(get_noc_addr(MEM_ZEROS_BASE), QPAGE);
            uint32_t nrd;
            if (l == 0) {
                nrd = chunk<0>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[0], in_base);
            } else if (l == 1) {
                nrd = chunk<1>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[1], in_base);
            } else if (l == 2) {
                nrd = chunk<2>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[2], in_base);
            } else {
                nrd = chunk<3>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[3], in_base);
            }
            asm volatile("" ::: "memory");
            noc_reads_num_issued[noc_index] += nrd;
#ifdef MSDA_K_TIMING
            t0 = TNOW();
            t_loop += t0 - t1;
#endif
            noc_async_read_barrier();
#ifdef MSDA_K_TIMING
            t1 = TNOW();
            t_bar += t1 - t0;
#endif
            cb_push_back(cb_geo, 3);
            cb_push_back(cb_in, NS);
        }
        cb_pop_front(cb_off, 1);
        cb_pop_front(cb_sm, 1);
        if constexpr (WRITES_OUT) {
            if (prev != 0xFFFFFFFF) {
#ifdef MSDA_K_TIMING
                t0 = TNOW();
#endif
                cb_wait_front(cb_out, 1);
#ifdef MSDA_K_TIMING
                t_out += TNOW() - t0;
#endif
                noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16);
                noc_async_writes_flushed();
                cb_pop_front(cb_out, 1);
            }
        }
        prev = w;
    }
    if constexpr (WRITES_OUT) {
        cb_wait_front(cb_out, 1);
        noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16);
        noc_async_write_barrier();
        cb_pop_front(cb_out, 1);
    }
#ifdef MSDA_K_TIMING
    DeviceTimestampedData("res", t_res);
    DeviceTimestampedData("hdr", t_hdr);
    DeviceTimestampedData("loop", t_loop);
    DeviceTimestampedData("bar", t_bar);
    DeviceTimestampedData("out", t_out);
#endif
}