File size: 4,142 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
# SPDX-License-Identifier: Apache-2.0
"""P1: the compact VFE input (OPT_PLAN P1, ``BEVFUSION_VFE_INPUT=compact``; needs ``DEVICE_PLAN=1``, K6 with L1
tables).

The host uploads the VFE rows (key order) as bf16 ROW_MAJOR ``[cap_l1 / 32 + 1, 32 * VW]`` (``VW = 8``: the
two-term ``[hi | lo]`` of the 4 VFE channels; 32 voxels per 512 B page) instead of the 32-wide padded table
``[1, 1, cap_l1 + 1, 32]`` (2.1 instead of 8.4 MB in bucket ``m``). One ``generic_op`` (``kernels/vfe_expand.cpp``,
both data-movement RISCs of every core) writes the first sparse layer's gather table straight into L1 (interleaved,
64 B rows ``[hi | lo | zeros]``): the frame's rows ``[0, count)`` (count from the ``meta`` row, so one trace serves
every frame) and the zero sentinel row. It replaces the padded upload and the DRAM -> L1 copy of the whole table;
the rows the K6 gathers read are the same bytes.

Parameters: compile-time = capacity, workers, row sizes, meta size, the accessors; common RT args = the three buffer
addresses; one per-core RT arg (the worker id; count in CT arg 0, probe P3).
"""
from __future__ import annotations

import os
from typing import Any

__all__ = ["VW", "compact_shape", "scratch_bytes", "expand_table"]

_KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels")
VW = 8              # compact row width (bf16 values): terms * 4 channels <= 8
N_RT = 1


def compact_shape(cap_l1: int) -> tuple:
    """The compact input's shape: ``cap / 32`` pages of 32 rows plus one page (the host's twin writes up to
    ``cap`` rows into a ``(rows - 1)``-row table view)."""
    if int(cap_l1) % 32:
        raise ValueError("cap_l1 must be a multiple of 32")
    return (int(cap_l1) // 32 + 1, 32 * VW)


def scratch_bytes(vb: int, ob: int) -> int:
    """L1 scratch bytes of one ``vfe_expand.cpp`` instance (mirrors its layout)."""
    return 64 + 2 * 32 * int(vb) + 2 * 32 * int(ob)


def expand_table(compact: Any, meta: Any, *, cap: int, width: int = 32) -> Any:
    """The L1 gather table ``[1, 1, cap + 1, width]`` bf16 ROW_MAJOR (module docstring) from ``compact`` and the
    ``meta`` row (word 0: the l1 count)."""
    import ttnn

    if list(compact.shape) != list(compact_shape(cap)) or compact.dtype != ttnn.bfloat16:
        raise ValueError(f"compact VFE input {list(compact.shape)}, expected {list(compact_shape(cap))} bf16")
    dev = compact.device()
    g = dev.compute_with_storage_grid_size()
    nc = int(g.x) * int(g.y)
    nw = 2 * nc
    out = ttnn.allocate_tensor_on_device(ttnn.Shape([1, 1, int(cap) + 1, int(width)]), ttnn.bfloat16,
                                         ttnn.ROW_MAJOR_LAYOUT, dev, ttnn.L1_MEMORY_CONFIG)
    crs = ttnn.CoreRangeSet({ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(g.x - 1, g.y - 1))})
    ra, rb = ttnn.RuntimeArgs(), ttnn.RuntimeArgs()
    for i in range(nc):
        cx, cy = i % g.x, i // g.x
        ra[cx][cy] = [2 * i]
        rb[cx][cy] = [2 * i + 1]
    vb, ob = VW * 2, int(width) * 2
    sb = scratch_bytes(vb, ob)
    meta_bytes = int(meta.shape[-1]) * 4

    def cb(i):
        return ttnn.CBDescriptor(total_size=sb, core_ranges=crs, format_descriptors=[
            ttnn.CBFormatDescriptor(buffer_index=i, data_format=ttnn.float32, page_size=sb)])

    def acc(t):
        return list(ttnn.TensorAccessorArgs(t).get_compile_time_args())

    common = [compact.buffer_address(), meta.buffer_address(), out.buffer_address()]
    tail = acc(compact) + acc(meta) + acc(out)
    SRC = ttnn.KernelDescriptor.SourceType.FILE_PATH

    def kd(cbi, rt, config):
        ct = [N_RT, int(cap), nw, vb, ob, cbi, meta_bytes] + tail
        return ttnn.KernelDescriptor(kernel_source=os.path.join(_KDIR, "vfe_expand.cpp"), source_type=SRC,
                                     core_ranges=crs, compile_time_args=ct, defines=[], runtime_args=rt,
                                     common_runtime_args=common, config=config)

    ks = [kd(0, ra, ttnn.ReaderConfigDescriptor()), kd(1, rb, ttnn.WriterConfigDescriptor())]
    ttnn.generic_op([compact, meta, out], ttnn.ProgramDescriptor(kernels=ks, semaphores=[], cbs=[cb(0), cb(1)]))
    return out