File size: 10,887 Bytes
5528e28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: Apache-2.0
// MK-S level megakernel (tt/sparse_mks.py, OPT_PLAN 3.3 MK-S (a)), reader (RISCV_1 / NCRISC).
//
// One persistent program runs the NL sub-manifold layers of one encoder level (same K, CIN_T = COUT_T, same index
// map): the K6 layer (k6_reader.cpp) inside a layer loop. Per layer l: its bias tiles -> CB_BIAS (2 COUT_T pages:
// layer l + 1's bias is read while layer l computes), its chunk weights -> CB_W (multicast along the grid row, as
// K6; CB_W holds 1 or 2 layers' chunks, so layer l + 1's first chunk is read and multicast during layer l's tail),
// then -- after the grid barrier that ends layer l - 1 (go semaphore 3 >= l, monotonic, released by core 0's
// writer; reset at the end) -- the gathers of
// the even-rank present taps from layer l's input table, and the identity tiles of layer l (RES_MASK).
// The index rows are the same map for every layer: the prefetch of (layer, chunk, block) runs across layer ends.
//
// CT args: [0] per-core RT-arg count (P3) [1] K [2] CIN_T [3] COUT_T [4] NCH [5] TG [6] NBLK [7] NC [8] SENT
//          [9] RES_MASK (bit l: layer l adds an identity) [10] DEAD_SKIP [11] MCAST [12] NRECV [13] NL
//          then the TensorAccessorArgs of the tables (all L1 interleaved), index, weights, biases, identities.
// Common RT args: per layer l, 6 words at 6 l: [table_in, table_out, weight, bias, identity, y]; then the index.
// Per-core RT args: [me, is_sender, sender x, y, the receivers' rectangle x0, y0, x1, y1] (as K6).
// Semaphores: 0 ready, 1 valid (weight multicast, as K6), 2 arrivals (core 0), 3 reader go, 4 writer go.
#include <cstdint>

#include "api/dataflow/dataflow_api.h"
#include "k6_gather.hpp"
#ifdef MKS_ZONES
#include "tools/profiler/kernel_profiler.hpp"
#define MKS_ZONE(n) DeviceZoneScopedN(n)
#else
#define MKS_ZONE(n)
#endif

constexpr uint32_t K = get_compile_time_arg_val(1);
constexpr uint32_t CIN_T = get_compile_time_arg_val(2);
constexpr uint32_t COUT_T = get_compile_time_arg_val(3);
constexpr uint32_t NCH = get_compile_time_arg_val(4);
constexpr uint32_t TG = get_compile_time_arg_val(5);
constexpr uint32_t NBLK = get_compile_time_arg_val(6);
constexpr uint32_t NC = get_compile_time_arg_val(7);
constexpr uint32_t SENT = get_compile_time_arg_val(8);
constexpr uint32_t RES_MASK = get_compile_time_arg_val(9);
constexpr uint32_t DEAD_SKIP = get_compile_time_arg_val(10);
constexpr uint32_t MCAST = get_compile_time_arg_val(11);
constexpr uint32_t NRECV = get_compile_time_arg_val(12);
constexpr uint32_t NL = get_compile_time_arg_val(13);
constexpr auto t_args = TensorAccessorArgs<14>();
constexpr auto i_args = TensorAccessorArgs<t_args.next_compile_time_args_offset()>();
constexpr auto w_args = TensorAccessorArgs<i_args.next_compile_time_args_offset()>();
constexpr auto b_args = TensorAccessorArgs<w_args.next_compile_time_args_offset()>();
constexpr auto r_args = TensorAccessorArgs<b_args.next_compile_time_args_offset()>();

constexpr uint32_t CB_GATH = 0, CB_W = 1, CB_BIAS = 2, CB_IDENT = 3, CB_META = 4, CB_IDX = 7, CB_ZBUF = 10;
constexpr uint32_t ROWB = CIN_T * 64;      // table row bytes (bf16)
constexpr uint32_t IDXB = K * 32 * 4;      // index row bytes
constexpr uint32_t TB32 = 4096;
constexpr uint32_t WCH = TG * CIN_T * COUT_T;

// The blocks of one (layer, chunk): K6's block loop. Kept out of line so that its gather loop is register-allocated
// as in K6's kernel_main: inlined into the layer loop it spilled the table accessor and constants to the stack (5
// extra loads per gathered row, ~11 % per layer; OPT_REPORT round 10).
__attribute__((noinline)) uint32_t gather_blocks(uint32_t l, uint32_t ch, uint32_t me, uint32_t idx0, uint32_t idx1,
                                                 uint32_t cur, uint64_t zero_noc) {
    const auto tab = TensorAccessor(t_args, get_common_arg_val<uint32_t>(6 * l + 0), ROWB);
    const auto rs = TensorAccessor(r_args, get_common_arg_val<uint32_t>(6 * l + 4), TB32);
    const auto idx = TensorAccessor(i_args, get_common_arg_val<uint32_t>(6 * NL), IDXB);
    const bool has_res = (RES_MASK >> l) & 1u;
    const uint32_t idx_buf[2] = {idx0, idx1};
    const uint32_t t0 = ch * TG;
    const uint32_t nt = (K - t0) < TG ? (K - t0) : TG;
    const bool last = ch == NCH - 1;
    for (uint32_t b = me; b < NBLK; b += NC) {
        noc_async_read_barrier();
        invalidate_l1_cache();
        asm volatile("" ::: "memory");
        const uint32_t* ip = reinterpret_cast<const uint32_t*>(idx_buf[cur]);
        bool prefetched = false;
        auto prefetch = [&]() {
            uint32_t nb = b + NC, nch = ch, nl = l;
            if (nb >= NBLK) {
                nb = me;
                if (++nch == NCH) {
                    nch = 0;
                    ++nl;
                }
            }
            if (nl < NL) {
                noc_async_read(idx.get_noc_addr(nb), idx_buf[cur ^ 1], IDXB);
            }
            prefetched = true;
        };
        uint32_t live, mask;
        k6_scan<K, SENT, DEAD_SKIP>(ip, t0, nt, live, mask);
        cb_reserve_back(CB_META, 1);
        {
            volatile tt_l1_ptr uint32_t* mp =
                reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(CB_META));
            mp[0] = mask;
            mp[1] = live;
        }
        cb_push_back(CB_META, 1);
        if (!live) {
            prefetch();
            cur ^= 1;
            continue;
        }
        k6_gather<CIN_T, ROWB, SENT, 0, 2>(ip, t0, nt, mask, CB_GATH, zero_noc, tab, prefetch);
        if (!prefetched) {
            prefetch();
        }
        if (last && has_res) {
            cb_reserve_back(CB_IDENT, COUT_T);
            const uint32_t wp = get_write_ptr(CB_IDENT);
            for (uint32_t n = 0; n < COUT_T; ++n) {
                noc_async_read(rs.get_noc_addr(b * COUT_T + n), wp + n * TB32, TB32);
            }
            noc_async_read_barrier();
            cb_push_back(CB_IDENT, COUT_T);
        }
        cur ^= 1;
    }
    return cur;
}

void kernel_main() {
    const uint32_t me = get_arg_val<uint32_t>(0);
    const uint32_t is_sender = get_arg_val<uint32_t>(1);
    const uint32_t snx = get_arg_val<uint32_t>(2), sny = get_arg_val<uint32_t>(3);
    const bool n1 = noc_index == 1;
    const uint32_t mx0 = get_arg_val<uint32_t>(n1 ? 6 : 4), my0 = get_arg_val<uint32_t>(n1 ? 7 : 5);
    const uint32_t mx1 = get_arg_val<uint32_t>(n1 ? 4 : 6), my1 = get_arg_val<uint32_t>(n1 ? 5 : 7);
    const uint32_t ready_addr = get_semaphore(0);
    const uint32_t valid_addr = get_semaphore(1);
    volatile tt_l1_ptr uint32_t* ready_ptr = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(ready_addr);
    volatile tt_l1_ptr uint32_t* valid_ptr = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(valid_addr);
    volatile tt_l1_ptr uint32_t* go_ptr = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_semaphore(3));
    const auto idx = TensorAccessor(i_args, get_common_arg_val<uint32_t>(6 * NL), IDXB);

    // a zeroed region of one tap (32 rows x CIN_T * 64 B): the source of the per-tap zero fills
    cb_reserve_back(CB_ZBUF, 1);
    const uint32_t zero_l1 = get_write_ptr(CB_ZBUF);
    {
        volatile tt_l1_ptr uint32_t* z = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(zero_l1);
        for (uint32_t j = 0; j < CIN_T * 512; ++j) {
            z[j] = 0;
        }
    }
    const uint64_t zero_noc = get_noc_addr(zero_l1);

    // two index-row buffers: the next (layer, chunk, block)'s row is prefetched while this block gathers
    cb_reserve_back(CB_IDX, 2);
    const uint32_t idx_buf[2] = {get_write_ptr(CB_IDX), get_write_ptr(CB_IDX) + IDXB};
    uint32_t cur = 0;
    if (me < NBLK) {
        noc_async_read(idx.get_noc_addr(me), idx_buf[0], IDXB);
    }

    for (uint32_t l = 0; l < NL; ++l) {
        MKS_ZONE("MKS-R-LAYER");
        const auto wt = TensorAccessor(w_args, get_common_arg_val<uint32_t>(6 * l + 2), TB32);
        const auto bs = TensorAccessor(b_args, get_common_arg_val<uint32_t>(6 * l + 3), TB32);

        cb_reserve_back(CB_BIAS, COUT_T);
        {
            const uint32_t wp = get_write_ptr(CB_BIAS);
            for (uint32_t n = 0; n < COUT_T; ++n) {
                noc_async_read(bs.get_noc_addr(n), wp + n * TB32, TB32);
            }
            noc_async_read_barrier();
        }
        cb_push_back(CB_BIAS, COUT_T);

        for (uint32_t ch = 0; ch < NCH; ++ch) {
            const uint32_t t0 = ch * TG;
            const uint32_t nt = (K - t0) < TG ? (K - t0) : TG;
            cb_reserve_back(CB_W, WCH);
            {
                const uint32_t wp = get_write_ptr(CB_W);
                const uint32_t first = t0 * CIN_T * COUT_T;
                const uint32_t cnt = nt * CIN_T * COUT_T;
                if (!MCAST || is_sender) {
                    for (uint32_t i = 0; i < cnt; ++i) {
                        noc_async_read(wt.get_noc_addr(first + i), wp + i * TB32, TB32);
                    }
                    noc_async_read_barrier();
                }
                if constexpr (MCAST) {
                    if (is_sender) {
                        noc_semaphore_wait(ready_ptr, NRECV);
                        noc_semaphore_set(ready_ptr, 0);
                        noc_async_write_multicast(wp, get_noc_multicast_addr(mx0, my0, mx1, my1, wp), cnt * TB32,
                                                  NRECV, true);
                        noc_async_writes_flushed();
                        *valid_ptr = 1;
                        noc_semaphore_set_multicast(valid_addr,
                                                    get_noc_multicast_addr(mx0, my0, mx1, my1, valid_addr), NRECV);
                        noc_async_write_barrier();
                    } else {
                        noc_semaphore_set(valid_ptr, 0);
                        noc_semaphore_inc(get_noc_addr(snx, sny, ready_addr), 1);
                        noc_semaphore_wait(valid_ptr, 1);
                    }
                }
            }
            cb_push_back(CB_W, WCH);
            if (l > 0 && ch == 0) {
                // grid barrier: every core's layer l - 1 rows have landed in layer l's input table. The go count
                // is monotonic (l releases before layer l) and reset at the kernel end: a wait-for-1-then-reset
                // form loses a release when this RISC lags a whole layer behind (cores without live blocks let
                // the writers run ahead: found hung in the model's warm-up, OPT_REPORT round 10)
                MKS_ZONE("MKS-R-GO");
                noc_semaphore_wait_min(go_ptr, l);
            }

            cur = gather_blocks(l, ch, me, idx_buf[0], idx_buf[1], cur, zero_noc);
        }
    }
    noc_async_read_barrier();
    noc_semaphore_set(go_ptr, 0);              // all NL - 1 releases have arrived (self-cleaning for the next launch)
    cb_push_back(CB_IDX, 2);
    cb_push_back(CB_ZBUF, 1);
}