File size: 16,553 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""The DEC-MoE program: persistent DRAM buffers (weight arena, tables, KV cache, embedding table, STATE, seen bitmap,
logits, route tables) uploaded once, and the ``ttnn.generic_op`` program descriptor of one decode step (md_*.cpp).
Adapted from this workspace's GLM-OCR DEC (tt/mk_dec/program.py, Apache-2.0). ttnn is imported lazily."""

from __future__ import annotations

import os
import struct
import time
from typing import Dict, List, Optional, Sequence

import numpy as np
import torch

from . import arena as A
from . import geometry as G

KERNELS = {r: os.path.join(G.KDIR, f"md_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")}
#: fp32 CBs read by copy_tile (unpack straight to DST in fp32); fp32 CBs used as matmul / reduce operands stay default
UNPACK32 = ("CB_X", "CB_X0", "CB_ACCD", "CB_ACSD", "CB_HS", "CB_RS", "CB_TAB", "CB_SD", "CB_PRO", "CB_PRM", "CB_PRL",
            "CB_MRG", "CB_RSM", "CB_RE")
RECIPES = {
    "bfp8": {"attn": "bfp8", "mlp": "bfp8", "head": "bf16"},
    "bfp8h8": {"attn": "bfp8", "mlp": "bfp8", "head": "bfp8"},
    "bf16": {"attn": "bf16", "mlp": "bf16", "head": "bf16"},
}
N_LAYERS = G.N_LAYERS
#: open the device with this worker L1 size when the DEC-MoE program is used: the kernel-config ring (binaries + RTAs
#: + CB configs of a program) grows from 69 KiB to 133 KiB (the program is ~80 KiB; TT_PLATFORM.md section 1)
WORKER_L1_SIZE = 1461248 - (64 << 10)
EPS = 1e-6
HD = 128


def f32_bits(x: float) -> int:
    return struct.unpack("<I", struct.pack("<f", float(x)))[0]


class DecMoE:
    """One decode step of the DeepSeek-OCR family MoE decoder as one program. ``W``: reference.model.Weights."""

    def __init__(self, device, W, recipe: Optional[Dict[str, str]] = None, max_pos: int = 8192, source: str = "",
                 k_max: int = 64, wfid: Optional[int] = None, attk: Optional[int] = None, log=print,
                 dummy_arena: bool = False):
        import ttnn

        self.ttnn = ttnn
        self.device = device
        self.recipe = dict(recipe or RECIPES["bfp8"])
        self.fa, self.fm, self.fh = self.recipe["attn"], self.recipe["mlp"], self.recipe["head"]
        self.max_pos = int(max_pos)
        self.attk = int(attk if attk is not None else os.environ.get("DSOCR_MK_ATTK", "4"))
        if self.max_pos % 32 or self.max_pos > 8192 * self.attk:
            raise ValueError(f"max_pos must be a multiple of 32 and <= {8192 * self.attk} (256 key blocks per slot)")
        self.wfid = int(wfid if wfid is not None else os.environ.get("DSOCR_MK_WFID", "4"))
        self.k_max = int(k_max)
        g = device.compute_with_storage_grid_size()
        self.grid = (int(g.x), int(g.y))
        opt0 = [(int(c.x), int(c.y)) for c in device.get_optimal_dram_bank_to_logical_worker_assignment(ttnn.NOC.NOC_0)]
        opt1 = [(int(c.x), int(c.y)) for c in device.get_optimal_dram_bank_to_logical_worker_assignment(ttnn.NOC.NOC_1)]
        self.geo = G.build(self.grid[0], self.grid[1], opt0, opt1, attk=self.attk)
        self._noc = {}
        for x in range(self.grid[0]):
            for y in range(self.grid[1]):
                c = device.worker_core_from_logical_core(ttnn.CoreCoord(x, y))
                self._noc[(x, y)] = (int(c.x), int(c.y))
        t0 = time.time()
        pages, self.offsets, self.rt_offsets = A.build_arena(W, self.geo, self.recipe, source=source, log=log,
                                                             dummy=dummy_arena)
        t1 = time.time()
        dram = ttnn.DRAM_MEMORY_CONFIG
        rm = ttnn.ROW_MAJOR_LAYOUT

        def up_u32(arr: np.ndarray, row_bytes: int):
            a = np.ascontiguousarray(arr).reshape(-1, row_bytes)
            t = torch.from_numpy(a.view(np.int32).reshape(a.shape[0], row_bytes // 4))
            return ttnn.from_torch(t, dtype=ttnn.uint32, layout=rm, device=device, memory_config=dram)

        def up_f32(t: torch.Tensor):
            return ttnn.from_torch(t.float().contiguous(), dtype=ttnn.float32, layout=rm, device=device,
                                   memory_config=dram)

        def up_bf16(t: torch.Tensor):
            return ttnn.from_torch(t.to(torch.bfloat16).contiguous(), dtype=ttnn.bfloat16, layout=rm, device=device,
                                   memory_config=dram)

        self.wts = up_u32(np.asarray(pages), A.PAGE)
        self.arena_bytes = int(np.asarray(pages).nbytes)
        del pages
        self.rope = up_f32(A.rope_table(self.max_pos))
        self.rope_q = up_f32(A.rope_table(self.max_pos, HD ** -0.5))
        self.mask = up_bf16(A.mask_tiles())
        self.consts = up_bf16(A.const_tiles_full())
        self.embed = up_bf16(W.get("model.embed_tokens.weight", cache=False))  # [V, D] bf16 rows
        self.nb_blocks = self.max_pos // 32
        # [24 = layer x (k, v), 10 heads, MAXP, 128] bf16 TILE (the ttnn prefill fills layer l's K / V at 2l / 2l + 1)
        self.kv = ttnn.zeros([N_LAYERS * 2, G.NG, self.max_pos, HD], dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
                             device=device, memory_config=dram)
        self.hc = G.HC
        self.logits = up_f32(torch.zeros(G.NW, self.hc * 32))
        self.state = up_u32(np.zeros((1, 8192), np.uint8), 8192)
        self.seen = up_u32(np.zeros((1, G.SEEN_WORDS * 4), np.uint8), G.SEEN_WORDS * 4)
        self.route_log = up_u32(np.zeros((N_LAYERS, 2048), np.uint8), 2048)
        self.froute = up_u32(np.zeros((N_LAYERS, 2048), np.uint8), 2048)
        n = self.grid[0] * self.grid[1]
        self.dbg = up_u32(np.zeros((n, G.SYNC_BYTES), np.uint8), G.SYNC_BYTES)
        l1 = G.cb_total(self.fa, self.fm, self.attk, self.fh)
        if l1 > G.L1_BUDGET:
            raise ValueError(f"CBs {l1} B exceed the L1 budget {G.L1_BUDGET} B")
        kvb = N_LAYERS * 2 * G.NG * self.max_pos * HD * 2
        log(f"[mk_moe] DEC-MoE {self.recipe}: arena {self.arena_bytes / 2**20:.0f} MiB (pack {t1 - t0:.0f} s, upload "
            f"{time.time() - t1:.0f} s), grid {self.grid}, attk {self.attk}, KV {kvb / 2**20:.0f} MiB, CBs "
            f"{l1 / 1024:.0f} KiB")
        self._desc = {}

    def persistent(self) -> List:
        return [self.wts, self.rope, self.rope_q, self.mask, self.consts, self.kv, self.logits, self.dbg, self.embed,
                self.state, self.seen, self.route_log, self.froute]

    def noc(self, c):
        return self._noc[tuple(c)]

    def _common(self, n_layers: int, flags: int, spin: int, stop: int = 0):
        c = G.common_args(self.geo, self.noc)
        c[G.K_STOP] = int(stop)
        c[G.K_NL] = int(n_layers)
        c[G.K_SPIN] = int(spin)
        c[G.K_EPS] = f32_bits(EPS)
        c[G.K_INV_D] = f32_bits(1.0 / G.D_MODEL)
        c[G.K_INV_HD] = f32_bits(1.0 / HD)
        c[G.K_STATE] = self.state.buffer_address()
        c[G.K_EMBED] = self.embed.buffer_address()
        c[G.K_LOGITS] = self.logits.buffer_address()
        c[G.K_WTS] = self.wts.buffer_address()
        c[G.K_ROPE] = self.rope.buffer_address()
        c[G.K_ROPEQ] = self.rope_q.buffer_address()
        c[G.K_ROUTE] = self.route_log.buffer_address()
        c[G.K_FROUTE] = self.froute.buffer_address()
        c[G.K_SEEN] = self.seen.buffer_address()
        c[G.K_KV] = self.kv.buffer_address()
        c[G.K_NB] = self.nb_blocks
        c[G.K_MASK] = self.mask.buffer_address()
        c[G.K_CONST] = self.consts.buffer_address()
        c[G.K_DBG] = self.dbg.buffer_address()
        c[G.K_FLAGS] = int(flags)
        c[G.K_MAXP] = self.max_pos
        c[G.K_NEG] = f32_bits(A.NEG_MASK)
        c[G.K_KMAX] = self.k_max
        return c

    def program(self, n_layers: int = N_LAYERS, flags: int = 0, spin: int = 1 << 26, stop: int = 0):
        key = (n_layers, flags, spin, stop)
        if key in self._desc:
            return self._desc[key]
        ttnn = self.ttnn
        gx, gy = self.grid
        allc = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))])
        dt = {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b, "bfp4": ttnn.bfloat4_b, "fp32": ttnn.float32,
              "raw": ttnn.uint32}
        cbs = []
        modes = [ttnn.UnpackToDestMode.Default] * 64
        unp = {getattr(G, n) for n in UNPACK32}
        for cb in G.cb_table(self.fa, self.fm, self.attk, self.fh):
            fds = []
            for cid, fmt, page, tile, _u in cb.ids:
                kw = {}
                if tile is not None:
                    kw["tile"] = ttnn.TileDescriptor(tile[0], tile[1], False)
                fds.append(ttnn.CBFormatDescriptor(buffer_index=cid, data_format=dt[fmt],
                                                   page_size=cb.total if fmt == "raw" else page, **kw))
                if cid in unp:
                    modes[cid] = ttnn.UnpackToDestMode.UnpackToDestFp32
            cbs.append(ttnn.CBDescriptor(total_size=cb.total, core_ranges=allc, format_descriptors=fds))
        rb = G.ring_bytes(self.fa, self.fm, self.fh)
        defines = [
            ("MT_TB_A", G.TILE_BYTES[self.fa]), ("MT_TB_M", G.TILE_BYTES[self.fm]), ("MT_TB_H", G.TILE_BYTES[self.fh]),
            ("MT_HC", self.hc), ("MT_RING_A", rb["A"]), ("MT_RING_M", rb["M"]), ("MT_RING_H", rb["H"]),
            ("MT_KV_RING_BLOCKS", G.KV_RING_BLOCKS), ("MT_WFID", self.wfid), ("MT_CAP_MRG", rb["A"] // G.T32),
        ]
        defines = [(k, str(v)) for k, v in defines]
        args = G.core_args(self.geo, self.noc, self.offsets, self.rt_offsets)
        common = self._common(n_layers, flags, spin, stop)
        ct = list(ttnn.TensorAccessorArgs(self.wts).get_compile_time_args())
        s1 = {m.xy for m in self.geo.mm if m.noc == 1}
        s0 = [(x, y) for y in range(gy) for x in range(gx) if (x, y) not in s1]
        crs = lambda cs: ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(*c), ttnn.CoreCoord(*c)) for c in cs])  # noqa
        fp = ttnn.KernelDescriptor.SourceType.FILE_PATH
        dm = ttnn.DataMovementConfigDescriptor
        kernels = []
        for cores, nc_noc, br_noc in ((s0, ttnn.NOC.NOC_0, ttnn.NOC.NOC_1), (sorted(s1), ttnn.NOC.NOC_1, ttnn.NOC.NOC_0)):
            rt = ttnn.RuntimeArgs()
            for c in cores:
                rt[c[0]][c[1]] = args[c]
            kernels.append(ttnn.KernelDescriptor(
                kernel_source=KERNELS["ncrisc"], source_type=fp, core_ranges=crs(cores), compile_time_args=ct,
                runtime_args=rt, common_runtime_args=common, defines=defines,
                config=dm(processor=ttnn.DataMovementProcessor.RISCV_1, noc=nc_noc)))
            rt2 = ttnn.RuntimeArgs()
            for c in cores:
                rt2[c[0]][c[1]] = args[c]
            kernels.append(ttnn.KernelDescriptor(
                kernel_source=KERNELS["brisc"], source_type=fp, core_ranges=crs(cores), compile_time_args=ct,
                runtime_args=rt2, common_runtime_args=common, defines=defines,
                config=dm(processor=ttnn.DataMovementProcessor.RISCV_0, noc=br_noc)))
        rt3 = ttnn.RuntimeArgs()
        for x in range(gx):
            for y in range(gy):
                rt3[x][y] = args[(x, y)]
        cc = ttnn.ComputeConfigDescriptor(math_fidelity=ttnn.MathFidelity.HiFi4, fp32_dest_acc_en=True,
                                          dst_full_sync_en=True, math_approx_mode=False)
        cc.unpack_to_dest_mode = modes
        kernels.append(ttnn.KernelDescriptor(kernel_source=KERNELS["trisc"], source_type=fp, core_ranges=allc,
                                             compile_time_args=[], runtime_args=rt3, common_runtime_args=common,
                                             defines=defines, config=cc))
        sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=allc, initial_value=0) for i in (0, 1)]
        desc = ttnn.ProgramDescriptor(kernels=kernels, semaphores=sems, cbs=cbs)
        self._desc[key] = desc
        return desc

    def run(self, n_layers: int = N_LAYERS, flags: int = 0, spin: int = 1 << 26, stop: int = 0):
        """Enqueue one step (no host sync; trace-capturable)."""
        self.ttnn.generic_op(self.persistent(), self.program(n_layers, flags, spin, stop))

    # ------------------------------------------------------------------ host helpers
    def read_logits(self) -> torch.Tensor:
        t = self.ttnn.to_torch(self.logits).reshape(-1).float()
        return t[:G.VOCAB]

    def state_host(self, L: int, token0: int, max_new: int, eos=(1, 1), temperature: float = 0.0, top_k: int = 0,
                   top_p: float = 1.0, seed: int = 0, done: bool = False, ntok: int = 1, penalty: float = 1.0,
                   ban_step: int = 0, bans: Sequence[int] = ()):
        st = np.zeros(2048, np.uint32)
        do_sample = temperature is not None and temperature > 0
        st[G.S_DOSAMPLE] = 1 if do_sample else 0
        st[G.S_INVT] = f32_bits(1.0 / temperature) if do_sample else f32_bits(1.0)
        st[G.S_TOPK] = int(top_k or 0)
        st[G.S_TOPP] = f32_bits(float(top_p if top_p is not None else 1.0))
        st[G.S_PEN] = f32_bits(float(penalty if penalty else 1.0))
        st[G.S_SEED_LO] = int(seed) & 0xFFFFFFFF
        st[G.S_SEED_HI] = (int(seed) >> 32) & 0xFFFFFFFF
        st[G.S_L] = int(L)
        st[G.S_MAXNEW] = int(max_new)
        st[G.S_EOS0], st[G.S_EOS1] = int(eos[0]), int(eos[1])
        st[G.S_NVOCAB] = G.VOCAB
        bans = list(bans)[:G.S_BAN_MAX]
        st[G.S_BAN_STEP] = int(ban_step)
        st[G.S_BAN_N] = len(bans)
        for i, b in enumerate(bans):
            st[G.S_BAN0 + i] = int(b)
        st[G.S_NTOK] = int(ntok)
        st[G.S_LAST] = int(token0)
        st[G.S_TOKENS + (int(ntok) - 1) % G.S_TOKENS_MAX] = int(token0)
        if done or int(token0) in eos or max_new <= 1:
            st[G.S_DONE] = 1
            st[G.S_STOP] = 1 if int(token0) in eos else 2
        t = torch.from_numpy(st.view(np.int32).reshape(1, 2048))
        return self.ttnn.from_torch(t, dtype=self.ttnn.uint32, layout=self.ttnn.ROW_MAJOR_LAYOUT)

    def write_state(self, host_state) -> None:
        self.ttnn.copy_host_to_device_tensor(host_state, self.state)

    def write_seen(self, ids) -> None:
        bm = A.seen_bitmap(ids)
        t = torch.from_numpy(bm.view(np.int32).reshape(1, G.SEEN_WORDS))
        self.ttnn.copy_host_to_device_tensor(
            self.ttnn.from_torch(t, dtype=self.ttnn.uint32, layout=self.ttnn.ROW_MAJOR_LAYOUT), self.seen)

    def write_forced_routes(self, ids: torch.Tensor, weights: torch.Tensor) -> None:
        """ids / weights [n_layers, 6] (rows 1..11 used): the F_FORCE_ROUTE table."""
        tab = np.zeros((N_LAYERS, 512), np.uint32)
        for l in range(1, min(N_LAYERS, ids.shape[0])):
            tab[l, :6] = ids[l].to(torch.int64).numpy().astype(np.uint32)
            tab[l, 8:14] = weights[l].float().numpy().view(np.uint32)
        t = torch.from_numpy(tab.view(np.int32))
        self.ttnn.copy_host_to_device_tensor(
            self.ttnn.from_torch(t, dtype=self.ttnn.uint32, layout=self.ttnn.ROW_MAJOR_LAYOUT), self.froute)

    def read_routes(self):
        t = self.ttnn.to_torch(self.route_log).reshape(N_LAYERS, 512).numpy().view(np.uint32)
        ids = t[:, :6].astype(np.int64)
        w = t[:, 8:14].copy().view(np.float32)
        return ids, w

    def read_state(self) -> np.ndarray:
        return self.ttnn.to_torch(self.state).reshape(-1).numpy().view(np.uint32).copy()

    def read_dbg(self) -> torch.Tensor:
        n = self.grid[0] * self.grid[1]
        return self.ttnn.to_torch(self.dbg).reshape(n, G.SYNC_BYTES // 4).to(torch.int64) & 0xFFFFFFFF

    def aborts(self):
        d = self.read_dbg()
        bad = []
        for i in range(d.shape[0]):
            if int(d[i, G.W_ABORT * 4]) == G.ABORT_MAGIC:
                bad.append((i, [int(d[i, (G.W_DBG + k) * 4]) for k in range(6)], int(d[i, G.W_STEP * 4])))
        return bad

    def read_prof(self):
        d = self.read_dbg()
        mm = self.geo.idx(self.geo.mm[0].xy)
        at = self.geo.idx(self.geo.att[0])
        p0 = G.SYNC_PROF // 4
        m = [int(d[mm, p0 + i]) for i in range(9)]
        a = [int(d[at, p0 + i]) for i in range(10, 15)]
        f = 1.35e3

        def us(x, i, j):
            return ((x[j] - x[i]) & 0xFFFFFFFF) / f

        return {"mm_norm1_gather": us(m, 0, 1), "mm_qkv_to_sent": us(m, 1, 2), "mm_wait_attention": us(m, 2, 3),
                "mm_oproj_norm2": us(m, 3, 4), "mm_wait_route": us(m, 4, 5), "mm_gateup_fgather": us(m, 5, 6),
                "mm_layer1_total": us(m, 0, 6), "att_wait_q": us(a, 0, 1), "att_kv_softmax_pv": us(a, 1, 3),
                "att_send_o": us(a, 3, 4)}