changh95's picture
tt-model push embeddinggemma-2 (container)
5c33f00 verified
Raw History Blame Contribute Delete
7.73 kB
# SPDX-License-Identifier: Apache-2.0
"""mk_vattn: a custom attention kernel for the vision tower (head dim 64, one image per launch, non-causal, key
padding mask), replacing ttnn SDPA (which runs at ~11 TFLOP/s at this head dim). ONE ``ttnn.generic_op`` program:
core c of the grid handles head ``c // cph`` (cph = cores per head = ncores // H) and a contiguous range of its
32-row query tiles; K / V of the head are read once into L1 and stay resident; no inter-core synchronisation.
Tensors (DRAM interleaved, bf16 TILE): q, k, v, o ``[1, H, P, 64]``; mask ``[1, 1, 1|32, P]`` (row 0: 0 for a valid
key, -1e9 for padding; other rows are ignored); status uint32 ROW_MAJOR ``[ncores, 512]`` (abort word per core).
Buffer addresses travel in the common runtime args (descriptor rebuilt per call: inside a trace the addresses are
those of the capture). Per-core runtime-arg counts are fixed (4)."""
from __future__ import annotations
import os
import re
from typing import Dict, List, Tuple
KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels")
KERNELS = {r: os.path.join(KDIR, f"va_{r}.cpp") for r in ("reader", "writer", "compute")}
def parse_defs() -> Dict[str, int]:
out = {}
with open(os.path.join(KDIR, "va_defs.hpp")) as f:
for line in f:
m = re.match(r"\s*constexpr uint32_t (\w+) = (\d+);", line)
if m:
out[m.group(1)] = int(m.group(2))
return out
D = parse_defs()
HEAD_DIM = 64
def split(total: int, parts: int) -> List[Tuple[int, int]]:
out, a = [], 0
for i in range(parts):
n = total // parts + (1 if i < total % parts else 0)
out.append((a, n))
a += n
return out
def l1_bytes(PT: int) -> int:
T16, T32 = D["T16"], D["T32"]
return 2 * (2 * PT * T16) + PT * T16 + 4 * T16 + PT * T32 + 2 * T32 + 2 * T16 + 4 * T16 + 4096
class VAttn:
"""Attention for one bucket of P rows (multiple of 32) and H heads of 64."""
def __init__(self, device, P: int, H: int = 12, spin: int = 1 << 24, fast_exp: bool = False):
import ttnn
if P % 32:
raise ValueError("P must be a multiple of 32")
self.device, self.P, self.H = device, int(P), int(H)
self.PT = self.P // 32
g = device.compute_with_storage_grid_size()
self.gx, self.gy = int(g.x), int(g.y)
self.ncores = self.gx * self.gy
self.cph = self.ncores // self.H
if self.cph < 1:
raise ValueError(f"{self.ncores} cores < {self.H} heads")
if l1_bytes(self.PT) > 1400 * 1024:
raise ValueError(f"P={P}: K / V / scores need {l1_bytes(self.PT)} B of L1 per core")
self.spin = int(spin)
self.fast_exp = bool(fast_exp)
self.status = ttnn.allocate_tensor_on_device(ttnn.Shape([self.ncores, D["STATUS_WORDS"]]), ttnn.uint32,
ttnn.ROW_MAJOR_LAYOUT, device, ttnn.DRAM_MEMORY_CONFIG)
self.assign = [] # per core (x, y): (head, q0, nq)
ranges = split(self.PT, self.cph)
for y in range(self.gy):
for x in range(self.gx):
c = y * self.gx + x
h = c // self.cph
if h < self.H:
q0, nq = ranges[c % self.cph]
self.assign.append((x, y, h, q0, nq, c))
else:
self.assign.append((x, y, 0, 0, 0, c))
def program(self, q, k, v, m, o):
import ttnn
T16, T32 = D["T16"], D["T32"]
PT = self.PT
cores = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(self.gx - 1, self.gy - 1))])
bf, f32 = ttnn.bfloat16, ttnn.float32
table = [
([(D["CB_K"], bf, 0)], 2 * PT * T16),
([(D["CB_V"], bf, 0)], 2 * PT * T16),
([(D["CB_M"], bf, 0)], PT * T16),
([(D["CB_Q"], bf, 0)], 4 * T16),
([(D["CB_S"], f32, 1), (D["CB_SF"], f32, 0), (D["CB_SP"], f32, 0)], PT * T32),
([(D["CB_MX"], f32, 0)], T32),
([(D["CB_MB"], f32, 1)], T32),
([(D["CB_C"], bf, 0)], 2 * T16),
([(D["CB_O"], bf, 0)], 4 * T16),
]
cbs = []
modes = [ttnn.UnpackToDestMode.Default] * 64 # one entry per CB index (NUM_CIRCULAR_BUFFERS)
for ids, total in table:
fds = []
for cb_id, fmt, u32 in ids:
fds.append(ttnn.CBFormatDescriptor(buffer_index=cb_id, data_format=fmt,
page_size=T32 if fmt == f32 else T16))
if u32:
modes[cb_id] = ttnn.UnpackToDestMode.UnpackToDestFp32
cbs.append(ttnn.CBDescriptor(total_size=total, core_ranges=cores, format_descriptors=fds))
cbs.append(ttnn.CBDescriptor(total_size=4096, core_ranges=cores, format_descriptors=[
ttnn.CBFormatDescriptor(buffer_index=D["CB_SYNC"], data_format=bf, page_size=4096)]))
rt = ttnn.RuntimeArgs()
for (x, y, h, q0, nq, c) in self.assign:
rt[x][y] = [h, q0, nq, c]
common = [0] * D["N_COMMON"]
common[D["K_Q"]] = q.buffer_address()
common[D["K_K"]] = k.buffer_address()
common[D["K_V"]] = v.buffer_address()
common[D["K_M"]] = m.buffer_address()
common[D["K_O"]] = o.buffer_address()
common[D["K_STATUS"]] = self.status.buffer_address()
common[D["K_SPIN"]] = self.spin
acc_in = list(ttnn.TensorAccessorArgs(q).get_compile_time_args())
acc_out = list(ttnn.TensorAccessorArgs(o).get_compile_time_args())
acc_st = list(ttnn.TensorAccessorArgs(self.status).get_compile_time_args())
defines = [("VA_ABI_HOST", str(D["VA_ABI"]))]
if self.fast_exp:
defines.append(("VA_FASTEXP", "1"))
cc = ttnn.ComputeConfigDescriptor(math_fidelity=ttnn.MathFidelity.HiFi4, fp32_dest_acc_en=True,
dst_full_sync_en=True, math_approx_mode=False)
cc.unpack_to_dest_mode = modes
fp = ttnn.KernelDescriptor.SourceType.FILE_PATH
dm = ttnn.DataMovementConfigDescriptor
kernels = [
ttnn.KernelDescriptor(kernel_source=KERNELS["reader"], source_type=fp, core_ranges=cores,
compile_time_args=[PT] + acc_in, 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["writer"], source_type=fp, core_ranges=cores,
compile_time_args=[PT] + acc_out + acc_st, 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["compute"], source_type=fp, core_ranges=cores,
compile_time_args=[PT], runtime_args=rt, common_runtime_args=common,
defines=defines, config=cc),
]
return ttnn.ProgramDescriptor(kernels=kernels, semaphores=[], cbs=cbs)
def __call__(self, q, k, v, m, o):
import ttnn
return ttnn.generic_op([q, k, v, m, o, self.status], self.program(q, k, v, m, o))
def read_status(self):
import ttnn
s = ttnn.to_torch(self.status).numpy().view("uint32")
bad = [(int(i), [int(w) for w in s[i, 1:4]]) for i in range(s.shape[0]) if s[i, 0] != 0]
return {"aborted_cores": bad, "rows": int(s.shape[0])}