# SPDX-License-Identifier: Apache-2.0 """Decoder engine ``mk`` (adapted from this workspace's Qwen3-ASR DEC engine, Apache-2.0): ttnn traced prefill (K / V of ERNIE's 2 kv heads repeated to the kernel's 8 groups, written straight into the DEC megakernel's KV tensor) + the DEC megakernel (one launch per token, on-device greedy / sampling, token ring and stop rule in STATE). eng = MkDecoder(device, W, cfg, pre_buckets=(...), max_pos=4096, recipe={...}) eng.capture() # prefill traces per bucket + a trace of BATCH DEC launches lg = eng.prefill(rows, cos, sin, L) # host logits of row L - 1 (token 0 is sampled on the host) eng.start(L, token0, max_new, rope_delta, temperature, top_k, top_p, seed) while True: eng.run_batch() # BATCH launches (no-ops once STATE says done) ntok, done, stop, toks = eng.poll() # one 8 KB D2H read of STATE """ from __future__ import annotations import os import time from typing import Dict, Optional, Sequence, Tuple import numpy as np import torch from . import geometry as G from . import weights as E from .program import DecTLK from .weights import load_dec class MkDecoder: device_sampling = True def __init__(self, device, W: Dict[str, torch.Tensor], cfg, *, pre_buckets: Sequence[int], max_pos: int, recipe: Optional[Dict[str, str]] = None, batch: int = 8, source: str = "", profile: str = "1.6", k_max: int = 64, pre_precision: Optional[Dict[str, str]] = None, log=print): """``cfg``: config.DecoderConfig; ``W``: the checkpoint dict; ``source``: the checkpoint revision (arena cache key); ``profile``: the serve profile (arena cache key).""" from ..ttnn_decoder import TtnnDecoder self.ttnn = __import__("ttnn") self.device, self.cfg, self.log = device, cfg, log self.recipe = dict(recipe or E.RECIPES["bfp8"]) self.batch = int(batch) t0 = time.time() w = load_dec(W) self.tlk = DecTLK(device, profile, self.recipe, w, max_pos=max_pos, source=source, k_max=k_max, log=log) del w pp = dict(attn="bf16", mlp="bfp8", head="bf16", pre_fid="HiFi4") pp.update(pre_precision or {}) self.pre = TtnnDecoder(device, W, cfg, pre_buckets, max_pos, attn_dtype=pp["attn"], mlp_dtype=pp["mlp"], head_dtype=pp["head"], kv=self.tlk.kv, kv_rep=E.KV_REP, decode=False, pre_fidelity=pp["pre_fid"]) self.trace = None log(f"[mk_dec] engine ready in {time.time() - t0:.1f}s (recipe {self.recipe}, batch {self.batch})") @property def buckets(self): return self.pre.buckets @property def max_pos(self) -> int: return self.tlk.max_pos def prefill(self, rows: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, L: int) -> torch.Tensor: self.pre.prefill(rows, cos, sin, L) return self.pre.logits_host() def start(self, L: int, token0: int, max_new: int, rope_delta: int, temperature: float = 0.0, top_k: int = 0, top_p: float = 1.0, seed: Optional[int] = None, eos=(2,)): seed = int(seed) if seed is not None else int.from_bytes(os.urandom(8), "little") self.tlk.write_state(self.tlk.state_host(L, token0, max_new, eos, temperature, top_k, top_p, seed, rope_delta=rope_delta)) def _launches(self, n: int): for _ in range(n): self.tlk.run() def run_batch(self): ttnn = self.ttnn if self.trace is not None: ttnn.execute_trace(self.device, self.trace, cq_id=0, blocking=False) else: self._launches(self.batch) def poll(self) -> Tuple[int, bool, int, np.ndarray]: """(n tokens so far, done, stop code, ring [S_TOKENS_MAX]: token i at ring[i % S_TOKENS_MAX]).""" st = self.tlk.read_state() n = int(st[G.S_NTOK]) return n, bool(st[G.S_DONE]), int(st[G.S_STOP]), st[G.S_TOKENS:G.S_TOKENS + G.S_TOKENS_MAX].copy() @staticmethod def ring_tokens(ring: np.ndarray, start: int, n: int): return [int(ring[i % G.S_TOKENS_MAX]) for i in range(start, n)] def tf_step(self, L: int, s: int, token_in: int, rope_delta: int) -> torch.Tensor: """Teacher-forced step s >= 1 (input = token_in at KV position L + s - 1): logits [V] (host), no sampling.""" self.tlk.write_state(self.tlk.state_host(L, token_in, 1 << 20, ntok=s, rope_delta=rope_delta)) self.tlk.run(flags=G.F_NOSAMPLE) return self.tlk.read_logits() def warmup(self, prefill: bool = True): """Compile the prefill buckets and the DEC program (a no-op launch: STATE done) before any trace capture.""" self.pre.warmup(prefill) self.tlk.write_state(self.tlk.state_host(1, 2, 1, done=True)) self._launches(1) self.tlk.run(flags=G.F_NOSAMPLE) # the logits-only program of host-sampled requests (tf_step), built now 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) self.pre.capture(prefill=prefill) self.trace = ttnn.begin_trace_capture(self.device, cq_id=0) self._launches(self.batch) ttnn.end_trace_capture(self.device, self.trace, cq_id=0) ttnn.synchronize_device(self.device) def release(self): if self.trace is not None: self.ttnn.release_trace(self.device, self.trace) self.trace = None self.pre.release()