# SPDX-License-Identifier: Apache-2.0 """K12 ``rerow`` (0.24.0): a ROW_MAJOR reshape that only changes the page width, as one data-movement ``generic_op``. A ROW_MAJOR DRAM-interleaved tensor ``[.., Rin, Win]`` viewed as ``[1, 1, Rout, Wout]`` (``Rin * Win == Rout * Wout``) keeps its logical byte stream; only the page size, and so the DRAM bank of every byte, changes. ttnn's RM reshape does this at ~60 GB/s at the C18 ``Resize2d`` shapes (METEOR ``[864, 30720] -> [165888, 160]`` fp32: 1.72 ms for 106 MB moved). :func:`rerow` does it as a page copy (kernel ``kernels/rerow_rm.cpp``) when one page width is a whole multiple ``M`` of the other and the smaller page is a multiple of 64 B (every DRAM address and L1 offset of the copy is then 64 B aligned); otherwise it falls back to ``ttnn.reshape``. Bit-identical by construction (bytes are copied, never converted). Kernel: chunks of up to ``K`` small pages inside one big page (one transfer on the big side, ``n`` page transfers on the small side), split evenly over the device's compute grid (``compute_with_storage_grid_size()``: ETH 12x10 and WORKER 11x10 alike); one RISC / NOC per core does the reads and the writes (no two-NOC small DRAM writes, Blackhole SYS-1419), double-buffered. Parameters: COMPILE = chunk count, grid, M, K, page bytes, direction (split / join); per call = the two buffer addresses (common RT args: probe P3). Measured (p150, ETH 12x10, traced, bit-identical to ``ttnn.reshape``; ``bundles/meteor-p150/code/scripts/ rerow_probe.py``, ``logs/meteor/opt_r5/job1_probe.log``): splits (big -> small pages) [864, 30720] -> [165888, 160] fp32 1.755 -> 0.846 ms, [800, 48000] -> [400000, 96] bf16 1.282 -> 0.722, [864, 18432] -> [165888, 96] fp32 1.117 -> 0.514, [800, 32000] -> [400000, 64] bf16 1.064 -> 0.526, [400, 32000] -> [100000, 128] fp32 0.904 -> 0.397 ms; joins (small -> big) are SLOWER than ttnn's reshape ([82944, 160] -> [432, 30720] 0.353 -> 0.511, [200000, 96] -> [400, 48000] 0.676 -> 0.887 ms), so :func:`rerow` leaves them to ttnn unless ``joins=True``. """ from __future__ import annotations import os from dataclasses import dataclass from typing import Any, Optional, Tuple from . import kernel_path __all__ = ["RerowPlan", "rerow_plan", "rerow", "rerow_reference", "KERNEL", "CHUNK_BYTES", "REROW_MODES"] KERNEL = "rerow_rm.cpp" CHUNK_BYTES = 32 * 1024 # bytes per L1 slot (two slots per core) REROW_MODES = ("stock", "kernel") @dataclass(frozen=True) class RerowPlan: rows_in: int rows_out: int page_in: int # bytes page_out: int direction: int # 0: split (input pages are the big ones), 1: join m: int # small pages per big page small: int # small page bytes k: int # small pages per chunk cpb: int # chunks per big page chunks: int slot: int # bytes per L1 slot @property def big_pages(self) -> int: return self.rows_in if self.direction == 0 else self.rows_out def rerow_plan(rows_in: int, width_in: int, rows_out: int, width_out: int, elem_bytes: int, chunk_bytes: int = CHUNK_BYTES) -> Optional[RerowPlan]: """The kernel's plan for ``[rows_in, width_in] -> [rows_out, width_out]``, or None when the kernel does not apply (the caller falls back to ``ttnn.reshape``).""" rows_in, width_in, rows_out, width_out = int(rows_in), int(width_in), int(rows_out), int(width_out) if rows_in * width_in != rows_out * width_out or min(rows_in, width_in, rows_out, width_out) <= 0: raise ValueError(f"rerow: [{rows_in}, {width_in}] -> [{rows_out}, {width_out}] changes the volume") p_in, p_out = width_in * elem_bytes, width_out * elem_bytes if p_in == p_out: return None # a view: nothing to copy big, small = max(p_in, p_out), min(p_in, p_out) if big % small or small % 64: return None m = big // small k = max(1, min(m, chunk_bytes // small)) if k * small > max(chunk_bytes, small): return None cpb = -(-m // k) direction = 0 if p_in > p_out else 1 big_pages = rows_in if direction == 0 else rows_out return RerowPlan(rows_in, rows_out, p_in, p_out, direction, m, small, k, cpb, big_pages * cpb, k * small) def rerow_reference(stream_in, plan: RerowPlan): """Host emulation of the kernel's page moves on a flat numpy byte array (tests): each chunk copies its big-side byte range and its ``n`` small pages; returns ``(output stream, per-byte write count)``. The logical stream does not move, so a correct plan gives the input back with every byte written exactly once.""" import numpy as np src = np.asarray(stream_in, np.uint8).reshape(-1) dst = np.zeros_like(src) hits = np.zeros(src.shape, np.int32) for q in range(plan.chunks): b, c = divmod(q, plan.cpb) j0 = c * plan.k n = min(plan.k, plan.m - j0) big0 = (b * plan.m + j0) * plan.small # big page b, offset j0 * PS for t in range(n): # small page b * M + j0 + t p = b * plan.m + j0 + t if plan.direction == 0: # big in -> small out dst[p * plan.small:(p + 1) * plan.small] = src[big0 + t * plan.small:big0 + (t + 1) * plan.small] hits[p * plan.small:(p + 1) * plan.small] += 1 else: # small in -> big out dst[big0 + t * plan.small:big0 + (t + 1) * plan.small] = src[p * plan.small:(p + 1) * plan.small] hits[big0 + t * plan.small:big0 + (t + 1) * plan.small] += 1 return dst, hits def _supported(t: Any) -> bool: import ttnn if not hasattr(ttnn, "generic_op") or t.layout != ttnn.ROW_MAJOR_LAYOUT: return False mc = t.memory_config() return (getattr(mc, "buffer_type", None) == ttnn.BufferType.DRAM and getattr(mc, "memory_layout", None) == ttnn.TensorMemoryLayout.INTERLEAVED) def _elem_bytes(t: Any) -> Optional[int]: import ttnn return {ttnn.float32: 4, ttnn.bfloat16: 2, ttnn.uint32: 4, ttnn.int32: 4, ttnn.uint16: 2, ttnn.uint8: 1}.get(t.dtype) def rerow(t: Any, shape: Tuple[int, int, int, int], *, mode: str = "kernel", joins: bool = False) -> Any: """``ttnn.reshape(t, shape)`` for a ROW_MAJOR DRAM-interleaved ``t`` and a 4-D ``shape`` ``(1, 1, R, W)``; with ``mode="kernel"`` the page re-cut runs as the K12 kernel where it applies (module docstring), else stock. Joins (small pages -> big pages) take ttnn's reshape unless ``joins=True``: it is faster there (module docstring, measured).""" import ttnn shape = tuple(int(s) for s in shape) if mode != "kernel" or len(shape) != 4 or shape[0] != 1 or shape[1] != 1 or not _supported(t): return ttnn.reshape(t, shape) eb = _elem_bytes(t) in_shape = [int(s) for s in t.shape] w_in = in_shape[-1] r_in = 1 for s in in_shape[:-1]: r_in *= s plan = None if eb is None else rerow_plan(r_in, w_in, shape[2], shape[3], eb) if plan is None or (plan.direction == 1 and not joins): return ttnn.reshape(t, shape) dev = t.device() out = ttnn.allocate_tensor_on_device(ttnn.Shape(list(shape)), t.dtype, ttnn.ROW_MAJOR_LAYOUT, dev, ttnn.DRAM_MEMORY_CONFIG) ttnn.generic_op([t, out], program(t, out, plan)) return out def program(t: Any, out: Any, plan: RerowPlan): """The ``ttnn.ProgramDescriptor`` of one call (buffer addresses in common runtime args).""" import ttnn g = t.device().compute_with_storage_grid_size() gx, gy = int(g.x), int(g.y) nc = max(1, min(plan.chunks, gx * gy)) full, rem = divmod(nc, gx) rs = [] if full: rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, full - 1))) if rem: rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, full), ttnn.CoreCoord(rem - 1, full))) crs = ttnn.CoreRangeSet(set(rs)) cbs = [ttnn.CBDescriptor(total_size=2 * plan.slot, core_ranges=crs, format_descriptors=[ ttnn.CBFormatDescriptor(buffer_index=0, data_format=ttnn.uint8, page_size=plan.slot)])] ct = [plan.chunks, nc, gx, plan.m, plan.k, plan.small, plan.direction, plan.cpb, plan.slot] \ + list(ttnn.TensorAccessorArgs(t).get_compile_time_args()) \ + list(ttnn.TensorAccessorArgs(out).get_compile_time_args()) k = ttnn.KernelDescriptor(kernel_source=kernel_path(KERNEL), source_type=ttnn.KernelDescriptor.SourceType.FILE_PATH, core_ranges=crs, compile_time_args=ct, defines=[], runtime_args=ttnn.RuntimeArgs(), common_runtime_args=[t.buffer_address(), out.buffer_address()], config=ttnn.ReaderConfigDescriptor()) return ttnn.ProgramDescriptor(kernels=[k], semaphores=[], cbs=cbs) def mode_from_env(default: str = "stock", var: str = "TTAW_REROW") -> str: mode = (os.environ.get(var) or default).strip().lower() if mode not in REROW_MODES: raise ValueError(f"{var}={mode!r}: expected one of {REROW_MODES}") return mode