Download code/tt_paddleocr/tt/mk_dec/geometry.py from changh95/PaddleOCR-VL: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/changh95/PaddleOCR-VL/resolve/main/code/tt_paddleocr/tt/mk_dec/geometry.py
- Command line
-
hf download hf://changh95/PaddleOCR-VL/code/tt_paddleocr/tt/mk_dec/geometry.py
-
curl -L -o geometry.py https://huggingface.co/changh95/PaddleOCR-VL/resolve/main/code/tt_paddleocr/tt/mk_dec/geometry.py
18.4 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """DEC megakernel geometry (host mirror of ``kernels/md_defs.hpp``; CPU only, no ttnn import at module level). | |
| PaddleOCR-VL copy of the Qwen3-ASR DEC geometry (unchanged roles; vocabulary 103424). | |
| Copied from the Qwen3-TTS talker megakernel (bundles/qwen3-tts tt/mk_talker/geometry.py, Apache-2.0) with the ASR | |
| head: MM core ``w`` owns LM-head column tiles ``[w HC, (w + 1) HC)`` (HC = ceil(ceil(151936 / 32) / 32) = 149; the | |
| columns past the vocabulary are zero weights and never candidates), streamed in the head format (bf16 | bfp8). | |
| Roles on the ``gx x gy`` grid (``device.compute_with_storage_grid_size()``, never hard-coded): | |
| * **MM** (32 cores, index ``w``): the weight-stream cores. Placement = the measured best DRAM arrangement (probe | |
| ``near2_split``, 492 GB/s): for every DRAM bank ``b``, the 2 cores nearest to the NOC0-optimal worker of ``b`` read | |
| bank ``b`` on NOC 0 and the 2 cores nearest to its NOC1-optimal worker read it on NOC 1 (one reader RISC each, the | |
| NCRISC; the BRISC uses the other NoC for exchanges). MM core ``w`` owns fused q|k|v head ``w`` (q 0..15, k 16..23, | |
| v 24..31), residual columns ``[w XS, (w + 1) XS)`` (o_proj / down_proj columns), SwiGLU columns | |
| ``[w FS, (w + 1) FS)`` and codec_head columns ``[w HC, (w + 1) HC)``. | |
| * **ATT** (8 cores, group ``g``): attention of kv group ``g`` (q heads 2g, 2g + 1), its KV cache reads / append. | |
| * **HUB** (1 core): boot barrier and STATE, the H / logits gathers and DRAM writes. | |
| * idle: every other core (kernels return at once). | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import re | |
| from dataclasses import dataclass, field | |
| from typing import Callable, Dict, List, Optional, Sequence, Tuple | |
| KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") | |
| DEFS_PATH = os.path.join(KDIR, "md_defs.hpp") | |
| def _parse_defs(path: str = DEFS_PATH) -> Dict[str, int]: | |
| out = {} | |
| pat = re.compile(r"^\s*constexpr\s+uint32_t\s+([A-Z0-9_]+)\s*=\s*(0x[0-9A-Fa-f]+|[0-9]+)u?\s*;") | |
| with open(path) as f: | |
| for line in f: | |
| m = pat.match(line) | |
| if m: | |
| out[m.group(1)] = int(m.group(2), 0) | |
| return out | |
| D = _parse_defs() | |
| globals().update(D) | |
| Core = Tuple[int, int] | |
| #: weight tile bytes and the packet tile counts (pt * tile <= 16 KB, pt divides every segment of both widths) | |
| TILE_BYTES = {"bf16": 2048, "bfp8": 1088, "bfp4": 576} | |
| PACKET_TILES = {"bf16": 8, "bfp8": 12, "bfp4": 24} | |
| VOCAB = 103424 # PaddleOCR-VL (ERNIE-4.5-0.3B): HC = ceil(3232 / 32) = 101 head column tiles per MM core | |
| #: head packets: 8 tiles in every format (8 divides HC * D_T for both widths) | |
| PACKET_TILES_H = 8 | |
| class Dims: | |
| d: int # hidden | |
| i: int # MLP | |
| v: int = VOCAB # vocabulary (head columns) | |
| def hc(self) -> int: # head column tiles per MM core | |
| return -(-(-(-self.v // 32)) // NW) | |
| def d_t(self) -> int: | |
| return self.d // 32 | |
| def i_t(self) -> int: | |
| return self.i // 32 | |
| def xs(self) -> int: # residual column tiles per MM core | |
| return self.d_t // NW | |
| def fs(self) -> int: # SwiGLU column tiles per MM core | |
| return self.i_t // NW | |
| def hd_dense(self) -> int: # dense 32x32 tiles of the D-vector | |
| return max(1, self.d // 1024) | |
| # per-layer stream tiles of one MM core | |
| def a_tiles(self) -> int: | |
| return HD_T * self.d_t + self.xs * AT | |
| def m_tiles(self) -> int: | |
| return 2 * self.fs * self.d_t + self.xs * self.i_t | |
| def h_tiles(self) -> int: | |
| return self.hc * self.d_t | |
| def dims_of(variant_or_width) -> Dims: | |
| if isinstance(variant_or_width, int): | |
| return Dims(1024, 3072) if variant_or_width == 1024 else Dims(2048, 6144) | |
| return Dims(1024, 3072) if str(variant_or_width).startswith("0.6") else Dims(2048, 6144) | |
| class MMCore: | |
| w: int | |
| xy: Core | |
| bank: int | |
| noc: int # NoC of the weight reads (NCRISC); the BRISC uses 1 - noc | |
| class Geometry: | |
| gx: int | |
| gy: int | |
| mm: List[MMCore] | |
| att: List[Core] # group g -> core | |
| hub: Core | |
| opt0: List[Core] = field(default_factory=list) | |
| opt1: List[Core] = field(default_factory=list) | |
| atts: int = 1 # ATT cores per kv group (TLK: 2 = one q head per core; PRE32 uses the slot-0 cores only) | |
| def n(self) -> int: | |
| return self.gx * self.gy | |
| def idx(self, c: Core) -> int: | |
| return c[1] * self.gx + c[0] | |
| def role_of(self, pre: bool = False) -> Dict[Core, Tuple[int, int]]: | |
| """(role, index); ATT index = the core's position a in ``att`` (group a // atts, slot a % atts). ``pre``: the | |
| PRE32 roles (one ATT core per group: slot 0; the other slots idle).""" | |
| r = {} | |
| for m in self.mm: | |
| r[m.xy] = (R_MM, m.w) | |
| for a, c in enumerate(self.att): | |
| if not pre or a % self.atts == 0: | |
| r[c] = (R_ATT, a) | |
| r[self.hub] = (R_HUB, 0) | |
| return r | |
| def active(self) -> List[Core]: | |
| return [m.xy for m in self.mm] + list(self.att) + [self.hub] | |
| def n_active(self, pre: bool = False) -> int: | |
| return NW + (NG if pre else len(self.att)) + 1 | |
| def build(gx: int, gy: int, opt0: Sequence[Core], opt1: Sequence[Core], per: int = 2, atts: int = 1) -> Geometry: | |
| """``opt0`` / ``opt1``: ``device.get_optimal_dram_bank_to_logical_worker_assignment(NOC_0 / NOC_1)`` (bank order). | |
| ``per`` cores per (bank, NoC) -> ``2 * per * banks`` MM cores (must be 32).""" | |
| nb = len(opt0) | |
| if 2 * per * nb != NW: | |
| raise ValueError(f"{nb} DRAM banks x 2 NoCs x {per} != {NW} MM cores") | |
| all_cores = [(x, y) for y in range(gy) for x in range(gx)] | |
| used, mm = set(), [] | |
| for b in range(nb): | |
| for noc, opt in ((0, opt0), (1, opt1)): | |
| ox, oy = opt[b] | |
| cands = sorted(all_cores, key=lambda c: (abs(c[0] - ox) + abs(c[1] - oy), c[1], c[0])) | |
| k = 0 | |
| for c in cands: | |
| if c in used: | |
| continue | |
| used.add(c) | |
| mm.append((c, b, noc)) | |
| k += 1 | |
| if k == per: | |
| break | |
| # head assignment: w in placement order (spreads q / k / v heads over the banks) | |
| mms = [MMCore(w, c, b, noc) for w, (c, b, noc) in enumerate(mm)] | |
| free = [c for c in all_cores if c not in used] | |
| # ATT cores near the grid centre (short paths from the MM cores), hub next to them | |
| cx, cy = (gx - 1) / 2.0, (gy - 1) / 2.0 | |
| free.sort(key=lambda c: (abs(c[0] - cx) + abs(c[1] - cy), c[1], c[0])) | |
| att = free[:NG * atts] | |
| hub = free[NG * atts] | |
| return Geometry(gx, gy, mms, att, hub, list(opt0), list(opt1), atts) | |
| # ---------------------------------------------------------------------------------------------- CB table | |
| class CB: | |
| ids: Tuple[Tuple[int, str, int, Optional[Tuple[int, int]], bool], ...] # (cb id, fmt, page bytes, tile, unpack32) | |
| total: int | |
| RING_BUDGET = {"A": 66 * 1024, "M": 112 * 1024, "H": 32 * 1024} | |
| KV_RING_BLOCKS = 4 # ATT K and V rings (blocks of 4 bf16 tiles) | |
| def packet_bytes(fmt: str) -> int: | |
| return PACKET_TILES[fmt] * TILE_BYTES[fmt] | |
| def packet_bytes_h(fmt: str) -> int: | |
| return PACKET_TILES_H * TILE_BYTES[fmt] | |
| def ring_bytes(fmt_a: str, fmt_m: str, fmt_h: str = "bf16") -> Dict[str, int]: | |
| """Weight ring sizes: whole packets within the budget (the NCRISC and the CB wrap at the same byte). Ring H shares | |
| its memory with the ATT scores (32 KB, the TRISC's full-capacity CB_S / CB_SD cycles): exactly 32 KB.""" | |
| out = {} | |
| for k, f in (("A", fmt_a), ("M", fmt_m)): | |
| pk = packet_bytes(f) | |
| out[k] = max(2, RING_BUDGET[k] // pk) * pk | |
| pk = packet_bytes_h(fmt_h) | |
| out["H"] = max(2, RING_BUDGET["H"] // pk) * pk | |
| return out | |
| def cb_table(dims: Dims, fmt_a: str, fmt_m: str, atts: int = 2, fmt_h: str = "bf16") -> List[CB]: | |
| """DEC CBs. ``atts`` = ATT cores per kv group: 1 needs 2-page T0 / T1 (the two heads' softmax per section).""" | |
| tp = 2 if atts == 1 else 1 | |
| rb = ring_bytes(fmt_a, fmt_m, fmt_h) | |
| tb = TILE_BYTES | |
| TINY = (1, 32) | |
| t16 = lambda cid, n, unp=False: CB(((cid, "bf16", T16, None, unp),), n * T16) # noqa: E731 | |
| t32 = lambda cid, n, unp=True: CB(((cid, "fp32", T32, None, unp),), n * T32) # noqa: E731 | |
| kvb = KV_RING_BLOCKS * KV_PAGE | |
| out = [ | |
| # weight rings (MM); ring H aliased with the ATT scores, the HUB gathers alias ring A / M (raw) | |
| CB(((CB_WA, fmt_a, tb[fmt_a], None, False), (CB_HG, "raw", rb["A"], None, False)), rb["A"]), | |
| CB(((CB_WM, fmt_m, tb[fmt_m], None, False), (CB_LG, "raw", rb["M"], None, False)), rb["M"]), | |
| ] | |
| if fmt_h == "bf16": # ring H (2 x 16 KB packets) aliases the 32 KB ATT score region (TLK layout) | |
| out.append(CB(((CB_WH, "bf16", T16, None, False), (CB_S, "fp32", TINY32, TINY, False), | |
| (CB_SD, "fp32", T32, None, True)), 32768)) | |
| else: # bfp8 packets (8704 B) cannot tile the 32 KB score region: separate CBs | |
| out.append(CB(((CB_WH, fmt_h, tb[fmt_h], None, False),), rb["H"])) | |
| out.append(CB(((CB_S, "fp32", TINY32, TINY, False), (CB_SD, "fp32", T32, None, True)), 32768)) | |
| out += [ | |
| # ATT K / V rings | |
| CB(((CB_KR, "bf16", T16, None, False),), kvb), | |
| CB(((CB_VR, "bf16", T16, None, False),), kvb), | |
| # gathers (every core, never aliased: multicast destinations) | |
| CB(((CB_H, "bf16", TINY16, TINY, False), (CB_HD, "bf16", T16, None, False)), max(dims.d_t * TINY16, T16)), | |
| CB(((CB_O, "bf16", TINY16, TINY, False),), AT * TINY16), | |
| CB(((CB_F, "bf16", TINY16, TINY, False),), dims.i_t * TINY16), | |
| # MM state / scratch (ATT aliases: P / PT on G, the mask tile on TAB; HS on ACS; GF on G at the end) | |
| t32(CB_X, 1), | |
| t16(CB_XB, 1), | |
| CB(((CB_ACC, "fp32", TINY32, TINY, False), (CB_ACCD, "fp32", T32, None, True)), T32), | |
| CB(((CB_ACS, "fp32", TINY32, TINY, False), (CB_ACSD, "fp32", T32, None, True), | |
| (CB_HS, "fp32", T32, None, True)), T32), | |
| t32(CB_RS, 2), | |
| CB(((CB_T0, "fp32", T32, None, False), (CB_X0, "fp32", T32, None, True)), tp * T32), | |
| t32(CB_T1, tp, False), | |
| CB(((CB_QO, "bf16", T16, None, False), (CB_QOT, "bf16", TINY16, TINY, False)), T16), | |
| CB(((CB_FS, "bf16", TINY16, TINY, False),), max(dims.fs * TINY16, 512)), | |
| CB(((CB_G, "fp32", T32, None, True), (CB_P, "bf16", T16, None, False), (CB_PT, "bf16", TINY16, TINY, False), | |
| (CB_GF, "fp32", T32, None, True), (CB_E, "raw", 4 * T32, None, False)), 4 * T32), | |
| CB(((CB_TAB, "fp32", T32, None, True), (CB_MSK, "bf16", T16, None, False)), 2 * T32), | |
| CB(((CB_CONST, "bf16", T16, None, False), (CB_CT, "bf16", TINY16, TINY, False)), N_CONST * T16), | |
| CB(((CB_KVN, "raw", 512, None, False),), 512), | |
| CB(((CB_GO, "raw", 64, None, False),), 64), | |
| CB(((CB_SYNC, "raw", SYNC_CB_TLK, None, False),), SYNC_CB_TLK), | |
| CB(((CB_Q, "bf16", TINY16, TINY, False),), 2 * HD_T * TINY16), | |
| CB(((CB_LS, "fp32", TINY32, TINY, False),), dims.hc * TINY32), | |
| ] | |
| return out | |
| def cb_total(dims: Dims, fmt_a: str = "bfp8", fmt_m: str = "bfp8", atts: int = 2, fmt_h: str = "bf16") -> int: # noqa: F811 | |
| return sum(c.total for c in cb_table(dims, fmt_a, fmt_m, atts, fmt_h)) | |
| # ---------------------------------------------------------------------------------------------- PRE32 CB table | |
| PRE_KV_RING_BLOCKS = 2 # ATT K / V rings of the PRE program (blocks of 4 bf16 tiles) | |
| PRE_W_PACKETS = 4 # weight ring packets (A and M share it: one format) | |
| PRE_F_CHUNKS = 2 # F ring chunks of PT bf16 tiles | |
| def pre_cb_table(dims: Dims, fmt: str) -> List[CB]: | |
| """CB table of the PRE32 program (mp_*.cpp). Region views (one allocation per row; an MM view and an ATT view of | |
| the same memory; rings never share memory with a larger view: the NCRISC and the CB wrap at the same byte). | |
| The ATT's P (bf16) overwrites the scores (fp32) of blocks it no longer needs (P_j at 2 KB * j only covers S_k, | |
| k <= j / 2, already consumed; head 1's P lands on head 0's scores).""" | |
| pt = PACKET_TILES[fmt] | |
| tb = TILE_BYTES[fmt] | |
| ring_w = PRE_W_PACKETS * pt * tb | |
| ring_f = PRE_F_CHUNKS * pt * T16 | |
| ring_h = (ring_f // packet_bytes("bf16")) * packet_bytes("bf16") | |
| if ring_h != ring_f or ring_h < 2 * packet_bytes("bf16"): | |
| raise ValueError(f"F ring {ring_f} B must hold whole codec_head packets (>= 2)") | |
| kvb = PRE_KV_RING_BLOCKS * KV_PAGE | |
| big = max(AT, dims.d_t) * T16 # 128 KB: h [32, D] / o [32, 2048] bf16 | |
| att_s = 2 * PRE_MAX_BLOCKS * T32 | |
| if att_s > big: | |
| raise ValueError("ATT scores do not fit the gather region") | |
| if ring_f < 2 * HD_T * T32: | |
| raise ValueError("the ATT P V accumulators do not fit the F ring memory") | |
| xs, fs = dims.xs, dims.fs | |
| out = [ | |
| CB(((PCB_PH, "bf16", T16, None, False), (PCB_PO, "bf16", T16, None, False), (PCB_AS, "fp32", T32, None, True), | |
| (PCB_AP, "bf16", T16, None, False), (PCB_HG, "raw", big, None, False)), big), | |
| CB(((PCB_W, fmt, tb, None, False), (PCB_LG, "raw", ring_w, None, False)), ring_w), | |
| CB(((PCB_FR, "bf16", T16, None, False), (PCB_WH, "bf16", T16, None, False), | |
| (PCB_ACA, "fp32", T32, None, True)), ring_f), | |
| CB(((PCB_TAB, "fp32", T32, None, True), (PCB_MASK, "fp32", T32, None, True)), 4 * T32), | |
| CB(((PCB_KR, "bf16", T16, None, False), (PCB_ACM, "fp32", T32, None, True), (PCB_GF, "fp32", T32, None, True)), | |
| max(kvb, 4 * T32, xs * T32)), | |
| CB(((PCB_VR, "bf16", T16, None, False), (PCB_FS, "bf16", T16, None, False)), max(kvb, fs * T16)), | |
| CB(((PCB_AQ, "bf16", T16, None, False), (PCB_LS, "fp32", T32, None, False)), max(2 * HD_T * T16, HC * T32)), | |
| CB(((PCB_X, "fp32", T32, None, True), (PCB_AKN, "bf16", T16, None, False)), max(xs * T32, HD_T * T16)), | |
| CB(((PCB_X0, "fp32", T32, None, True), (PCB_XB, "bf16", T16, None, False), (PCB_HS, "fp32", T32, None, False), | |
| (PCB_AVN, "bf16", T16, None, False)), max(xs * T32, HD_T * T16)), | |
| CB(((PCB_G, "bf16", T16, None, False), (PCB_AMX, "fp32", T32, None, False)), max(HD_T * T16, T32)), | |
| CB(((PCB_PSS, "fp32", T32, None, False), (PCB_AM, "fp32", T32, None, True)), T32), | |
| # common | |
| CB(((PCB_PP, "fp32", T32, None, False),), T32), | |
| CB(((CB_SYNC, "raw", SYNC_CB_PRE, None, False),), SYNC_CB_PRE), | |
| CB(((CB_GO, "raw", 64, None, False),), 64), | |
| CB(((PCB_CONST, "bf16", T16, None, False),), PN_CONST * T16), | |
| CB(((PCB_T0, "fp32", T32, None, False),), T32), | |
| CB(((PCB_T1, "fp32", T32, None, False),), T32), | |
| CB(((PCB_RS, "fp32", T32, None, True),), 2 * T32), | |
| CB(((PCB_QO, "bf16", T16, None, False),), 2 * HD_T * T16), | |
| ] | |
| return out | |
| def pre_caps(dims: Dims, fmt: str) -> Dict[str, int]: | |
| """Full-capacity page counts of every PRE view (kernel defines MP_CAP_<name>).""" | |
| names = {v: k for k, v in globals().items() if k.startswith("PCB_") or k in ("CB_SYNC", "CB_GO")} | |
| out = {} | |
| for cb in pre_cb_table(dims, fmt): | |
| for cid, f, page, _t, _u in cb.ids: | |
| if f != "raw": | |
| if cb.total % page: | |
| raise ValueError(f"{names[cid]}: total {cb.total} not a multiple of the page {page}") | |
| out[names[cid][4:]] = cb.total // page | |
| return out | |
| def pre_cb_total(dims: Dims, fmt: str = "bfp8") -> int: | |
| return sum(c.total for c in pre_cb_table(dims, fmt)) | |
| def pre_ring_bytes(fmt: str) -> Dict[str, int]: | |
| pt = PACKET_TILES[fmt] | |
| ring_f = PRE_F_CHUNKS * pt * T16 | |
| return {"W": PRE_W_PACKETS * pt * TILE_BYTES[fmt], "F": ring_f, "H": ring_f, "KV": PRE_KV_RING_BLOCKS * KV_PAGE} | |
| L1_BUDGET = 384 * 1024 | |
| # ---------------------------------------------------------------------------------------------- runtime args | |
| def core_args(g: Geometry, noc_xy: Callable[[Core], Core], offsets: Dict[int, Tuple[int, int, int]], | |
| pre: bool = False) -> Dict[Core, List[int]]: | |
| """Per-core runtime args. ``offsets[w] = (off_A, off_M, off_H)``: bank-local byte offsets of MM core w's streams. | |
| TLK with ``atts`` = 2: q head 2g + s -> ATT core (g, s) slot 0; k / v head g -> both ATT cores of group g. | |
| ``pre``: the PRE32 args (ATT core of group g = the slot-0 core; q heads 2g, 2g + 1 -> its slots 0 / 1).""" | |
| roles = g.role_of(pre) | |
| S = 1 if pre else g.atts | |
| out = {} | |
| for y in range(g.gy): | |
| for x in range(g.gx): | |
| c = (x, y) | |
| a = [0] * N_RT_ARGS | |
| a[A_IDX] = g.idx(c) | |
| role, k = roles.get(c, (R_IDLE, 0)) | |
| a[A_ROLE] = role | |
| a[A_W] = k | |
| if role == R_ATT: | |
| a[A_W] = k // g.atts # kv group | |
| a[A_SLOT] = k % g.atts # q head of the group (split ATT) | |
| if role == R_MM: | |
| m = g.mm[k] | |
| a[A_HK] = HK_Q if k < 16 else (HK_K if k < 24 else HK_V) | |
| a[A_BANK] = m.bank | |
| a[A_VC] = (m.bank + m.noc) & 3 | |
| a[A_OFF_A], a[A_OFF_M], a[A_OFF_H] = offsets[k] | |
| grp = k // 2 if k < 16 else (k - 16 if k < 24 else k - 24) | |
| if k < 16 and S == 2: | |
| a[A_ATT_X], a[A_ATT_Y] = noc_xy(g.att[grp * g.atts + k % 2]) | |
| a[A_SLOT] = 0 | |
| else: | |
| a[A_ATT_X], a[A_ATT_Y] = noc_xy(g.att[grp * g.atts]) | |
| a[A_SLOT] = k % 2 if k < 16 else 0 | |
| if k >= 16 and S == 2: | |
| a[A_ATT2_X], a[A_ATT2_Y] = noc_xy(g.att[grp * g.atts + 1]) | |
| out[c] = a | |
| return out | |
| def common_args(g: Geometry, noc_xy: Callable[[Core], Core]) -> List[int]: | |
| c = [0] * N_COMMON | |
| x0, y0 = noc_xy((0, 0)) | |
| x1, y1 = noc_xy((g.gx - 1, g.gy - 1)) | |
| c[K_ALL_X0], c[K_ALL_Y0], c[K_ALL_X1], c[K_ALL_Y1] = min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1) | |
| c[K_N_ALL] = g.n | |
| c[K_N_ACT] = g.n_active() | |
| c[K_HUB_X], c[K_HUB_Y] = noc_xy(g.hub) | |
| for m in g.mm: | |
| nx, ny = noc_xy(m.xy) | |
| c[K_MM0 + m.w] = (nx << 16) | ny | |
| for gi, a in enumerate(g.att): | |
| nx, ny = noc_xy(a) | |
| c[K_ATT0 + gi] = (nx << 16) | ny | |
| return c | |