# SPDX-License-Identifier: Apache-2.0 """Small ttnn helpers shared by the ttnn engines (weights to device, compute configs, buckets).""" from __future__ import annotations from typing import Sequence import numpy as np NEG = -1e9 # additive mask value (bf16-representable, exp() underflows to 0) def bucket(n: int, buckets: Sequence[int]) -> int: for b in sorted(buckets): if n <= b: return int(b) raise ValueError(f"{n} exceeds the largest bucket {max(buckets)}") def wdtype(name: str): import ttnn return {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b, "bfp4": ttnn.bfloat4_b}[name] def mat(device, t, dtype="bf16", mem=None): """torch [out, in] (nn.Linear layout) -> ttnn [in, out] TILE in DRAM.""" import ttnn return ttnn.from_torch(t.t().contiguous().float(), dtype=wdtype(dtype), layout=ttnn.TILE_LAYOUT, device=device, memory_config=mem or ttnn.DRAM_MEMORY_CONFIG) def mat_in_out(device, t, dtype="bf16", mem=None): """torch [in, out] -> ttnn TILE in DRAM.""" import ttnn return ttnn.from_torch(t.contiguous().float(), dtype=wdtype(dtype), layout=ttnn.TILE_LAYOUT, device=device, memory_config=mem or ttnn.DRAM_MEMORY_CONFIG) def norm_w(device, w): """RMSNorm weight [d] -> ttnn [1, 1, d/32, 32] ROW_MAJOR bf16 (the layout ttnn.rms_norm expects).""" import ttnn d = int(w.numel()) return ttnn.from_torch(w.float().reshape(1, 1, d // 32, 32), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) def ckc(device, fidelity: str = "HiFi4", fp32_acc: bool = True, approx: bool = False): import ttnn fid = {"HiFi4": ttnn.MathFidelity.HiFi4, "HiFi3": ttnn.MathFidelity.HiFi3, "HiFi2": ttnn.MathFidelity.HiFi2, "LoFi": ttnn.MathFidelity.LoFi}[fidelity] return ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=fid, math_approx_mode=approx, fp32_dest_acc_en=fp32_acc, packer_l1_acc=True) def host_tensor(arr: np.ndarray, dtype, layout): """numpy -> ttnn host tensor (no device). TILE host tensors open the device (CLAUDE.md probe G4-X): callers run under bin/devrun anyway; ROW_MAJOR is used for per-request inputs where possible.""" import torch import ttnn return ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(arr)), dtype=dtype, layout=layout) def knobs() -> dict: """Experiment knobs (``EMBGEMMA_KNOBS="grid=1,l1=1,vfid=HiFi2"``), read at program build. Defaults = shipped.""" import os out = {"grid": "1", "l1": "1", "vfid": "", "tfid": "", "afid": "", "sdpa": "", "sdpa_ck": "acc"} for kv in os.environ.get("EMBGEMMA_KNOBS", "").split(","): if "=" in kv: k, v = kv.split("=", 1) out[k.strip()] = v.strip() return out def mm_1d_config(M_t: int, K_t: int, N_t: int, gx: int, max_cores: int = 64, in0_block_w: int = 8): """1D multicast matmul config for small M (<= 2 row tiles): in0 multicast, ceil(N_t / max_cores) output tiles per core, K blocks of 8 tiles (measured 1.4-2.8x faster than the auto config at 32 / 64 rows, scripts/mm_micro.py).""" import ttnn per_n = max(1, -(-N_t // max_cores)) ncores = -(-N_t // per_n) cx = min(gx, ncores) cy = -(-ncores // cx) bw = in0_block_w if K_t % in0_block_w == 0 else (4 if K_t % 4 == 0 else (2 if K_t % 2 == 0 else 1)) sw = 1 for c in (4, 3, 2): if per_n % c == 0 and c * M_t <= 8: sw = c break return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig( compute_with_storage_grid_size=ttnn.CoreCoord(cx, cy), in0_block_w=bw, out_subblock_h=1, out_subblock_w=sw, out_block_h=M_t, out_block_w=per_n, per_core_M=M_t, per_core_N=per_n, fuse_batch=True, fused_activation=None, mcast_in0=True) def lin(x, w, ck, dtype, mem=None, grid=None, act=None, pc=None): """ttnn.linear with the full compute grid (core_grid) or an explicit program config, and an explicit output memory config.""" import ttnn kw = {"compute_kernel_config": ck, "dtype": dtype} if pc is not None: kw["program_config"] = pc grid = None if mem is not None: kw["memory_config"] = mem if grid is not None: kw["core_grid"] = grid if act is not None: kw["activation"] = act return ttnn.linear(x, w, **kw)