# SPDX-License-Identifier: Apache-2.0 """The two-term conv epilogue as one ``generic_op`` (OPT_PLAN B1, ``BEVFUSION_BACKBONE_EPI=k; ported from bundles/transfusion-p150 tt/epi_kernel.py (TF OPT_REPORT R2.2 / R3.2 / R3.3)``). ``epilogue_2t(parts, relu)``: the NP = 2 or 3 fp32 TILE conv products of a :class:`TwoTermConv` (the ``hi x w_hi``, ``hi x w_lo`` and ``lo x w_hi`` convs, DRAM interleaved, same shape) -> ``(hi, lo)`` bf16 TILE DRAM tensors with ``y = relu((c0 + c1) + c2)``, ``hi = bf16(y)``, ``lo = bf16(y - fp32(hi))``. It replaces the 6 stock programs per conv (the C17 weight-term add, the lo-conv add with the fused ReLU, and ``split_terms``' typecast, typecast, subtract, typecast: about 54 B of DRAM traffic per element) by one program (16 B per element) with the same LLKs in the same order (``kernels/epi2t_compute.cpp``), so the output is expected to be bit-identical. Tiles are split in contiguous ranges over the device grid (read from the device, never hard-coded). Per-core RT-arg counts are compile-time arg 0 (probe P3); the buffer addresses are common RT args. """ from __future__ import annotations import os from typing import Any, Optional, Sequence, Tuple __all__ = ["epilogue_2t", "supported", "epilogue_2t_rm", "supported_rm"] _KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") TB32, TB16 = 4096, 2048 N_RT = 2 def supported(parts: Sequence[Any], cols: Optional[Sequence[int]] = None, width: Optional[int] = None) -> bool: """True for 2-3 device fp32 TILE tensors of one tile-aligned shape, DRAM / L1 interleaved or height / block sharded (the reader's TensorAccessor resolves the shard of each tile; not the host fake ttnn).""" import ttnn try: if not 2 <= len(parts) <= 3 or not hasattr(ttnn, "generic_op"): return False shp = list(parts[0].padded_shape) cols = list(cols) if cols is not None else [0] * len(parts) width = int(width) if width is not None else shp[-1] if len(cols) != len(parts) or width % 32: return False for p, c in zip(parts, cols): ps = list(p.padded_shape) if p.dtype != ttnn.float32 or p.layout != ttnn.TILE_LAYOUT or ps[:-1] != shp[:-1] \ or c % 32 or c + width > ps[-1]: return False if p.is_sharded() and p.memory_config().memory_layout != ttnn.TensorMemoryLayout.HEIGHT_SHARDED \ and p.memory_config().memory_layout != ttnn.TensorMemoryLayout.BLOCK_SHARDED: return False return shp[-2] % 32 == 0 except Exception: # noqa: BLE001 - the host fake ttnn return False def epilogue_2t(parts: Sequence[Any], relu: bool, memory_config: Any = None, cols: Optional[Sequence[int]] = None, width: Optional[int] = None) -> Tuple[Any, Any]: """Module docstring. ``parts`` are kept (the caller frees them). ``cols`` / ``width`` (B1n): part ``i`` is the column range ``[cols[i], cols[i] + width)`` of its tensor (one tensor may appear twice: the merged weight-term conv); default: every part is a whole ``[.., R, C]`` tensor.""" import ttnn parts = list(parts) np_ = len(parts) x = parts[0] dev = x.device() shp = list(x.padded_shape) width = int(width) if width is not None else int(shp[-1]) cols = [int(c) for c in cols] if cols is not None else [0] * np_ total = 1 for d in shp[:-1]: total *= d total = total * width // 1024 mc = memory_config or ttnn.DRAM_MEMORY_CONFIG oshape = list(x.shape)[:-1] + [width] hi = ttnn.allocate_tensor_on_device(ttnn.Shape(oshape), ttnn.bfloat16, ttnn.TILE_LAYOUT, dev, mc) lo = ttnn.allocate_tensor_on_device(ttnn.Shape(oshape), ttnn.bfloat16, ttnn.TILE_LAYOUT, dev, mc) g = dev.compute_with_storage_grid_size() n = min(total, g.x * g.y) cs = [(i % g.x, i // g.x) for i in range(n)] full, rem = divmod(n, g.x) rs = [] if full: rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(g.x - 1, full - 1))) if rem: rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, full), ttnn.CoreCoord(rem - 1, full))) crs = ttnn.CoreRangeSet(set(rs)) base, extra = divmod(total, n) rd, wr, cp = ttnn.RuntimeArgs(), ttnn.RuntimeArgs(), ttnn.RuntimeArgs() t0 = 0 for i, (cx, cy) in enumerate(cs): k = base + (1 if i < extra else 0) rd[cx][cy] = [t0, k] wr[cx][cy] = [t0, k] cp[cx][cy] = [k, 0] t0 += k def cb(idx, pages, dtype, size): return ttnn.CBDescriptor(total_size=pages * size, core_ranges=crs, format_descriptors=[ ttnn.CBFormatDescriptor(buffer_index=idx, data_format=dtype, page_size=size)]) cbs = [cb(i, 2, ttnn.float32, TB32) for i in range(np_)] cbs += [cb(16, 2, ttnn.bfloat16, TB16), cb(17, 2, ttnn.bfloat16, TB16)] um = [ttnn.UnpackToDestMode.Default] * 64 for i in range(np_): um[i] = ttnn.UnpackToDestMode.UnpackToDestFp32 ccfg = ttnn.ComputeConfigDescriptor(math_fidelity=ttnn.MathFidelity.HiFi4, fp32_dest_acc_en=True, math_approx_mode=False) ccfg.unpack_to_dest_mode = um SRC = ttnn.KernelDescriptor.SourceType.FILE_PATH def acc(t): return list(ttnn.TensorAccessorArgs(t).get_compile_time_args()) def kd(name, ct, rt, common, config): return ttnn.KernelDescriptor(kernel_source=os.path.join(_KDIR, name), source_type=SRC, core_ranges=crs, compile_time_args=ct, defines=[], runtime_args=rt, common_runtime_args=common, config=config) # the reader always declares three accessors (the third repeats the first for NP = 2; never read) srcs = parts + [parts[0]] * (3 - np_) offs = cols + [0] * (3 - np_) geo = [width // 32] for p, c in zip(srcs, offs): geo += [int(p.padded_shape[-1]) // 32, c // 32] rd_ct = [N_RT, np_] + geo + [a for p in srcs for a in acc(p)] ks = [kd("epi2t_reader.cpp", rd_ct, rd, [p.buffer_address() for p in parts], ttnn.ReaderConfigDescriptor()), kd("epi2t_writer.cpp", [N_RT] + acc(hi) + acc(lo), wr, [hi.buffer_address(), lo.buffer_address()], ttnn.WriterConfigDescriptor()), kd("epi2t_compute.cpp", [N_RT, np_, int(bool(relu))], cp, [], ccfg)] ios = [] for p in parts: if all(p is not q for q in ios): ios.append(p) ttnn.generic_op(ios + [hi, lo], ttnn.ProgramDescriptor(kernels=ks, semaphores=[], cbs=cbs)) return hi, lo def supported_rm(parts: Sequence[Any]) -> bool: """True for 2-3 device fp32 ROW_MAJOR interleaved tensors of one shape ``[.., R, C]`` with ``1024 % C == 0`` and ``R`` a multiple of ``1024 / C`` (:func:`epilogue_2t_rm`; not the host fake ttnn).""" import ttnn try: if not 2 <= len(parts) <= 3 or not hasattr(ttnn, "generic_op"): return False shp = list(parts[0].shape) c = int(shp[-1]) rows = 1 for d in shp[:-1]: rows *= int(d) if c <= 0 or 1024 % c or rows % (1024 // c): return False for p in parts: if p.dtype != ttnn.float32 or p.layout != ttnn.ROW_MAJOR_LAYOUT or list(p.shape) != shp \ or p.is_sharded(): return False return True except Exception: # noqa: BLE001 - the host fake ttnn return False def epilogue_2t_rm(parts: Sequence[Any], relu: bool, memory_config: Any = None) -> Tuple[Any, Any]: """:func:`epilogue_2t` on ROW_MAJOR fp32 products (OPT_PLAN D9: a DRAM-path conv writing ROW_MAJOR needs no ``[1, H, W, C]`` -> ``[1, 1, HW, C]`` ReshapeView copy) -> ROW_MAJOR bf16 ``(hi, lo)`` of the same shape. The compute kernel is the same (``epi2t_compute.cpp``): its math is elementwise, so the 1024 values of a "tile" may be ``1024 / C`` consecutive rows (``kernels/epi2t_reader_rm.cpp`` / ``epi2t_writer_rm.cpp``). ``parts`` are kept.""" import ttnn parts = list(parts) np_ = len(parts) x = parts[0] dev = x.device() shp = [int(s) for s in x.shape] c = shp[-1] rows = 1 for d in shp[:-1]: rows *= d rpc = 1024 // c total = rows // rpc mc = memory_config or ttnn.DRAM_MEMORY_CONFIG hi = ttnn.allocate_tensor_on_device(ttnn.Shape(shp), ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT, dev, mc) lo = ttnn.allocate_tensor_on_device(ttnn.Shape(shp), ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT, dev, mc) g = dev.compute_with_storage_grid_size() n = min(total, g.x * g.y) cs = [(i % g.x, i // g.x) for i in range(n)] full, rem = divmod(n, g.x) rs = [] if full: rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(g.x - 1, full - 1))) if rem: rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, full), ttnn.CoreCoord(rem - 1, full))) crs = ttnn.CoreRangeSet(set(rs)) base, extra = divmod(total, n) rd, wr, cp = ttnn.RuntimeArgs(), ttnn.RuntimeArgs(), ttnn.RuntimeArgs() t0 = 0 for i, (cx, cy) in enumerate(cs): k = base + (1 if i < extra else 0) rd[cx][cy] = [t0, k] wr[cx][cy] = [t0, k] cp[cx][cy] = [k, 0] t0 += k def cb(idx, pages, dtype, size): return ttnn.CBDescriptor(total_size=pages * size, core_ranges=crs, format_descriptors=[ ttnn.CBFormatDescriptor(buffer_index=idx, data_format=dtype, page_size=size)]) cbs = [cb(i, 2, ttnn.float32, TB32) for i in range(np_)] cbs += [cb(16, 2, ttnn.bfloat16, TB16), cb(17, 2, ttnn.bfloat16, TB16)] um = [ttnn.UnpackToDestMode.Default] * 64 for i in range(np_): um[i] = ttnn.UnpackToDestMode.UnpackToDestFp32 ccfg = ttnn.ComputeConfigDescriptor(math_fidelity=ttnn.MathFidelity.HiFi4, fp32_dest_acc_en=True, math_approx_mode=False) ccfg.unpack_to_dest_mode = um SRC = ttnn.KernelDescriptor.SourceType.FILE_PATH def acc(t): return list(ttnn.TensorAccessorArgs(t).get_compile_time_args()) def kd(name, ct, rt, common, config): return ttnn.KernelDescriptor(kernel_source=os.path.join(_KDIR, name), source_type=SRC, core_ranges=crs, compile_time_args=ct, defines=[], runtime_args=rt, common_runtime_args=common, config=config) srcs = parts + [parts[0]] * (3 - np_) rd_ct = [N_RT, np_, rpc, c * 4] + [a for p in srcs for a in acc(p)] ks = [kd("epi2t_reader_rm.cpp", rd_ct, rd, [p.buffer_address() for p in parts], ttnn.ReaderConfigDescriptor()), kd("epi2t_writer_rm.cpp", [N_RT, rpc, c * 2] + acc(hi) + acc(lo), wr, [hi.buffer_address(), lo.buffer_address()], ttnn.WriterConfigDescriptor()), kd("epi2t_compute.cpp", [N_RT, np_, int(bool(relu))], cp, [], ccfg)] ttnn.generic_op(parts + [hi, lo], ttnn.ProgramDescriptor(kernels=ks, semaphores=[], cbs=cbs)) return hi, lo