File size: 17,886 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
 
 
 
 
 
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
357
# SPDX-License-Identifier: Apache-2.0
"""The ENC megakernel: one persistent ``ttnn.generic_op`` program per (size, T, gh, gw, mode) that runs DepthPro2's
whole encoder (patch embed + prefix + every DINOv3 block) and writes the 4 tapped patch-token tensors.

``MkEnc(device, weights, size, T, gh, gw, mode)`` folds and uploads the weights (one DRAM arena per phase), the
constants and the persistent staging / output buffers once; ``run(patches)`` only enqueues the program (no host sync,
trace-capturable) and returns ``taps`` (4 x bf16 TILE ``[T * Np, C]``; FOV mode: ``[T * (32 + Np), C]``, per frame the
prefix tile then the patch tiles).

Contract (SPEC section 3): ``patches [T * Np, 768]`` bf16 TILE in DRAM, row ``t * Np + n`` = frame t's patch n in
raster order, columns in (c, ky, kx) order (``arena.patchify``); rows >= N of each frame are zero.
"""

from __future__ import annotations

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

import torch

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

KERNELS = {r: os.path.join(G.KDIR, f"me_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")}
LN_EPS = 1e-5


def _sources_hash() -> str:
    import hashlib

    h = hashlib.sha1()
    d = os.path.dirname(os.path.abspath(__file__))
    for sub_dir in ("", "kernels"):
        p = os.path.join(d, sub_dir)
        for n in sorted(os.listdir(p)):
            if n.endswith((".py", ".cpp", ".hpp")):
                with open(os.path.join(p, n), "rb") as f:
                    h.update(n.encode() + f.read())
    return h.hexdigest()


_SOURCES_AT_IMPORT = _sources_hash()


def _opt_level(name: str):
    from ttnn._ttnn.operations.experimental.fabric_mux import KernelBuildOptLevel

    return getattr(KernelBuildOptLevel, name)


def env_options() -> Dict:
    """``DEPTHPRO2_MK_ENC_OPTS`` (A/B knobs, comma-separated ``key=value``): ``exp`` (0 fp32 exp, 1 exp_21f),
    ``giant_all`` (0/1), ``fc1p`` (0/1), ``fid`` (HiFi4 / HiFi3 / ...), ``inx32`` (0/1: LN-gather tiles bf16 / fp32)."""
    out: Dict = {}
    for kv in os.environ.get("DEPTHPRO2_MK_ENC_OPTS", "").split(","):
        if "=" not in kv:
            continue
        k, v = (t.strip() for t in kv.split("=", 1))
        if k == "exp":
            out["exp_mode"] = int(v)
        elif k == "giant_all":
            out["giant_all"] = bool(int(v))
        elif k == "fc1p":
            out["fc1p_ok"] = bool(int(v))
        elif k == "fid":
            out["fidelity"] = v
        elif k == "inx32":
            out["inx32"] = bool(int(v))
        elif k == "klo":
            out["klo"] = int(v)
        elif k == "ring_first":
            out["ring_first"] = bool(int(v))
        else:
            raise ValueError(f"DEPTHPRO2_MK_ENC_OPTS: unknown key {k!r}")
    return out


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


class MkEncWeights:
    """The folded weights of one (size, mode) uploaded once as DRAM arenas (one per phase: embed, every block) for the
    device grid; shared by every :class:`MkEnc` shape (bucket / clip length). The arenas depend on the grid columns
    and ``rb`` only (geometry column splits, n-groups, f-blocks), never on T / gh / gw."""

    def __init__(self, device, host_weights: Dict[str, torch.Tensor], size: str, mode: str = "depth", rb: int = 0,
                 timings: Optional[Dict] = None):
        import ttnn

        t0 = time.perf_counter()
        g = device.compute_with_storage_grid_size()
        geo = G.Geometry(size, 1, 2, 2, mode, int(g.x), int(g.y), rb=rb)
        self.size, self.mode, self.rb, self.grid = size, mode, geo.rb, (int(g.x), int(g.y))
        prefix = "trunk." if mode == "fov" else "encoder."
        dram = ttnn.DRAM_MEMORY_CONFIG
        fw = A.fold(host_weights, geo, prefix)
        t1 = time.perf_counter()
        up_rm = lambda t: ttnn.from_torch(t.reshape(1, 1, *t.shape).contiguous(), dtype=ttnn.bfloat16,  # noqa: E731
                                          layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram)
        self.arena_e = up_rm(A.arena(fw, geo, "E"))
        self.arenas = [up_rm(A.arena(fw, geo, "BL" if l == geo.L - 1 else "B", l)) for l in range(geo.L)]
        self.pfx = ttnn.from_torch(fw["pfx"].contiguous(), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT,
                                   device=device, memory_config=dram)
        self.dram_bytes = sum(a.padded_shape[-2] * a.padded_shape[-1] * 2 for a in [self.arena_e, *self.arenas])
        if timings is not None:
            timings["mk_enc_fold_s"] = t1 - t0
            timings["mk_enc_upload_s"] = time.perf_counter() - t1

    def tensors(self) -> List:
        return [self.arena_e, *self.arenas, self.pfx]


def _vf_tile(n: int) -> torch.Tensor:
    t = torch.zeros(1, 1, 32, 32, dtype=torch.int32)
    t[0, 0, 0, 0] = n
    t[0, 0, 0, 1] = f32_bits(1.0 / n)
    return t


class MkEnc:
    def __init__(self, device, weights, size: str, T: int, gh: int, gw: int,
                 mode: str = "depth", rb: int = 0, qb: int = 0, kc: int = 32, fidelity: str = "HiFi4", probe: bool = False, prof: bool = False,
                 opt: str = "O2",
                 defines: Sequence[Tuple[str, str]] = (), timings: Optional[Dict] = None):
        import ttnn

        self.device = device
        g = device.compute_with_storage_grid_size()
        self.grid = (int(g.x), int(g.y))
        env = env_options()
        fidelity = env.pop("fidelity", fidelity)
        self.geo = geo = G.Geometry(size, T, gh, gw, mode, self.grid[0], self.grid[1], rb=rb, qb=qb, kc=kc,
                                    probe=probe, prof=prof, **env)
        self.fidelity = fidelity
        self.opt = opt  # TRISC build optimization level (the kernel-config buffer holds every binary: ~70 KB)
        fid = {"LoFi": 0, "HiFi2": 2, "HiFi3": 3, "HiFi4": 4}[fidelity]
        self.defines = list(geo.defines()) + list(defines) + ([("ME_FID", str(fid))] if fidelity != "HiFi4" else [])
        self._noc: Dict[Tuple[int, int], Tuple[int, int]] = {}
        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))
        for x in range(self.grid[0] - 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(self.grid[1] - 1):
            if self._noc[(0, y)][1] >= self._noc[(0, y + 1)][1]:
                raise RuntimeError("logical y order differs from NoC y order")
        dram = ttnn.DRAM_MEMORY_CONFIG
        if isinstance(weights, dict):
            weights = MkEncWeights(device, weights, size, mode, rb=rb, timings=timings)
        if (weights.size, weights.mode, weights.rb, weights.grid) != (size, mode, geo.rb, self.grid):
            raise ValueError(f"prepared weights {weights.size}/{weights.mode}/rb {weights.rb}/{weights.grid} do not match "
                             f"{size}/{mode}/rb {geo.rb}/{self.grid}")
        self.weights = weights
        self.arena_e, self.arenas, self.pfx = weights.arena_e, weights.arenas, weights.pfx
        t2 = time.perf_counter()
        tile = lambda t, dt: ttnn.from_torch(t.contiguous(), dtype=dt, layout=ttnn.TILE_LAYOUT,  # noqa: E731
                                             device=device, memory_config=dram)
        self.consts = tile(A.const_tiles().reshape(-1, 32), ttnn.bfloat16)
        self.cf32 = tile(A.cf32_tiles(geo.nlast).reshape(-1, 32), ttnn.float32)
        self.rope = tile(A.rope_tiles(gh, gw, geo.Pt), ttnn.float32)
        z = lambda rows, dt: tile(torch.zeros(rows, geo.dim), dt)  # noqa: E731
        z4 = lambda rows, dt: tile(torch.zeros(1, 1, rows, geo.dim), dt)  # noqa: E731
        mt32 = geo.Mt * 32
        self.xd = z(mt32, ttnn.float32)
        self.q, self.k, self.v, self.o = (z(mt32, ttnn.bfloat16) for _ in range(4))
        self.klo = z(max(1, geo.klo_rows) * 32, ttnn.bfloat16)  # k - bf16(k) of the special / every key tile
        tap_rows = T * (geo.Np + 32) if mode == "fov" else T * geo.Np
        self.taps = [z4(tap_rows, ttnn.bfloat16) for _ in range(4)]  # [1, 1, rows, C] (the ttnn engines' shape)
        self.prb = tile(torch.zeros(G.N_PROBE * 32, 32), ttnn.float32)
        # runtime valid-frame count (set_valid_frames; read by the kernels when T > 1): [n, bits(1 / n)]
        self.vf = ttnn.from_torch(_vf_tile(T), dtype=ttnn.uint32, layout=ttnn.TILE_LAYOUT, device=device,
                                  memory_config=dram)
        self.valid_frames = T
        self.prof = ttnn.from_torch(torch.zeros(1, 1, geo.NC, G.PROF_WORDS, dtype=torch.int32), dtype=ttnn.uint32,
                                    layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram)
        self._acc = list(ttnn.TensorAccessorArgs(self.q).get_compile_time_args())
        self._desc: Dict[Tuple, object] = {}
        if timings is not None:
            timings["mk_enc_consts_s"] = time.perf_counter() - t2

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

    def persistent(self) -> List:
        return [self.arena_e, *self.arenas, self.consts, self.cf32, self.rope, self.pfx, self.xd, self.q, self.k,
                self.v, self.o, self.prb, self.prof, self.vf, self.klo]

    def set_valid_frames(self, n: int) -> None:
        """The next runs / trace replays process frames ``[0, n)`` as an n-frame clip (BASELINE.md 9.2: frames >= n
        must be zero patches; their taps are don't-care). Host call: one 4 KB write to a persistent DRAM tile on CQ 0
        (no allocation, no compile, no sync)."""
        import ttnn

        n = int(n)
        if not 1 <= n <= self.geo.T:
            raise ValueError(f"valid frames {n} outside [1, {self.geo.T}]")
        if self.geo.pool:
            host = ttnn.from_torch(_vf_tile(n), dtype=ttnn.uint32, layout=ttnn.TILE_LAYOUT)
            ttnn.copy_host_to_device_tensor(host, self.vf)
        elif n != self.geo.T:
            raise ValueError("this program has no cross-frame pool (T = 1 or FOV mode): n must equal T")
        self.valid_frames = n

    def common_args(self, patches, nl: int, dump: bool) -> List[int]:
        geo = self.geo
        c = [0] * G.N_COMMON_ARGS
        c[G.K_ALL_X0:G.K_ALL_Y1 + 1] = geo.rect(self.noc)
        c[G.K_N_ALL] = geo.NC
        c[G.K_HUB_X], c[G.K_HUB_Y] = self.noc(geo.hub())
        c[G.K_NL] = int(nl)
        c[G.K_DUMP] = int(bool(dump))
        c[G.K_EPS] = f32_bits(LN_EPS)
        c[G.K_INVD] = f32_bits(1.0 / geo.dim)
        c[G.K_INVT] = f32_bits(1.0 / geo.T)
        c[G.K_PATCH] = patches.buffer_address()
        for i in range(4):
            c[G.K_TAP0 + i] = self.taps[i].buffer_address()
        c[G.K_XD] = self.xd.buffer_address()
        c[G.K_Q], c[G.K_K], c[G.K_V], c[G.K_O] = (t.buffer_address() for t in (self.q, self.k, self.v, self.o))
        c[G.K_CONST] = self.consts.buffer_address()
        c[G.K_CF32] = self.cf32.buffer_address()
        c[G.K_ROPE] = self.rope.buffer_address()
        c[G.K_PFX] = self.pfx.buffer_address()
        c[G.K_ARENA_E] = self.arena_e.buffer_address()
        for i, a in enumerate(self.arenas):
            c[G.K_ARENA0 + i] = a.buffer_address()
        c[G.K_PROBE] = self.prb.buffer_address()
        c[G.K_PROF] = self.prof.buffer_address()
        c[G.K_VF] = self.vf.buffer_address()
        c[G.K_KLO] = self.klo.buffer_address()
        return c

    def program(self, patches, nl: Optional[int] = None, dump: bool = False):
        import ttnn

        geo = self.geo
        nl = geo.L if nl is None else int(nl)
        common = self.common_args(patches, nl, dump)
        key = tuple(common)
        if key in self._desc:
            return self._desc[key]
        if _sources_hash() != _SOURCES_AT_IMPORT:  # a new program compiles the kernel files as they are NOW
            raise RuntimeError("tt/mk_enc sources changed since this process imported them (kernel / host skew would "
                               "compute garbage): restart the process")
        gx, gy = self.grid
        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}
        cbs = []
        modes = [ttnn.UnpackToDestMode.Default] * 64
        for ids, total in geo.cb_table():
            fds = []
            for cb_id, f, unpack32 in ids:
                page = total if f == "raw" else (G.T16 if f == "bf16" else G.T32)
                fds.append(ttnn.CBFormatDescriptor(buffer_index=cb_id, data_format=fmt[f], page_size=page))
                if unpack32:
                    modes[cb_id] = ttnn.UnpackToDestMode.UnpackToDestFp32
            cbs.append(ttnn.CBDescriptor(total_size=total, core_ranges=cores, format_descriptors=fds))
        ct = list(self._acc)
        args = geo.core_args(self.noc)
        rt = ttnn.RuntimeArgs()
        for x in range(gx):
            for y in range(gy):
                rt[x][y] = args[(x, y)]
        cc = ttnn.ComputeConfigDescriptor(math_fidelity=getattr(ttnn.MathFidelity, self.fidelity),
                                          fp32_dest_acc_en=True, dst_full_sync_en=True, math_approx_mode=False)
        cc.unpack_to_dest_mode = modes
        defines = list(self.defines) + [("ME_OPT_" + self.opt, "1")]  # the JIT disk cache key ignores opt_level
        fp = ttnn.KernelDescriptor.SourceType.FILE_PATH
        dm = ttnn.DataMovementConfigDescriptor
        kernels = [
            ttnn.KernelDescriptor(kernel_source=KERNELS["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["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["trisc"], source_type=fp, core_ranges=cores,
                                  compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines,
                                  config=cc, opt_level=_opt_level(self.opt)),
        ]
        sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=cores, 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, patches, nl: Optional[int] = None, dump: bool = False) -> List:
        """Enqueue the ENC program (one ``generic_op``); returns the 4 taps. ``nl`` < L (debug): run only the first
        ``nl`` blocks (``dump``: x (fp32) of the last block run is stored to ``self.xd``)."""
        import ttnn

        io = [*self.persistent(), patches, *self.taps]
        ttnn.generic_op(io, self.program(patches, nl, dump))
        return self.taps

    # ------------------------------------------------------------------ debug readers
    def read_x(self) -> torch.Tensor:
        """x (fp32) per row tile ``[Mt, 32, dim]`` from XD (after a ``dump`` run, or always with W > 1)."""
        import ttnn

        return ttnn.to_torch(self.xd).float().reshape(self.geo.Mt, 32, self.geo.dim)

    def read_prof(self) -> torch.Tensor:
        import ttnn

        return ttnn.to_torch(self.prof).reshape(self.geo.NC, G.PROF_WORDS).to(torch.int64) & 0xFFFFFFFF

    def read_probe(self) -> torch.Tensor:
        import ttnn

        return ttnn.to_torch(self.prb).float().reshape(G.N_PROBE, 32, 32)

    def read_stage(self, which: str) -> torch.Tensor:
        import ttnn

        t = {"q": self.q, "k": self.k, "v": self.v, "o": self.o}[which]
        return ttnn.to_torch(t).float().reshape(self.geo.Mt, 32, self.geo.dim)


class Engine:
    """SPEC section 3 stage-engine adapter (``tt/__init__.py`` contract): ``Engine(device, weights, shape)`` with
    ``weights`` = :meth:`prepare_weights` (shared by every shape) or the host dict (+ ``size``); ``run(patches)``
    -> 4 taps ``[1, 1, T * Np, C]`` bf16 TILE (FOV mode: ``[1, 1, T * (32 + Np), C]``, per frame the prefix tile, then
    the patch tiles).

    Runtime valid-frame count (BASELINE.md 9.2): ``supports_valid_frames``; ``set_valid_frames(n)`` before a run / trace
    replay makes the T-frame program process frames ``[0, n)`` as an n-frame clip (depth mode, T > 1)."""

    supports_valid_frames = True

    def __init__(self, device, weights, shape, size: Optional[str] = None, mode: str = "depth", **kw):
        if isinstance(weights, dict):
            if size is None:
                raise ValueError("size is required with host weights")
            weights = MkEncWeights(device, weights, size, mode)
        self.shape = shape
        self.mk = MkEnc(device, weights, weights.size, shape.frames, shape.hp // 16, shape.wp // 16,
                        mode=weights.mode, **kw)

    @staticmethod
    def prepare_weights(device, host_weights, size: str, mode: str = "depth") -> MkEncWeights:
        return MkEncWeights(device, host_weights, size, mode)

    def set_valid_frames(self, n: int) -> None:
        self.mk.set_valid_frames(n)

    def input_spec(self):
        return (1, 1, self.shape.frames * self.mk.geo.Np, 768), "bf16 TILE DRAM"

    def run(self, patches) -> List:
        return self.mk.run(patches)