# SPDX-License-Identifier: Apache-2.0 """Decoder engine ``mk``: the ttnn traced prefill (K / V written straight into the DEC-MoE megakernel's KV tensor) + the DEC-MoE megakernel (one launch per token: on-device routing / expert gather, greedy / sampling, n-gram bans, circular token ring and the stop rule in STATE). Adapted from this workspace's GLM-OCR DEC engine (Apache-2.0). eng = MkDecoder(device, W, buckets, max_pos) eng.capture() # prefill traces per bucket + a trace of BATCH launches lg = eng.prefill(rows, L) # host logits of row L - 1 (token 0 is chosen on the host) eng.start(L, token0, max_new, ...) 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 Optional, Sequence, Tuple import numpy as np import torch from . import geometry as G from .program import DecMoE, RECIPES class MkDecoder: device_sampling = True def __init__(self, device, W, buckets: Sequence[int], max_pos: int, recipe=None, batch: int = 8, source: str = "", k_max: int = 64, attk: Optional[int] = None, pre_precision=None, log=print): from ..ttnn_decoder import TtnnDecoder self.ttnn = __import__("ttnn") self.device, self.log = device, log self.recipe = dict(recipe or RECIPES["bfp8"]) self.batch = int(batch) t0 = time.time() self.tlk = DecMoE(device, W, self.recipe, max_pos=max_pos, source=source, k_max=k_max, attk=attk, log=log) pp = dict(attn="bf16", mlp="bfp8", experts="bfp8", head="bf16", pre_fid="HiFi2") pp.update(pre_precision or {}) self.pre = TtnnDecoder(device, W, buckets, self.tlk.max_pos, attn_dtype=pp["attn"], mlp_dtype=pp["mlp"], expert_dtype=pp["experts"], head_dtype=pp["head"], kv=self.tlk.kv, decode=False, pre_fidelity=pp["pre_fid"]) self.trace = None log(f"[mk_moe] 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 bucket(self, L: int) -> int: return self.pre.bucket(L) def prefill(self, rows: torch.Tensor, L: int) -> torch.Tensor: self.pre.prefill(rows, L) return self.pre.logits_host() def start(self, L: int, token0: int, max_new: int, temperature: float = 0.0, top_k: int = 0, top_p: float = 1.0, seed: Optional[int] = None, penalty: float = 1.0, seen_ids=None, eos=(1, 1), ntok: int = 1, ban_step: int = 0, bans=()): seed = int(seed) if seed is not None else int.from_bytes(os.urandom(8), "little") if penalty != 1.0: self.tlk.write_seen(seen_ids or []) self.tlk.write_state(self.tlk.state_host(L, token0, max_new, eos, temperature, top_k, top_p, seed, ntok=ntok, penalty=penalty, ban_step=ban_step, bans=bans)) def _launches(self, n: int): for _ in range(n): self.tlk.run() def run_batch(self): if self.trace is not None: self.ttnn.execute_trace(self.device, self.trace, cq_id=0, blocking=False) else: self._launches(self.batch) last_aborts = 0 def poll(self) -> Tuple[int, bool, int, np.ndarray]: st = self.tlk.read_state() n = int(st[G.S_NTOK]) self.last_aborts = int(st[G.S_ABORTS]) # launches not committed because a core aborted (retried) return n, bool(st[G.S_DONE]), int(st[G.S_STOP]), st[G.S_TOKENS:G.S_TOKENS + G.S_TOKENS_MAX].copy() def tf_step(self, L: int, s: int, token_in: int, flags: int = 0) -> torch.Tensor: """Teacher-forced step s >= 1 (input = token_in at cache index L + s - 1): logits [V] (host), no sampling.""" self.tlk.write_state(self.tlk.state_host(L, token_in, 1 << 20, ntok=s)) self.tlk.run(flags=G.F_NOSAMPLE | flags) return self.tlk.read_logits() def warmup(self, prefill: bool = True): self.pre.warmup(prefill) self.tlk.write_state(self.tlk.state_host(1, 1, 1, done=True)) self._launches(1) self.ttnn.synchronize_device(self.device) self._warm = True def capture(self, prefill: bool = True, decode: bool = True): """Prefill traces per bucket; the decode trace of ``batch`` launches only when ``decode`` (back-to-back launches of this program are unproven: FAULTS #1; batch 1 = one eager launch per poll).""" ttnn = self.ttnn if not getattr(self, "_warm", False): self.warmup(prefill) self.pre.capture(prefill=prefill) if decode and self.batch > 1: 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()