# SPDX-License-Identifier: Apache-2.0 """PaddleOCR-VL copy of the Qwen3-ASR DEC program (MT_QKNORM 0, separate embedding / LM head, S_ROPE offset). The DEC program: persistent DRAM buffers (weight arena, tables, KV cache, embedding table, STATE, logits) uploaded once, and the ``ttnn.generic_op`` program descriptor of one decode step (md_*.cpp). Adapted from the Qwen3-TTS talker megakernel (bundles/qwen3-tts tt/mk_talker/program.py, Apache-2.0). ttnn is imported lazily.""" from __future__ import annotations import os import struct import time from types import SimpleNamespace from typing import Dict, List, Optional import numpy as np import torch from . import arena as A from . import weights as E from . import geometry as G KERNELS = {r: os.path.join(G.KDIR, f"md_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")} #: fp32 CBs read by copy_tile (unpack straight to DST in fp32); fp32 CBs used as matmul / reduce operands stay default UNPACK32 = ("CB_X", "CB_X0", "CB_ACCD", "CB_ACSD", "CB_HS", "CB_RS", "CB_G", "CB_GF", "CB_TAB", "CB_SD") def f32_bits(x: float) -> int: return struct.unpack(" 4096 or self.max_pos < 64: raise ValueError("max_pos must be a multiple of 32 and <= 4096 (ATT score buffer: 128 key blocks)") self.n_layers = E.N_LAYERS self.wfid = int(wfid if wfid is not None else os.environ.get("PADDLEOCR_MK_WFID", "4")) self.mmblk = 0 self.k_max = int(k_max) g = device.compute_with_storage_grid_size() self.grid = (int(g.x), int(g.y)) opt0 = [(int(c.x), int(c.y)) for c in device.get_optimal_dram_bank_to_logical_worker_assignment(ttnn.NOC.NOC_0)] opt1 = [(int(c.x), int(c.y)) for c in device.get_optimal_dram_bank_to_logical_worker_assignment(ttnn.NOC.NOC_1)] self.atts = int(os.environ.get("PADDLEOCR_MK_ATTS", "2")) self.geo = G.build(self.grid[0], self.grid[1], opt0, opt1, atts=self.atts) self._noc = {} for x in range(self.grid[0]): for y in range(self.grid[1]): c = device.worker_core_from_logical_core(ttnn.CoreCoord(x, y)) self._noc[(x, y)] = (int(c.x), int(c.y)) t0 = time.time() pages, self.offsets = A.build_arena(profile, self.recipe, self.geo, w, self.n_layers, log=log, source=source) t1 = time.time() dram = ttnn.DRAM_MEMORY_CONFIG rm = ttnn.ROW_MAJOR_LAYOUT def up_u32(arr: np.ndarray, row_bytes: int): a = np.ascontiguousarray(arr).reshape(-1, row_bytes) t = torch.from_numpy(a.view(np.int32).reshape(a.shape[0], row_bytes // 4)) return ttnn.from_torch(t, dtype=ttnn.uint32, layout=rm, device=device, memory_config=dram) def up_f32(t: torch.Tensor): return ttnn.from_torch(t.float().contiguous(), dtype=ttnn.float32, layout=rm, device=device, memory_config=dram) def up_bf16(t: torch.Tensor): return ttnn.from_torch(t.to(torch.bfloat16).contiguous(), dtype=ttnn.bfloat16, layout=rm, device=device, memory_config=dram) self.wts = up_u32(np.asarray(pages), A.PAGE) self.gam = up_f32(A.gamma_table(w, self.n_layers)) self.rope = up_f32(A.rope_table(self.max_pos)) self.mask = up_bf16(A.mask_tiles()) self.consts = up_bf16(A.const_tiles_full()) self.embed = up_bf16(w.embed) # [V, D] bf16 rows (the step input = embed_tokens[last token]) self.nb_blocks = self.max_pos // 32 kv_pages = E.N_LAYERS * 2 * G.NG * self.nb_blocks # [56 = layer x (k, v), 8 groups, MAXP, 128] bf16 TILE (tile pages; ttnn.fill_cache(kv, x, l * 2 + kv) fills a # layer's K or V from any prefill) self.kv = ttnn.zeros([E.N_LAYERS * 2, G.NG, self.max_pos, E.HD], dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=dram) self.hc = self.dims.hc self.logits = up_f32(torch.zeros(G.NW, self.hc * 32)) self.state = up_u32(np.zeros((1, 8192), np.uint8), 8192) n = self.grid[0] * self.grid[1] self.dbg = up_u32(np.zeros((n, G.SYNC_BYTES), np.uint8), G.SYNC_BYTES) self.arena_bytes = int(np.asarray(pages).nbytes) log(f"[mk_dec] DEC {profile} {self.recipe}: arena {self.arena_bytes / 2**20:.0f} MiB (pack {t1 - t0:.0f} s, " f"upload {time.time() - t1:.0f} s), grid {self.grid}, KV {kv_pages * G.KV_PAGE / 2**20:.0f} MiB, " f"CBs {G.cb_total(self.dims, self.fa, self.fm, self.atts, self.fh) / 1024:.0f} KiB") self._desc = {} # ------------------------------------------------------------------ descriptor def persistent(self) -> List: return [self.wts, self.gam, self.rope, self.mask, self.consts, self.kv, self.logits, self.dbg, self.embed, self.state] def noc(self, c): return self._noc[tuple(c)] def _common(self, n_layers: int, flags: int, spin: int, stop: int = 0): c = G.common_args(self.geo, self.noc) c[G.K_STOP] = int(stop) c[G.K_NL] = int(n_layers) c[G.K_SPIN] = int(spin) c[G.K_EPS] = f32_bits(E.EPS) c[G.K_INV_D] = f32_bits(1.0 / self.dims.d) c[G.K_INV_HD] = f32_bits(1.0 / E.HD) c[G.K_STATE] = self.state.buffer_address() c[G.K_EMBED] = self.embed.buffer_address() c[G.K_LOGITS] = self.logits.buffer_address() c[G.K_WTS] = self.wts.buffer_address() c[G.K_GAM] = self.gam.buffer_address() c[G.K_ROPE] = self.rope.buffer_address() c[G.K_KV] = self.kv.buffer_address() c[G.K_NB] = self.nb_blocks c[G.K_MASK] = self.mask.buffer_address() c[G.K_CONST] = self.consts.buffer_address() c[G.K_DBG] = self.dbg.buffer_address() c[G.K_FLAGS] = int(flags) c[G.K_MAXP] = self.max_pos c[G.K_NEG] = f32_bits(A.NEG_MASK) c[G.K_KMAX] = self.k_max return c def program(self, n_layers: int = E.N_LAYERS, flags: int = 0, spin: int = 1 << 26, stop: int = 0): key = (n_layers, flags, spin, stop) if key in self._desc: return self._desc[key] ttnn = self.ttnn gx, gy = self.grid d = self.dims allc = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))]) dt = {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b, "bfp4": ttnn.bfloat4_b, "fp32": ttnn.float32, "raw": ttnn.uint32} cbs = [] modes = [ttnn.UnpackToDestMode.Default] * 64 unp = {getattr(G, n) for n in UNPACK32} for cb in G.cb_table(d, self.fa, self.fm, self.atts, self.fh): fds = [] for cid, fmt, page, tile, _u in cb.ids: kw = {} if tile is not None: kw["tile"] = ttnn.TileDescriptor(tile[0], tile[1], False) fds.append(ttnn.CBFormatDescriptor(buffer_index=cid, data_format=dt[fmt], page_size=cb.total if fmt == "raw" else page, **kw)) if cid in unp: modes[cid] = ttnn.UnpackToDestMode.UnpackToDestFp32 cbs.append(ttnn.CBDescriptor(total_size=cb.total, core_ranges=allc, format_descriptors=fds)) rb = G.ring_bytes(self.fa, self.fm, self.fh) defines = [ ("MT_DT", d.d_t), ("MT_IT", d.i_t), ("MT_XS", d.xs), ("MT_FS", d.fs), ("MT_NHD", d.hd_dense), ("MT_D", d.d), ("MT_PT_A", G.PACKET_TILES[self.fa]), ("MT_PT_M", G.PACKET_TILES[self.fm]), ("MT_PT_H", G.PACKET_TILES_H), ("MT_TB_H", G.TILE_BYTES[self.fh]), ("MT_HC", self.hc), ("MT_TB_A", G.TILE_BYTES[self.fa]), ("MT_TB_M", G.TILE_BYTES[self.fm]), ("MT_RING_A", rb["A"]), ("MT_RING_M", rb["M"]), ("MT_RING_H", rb["H"]), ("MT_A_TILES", d.a_tiles), ("MT_M_TILES", d.m_tiles), ("MT_H_TILES", d.h_tiles), ("MT_FS_CAP", max(d.fs * G.TINY16, 512) // G.TINY16), ("MT_KV_RING_BLOCKS", G.KV_RING_BLOCKS), ("MT_WFID", self.wfid), ("MT_MMBLK", self.mmblk), ("MT_ATTS", self.atts), ("MT_QKNORM", 0), ] defines = [(k, str(v)) for k, v in defines] args = G.core_args(self.geo, self.noc, self.offsets) common = self._common(n_layers, flags, spin, stop) ct = list(ttnn.TensorAccessorArgs(self.wts).get_compile_time_args()) # core sets by the NoC of the weight reads: MM cores reading on NOC1 swap the RISC NoCs s1 = {m.xy for m in self.geo.mm if m.noc == 1} s0 = [(x, y) for y in range(gy) for x in range(gx) if (x, y) not in s1] crs = lambda cs: ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(*c), ttnn.CoreCoord(*c)) for c in cs]) # noqa fp = ttnn.KernelDescriptor.SourceType.FILE_PATH dm = ttnn.DataMovementConfigDescriptor kernels = [] for cores, nc_noc, br_noc in ((s0, ttnn.NOC.NOC_0, ttnn.NOC.NOC_1), (sorted(s1), ttnn.NOC.NOC_1, ttnn.NOC.NOC_0)): rt = ttnn.RuntimeArgs() for c in cores: rt[c[0]][c[1]] = args[c] kernels.append(ttnn.KernelDescriptor( kernel_source=KERNELS["ncrisc"], source_type=fp, core_ranges=crs(cores), compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, config=dm(processor=ttnn.DataMovementProcessor.RISCV_1, noc=nc_noc))) rt2 = ttnn.RuntimeArgs() for c in cores: rt2[c[0]][c[1]] = args[c] kernels.append(ttnn.KernelDescriptor( kernel_source=KERNELS["brisc"], source_type=fp, core_ranges=crs(cores), compile_time_args=ct, runtime_args=rt2, common_runtime_args=common, defines=defines, config=dm(processor=ttnn.DataMovementProcessor.RISCV_0, noc=br_noc))) rt3 = ttnn.RuntimeArgs() for x in range(gx): for y in range(gy): rt3[x][y] = args[(x, y)] 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 kernels.append(ttnn.KernelDescriptor(kernel_source=KERNELS["trisc"], source_type=fp, core_ranges=allc, compile_time_args=[], runtime_args=rt3, common_runtime_args=common, defines=defines, config=cc)) sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=allc, initial_value=0) for i in (0, 1)] desc = ttnn.ProgramDescriptor(kernels=kernels, semaphores=sems, cbs=cbs) self._desc[key] = desc return desc def io(self) -> List: return self.persistent() def run(self, n_layers: int = E.N_LAYERS, flags: int = 0, spin: int = 1 << 26, stop: int = 0): """Enqueue one TLK step (no host sync; trace-capturable).""" self.ttnn.generic_op(self.io(), self.program(n_layers, flags, spin, stop)) # ------------------------------------------------------------------ host helpers def read_logits(self) -> torch.Tensor: """The last step's raw logits [V] (fp32; padded head columns dropped).""" t = self.ttnn.to_torch(self.logits).reshape(-1).float() return t[:G.VOCAB] def state_host(self, L: int, token0: int, max_new: int, eos=(2,), temperature: float = 0.0, top_k: int = 0, top_p: float = 1.0, seed: int = 0, done: bool = False, ntok: int = 1, rope_delta: int = 0): """Host STATE page (ttnn host tensor) after a prefill of L rows that produced token 0 (``ntok`` > 1: the step input is ``token0`` at position L + ntok - 1, the teacher-forced gates).""" st = np.zeros(2048, np.uint32) do_sample = temperature is not None and temperature > 0 st[G.S_DOSAMPLE] = 1 if do_sample else 0 st[G.S_INVT] = f32_bits(1.0 / temperature) if do_sample else f32_bits(1.0) st[G.S_TOPK] = int(top_k or 0) st[G.S_TOPP] = f32_bits(float(top_p if top_p is not None else 1.0)) st[G.S_SEED_LO] = int(seed) & 0xFFFFFFFF st[G.S_SEED_HI] = (int(seed) >> 32) & 0xFFFFFFFF st[G.S_L] = int(L) st[G.S_MAXNEW] = int(max_new) eos = tuple(int(e) for e in eos) or (2,) st[G.S_EOS0], st[G.S_EOS1] = eos[0], eos[1] if len(eos) > 1 else eos[0] st[G.S_ROPE] = int(rope_delta) & 0xFFFFFFFF st[G.S_NVOCAB] = G.VOCAB st[G.S_NTOK] = int(ntok) st[G.S_LAST] = int(token0) st[G.S_TOKENS] = int(token0) if done or int(token0) in eos or max_new <= 1: st[G.S_DONE] = 1 st[G.S_STOP] = 1 if int(token0) in eos else 2 t = torch.from_numpy(st.view(np.int32).reshape(1, 2048)) return self.ttnn.from_torch(t, dtype=self.ttnn.uint32, layout=self.ttnn.ROW_MAJOR_LAYOUT) def write_state(self, host_state) -> None: self.ttnn.copy_host_to_device_tensor(host_state, self.state) def read_state(self) -> np.ndarray: return self.ttnn.to_torch(self.state).reshape(-1).numpy().view(np.uint32).copy() def read_dbg(self) -> torch.Tensor: n = self.grid[0] * self.grid[1] t = self.ttnn.to_torch(self.dbg).reshape(n, G.SYNC_BYTES // 4).to(torch.int64) & 0xFFFFFFFF return t def read_prof(self): """Layer-1 time stamps (cycles) of MM core 0 and ATT core 0 (brisc tstamp): dict of phase -> us.""" d = self.read_dbg() mm = self.geo.idx(self.geo.mm[0].xy) at = self.geo.idx(self.geo.att[0]) p0 = G.SYNC_PROF // 4 m = [int(d[mm, p0 + i]) for i in range(9)] a = [int(d[at, p0 + i]) for i in range(10, 15)] f = 1.35e3 # cycles per us (AICLK ~1.35 GHz) def us(x, i, j): return ((x[j] - x[i]) & 0xFFFFFFFF) / f return {"mm_norm1_gather": us(m, 0, 1), "mm_qkv_to_sent": us(m, 1, 2), "mm_wait_attention": us(m, 2, 3), "mm_oproj_norm2": us(m, 3, 4), "mm_gateup_fgather": us(m, 4, 5), "mm_layer1_total": us(m, 0, 5), "att_wait_q": us(a, 0, 1), "att_kv_softmax_pv": us(a, 1, 3), "att_send_o": us(a, 3, 4)} def write_kv(self, k: torch.Tensor, v: torch.Tensor, n_pos: int): """Host upload of K / V ``[28, 8, P, 128]`` (positions 0..n_pos-1) into the KV cache (tests: seed the cache from the CPU emulator). Rewrites the whole buffer.""" ttnn = self.ttnn out = torch.zeros(E.N_LAYERS, 2, G.NG, self.max_pos, E.HD) out[:, 0, :, :n_pos] = k[:, :, :n_pos].float() out[:, 1, :, :n_pos] = v[:, :, :n_pos].float() host = ttnn.from_torch(out.reshape(E.N_LAYERS * 2, G.NG, self.max_pos, E.HD).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT) ttnn.copy_host_to_device_tensor(host, self.kv) def read_kv(self) -> torch.Tensor: """[28, 2, 8, MAXP, 128] float (tests).""" t = self.ttnn.to_torch(self.kv).float() return t.reshape(E.N_LAYERS, 2, G.NG, self.max_pos, E.HD)