# SPDX-License-Identifier: Apache-2.0 # Adapted from this workspace's Qwen3-ASR bundle (tt_qwen3_asr/tt/ttnn_decoder.py, Apache-2.0), itself adapted from # tt-metal models/demos/audio/qwen3_tts (Apache-2.0, Tenstorrent): the M=1 decode matmul configs, fused QKV, # nlp_create_qkv_heads_decode + rotary_embedding_hf + paged_fused_update_cache + sdpa_decode, the KV fill_cache # chunking and the persistent-input trace pattern. Changes for ERNIE-4.5-0.3B: no q / k norm, GQA 16 : 2, untied # LM head, per-request M-RoPE tables for the prefill (3-D positions of the image tokens) and a decode RoPE position # = KV index + delta. """ttnn decoder of PaddleOCR-VL (ERNIE-4.5-0.3B): bucketed traced prefill, traced decode step, LM head. * ``prefill(rows [L, D] host, cos, sin [L, 128] host, L)``: rows zero-padded to the bucket, H2D into the bucket's persistent inputs, the bucket's trace (eager before ``capture``): KV [0, Lb), logits of row L - 1. * ``step(token_row [D] host, kv_pos, rope_pos)``: one decode step; ``self.logits`` [1, 1, 1, V] fp32 row-major. * ``kv``: optional external KV tensor [2 * layers, kv_rep * 2, S, 128] (the DEC megakernel's, kv heads repeated ``kv_rep`` times): the prefill writes layer l's K / V into batch rows 2 l / 2 l + 1 and allocates no caches. """ from __future__ import annotations from typing import Dict, Sequence import torch from ..config import DecoderConfig CACHE_TILE_MULTIPLE = 64 DECODE_IN0_BLOCK_W = 4 DECODE_MAX_SUBBLOCK = 4 TARGET_PER_CORE_N = 5 def ttnn_dtype(name: str): import ttnn return {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b, "bfp4": ttnn.bfloat4_b, "fp32": ttnn.float32}[name] def decode_matmul_config(device, in_features: int, out_features: int, fused_activation=None): import ttnn k_tiles, n_tiles = in_features // 32, out_features // 32 grid = device.compute_with_storage_grid_size() in0_block_w = 8 if k_tiles % 8 == 0 and k_tiles > 64 else DECODE_IN0_BLOCK_W if k_tiles % in0_block_w: return None cols = grid.x rows = max(1, min(grid.y, round(n_tiles / (cols * TARGET_PER_CORE_N)))) per_core_n = -(-n_tiles // (cols * rows)) return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig( compute_with_storage_grid_size=(cols, rows), in0_block_w=in0_block_w, out_subblock_h=1, out_subblock_w=next(w for w in range(min(per_core_n, DECODE_MAX_SUBBLOCK), 0, -1) if per_core_n % w == 0), per_core_M=1, per_core_N=per_core_n, fuse_batch=True, fused_activation=fused_activation, mcast_in0=True) def rope_rows(positions: torch.Tensor, head_dim: int = 128, theta: float = 500000.0): inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.int64).float() / head_dim)) fr = positions.float()[:, None] * inv[None] emb = torch.cat([fr, fr], -1) return emb.cos(), emb.sin() class TtnnDecoder: def __init__(self, device, W: Dict[str, torch.Tensor], cfg: DecoderConfig, buckets: Sequence[int], max_seq: int, attn_dtype: str = "bf16", mlp_dtype: str = "bfp8", head_dtype: str = "bf16", residual_fp32: bool = True, kv=None, kv_rep: int = 1, decode: bool = True, pre_fidelity: str = "HiFi4"): import ttnn self.ttnn, self.device, self.c = ttnn, device, cfg self.buckets = sorted(int(b) for b in buckets) self.max_seq = -(-int(max_seq) // CACHE_TILE_MULTIPLE) * CACHE_TILE_MULTIPLE self.cc_pre = ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=getattr(ttnn.MathFidelity, pre_fidelity), math_approx_mode=False, fp32_dest_acc_en=True, packer_l1_acc=True) self.cc = ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=ttnn.MathFidelity.HiFi4, math_approx_mode=False, fp32_dest_acc_en=True, packer_l1_acc=True) self.res_dtype = ttnn.float32 if residual_fp32 else ttnn.bfloat16 up = lambda t, dt: ttnn.from_torch(t.float().contiguous(), dtype=dt, layout=ttnn.TILE_LAYOUT, # noqa device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) ad, md = ttnn_dtype(attn_dtype), ttnn_dtype(mlp_dtype) self.layers = [] for i in range(cfg.layers): p = f"model.layers.{i}." qkv = torch.cat([W[p + "self_attn.q_proj.weight"], W[p + "self_attn.k_proj.weight"], W[p + "self_attn.v_proj.weight"]], 0).float() nrm = lambda n: up(W[p + n].reshape(1, 1, 1, -1), ttnn.bfloat16) # noqa: E731 self.layers.append({ "in_norm": nrm("input_layernorm.weight"), "post_norm": nrm("post_attention_layernorm.weight"), "qkv": up(qkv.T, ad), "o": up(W[p + "self_attn.o_proj.weight"].float().T, ad), "gate": up(W[p + "mlp.gate_proj.weight"].float().T, md), "up": up(W[p + "mlp.up_proj.weight"].float().T, md), "down": up(W[p + "mlp.down_proj.weight"].float().T, md), }) self.norm = up(W["model.norm.weight"].reshape(1, 1, 1, -1), ttnn.bfloat16) self.head = up(W["lm_head.weight"].float().T, ttnn_dtype(head_dtype)) # [D, V] self.kv_ext, self.kv_rep = kv, int(kv_rep) self.decode_enabled = decode and kv is None if kv is None: mk = lambda: ttnn.zeros([1, cfg.kv_heads, self.max_seq, cfg.head_dim], dtype=ttnn.bfloat16, # noqa layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) self.k_cache = [mk() for _ in self.layers] self.v_cache = [mk() for _ in self.layers] g = device.compute_with_storage_grid_size() self.n_cores = int(g.x) * int(g.y) silu = ttnn.UnaryWithParam(ttnn.UnaryOpType.SILU) L0 = self.layers[0] self.mm = {n: decode_matmul_config(device, *tuple(L0[n].shape)[-2:], silu if n == "gate" else None) for n in ("qkv", "o", "gate", "up", "down")} self.k_shard = self._single_core_shard(0) self.v_shard = self._single_core_shard(1) self.sdpa_dec_cfg = ttnn.SDPAProgramConfig(compute_with_storage_grid_size=(g.x, g.y), q_chunk_size=32, k_chunk_size=0, exp_approx_mode=False) self.sdpa_pre_cfg = ttnn.SDPAProgramConfig(compute_with_storage_grid_size=(g.x, g.y), q_chunk_size=64, k_chunk_size=64, exp_approx_mode=False) self._x = ttnn.from_torch(torch.zeros(1, 1, 1, cfg.d), dtype=self.res_dtype, layout=ttnn.TILE_LAYOUT, device=device) self._pos = ttnn.from_torch(torch.zeros(1, dtype=torch.int32), device=device) c, s = self._rope_step(0) self._cos = ttnn.from_torch(c, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device) self._sin = ttnn.from_torch(s, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device) self._pin, self._psel, self._prope = {}, {}, {} for Lb in self.buckets: z = lambda cols: ttnn.from_torch(torch.zeros(1, 1, Lb, cols), dtype=ttnn.bfloat16, # noqa: E731 layout=ttnn.TILE_LAYOUT, device=device) self._pin[Lb] = z(cfg.d) self._psel[Lb] = ttnn.from_torch(torch.zeros(1, 1, 1, Lb), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device) self._prope[Lb] = (z(cfg.head_dim), z(cfg.head_dim)) self.step_trace = None self.step_out = None self.pre_traces: Dict[int, int] = {} self.pre_outs: Dict[int, object] = {} self._poscache = {} self.logits = None def _single_core_shard(self, column): ttnn = self.ttnn return ttnn.MemoryConfig( ttnn.TensorMemoryLayout.HEIGHT_SHARDED, ttnn.BufferType.L1, ttnn.ShardSpec(ttnn.CoreRangeSet({ttnn.CoreRange(ttnn.CoreCoord(column, 0), ttnn.CoreCoord(column, 0))}), (32, self.c.head_dim), ttnn.ShardOrientation.ROW_MAJOR)) def _rope_step(self, pos: int): c, s = rope_rows(torch.tensor([int(pos)]), self.c.head_dim, self.c.theta) return (c.reshape(1, 1, 1, -1).expand(1, 1, 32, self.c.head_dim).contiguous(), s.reshape(1, 1, 1, -1).expand(1, 1, 32, self.c.head_dim).contiguous()) def bucket(self, L: int) -> int: for b in self.buckets: if L <= b: return b raise ValueError(f"prompt of {L} rows exceeds the largest prefill bucket {self.buckets[-1]}") # ------------------------------------------------------------------ pieces def _rms(self, x, w): ttnn = self.ttnn y = ttnn.rms_norm(x, weight=w, epsilon=self.c.eps, compute_kernel_config=self.cc) return ttnn.typecast(y, ttnn.bfloat16) if y.dtype != ttnn.bfloat16 else y def _add(self, x, y): ttnn = self.ttnn if self.res_dtype == ttnn.float32 and y.dtype != ttnn.float32: y = ttnn.typecast(y, ttnn.float32) return ttnn.add(x, y) def _mlp(self, x, L, decode: bool): ttnn = self.ttnn cfg = self.mm if decode else {} cc = self.cc if decode else self.cc_pre gate = ttnn.linear(x, L["gate"], compute_kernel_config=cc, program_config=cfg.get("gate")) if cfg.get("gate") is None or cfg["gate"].fused_activation is None: gate = ttnn.silu(gate) upv = ttnn.linear(x, L["up"], compute_kernel_config=cc, program_config=cfg.get("up")) return ttnn.linear(ttnn.multiply(gate, upv), L["down"], compute_kernel_config=cc, program_config=cfg.get("down")) def _rotate(self, x, cos, sin): return self.ttnn.experimental.rotary_embedding_hf(x, cos, sin, is_decode_mode=False, compute_kernel_config=self.cc) # ------------------------------------------------------------------ prefill def _prefill_ops(self, Lb: int): ttnn, c = self.ttnn, self.c cos, sin = self._prope[Lb] x = self._pin[Lb] if self.res_dtype != ttnn.bfloat16: x = ttnn.typecast(x, self.res_dtype) for i, L in enumerate(self.layers): a = self._rms(x, L["in_norm"]) qkv = ttnn.linear(a, L["qkv"], compute_kernel_config=self.cc_pre, dtype=ttnn.bfloat16) q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=c.heads, num_kv_heads=c.kv_heads, transpose_k_heads=False, memory_config=ttnn.DRAM_MEMORY_CONFIG) ttnn.deallocate(qkv) q = self._rotate(q, cos, sin) k = self._rotate(k, cos, sin) if self.kv_ext is not None: kk = ttnn.repeat_interleave(k, self.kv_rep, dim=1) if self.kv_rep > 1 else k vv = ttnn.repeat_interleave(v, self.kv_rep, dim=1) if self.kv_rep > 1 else v self._seed(self.kv_ext, 2 * i, kk, Lb) self._seed(self.kv_ext, 2 * i + 1, vv, Lb) else: self._seed(self.k_cache[i], 0, k, Lb) self._seed(self.v_cache[i], 0, v, Lb) o = ttnn.transformer.scaled_dot_product_attention(q, k, v, is_causal=True, scale=c.head_dim ** -0.5, compute_kernel_config=self.cc, program_config=self.sdpa_pre_cfg) o = ttnn.experimental.nlp_concat_heads(o, memory_config=ttnn.DRAM_MEMORY_CONFIG) x = self._add(x, ttnn.linear(o, L["o"], compute_kernel_config=self.cc_pre)) a = self._rms(x, L["post_norm"]) x = self._add(x, self._mlp(a, L, False)) last = ttnn.matmul(self._psel[Lb], ttnn.typecast(x, ttnn.bfloat16) if x.dtype != ttnn.bfloat16 else x, compute_kernel_config=self.cc, dtype=ttnn.float32) # [1, 1, 1, D] = row L-1 h = ttnn.rms_norm(last, weight=self.norm, epsilon=c.eps, compute_kernel_config=self.cc) lg = ttnn.linear(ttnn.typecast(h, ttnn.bfloat16), self.head, compute_kernel_config=self.cc, dtype=ttnn.float32) return ttnn.to_layout(lg, ttnn.ROW_MAJOR_LAYOUT) def _seed(self, cache, batch: int, x, length: int): ttnn = self.ttnn heads = int(x.shape[1]) tiles = (length + 31) // 32 if heads * tiles <= self.n_cores: ttnn.fill_cache(cache, x, batch) return step = max(1, self.n_cores // heads) for start in range(0, tiles, step): first, last = 32 * start, min(32 * (start + step), length) chunk = ttnn.slice(x, (0, 0, first, 0), (1, heads, last, self.c.head_dim)) ttnn.fill_cache(cache, chunk, batch, update_idx=first) ttnn.deallocate(chunk) def prefill_upload(self, rows: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, L: int) -> int: """H2D of one prompt (rows [L, D], M-RoPE tables [L, 128]) into its bucket's persistent inputs.""" ttnn = self.ttnn Lb = self.bucket(L) x = torch.zeros(1, 1, Lb, self.c.d) x[0, 0, :L] = rows[:L].float() cs = torch.ones(1, 1, Lb, self.c.head_dim) sn = torch.zeros(1, 1, Lb, self.c.head_dim) cs[0, 0, :L] = cos[:L].float() sn[0, 0, :L] = sin[:L].float() sel = torch.zeros(1, 1, 1, Lb) sel[0, 0, 0, L - 1] = 1.0 bf = lambda t: ttnn.from_torch(t, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT) # noqa: E731 ttnn.copy_host_to_device_tensor(bf(x), self._pin[Lb]) ttnn.copy_host_to_device_tensor(bf(cs), self._prope[Lb][0]) ttnn.copy_host_to_device_tensor(bf(sn), self._prope[Lb][1]) ttnn.copy_host_to_device_tensor(bf(sel), self._psel[Lb]) return Lb def prefill(self, rows: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, L: int): ttnn = self.ttnn Lb = self.prefill_upload(rows, cos, sin, L) if Lb in self.pre_traces: ttnn.execute_trace(self.device, self.pre_traces[Lb], cq_id=0, blocking=False) self.logits = self.pre_outs[Lb] else: self.logits = self._prefill_ops(Lb) return self.logits # ------------------------------------------------------------------ decode step def _step_ops(self): ttnn, c = self.ttnn, self.c x = self._x for i, L in enumerate(self.layers): a = self._rms(x, L["in_norm"]) qkv = ttnn.linear(a, L["qkv"], compute_kernel_config=self.cc, program_config=self.mm["qkv"], dtype=ttnn.bfloat16) q, k, v = ttnn.experimental.nlp_create_qkv_heads_decode( ttnn.reshape(qkv, (1, 1, 1, qkv.shape[-1])), num_heads=c.heads, num_kv_heads=c.kv_heads) q = ttnn.sharded_to_interleaved(q) k = ttnn.sharded_to_interleaved(k) q = self._rotate(q, self._cos, self._sin) k = self._rotate(k, self._cos, self._sin) ttnn.experimental.paged_fused_update_cache( self.k_cache[i], ttnn.to_memory_config(k, self.k_shard), self.v_cache[i], ttnn.to_memory_config(v, self.v_shard), update_idxs_tensor=self._pos, page_table=None) att = ttnn.transformer.scaled_dot_product_attention_decode( q, self.k_cache[i], self.v_cache[i], cur_pos_tensor=self._pos, scale=c.head_dim ** -0.5, compute_kernel_config=self.cc, program_config=self.sdpa_dec_cfg) att = ttnn.reshape(ttnn.experimental.nlp_concat_heads(att), (1, 1, 1, c.heads * c.head_dim)) x = self._add(x, ttnn.linear(att, L["o"], compute_kernel_config=self.cc, program_config=self.mm["o"])) a = self._rms(x, L["post_norm"]) x = self._add(x, self._mlp(a, L, True)) h = self._rms(x, self.norm) lg = ttnn.linear(h, self.head, compute_kernel_config=self.cc, dtype=ttnn.float32) return ttnn.to_layout(lg, ttnn.ROW_MAJOR_LAYOUT) def _pos_host(self, kv_pos: int, rope_pos: int): ttnn = self.ttnn key = (kv_pos, rope_pos) h = self._poscache.get(key) if h is None: c, s = self._rope_step(rope_pos) if len(self._poscache) > 8192: self._poscache.clear() h = self._poscache[key] = (ttnn.from_torch(torch.full((1,), int(kv_pos), dtype=torch.int32)), ttnn.from_torch(c, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT), ttnn.from_torch(s, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT)) return h def step(self, row: torch.Tensor, kv_pos: int, rope_pos: int): ttnn = self.ttnn x = row.float().reshape(1, 1, 1, self.c.d) hp, hc, hs = self._pos_host(kv_pos, rope_pos) ttnn.copy_host_to_device_tensor(ttnn.from_torch(x, dtype=self.res_dtype, layout=ttnn.TILE_LAYOUT), self._x) ttnn.copy_host_to_device_tensor(hp, self._pos) ttnn.copy_host_to_device_tensor(hc, self._cos) ttnn.copy_host_to_device_tensor(hs, self._sin) if self.step_trace is not None: ttnn.execute_trace(self.device, self.step_trace, cq_id=0, blocking=False) self.logits = self.step_out else: self.logits = self._step_ops() return self.logits def logits_host(self) -> torch.Tensor: return self.ttnn.to_torch(self.logits).float().reshape(-1, self.logits.shape[-1])[0, :self.c.vocab] # ------------------------------------------------------------------ traces def warmup(self, prefill: bool = True): if self.decode_enabled: self._step_ops() for Lb in self.buckets if prefill else (): self._prefill_ops(Lb) self.ttnn.synchronize_device(self.device) self._warm = True def capture(self, prefill: bool = True): ttnn = self.ttnn if not getattr(self, "_warm", False): self.warmup(prefill) if self.decode_enabled: self.step_trace = ttnn.begin_trace_capture(self.device, cq_id=0) self.step_out = self._step_ops() ttnn.end_trace_capture(self.device, self.step_trace, cq_id=0) for Lb in self.buckets if prefill else (): tid = ttnn.begin_trace_capture(self.device, cq_id=0) self.pre_outs[Lb] = self._prefill_ops(Lb) ttnn.end_trace_capture(self.device, tid, cq_id=0) self.pre_traces[Lb] = tid ttnn.synchronize_device(self.device) def release(self): ttnn = self.ttnn if self.step_trace is not None: ttnn.release_trace(self.device, self.step_trace) self.step_trace = None for tid in self.pre_traces.values(): ttnn.release_trace(self.device, tid) self.pre_traces.clear()