File size: 7,517 Bytes
f882f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""The megakernel program: the ``ttnn.generic_op`` program descriptor of one launch (all 120 cores, three RISC
kernels, the CB table, two semaphores).  Every launch runs the same program; the per-launch plan (a DRAM table)
holds what changes.  Arena / table tensors are allocated by the engine (tt/mk/engine.py)."""
from __future__ import annotations

import os
import struct
from typing import Dict, List, Sequence, Tuple

from . import geometry as G

KERNELS = {r: os.path.join(G.KDIR, f"lm_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")}
FIDELITY = {"HiFi4": 4, "HiFi3": 3, "HiFi2": 2, "LoFi": 0}


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


def float_literal(x: float) -> str:
    return repr(float(x)) + "f"


class Program:
    def __init__(self, device, geo: G.Geometry, slots: int, eps: float, fidelity: str = "HiFi4",
                 variant: Sequence[str] = (), wfmt: str = "bf16", rmax: int = 2):
        import ttnn

        self.device, self.geo, self.slots, self.eps = device, geo, int(slots), float(eps)
        if fidelity not in FIDELITY:
            raise ValueError(f"fidelity {fidelity!r}: one of {sorted(FIDELITY)}")
        self.fidelity = fidelity
        self.wfmt = wfmt
        self.rmax = int(rmax)
        self.variant = tuple(variant)   # "prof" (LM_PROF time stamps), "stream" (LM_STREAM_ONLY timing arm)
        self._noc: Dict[Tuple[int, int], Tuple[int, int]] = {}
        for x in range(geo.C):
            for y in range(geo.NB):
                c = device.worker_core_from_logical_core(ttnn.CoreCoord(x, y))
                self._noc[(x, y)] = (int(c.x), int(c.y))
        for x in range(geo.C - 1):  # logical order must be NoC order (rectangles map corner to corner)
            if self._noc[(x, 0)][0] >= self._noc[(x + 1, 0)][0]:
                raise RuntimeError("logical x order differs from NoC x order")
        for y in range(geo.NB - 1):
            if self._noc[(0, y)][1] >= self._noc[(0, y + 1)][1]:
                raise RuntimeError("logical y order differs from NoC y order")
        if G.cb_bytes(geo.m, geo.C, self.slots, wfmt, self.rmax) > G.CB_LIMIT:
            raise ValueError(f"{self.slots} ring pages: CBs exceed {G.CB_LIMIT} B")

    def noc(self, xy) -> Tuple[int, int]:
        return self._noc[tuple(xy)]

    def common_args(self, t: Dict[str, object], arenas: Sequence) -> List[int]:
        g = self.geo
        c = [0] * G.N_COMMON_ARGS
        (c[G.K_ALL_X0], c[G.K_ALL_Y0]) = self.noc((0, 0))
        (c[G.K_ALL_X1], c[G.K_ALL_Y1]) = self.noc((g.C - 1, g.NB - 1))
        c[G.K_N_ALL] = g.n
        (c[G.K_HUB_X], c[G.K_HUB_Y]) = self.noc((g.C - 1, g.NB - 1))
        c[G.K_EPS] = f32_bits(self.eps)
        c[G.K_EPSH] = f32_bits(1e-5)
        for key, k in (("plan", G.K_PLAN), ("stage", G.K_STAGE), ("e", G.K_E), ("h", G.K_H), ("vec", G.K_VEC),
                       ("rope", G.K_ROPE), ("const", G.K_CONST), ("pad", G.K_PAD), ("dbg", G.K_DBG),
                       ("oh", G.K_OH)):
            c[k] = t[key].buffer_address()
        for x in range(g.C):
            c[G.K_NOCX + x] = self.noc((x, 0))[0]
        for y in range(g.NB):
            c[G.K_NOCY + y] = self.noc((0, y))[1]
        if len(arenas) != g.m.NL + g.m.NHL or G.K_ARENA0 + len(arenas) > G.K_DBG:
            raise ValueError("arena count")
        for i, a in enumerate(arenas):
            c[G.K_ARENA0 + i] = a.buffer_address()
        return c

    def descriptor(self, t: Dict[str, object], arenas: Sequence):
        import ttnn

        g = self.geo
        gx, gy = g.C, g.NB
        cores = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))])
        fmt = {"bf16": ttnn.bfloat16, "fp32": ttnn.float32, "raw": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b}
        cbs = []
        modes = [ttnn.UnpackToDestMode.Default] * 64
        for cb in G.cb_table(g.m, g.C, self.slots, self.wfmt, self.rmax):
            fds = []
            for cb_id, f, page, unpack32 in cb.ids:
                fds.append(ttnn.CBFormatDescriptor(buffer_index=cb_id, data_format=fmt[f],
                                                   page_size=page if f != "raw" else cb.total))
                if unpack32:
                    modes[cb_id] = ttnn.UnpackToDestMode.UnpackToDestFp32
            cbs.append(ttnn.CBDescriptor(total_size=cb.total, core_ranges=cores, format_descriptors=fds))
        m = g.m
        ct = [gx, gy, self.slots, m.DT, m.FE, m.FH, m.NL, m.NHL, m.H, m.GEVERY]
        assert len(ct) == G.CT_ACC0
        ct += list(ttnn.TensorAccessorArgs(t["stage"]).get_compile_time_args())
        args = g.core_args(self.noc)
        rt = ttnn.RuntimeArgs()
        for x in range(gx):
            for y in range(gy):
                rt[x][y] = args[(x, y)]
        common = self.common_args(t, arenas)
        fid = getattr(ttnn.MathFidelity, self.fidelity)
        cc = ttnn.ComputeConfigDescriptor(math_fidelity=fid, fp32_dest_acc_en=True, dst_full_sync_en=True,
                                          math_approx_mode=False)
        cc.unpack_to_dest_mode = modes
        defines = [("LM_N_RT_ARGS", str(G.N_RT_ARGS)), ("LM_INV_D", float_literal(1.0 / (32 * m.DT))),
                   ("LM_EPS", float_literal(self.eps)), ("LM_FID", str(FIDELITY[self.fidelity])),
                   ("LM_OPT_O2", "1"), ("LM_WTILE", str(G.WTILE[self.wfmt]))]
        if self.rmax != 2:
            defines += [("LM_RMAX", str(self.rmax)), ("LM_AKV_CAP", str(G.akv_cap(self.rmax)))]
        if "prof" in self.variant:
            defines.append(("LM_PROF", "1"))
        if "stream" in self.variant:
            defines.append(("LM_STREAM_ONLY", "1"))
        if "mmb" in self.variant:
            defines.append(("LM_MMB", "1"))
        for v in self.variant:
            if v.startswith("depth"):
                defines.append(("LM_DEPTH", str(int(v[5:]))))
        kdir = G.KDIR
        for v in self.variant:   # "kdir=<dir>": an alternative kernel directory next to kernels/ (development)
            if v.startswith("kdir="):
                kdir = os.path.join(os.path.dirname(G.KDIR), v[5:])
        kernels_src = {r: os.path.join(kdir, f"lm_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")}
        fp = ttnn.KernelDescriptor.SourceType.FILE_PATH
        dm = ttnn.DataMovementConfigDescriptor
        kernels = [
            ttnn.KernelDescriptor(kernel_source=kernels_src["ncrisc"], source_type=fp, core_ranges=cores,
                                  compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines,
                                  config=dm(processor=ttnn.DataMovementProcessor.RISCV_1, noc=ttnn.NOC.NOC_0)),
            ttnn.KernelDescriptor(kernel_source=kernels_src["brisc"], source_type=fp, core_ranges=cores,
                                  compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines,
                                  config=dm(processor=ttnn.DataMovementProcessor.RISCV_0, noc=ttnn.NOC.NOC_1)),
            ttnn.KernelDescriptor(kernel_source=kernels_src["trisc"], source_type=fp, core_ranges=cores,
                                  compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines,
                                  config=cc),
        ]
        sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=cores, initial_value=0) for i in (0, 1)]
        return ttnn.ProgramDescriptor(kernels=kernels, semaphores=sems, cbs=cbs)