Download code/tt_laya/tt/mk/engine.py from changh95/laya: direct link, hf CLI and curl.
- Browser
- Download file 19.6 kB
-
https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/tt/mk/engine.py
- Command line
-
hf download hf://changh95/laya/code/tt_laya/tt/mk/engine.py
-
curl -L -o engine.py https://huggingface.co/changh95/laya/resolve/main/code/tt_laya/tt/mk/engine.py
19.6 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """The ``mk`` engine: the whole decision model as one megakernel launch per <= 20 row tiles (tt/mk/kernels). | |
| Two programs of the same kernels (one Metal trace each; the plan makes every batch / length run on them): | |
| R1 one row tile per band (launches of <= 10 row tiles = 1 .. ~10 questions): the L1 that the second row tile would | |
| use deepens the weight ring 12 -> ~40 pages, so the bands of a column are less coupled through it; | |
| R2 up to two row tiles per band (11 .. 20 row tiles). | |
| Per launch: | |
| ids [T_MAX * 32] (uint32) -> E = emb_hi[ids] + emb_lo[ids] (tt-nn, fp32) -> the megakernel -> H (fp32, final hidden | |
| state of every token) -> tt-nn tail: [CLS] / [MASK] rows of each row (selection matmul) -> scorer logits and the | |
| pooled projection of the action head. The host finishes the action head (4 features) as for the ttnn engine. | |
| Rows longer than 512 tokens (16 row tiles) are not supported here (the api routes them to the ttnn engine). | |
| """ | |
| from __future__ import annotations | |
| import time | |
| from typing import Dict, List, Optional, Sequence, Tuple | |
| import numpy as np | |
| from ...weights import Arch | |
| from . import arena as A | |
| from . import geometry as G | |
| from .program import Program | |
| from .. import traces | |
| NSEL = G.T_MAX * 32 # gathered rows per launch: each model row's [CLS] + its markers, packed (<= 640) | |
| MAX_MARKERS = 255 | |
| def pack_launches(rows, align: bool = False, r_max: int = G.T_MAX, s_max: int = NSEL, | |
| t_max: int = G.T_MAX) -> List[List[int]]: | |
| """Greedy, in order: row indices grouped into launches whose rows fit t_max row tiles (packed back to back, | |
| geometry.place_rows), with <= r_max rows and <= s_max gathered ([CLS] + marker) rows.""" | |
| out, cur, cs = [], [], 0 | |
| for i, r in enumerate(rows): | |
| s = 1 + len(r.markers) | |
| trial = [G.LaunchRow(len(rows[j].ids), 0) for j in cur + [i]] | |
| if cur and (len(cur) >= r_max or cs + s > s_max or G.place_rows(trial, align, t_max) is None): | |
| out.append(cur) | |
| cur, cs = [], 0 | |
| cur.append(i) | |
| cs += s | |
| if cur: | |
| out.append(cur) | |
| return out | |
| class MkEngine: | |
| name = "mk" | |
| max_tokens = G.L_MAX * 32 | |
| def __init__(self, device, sd: Dict, arch: Arch, fidelity: str = "HiFi4", weight_dtype: str = "bf16", | |
| pad_id: int = 0, slots: Optional[int] = None, trace: bool = True, spin: int = 0, | |
| timings: Optional[Dict] = None, variant: Sequence[str] = ()): | |
| import torch | |
| import ttnn | |
| if weight_dtype not in ("bf16", "bfp8"): | |
| raise ValueError("the megakernel streams bf16 or bfp8 weights (LAYA_WEIGHTS)") | |
| A._FMT["v"] = weight_dtype | |
| traces.invalidate(device) # this engine's buffers must not sit under another engine's trace | |
| t0 = time.perf_counter() | |
| self.device, self.a, self.pad_id, self.spin = device, arch, int(pad_id), int(spin) | |
| self.fidelity, self.weight_dtype = fidelity, weight_dtype | |
| g = device.compute_with_storage_grid_size() | |
| self.C, self.NB = int(g.x), int(g.y) | |
| self.m = G.Model.of(arch) | |
| self.geo = G.build(self.C, min(self.NB, G.NB_MAX), self.m) | |
| # programs: "rmax1" / "rmax2" variants force one; default both (R1 for launches of <= NB row tiles) | |
| self.rmaxes = (1,) if "rmax1" in variant else (2,) if "rmax2" in variant else (1, 2) | |
| self.progs = {} | |
| for r in self.rmaxes: | |
| want = 12 if r == 2 else 64 | |
| sl = G.max_slots(self.m, self.C, want, weight_dtype, r) if slots is None else int(slots) | |
| self.progs[r] = Program(device, self.geo, sl, arch.norm_eps, fidelity, variant, weight_dtype, r) | |
| self.t_max = min(G.T_MAX, self.geo.NB * max(self.rmaxes)) | |
| self.slots = {r: p.slots for r, p in self.progs.items()} | |
| self.trace = bool(trace) | |
| dram = ttnn.DRAM_MEMORY_CONFIG | |
| w = A.Weights(sd, arch) | |
| self.w = w | |
| def up_rm(t, dt=ttnn.bfloat16): | |
| return ttnn.from_torch(t.reshape(1, 1, *t.shape), dtype=dt, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, | |
| memory_config=dram) | |
| def up_tiles(t, dt): # [n, 32, 32] tile contents -> TILE tensor whose page i is tile i | |
| return ttnn.from_torch(t.reshape(1, 1, -1, 32), dtype=dt, layout=ttnn.TILE_LAYOUT, device=device, | |
| memory_config=dram) | |
| self.arenas = [up_rm(A.enc_arena(L, self.geo)) for L in w.enc] + [up_rm(A.head_arena(L, self.geo)) | |
| for L in w.head] | |
| t1 = time.perf_counter() | |
| D = arch.hidden | |
| self.t = { | |
| "vec": up_tiles(A.vec_table(w, self.m), ttnn.float32), | |
| "rope": up_tiles(torch.zeros(4 * G.T_MAX, 32, 32), ttnn.float32), # per launch | |
| "oh": up_tiles(torch.zeros(G.T_MAX, 32, 32), ttnn.bfloat16), # per launch | |
| "const": up_tiles(A.const_tiles(), ttnn.bfloat16), | |
| "pad": up_tiles(A.pad_tiles(), ttnn.bfloat16), | |
| "stage": up_rm(torch.zeros(2 * 3 * self.m.H * G.TS, G.STAGE_PAGE // 2, dtype=torch.bfloat16)), | |
| "plan": ttnn.from_torch(torch.zeros(1, 1, 1, G.PLAN_WORDS, dtype=torch.int32), dtype=ttnn.uint32, | |
| layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram), | |
| "ids": ttnn.from_torch(torch.zeros(1, G.T_MAX * 32, dtype=torch.int32), dtype=ttnn.uint32, | |
| layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram), | |
| "e": ttnn.from_torch(torch.zeros(1, 1, G.T_MAX * 32, D), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, | |
| device=device, memory_config=dram), | |
| "h": ttnn.from_torch(torch.zeros(1, 1, G.T_MAX * 32, D), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, | |
| device=device, memory_config=dram), | |
| "dbg": ttnn.from_torch(torch.zeros(1, 1, self.geo.n, G.DBG_PAGE // 4, dtype=torch.int32), dtype=ttnn.uint32, | |
| layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram), | |
| "sel": ttnn.from_torch(torch.zeros(1, 1, NSEL, G.T_MAX * 32), dtype=ttnn.bfloat16, | |
| layout=ttnn.TILE_LAYOUT, device=device, memory_config=dram), | |
| } | |
| tab = sd["encoder.embeddings.tok_embeddings.weight"].float() | |
| hi = tab.to(torch.bfloat16) | |
| lo = (tab - hi.float()).to(torch.bfloat16) | |
| self.emb = [ttnn.from_torch(x, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, | |
| memory_config=dram) for x in (hi, lo)] | |
| # tail: scorer + pooled action projection | |
| W = {k: v.float() for k, v in sd.items()} | |
| def mat(x, dt=ttnn.bfloat16): | |
| return ttnn.from_torch(x.t().contiguous(), dtype=dt, layout=ttnn.TILE_LAYOUT, device=device, | |
| memory_config=dram) | |
| def vec(x, dt=ttnn.float32): | |
| return ttnn.from_torch(x.reshape(1, -1).contiguous(), dtype=dt, layout=ttnn.TILE_LAYOUT, device=device, | |
| memory_config=dram) | |
| self.s_lnw, self.s_lnb = vec(W["scorer.0.weight"]), vec(W["scorer.0.bias"]) | |
| self.s_w1, self.s_b1 = mat(W["scorer.1.weight"]), vec(W["scorer.1.bias"], ttnn.bfloat16) | |
| w3 = torch.zeros(32, D) | |
| w3[0] = W["scorer.3.weight"][0] | |
| b3 = torch.zeros(32) | |
| b3[0] = W["scorer.3.bias"][0] | |
| self.s_w3, self.s_b3 = mat(w3), vec(b3) | |
| aw = W["act_head.0.weight"] | |
| self.act_wp = mat(aw[:, :D]) | |
| self.act_wf = aw[:, D:].numpy().astype(np.float32) | |
| self.act_b0 = W["act_head.0.bias"].numpy().astype(np.float32) | |
| self.act_w2 = W["act_head.2.weight"].numpy().astype(np.float32) | |
| self.act_b2 = W["act_head.2.bias"].numpy().astype(np.float32) | |
| self.ckc = 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.rope = A.Rope(arch) | |
| self.align = False | |
| self.qch = None # attention query-tile chunk (None: geometry.assign_items' heuristic) | |
| self.desc = {r: p.descriptor(self.t, self.arenas) for r, p in self.progs.items()} | |
| self.tid = {} | |
| self.out = {} | |
| self.cur = None # the program of the last host_inputs | |
| self.nl, self.nhl = arch.layers, arch.head_layers | |
| self.timings = {"mk_pack_upload_s": t1 - t0, "mk_tables_s": time.perf_counter() - t1} | |
| if timings is not None: | |
| timings.update(self.timings) | |
| traces.register(device, self) | |
| # ------------------------------------------------------------------ graph | |
| def _io(self): | |
| return [*self.arenas, self.t["vec"], self.t["rope"], self.t["const"], self.t["pad"], self.t["stage"], | |
| self.t["plan"], self.t["e"], self.t["h"], self.t["dbg"], self.t["oh"]] | |
| def _forward(self, r: int): | |
| import ttnn | |
| f32, bf = ttnn.float32, ttnn.bfloat16 | |
| e0 = ttnn.embedding(self.t["ids"], self.emb[0], layout=ttnn.TILE_LAYOUT, dtype=f32) | |
| e1 = ttnn.embedding(self.t["ids"], self.emb[1], layout=ttnn.TILE_LAYOUT, dtype=f32) | |
| ttnn.add(ttnn.reshape(e0, (1, 1, G.T_MAX * 32, self.a.hidden)), | |
| ttnn.reshape(e1, (1, 1, G.T_MAX * 32, self.a.hidden)), dtype=f32, output_tensor=self.t["e"]) | |
| ttnn.deallocate(e0) | |
| ttnn.deallocate(e1) | |
| ttnn.generic_op(self._io(), self.desc[r]) | |
| m = ttnn.matmul(self.t["sel"], self.t["h"], compute_kernel_config=self.ckc, dtype=f32) # [640, D] | |
| y = ttnn.layer_norm(m, epsilon=1e-5, weight=self.s_lnw, bias=self.s_lnb, compute_kernel_config=self.ckc) | |
| yb = ttnn.typecast(y, bf) | |
| ttnn.deallocate(y) | |
| z = ttnn.linear(yb, self.s_w1, bias=self.s_b1, compute_kernel_config=self.ckc, dtype=f32) | |
| ttnn.deallocate(yb) | |
| z = ttnn.gelu(z, fast_and_approximate_mode=False) | |
| zb = ttnn.typecast(z, bf) | |
| ttnn.deallocate(z) | |
| logits = ttnn.linear(zb, self.s_w3, bias=self.s_b3, compute_kernel_config=self.ckc, dtype=f32) | |
| ttnn.deallocate(zb) | |
| mb = ttnn.typecast(m, bf) | |
| ttnn.deallocate(m) | |
| actp = ttnn.matmul(mb, self.act_wp, compute_kernel_config=self.ckc, dtype=f32) | |
| ttnn.deallocate(mb) | |
| return logits, actp | |
| def _ensure(self): | |
| import ttnn | |
| if self.out: | |
| return | |
| t0 = time.perf_counter() | |
| for r in self.rmaxes: | |
| self.out[r] = self._forward(r) | |
| ttnn.synchronize_device(self.device) | |
| self.timings["compile_s"] = time.perf_counter() - t0 | |
| if self.trace: | |
| for r in self.rmaxes: | |
| for x in self.out[r]: | |
| ttnn.deallocate(x) | |
| self.tid[r] = ttnn.begin_trace_capture(self.device, cq_id=0) | |
| self.out[r] = self._forward(r) | |
| ttnn.end_trace_capture(self.device, self.tid[r], cq_id=0) | |
| def drop_traces(self) -> bool: | |
| """Release the traces (another engine allocates device buffers); the next launch captures them again.""" | |
| import ttnn | |
| had = bool(self.tid) | |
| for tid in self.tid.values(): | |
| ttnn.release_trace(self.device, tid) | |
| self.tid = {} | |
| for out in self.out.values(): | |
| for x in out: | |
| ttnn.deallocate(x) | |
| self.out = {} | |
| return had | |
| def _launch(self): | |
| """Run the program chosen by the last host_inputs; its (logits, act projection) outputs.""" | |
| import ttnn | |
| r = self.cur | |
| if r in self.tid: | |
| ttnn.execute_trace(self.device, self.tid[r], cq_id=0, blocking=False) | |
| else: | |
| self.out[r] = self._forward(r) | |
| return self.out[r] | |
| # ------------------------------------------------------------------ host inputs of one launch | |
| def host_inputs(self, rows, nl: Optional[int] = None, nhl: Optional[int] = None): | |
| lr = [G.LaunchRow(len(r.ids), r.qtype) for r in rows] | |
| w, placed = G.plan_rows(lr, self.geo.NB, self.geo.n, self.nl if nl is None else nl, | |
| self.nhl if nhl is None else nhl, self.spin, self.align) | |
| fit = [r for r in self.rmaxes if w[G.PL_T] <= self.geo.NB * r] | |
| if not fit: | |
| raise ValueError(f"{w[G.PL_T]} row tiles > {self.t_max} for these programs") | |
| self.cur = fit[0] | |
| G.assign_items(placed, self.m.H, self.geo.n, w, self.qch) | |
| import torch | |
| ids = np.full((1, G.T_MAX * 32), self.pad_id, dtype=np.int32) | |
| si, sj = [], [] # one-hot selection matrix [NSEL, T_MAX * 32]: (gathered row, token lane) | |
| pos = np.zeros(G.T_MAX * 32, dtype=np.int64) | |
| qt = np.zeros(G.T_MAX * 32, dtype=np.int64) | |
| o = 0 | |
| self._offs = [] | |
| for rho, (p, r) in enumerate(zip(placed, rows)): | |
| s0 = p.start | |
| ids[0, s0:s0 + len(r.ids)] = r.ids | |
| pos[s0:s0 + len(r.ids)] = np.arange(len(r.ids)) | |
| qt[s0:s0 + len(r.ids)] = r.qtype | |
| if len(r.markers) > MAX_MARKERS: | |
| raise ValueError("%d options: the device engines take at most %d" % (len(r.markers), MAX_MARKERS)) | |
| self._offs.append(o) | |
| si.append(o) | |
| sj.append(s0) | |
| for j, mk in enumerate(r.markers): | |
| si.append(o + 1 + j) | |
| sj.append(s0 + mk) | |
| o += 1 + len(r.markers) | |
| # built as bf16 torch tensors: the host fp32 -> bf16 conversion of the 640 x 640 matrix cost 1.4 ms | |
| sel = torch.zeros((1, 1, NSEL, G.T_MAX * 32), dtype=torch.bfloat16) | |
| sel[0, 0, si, sj] = 1.0 | |
| rope = self.rope.launch_tiles(pos) | |
| oh = torch.from_numpy(A.onehot_tiles(qt).reshape(1, 1, -1, 32)).to(torch.bfloat16) | |
| return np.asarray(w, dtype=np.int64).astype(np.uint32).view(np.int32), ids, sel, rope, oh | |
| def upload(self, plan, ids, sel, rope, oh): | |
| import torch | |
| import ttnn | |
| up = ttnn.copy_host_to_device_tensor | |
| up(ttnn.from_torch(torch.from_numpy(rope.reshape(1, 1, -1, 32)), dtype=ttnn.float32, | |
| layout=ttnn.TILE_LAYOUT), self.t["rope"]) | |
| up(ttnn.from_torch(oh, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT), self.t["oh"]) | |
| up(ttnn.from_torch(torch.from_numpy(plan.reshape(1, 1, 1, -1)), dtype=ttnn.uint32, | |
| layout=ttnn.ROW_MAJOR_LAYOUT), self.t["plan"]) | |
| up(ttnn.from_torch(torch.from_numpy(ids), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT), self.t["ids"]) | |
| up(ttnn.from_torch(sel, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT), self.t["sel"]) | |
| # ------------------------------------------------------------------ run | |
| def run(self, rows) -> Tuple[List[np.ndarray], List[np.ndarray]]: | |
| """text.Row list -> (raw logits [K] per row, act probabilities [n_act] per row).""" | |
| import ttnn | |
| from ..ttnn_engine import finish_act | |
| self._ensure() | |
| logits, acts = [None] * len(rows), [None] * len(rows) | |
| groups = pack_launches(rows, self.align, t_max=self.t_max) | |
| st = {"prep_ms": 0.0, "upload_ms": 0.0, "device_read_ms": 0.0, "launches": len(groups)} | |
| t0 = time.perf_counter() | |
| nxt = self.host_inputs([rows[i] for i in groups[0]]) if groups else None | |
| st["prep_ms"] += (time.perf_counter() - t0) * 1e3 | |
| for gi, group in enumerate(groups): | |
| t0 = time.perf_counter() | |
| offs = self._offs | |
| self.upload(*nxt) | |
| t1 = time.perf_counter() | |
| out = self._launch() # non-blocking: the next launch's inputs are built meanwhile | |
| if gi + 1 < len(groups): | |
| nxt = self.host_inputs([rows[i] for i in groups[gi + 1]]) | |
| t2 = time.perf_counter() | |
| lg = ttnn.to_torch(out[0]).float().numpy().reshape(-1, 32) | |
| ap = ttnn.to_torch(out[1]).float().numpy().reshape(-1, 256) | |
| t3 = time.perf_counter() | |
| st["upload_ms"] += (t1 - t0) * 1e3 | |
| st["prep_ms"] += (t2 - t1) * 1e3 | |
| st["device_read_ms"] += (t3 - t2) * 1e3 | |
| for rho, i in enumerate(group): | |
| K, o = len(rows[i].markers), offs[rho] | |
| l = lg[o + 1:o + 1 + K, 0].astype(np.float32) | |
| logits[i] = l | |
| acts[i] = finish_act(ap[o], l, self.act_wf, self.act_b0, self.act_w2, self.act_b2) | |
| self.last_stages = st | |
| return logits, acts | |
| def bench_device(self, rows, n: int = 20) -> float: | |
| """Device time per launch (ms): the trace of ``rows`` (one launch) replayed n times back to back.""" | |
| import ttnn | |
| self._ensure() | |
| self.upload(*self.host_inputs(rows)) | |
| tid = self.tid[self.cur] | |
| ttnn.execute_trace(self.device, tid, cq_id=0, blocking=True) | |
| t0 = time.perf_counter() | |
| for _ in range(n): | |
| ttnn.execute_trace(self.device, tid, cq_id=0, blocking=False) | |
| ttnn.synchronize_device(self.device) | |
| return (time.perf_counter() - t0) * 1e3 / n | |
| def read_prof(self) -> np.ndarray: | |
| """[n_cores, 1024] int64 time stamps of the last launch (LM_PROF builds): TRISC words l * 16 + phase, BRISC | |
| 512 + l * 16 + phase (TRISC phases: 1 norm1, 2 qkv, 4 attention, 5 o, 6 norm2, 7 ffn, 8 down; BRISC: 1 norm1, | |
| 2 qkv, 3 barrier, 4 attention, 5 o, 6 norm2, 7 ffn, 8 end).""" | |
| self.read_debug() | |
| return self._dbg_raw[:, G.SYNC_PROF // 4:G.SYNC_PROF // 4 + 1024] | |
| def read_h(self) -> np.ndarray: | |
| import ttnn | |
| return ttnn.to_torch(self.t["h"]).float().numpy().reshape(G.T_MAX * 32, -1) | |
| def read_debug(self) -> Dict: | |
| """Per-core abort codes and the BRISC progress word from the last launch's debug dump.""" | |
| import ttnn | |
| d = ttnn.to_torch(self.t["dbg"]).numpy().astype(np.int64).reshape(self.geo.n, G.DBG_PAGE // 4) & 0xFFFFFFFF | |
| self._dbg_raw = d | |
| wd = lambda w: d[:, w * (G.SYNC_STRIDE // 4)] # noqa: E731 | |
| out = {"aborted": [], "step": wd(G.W_STEP).tolist(), "tstep": wd(G.W_TSTEP).tolist()} | |
| for i in range(self.geo.n): | |
| if wd(G.W_ABORT)[i] == G.ABORT_MAGIC: | |
| out["aborted"].append({"core": i, "xy": self.geo.core(i), | |
| "brisc": [int(wd(G.W_DBG)[i]), int(wd(G.W_DBG + 1)[i])], | |
| "ncrisc": [int(wd(G.W_DBG + 2)[i]), int(wd(G.W_DBG + 3)[i])], | |
| "trisc_front": [int(wd(G.W_DBG + 4)[i]), int(wd(G.W_DBG + 5)[i])], | |
| "trisc_back": [int(wd(G.W_DBG + 6)[i]), int(wd(G.W_DBG + 7)[i])], | |
| "step": int(wd(G.W_STEP)[i]), "tstep": int(wd(G.W_TSTEP)[i])}) | |
| return out | |
| def describe(self): | |
| return {"engine": "mk", "fidelity": self.fidelity, "weights": self.weight_dtype, "grid": [self.C, self.NB], | |
| "ring_pages": {"R%d" % r: s for r, s in self.slots.items()}, "t_max": self.t_max, "trace": self.trace} | |
| def close(self): | |
| import ttnn | |
| for tid in self.tid.values(): | |
| try: | |
| ttnn.release_trace(self.device, tid) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| self.tid = {} | |