# SPDX-License-Identifier: Apache-2.0 """The ``ttnn`` engine: the pipeline engine interface (vision / audio / text) over the bucketed ttnn programs. Launch planning (host): text sequences of <= 513 tokens are packed in order into launches of <= ``max_batch`` sequences and <= the largest packed bucket; longer sequences run alone in "long" mode. Images / video frames are packed into vision launches (<= 64 per launch, <= the largest patch bucket). Audio clips run one per launch.""" from __future__ import annotations import time from dataclasses import dataclass, field from typing import Dict, List, Optional, Sequence, Tuple import numpy as np from .. import model_spec as S from .common import bucket PACKED_MAX_SEQ = S.SLIDING_RADIUS + 1 # 513: sliding == full attention @dataclass class EngineConfig: modalities: Tuple[str, ...] = ("text", "image", "video", "audio") max_batch: int = 32 text_buckets: Tuple[int, ...] = (32, 64, 128, 256, 512, 1024, 2048) long_buckets: Tuple[int, ...] = (1024, 2048) vision_buckets: Tuple[int, ...] = (864, 1440, 2592) audio_buckets: Tuple[int, ...] = (512, 1024, 2048, 3072) # mel frames (multiples of 128) text_act: str = "bf16" weights: str = "bf16" fidelity: str = "HiFi4" trace: bool = True vision_attn: str = "sdpa" # single-image launches: "sdpa" (ttnn) or "mk" (tt/mk_vattn kernel) stats: Dict = field(default_factory=dict) class TtnnEngine: name = "ttnn" def __init__(self, device, W: Dict, cfg: EngineConfig): from .ttnn_text import RopeTables, TextWeights self.device, self.cfg = device, cfg t0 = time.time() self.tw = TextWeights(device, W, cfg.weights) self.rope = RopeTables(max(cfg.text_buckets + cfg.long_buckets)) self.text_progs: Dict = {} self.vh = self.vw = None self.vision_progs: Dict = {} if "image" in cfg.modalities or "video" in cfg.modalities: from .ttnn_vision import VisionHost, VisionWeights self.vh = VisionHost(W) self.vw = VisionWeights(device, W, cfg.weights) self.aw = None self.audio_progs: Dict = {} self.traced = False if "audio" in cfg.modalities: from .ttnn_audio import AudioWeights self.aw = AudioWeights(device, W, cfg.weights) cfg.stats["weights_s"] = round(time.time() - t0, 2) # ---------------------------------------------------------------------------------------------- programs def _get(self, store: Dict, key, make): if key not in store: if self.cfg.trace and self.traced: raise RuntimeError(f"program {key} was not compiled at start (traces are captured once at warmup; " "a later allocation could overlap a trace's buffers)") p = make() store[key] = p if not self.cfg.trace: return p return store[key] def _text_prog(self, Sb: int, mode: str): from .ttnn_text import TextProgram return self._get(self.text_progs, (Sb, mode), lambda: TextProgram( self.device, self.tw, Sb, mode, self.cfg.text_act, self.cfg.fidelity)) def _vision_prog(self, P: int, attn: str = "mask"): from .ttnn_vision import VisionProgram return self._get(self.vision_progs, (P, attn), lambda: VisionProgram(self.device, self.vw, P, self.cfg.fidelity, attn)) def _single_attn(self, P: int) -> str: """Attention program of a one-image launch: the mk_vattn kernel when enabled and its L1 budget fits.""" if self.cfg.vision_attn == "mk": from .mk_vattn.program import l1_bytes g = self.device.compute_with_storage_grid_size() if g.x * g.y >= 12 and l1_bytes(P // 32) <= 1400 * 1024: return "mk" return "mask" def _audio_prog(self, Tb: int): from .ttnn_audio import AudioProgram return self._get(self.audio_progs, Tb, lambda: AudioProgram(self.device, self.aw, Tb, self.cfg.fidelity)) def warmup(self): """Create every bucket's program (all persistent allocations first), compile each (eager run), then capture every trace. Must run before any request when tracing.""" t0 = time.time() for b in self.cfg.text_buckets: self._text_prog(b, "packed") for b in self.cfg.long_buckets: self._text_prog(b, "long") if self.vw is not None: for P in self.cfg.vision_buckets: self._vision_prog(P, self._single_attn(P)) self._vision_prog(P, "cu") if self.aw is not None: for Tb in self.cfg.audio_buckets: self._audio_prog(Tb) progs = list(self.text_progs.values()) + list(self.vision_progs.values()) + list(self.audio_progs.values()) for p in progs: p.compile() self.cfg.stats["compile_s"] = round(time.time() - t0, 1) if self.cfg.trace: for p in progs: p.capture() self.traced = True self.cfg.stats["warmup_s"] = round(time.time() - t0, 1) # ---------------------------------------------------------------------------------------------- stages def text(self, xs: Sequence[np.ndarray], want_tokens: bool = False): from .ttnn_text import pack n = [x.shape[0] for x in xs] sums = np.zeros((len(xs), S.EMB_DIM), np.float32) toks: List = [None] * len(xs) maxp = max(b for b in self.cfg.text_buckets) launches: List[Tuple[str, List[int]]] = [] cur, tot = [], 0 for i, ni in enumerate(n): if ni > PACKED_MAX_SEQ: launches.append(("long", [i])) continue if cur and (tot + ni > maxp or len(cur) >= self.cfg.max_batch): launches.append(("packed", cur)) cur, tot = [], 0 cur.append(i) tot += ni if cur: launches.append(("packed", cur)) for mode, idx in launches: tot = sum(n[i] for i in idx) Sb = bucket(tot, self.cfg.text_buckets if mode == "packed" else self.cfg.long_buckets) buf, cu = pack([xs[i] for i in idx], Sb, self.rope) pooled, tk = self._text_prog(Sb, mode).run(buf, cu, want_tokens) off = 0 for j, i in enumerate(idx): sums[i] = pooled[j] if want_tokens: toks[i] = tk[off: off + n[i]].copy() off += n[i] return sums, (toks if want_tokens else None) def vision(self, patches: Sequence) -> List[np.ndarray]: from .ttnn_vision import MAX_IMAGES out: List = [None] * len(patches) maxP = max(self.cfg.vision_buckets) cur, tot = [], 0 groups = [] for i, p in enumerate(patches): if p.n_patches > maxP: raise ValueError(f"image with {p.n_patches} patches exceeds the largest vision bucket {maxP} " "(raise EMBGEMMA_IMAGE_TOKENS_MAX)") if cur and (tot + p.n_patches > maxP or len(cur) >= MAX_IMAGES): groups.append(cur) cur, tot = [], 0 cur.append(i) tot += p.n_patches if cur: groups.append(cur) for g in groups: tot = sum(patches[i].n_patches for i in g) P = bucket(tot, self.cfg.vision_buckets) buf, cu, toks = self.vh.pack([patches[i] for i in g], P) rows = self._vision_prog(P, self._single_attn(P) if len(g) == 1 else "cu").run(buf, cu, toks) for j, i in enumerate(g): out[i] = rows[j] return out def audio(self, clips: Sequence) -> List[np.ndarray]: out = [] for feats, mask in clips: Tb = bucket(feats.shape[0], self.cfg.audio_buckets) out.append(self._audio_prog(Tb).run(feats, mask)) return out def describe(self): return {"engine": "ttnn", "text_buckets": list(self.cfg.text_buckets), "long_buckets": list(self.cfg.long_buckets), "vision_buckets": list(self.cfg.vision_buckets), "audio_buckets": list(self.cfg.audio_buckets), "weights": self.cfg.weights, "fidelity": self.cfg.fidelity, "trace": self.cfg.trace, "vision_attn": self.cfg.vision_attn, "compiled": {"text": [list(k) for k in self.text_progs], "vision": list(self.vision_progs), "audio": list(self.audio_progs)}} def close(self): for d in (self.text_progs, self.vision_progs, self.audio_progs): for p in d.values(): p.release() d.clear()