File size: 15,672 Bytes
aa204f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | # SPDX-License-Identifier: Apache-2.0
"""The GLM-OCR DEC program: persistent DRAM buffers (weight arena, tables, KV cache, embedding table, STATE, seen
bitmap, logits) uploaded once, and the ``ttnn.generic_op`` program descriptor of one decode step (md_*.cpp). Adapted
from this workspace's Qwen3-ASR DEC (bundles/qwen3-asr tt/mk_dec/program.py, Apache-2.0). ttnn is imported lazily."""
from __future__ import annotations
import os
import struct
import time
from types import SimpleNamespace
from typing import Dict, List, Optional
import numpy as np
import torch
from . import arena as A
from . import weights as E
from . import geometry as G
KERNELS = {r: os.path.join(G.KDIR, f"md_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")}
#: fp32 CBs read by copy_tile (unpack straight to DST in fp32); fp32 CBs used as matmul / reduce operands stay default
UNPACK32 = ("CB_X", "CB_X0", "CB_ACCD", "CB_ACSD", "CB_HS", "CB_RS", "CB_G", "CB_GF", "CB_TAB", "CB_SD", "CB_PRO",
"CB_PRM", "CB_PRL", "CB_MRG")
def f32_bits(x: float) -> int:
return struct.unpack("<I", struct.pack("<f", float(x)))[0]
class DecTLK:
"""One decode step of the GLM-OCR text decoder as one program. ``recipe``: weight formats (weights.RECIPES:
attn, mlp, head). ``w``: :class:`weights.DecWeights` (fp32). ``attk``: key slots per kv group (split-K attention,
max_pos <= attk x 4096)."""
def __init__(self, device, recipe: Dict[str, str], w: E.DecWeights, max_pos: int = 4096, source: str = "",
k_max: int = 64, wfid: Optional[int] = None, attk: Optional[int] = None, log=print):
import ttnn
self.ttnn = ttnn
self.device = device
self.dims = G.GLM
self.recipe = E.expand_recipe(recipe)
self.fa, self.fm, self.fh = self.recipe["qkv"], self.recipe["gate"], self.recipe["head"]
self.max_pos = int(max_pos)
self.attk = int(attk if attk is not None else os.environ.get("GLMOCR_MK_ATTK", "4"))
if self.max_pos % 32 or self.max_pos > 4096 * self.attk:
raise ValueError(f"max_pos must be a multiple of 32 and <= {4096 * self.attk} (128 key blocks per slot)")
self.n_layers = E.N_LAYERS
self.wfid = int(wfid if wfid is not None else os.environ.get("GLMOCR_MK_WFID", "4"))
self.mmblk = 0
self.k_max = int(k_max)
g = device.compute_with_storage_grid_size()
self.grid = (int(g.x), int(g.y))
opt0 = [(int(c.x), int(c.y)) for c in device.get_optimal_dram_bank_to_logical_worker_assignment(ttnn.NOC.NOC_0)]
opt1 = [(int(c.x), int(c.y)) for c in device.get_optimal_dram_bank_to_logical_worker_assignment(ttnn.NOC.NOC_1)]
self.geo = G.build(self.grid[0], self.grid[1], opt0, opt1, attk=self.attk)
self._noc = {}
for x in range(self.grid[0]):
for y in range(self.grid[1]):
c = device.worker_core_from_logical_core(ttnn.CoreCoord(x, y))
self._noc[(x, y)] = (int(c.x), int(c.y))
t0 = time.time()
pages, self.offsets = A.build_arena(self.recipe, self.geo, w, self.n_layers, log=log, source=source)
t1 = time.time()
dram = ttnn.DRAM_MEMORY_CONFIG
rm = ttnn.ROW_MAJOR_LAYOUT
def up_u32(arr: np.ndarray, row_bytes: int):
a = np.ascontiguousarray(arr).reshape(-1, row_bytes)
t = torch.from_numpy(a.view(np.int32).reshape(a.shape[0], row_bytes // 4))
return ttnn.from_torch(t, dtype=ttnn.uint32, layout=rm, device=device, memory_config=dram)
def up_f32(t: torch.Tensor):
return ttnn.from_torch(t.float().contiguous(), dtype=ttnn.float32, layout=rm, device=device,
memory_config=dram)
def up_bf16(t: torch.Tensor):
return ttnn.from_torch(t.to(torch.bfloat16).contiguous(), dtype=ttnn.bfloat16, layout=rm, device=device,
memory_config=dram)
self.wts = up_u32(np.asarray(pages), A.PAGE)
self.gam = up_f32(A.gamma_table(w, self.n_layers))
self.rope = up_f32(A.rope_table(self.max_pos))
self.rope_q = up_f32(A.rope_table(self.max_pos, E.HD ** -0.5))
self.mask = up_bf16(A.mask_tiles())
self.consts = up_bf16(A.const_tiles_full())
self.embed = up_bf16(w.embed) # [V, D] bf16 rows (the step input = embed[last token])
self.nb_blocks = self.max_pos // 32
kv_pages = E.N_LAYERS * 2 * G.NG * self.nb_blocks
# [32 = layer x (k, v), 8 groups, MAXP, 128] bf16 TILE (the ttnn prefill fills layer l's K / V at 2l / 2l + 1)
self.kv = ttnn.zeros([E.N_LAYERS * 2, G.NG, self.max_pos, E.HD], dtype=ttnn.bfloat16,
layout=ttnn.TILE_LAYOUT, device=device, memory_config=dram)
self.hc = self.dims.hc
self.logits = up_f32(torch.zeros(G.NW, self.hc * 32))
self.state = up_u32(np.zeros((1, 8192), np.uint8), 8192)
self.seen = up_u32(np.zeros((1, 8192), np.uint8), 8192)
n = self.grid[0] * self.grid[1]
self.dbg = up_u32(np.zeros((n, G.SYNC_BYTES), np.uint8), G.SYNC_BYTES)
self.arena_bytes = int(np.asarray(pages).nbytes)
l1 = G.cb_total(self.dims, self.fa, self.fm, self.attk, self.fh)
if l1 > G.L1_BUDGET:
raise ValueError(f"CBs {l1} B exceed the L1 budget {G.L1_BUDGET} B")
log(f"[mk_dec] DEC {self.recipe}: arena {self.arena_bytes / 2**20:.0f} MiB (pack {t1 - t0:.0f} s, "
f"upload {time.time() - t1:.0f} s), grid {self.grid}, attk {self.attk}, KV "
f"{kv_pages * G.KV_PAGE / 2**20:.0f} MiB, CBs {l1 / 1024:.0f} KiB")
self._desc = {}
# ------------------------------------------------------------------ descriptor
def persistent(self) -> List:
return [self.wts, self.gam, self.rope, self.rope_q, self.mask, self.consts, self.kv, self.logits, self.dbg,
self.embed, self.state, self.seen]
def noc(self, c):
return self._noc[tuple(c)]
def _common(self, n_layers: int, flags: int, spin: int, stop: int = 0):
c = G.common_args(self.geo, self.noc)
c[G.K_STOP] = int(stop)
c[G.K_NL] = int(n_layers)
c[G.K_SPIN] = int(spin)
c[G.K_EPS] = f32_bits(E.EPS)
c[G.K_INV_D] = f32_bits(1.0 / self.dims.d)
c[G.K_INV_HD] = f32_bits(1.0 / E.HD)
c[G.K_STATE] = self.state.buffer_address()
c[G.K_EMBED] = self.embed.buffer_address()
c[G.K_LOGITS] = self.logits.buffer_address()
c[G.K_WTS] = self.wts.buffer_address()
c[G.K_GAM] = self.gam.buffer_address()
c[G.K_ROPE] = self.rope.buffer_address()
c[G.K_ROPEQ] = self.rope_q.buffer_address()
c[G.K_SEEN] = self.seen.buffer_address()
c[G.K_KV] = self.kv.buffer_address()
c[G.K_NB] = self.nb_blocks
c[G.K_MASK] = self.mask.buffer_address()
c[G.K_CONST] = self.consts.buffer_address()
c[G.K_DBG] = self.dbg.buffer_address()
c[G.K_FLAGS] = int(flags)
c[G.K_MAXP] = self.max_pos
c[G.K_NEG] = f32_bits(A.NEG_MASK)
c[G.K_KMAX] = self.k_max
return c
def program(self, n_layers: int = E.N_LAYERS, flags: int = 0, spin: int = 1 << 26, stop: int = 0):
key = (n_layers, flags, spin, stop)
if key in self._desc:
return self._desc[key]
ttnn = self.ttnn
gx, gy = self.grid
d = self.dims
allc = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))])
dt = {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b, "bfp4": ttnn.bfloat4_b, "fp32": ttnn.float32,
"raw": ttnn.uint32}
cbs = []
modes = [ttnn.UnpackToDestMode.Default] * 64
unp = {getattr(G, n) for n in UNPACK32}
for cb in G.cb_table(d, self.fa, self.fm, self.attk, self.fh):
fds = []
for cid, fmt, page, tile, _u in cb.ids:
kw = {}
if tile is not None:
kw["tile"] = ttnn.TileDescriptor(tile[0], tile[1], False)
fds.append(ttnn.CBFormatDescriptor(buffer_index=cid, data_format=dt[fmt],
page_size=cb.total if fmt == "raw" else page, **kw))
if cid in unp:
modes[cid] = ttnn.UnpackToDestMode.UnpackToDestFp32
cbs.append(ttnn.CBDescriptor(total_size=cb.total, core_ranges=allc, format_descriptors=fds))
rb = G.ring_bytes(self.fa, self.fm, self.fh)
defines = [
("MT_DT", d.d_t), ("MT_DTK", d.dtk), ("MT_IT", d.i_t), ("MT_ITK", d.itk), ("MT_XS", d.xs),
("MT_FS", d.fs), ("MT_NHD", d.hd_dense), ("MT_D", d.d), ("MT_PT_A", G.PACKET_TILES[self.fa]),
("MT_PT_M", G.PACKET_TILES[self.fm]), ("MT_PT_H", G.PACKET_TILES_H), ("MT_TB_H", G.TILE_BYTES[self.fh]),
("MT_HC", self.hc), ("MT_TB_A", G.TILE_BYTES[self.fa]), ("MT_TB_M", G.TILE_BYTES[self.fm]),
("MT_RING_A", rb["A"]), ("MT_RING_M", rb["M"]), ("MT_RING_H", rb["H"]), ("MT_A_TILES", d.a_tiles),
("MT_M_TILES", d.m_tiles), ("MT_H_TILES", d.h_tiles),
("MT_FS_CAP", max(d.fs * G.TINY16, 512) // G.TINY16), ("MT_KV_RING_BLOCKS", G.KV_RING_BLOCKS),
("MT_WFID", self.wfid), ("MT_MMBLK", self.mmblk), ("MT_CAP_MRG", rb["A"] // G.T32),
]
defines = [(k, str(v)) for k, v in defines]
args = G.core_args(self.geo, self.noc, self.offsets)
common = self._common(n_layers, flags, spin, stop)
ct = list(ttnn.TensorAccessorArgs(self.wts).get_compile_time_args())
s1 = {m.xy for m in self.geo.mm if m.noc == 1}
s0 = [(x, y) for y in range(gy) for x in range(gx) if (x, y) not in s1]
crs = lambda cs: ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(*c), ttnn.CoreCoord(*c)) for c in cs]) # noqa
fp = ttnn.KernelDescriptor.SourceType.FILE_PATH
dm = ttnn.DataMovementConfigDescriptor
kernels = []
for cores, nc_noc, br_noc in ((s0, ttnn.NOC.NOC_0, ttnn.NOC.NOC_1), (sorted(s1), ttnn.NOC.NOC_1, ttnn.NOC.NOC_0)):
rt = ttnn.RuntimeArgs()
for c in cores:
rt[c[0]][c[1]] = args[c]
kernels.append(ttnn.KernelDescriptor(
kernel_source=KERNELS["ncrisc"], source_type=fp, core_ranges=crs(cores), compile_time_args=ct,
runtime_args=rt, common_runtime_args=common, defines=defines,
config=dm(processor=ttnn.DataMovementProcessor.RISCV_1, noc=nc_noc)))
rt2 = ttnn.RuntimeArgs()
for c in cores:
rt2[c[0]][c[1]] = args[c]
kernels.append(ttnn.KernelDescriptor(
kernel_source=KERNELS["brisc"], source_type=fp, core_ranges=crs(cores), compile_time_args=ct,
runtime_args=rt2, common_runtime_args=common, defines=defines,
config=dm(processor=ttnn.DataMovementProcessor.RISCV_0, noc=br_noc)))
rt3 = ttnn.RuntimeArgs()
for x in range(gx):
for y in range(gy):
rt3[x][y] = args[(x, y)]
cc = ttnn.ComputeConfigDescriptor(math_fidelity=ttnn.MathFidelity.HiFi4, fp32_dest_acc_en=True,
dst_full_sync_en=True, math_approx_mode=False)
cc.unpack_to_dest_mode = modes
kernels.append(ttnn.KernelDescriptor(kernel_source=KERNELS["trisc"], source_type=fp, core_ranges=allc,
compile_time_args=[], runtime_args=rt3, common_runtime_args=common,
defines=defines, config=cc))
sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=allc, initial_value=0) for i in (0, 1)]
desc = ttnn.ProgramDescriptor(kernels=kernels, semaphores=sems, cbs=cbs)
self._desc[key] = desc
return desc
def io(self) -> List:
return self.persistent()
def run(self, n_layers: int = E.N_LAYERS, flags: int = 0, spin: int = 1 << 26, stop: int = 0):
"""Enqueue one step (no host sync; trace-capturable)."""
self.ttnn.generic_op(self.io(), self.program(n_layers, flags, spin, stop))
# ------------------------------------------------------------------ host helpers
def read_logits(self) -> torch.Tensor:
t = self.ttnn.to_torch(self.logits).reshape(-1).float()
return t[:G.VOCAB]
def state_host(self, L: int, token0: int, max_new: int, eos=(59246, 59253), temperature: float = 0.0,
top_k: int = 0, top_p: float = 1.0, seed: int = 0, done: bool = False, ntok: int = 1,
delta: int = 0, penalty: float = 1.0):
"""Host STATE page after a prefill of L rows that produced token 0 (``ntok`` > 1: the step input is
``token0`` at cache index L + ntok - 1, teacher-forced gates). ``delta``: the M-RoPE delta."""
st = np.zeros(2048, np.uint32)
do_sample = temperature is not None and temperature > 0
st[G.S_DOSAMPLE] = 1 if do_sample else 0
st[G.S_INVT] = f32_bits(1.0 / temperature) if do_sample else f32_bits(1.0)
st[G.S_TOPK] = int(top_k or 0)
st[G.S_TOPP] = f32_bits(float(top_p if top_p is not None else 1.0))
st[G.S_DELTA] = np.uint32(int(delta) & 0xFFFFFFFF)
st[G.S_PEN] = f32_bits(float(penalty if penalty else 1.0))
st[G.S_SEED_LO] = int(seed) & 0xFFFFFFFF
st[G.S_SEED_HI] = (int(seed) >> 32) & 0xFFFFFFFF
st[G.S_L] = int(L)
st[G.S_MAXNEW] = int(max_new)
st[G.S_EOS0], st[G.S_EOS1] = int(eos[0]), int(eos[1])
st[G.S_NVOCAB] = G.VOCAB
st[G.S_NTOK] = int(ntok)
st[G.S_LAST] = int(token0)
st[G.S_TOKENS + (int(ntok) - 1) % G.S_TOKENS_MAX] = int(token0)
if done or int(token0) in eos or max_new <= 1:
st[G.S_DONE] = 1
st[G.S_STOP] = 1 if int(token0) in eos else 2
t = torch.from_numpy(st.view(np.int32).reshape(1, 2048))
return self.ttnn.from_torch(t, dtype=self.ttnn.uint32, layout=self.ttnn.ROW_MAJOR_LAYOUT)
def write_state(self, host_state) -> None:
self.ttnn.copy_host_to_device_tensor(host_state, self.state)
def write_seen(self, ids) -> None:
bm = A.seen_bitmap(ids)
t = torch.from_numpy(bm.view(np.int32).reshape(1, 2048))
self.ttnn.copy_host_to_device_tensor(
self.ttnn.from_torch(t, dtype=self.ttnn.uint32, layout=self.ttnn.ROW_MAJOR_LAYOUT), self.seen)
def read_state(self) -> np.ndarray:
return self.ttnn.to_torch(self.state).reshape(-1).numpy().view(np.uint32).copy()
def read_dbg(self) -> torch.Tensor:
n = self.grid[0] * self.grid[1]
return self.ttnn.to_torch(self.dbg).reshape(n, G.SYNC_BYTES // 4).to(torch.int64) & 0xFFFFFFFF
def read_prof(self):
d = self.read_dbg()
mm = self.geo.idx(self.geo.mm[0].xy)
at = self.geo.idx(self.geo.att[0])
p0 = G.SYNC_PROF // 4
m = [int(d[mm, p0 + i]) for i in range(9)]
a = [int(d[at, p0 + i]) for i in range(10, 15)]
f = 1.35e3
def us(x, i, j):
return ((x[j] - x[i]) & 0xFFFFFFFF) / f
return {"mm_norm1_gather": us(m, 0, 1), "mm_qkv_to_sent": us(m, 1, 2), "mm_wait_attention": us(m, 2, 3),
"mm_oproj_psa_norm2": us(m, 3, 4), "mm_gateup_fgather": us(m, 4, 5), "mm_layer1_total": us(m, 0, 5),
"att_wait_q": us(a, 0, 1), "att_kv_softmax_pv": us(a, 1, 3), "att_send_o": us(a, 3, 4)}
def read_kv(self) -> torch.Tensor:
t = self.ttnn.to_torch(self.kv).float()
return t.reshape(E.N_LAYERS, 2, G.NG, self.max_pos, E.HD)
|