File size: 9,680 Bytes
ca1a504 | 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 | # SPDX-License-Identifier: Apache-2.0
"""Host side of the Unlimited-OCR-2 DASH attention on the device (tt/ttnn_dash.py): the per-request page coordinates
and candidate domain, per-layer router caches (ik, block summaries kbar) and the exact fp32 routing of
reference/uocr2.py, turned into a block-bias matrix that the device expands into the additive attention mask:
mask[i, j] = 0 if P_i - 128 < j <= P_i (local window)
= B[i, j // 32] otherwise, with B[i, b] = bias of block b if the row selected it, else NEG
The device computes ``(B @ E) * notlocal`` with E [nblk, S] the one-hot block -> key expansion (exact) and the static
``notlocal`` 0 / 1 matrix of the flat positions.
"""
from __future__ import annotations
import math
from typing import Optional, Sequence, Tuple
import torch
import torch.nn.functional as F
from ..reference import model as R
from ..reference import uocr2 as U
NEG = -1.0e4 # unselected / non-causal keys (exp underflows to 0 in the fp32 softmax)
IDX_D = U.IDX_D
def round_up(n: int, m: int) -> int:
return -(-int(n) // m) * m
def block_bias(sel: torch.Tensor, bias: torch.Tensor, valid: torch.Tensor, rows: int, nbp: int) -> torch.Tensor:
"""[rows, nbp] block-bias matrix (NEG where a block is not selected)."""
B = torch.full((rows, nbp), NEG)
n = sel.shape[0]
src = torch.where(valid, bias.float(), torch.full_like(bias.float(), NEG))
B[:n].scatter_(1, sel.long(), src)
return B
def expansion(nbp: int, S: int) -> torch.Tensor:
"""E [nbp, S]: E[b, j] = 1 if j // 32 == b."""
E = torch.zeros(nbp, S)
j = torch.arange(S)
b = j // U.BLOCK
E[b[b < nbp], j[b < nbp]] = 1.0
return E
def notlocal(q_pos: torch.Tensor, S: int) -> torch.Tensor:
"""[n, S]: 1 where key j is NOT in the local window (P - 128, P] of the query at P."""
j = torch.arange(S)[None, :]
p = q_pos[:, None]
return (~((j > p - U.LOCAL_WINDOW) & (j <= p))).float()
def mask_from_blocks(B: torch.Tensor, E: torch.Tensor, nl: torch.Tensor) -> torch.Tensor:
"""CPU emulation of the device mask: (B @ E) * notlocal."""
return (B @ E) * nl
class DashRouter:
"""Routing state of one request (batch 1)."""
def __init__(self, W, max_pos: int):
p = R.PFX + "layers.{}.self_attn.dash_router."
self.hc = [W.get(p.format(l) + "head_cls").float() for l in range(R.NL)]
self.wq = [W.get(p.format(l) + "q_norm.weight").float() for l in range(R.NL)]
self.wk = [W.get(p.format(l) + "k_norm.weight").float() for l in range(R.NL)]
self.max_pos = int(max_pos)
self.nb_max = -(-self.max_pos // U.BLOCK)
self.ik = torch.zeros(R.NL, self.max_pos, IDX_D)
self.kbar = torch.zeros(R.NL, self.nb_max, IDX_D)
self.nb_dec_pad = round_up(self.nb_max, 32) # the decode block-bias row (TtnnDashDecoder.nbp_dec)
# ------------------------------------------------------------------ prompt
def begin(self, ids: Sequence[int]):
ids = list(ids)
self.L = len(ids)
if self.L > self.max_pos:
raise ValueError(f"prompt of {self.L} tokens exceeds {self.max_pos} positions")
tok, page, st = U.page_coords(ids)
self.state = st
self.cos, self.sin = U.rope2d(tok, page)
self.ipage, self.qpage = U.prefill_page_ids(ids, st["n_pages"], st["last_img"])
self.nb_prefill = -(-self.L // U.BLOCK)
self.cand = U.block_candidates(self.ipage, self.qpage, self.nb_prefill)
ip = F.pad(self.ipage, (0, self.nb_prefill * U.BLOCK - self.L), value=-1).view(self.nb_prefill, U.BLOCK)
has = ip >= 0
self.bmin = torch.where(has.any(-1), torch.where(has, ip, torch.full_like(ip, 1 << 30)).min(-1).values,
torch.full((self.nb_prefill,), -1))
self.bmax = torch.where(has.any(-1), torch.where(has, ip, torch.full_like(ip, -1)).max(-1).values,
torch.full((self.nb_prefill,), -1))
self.mcum = ids.count(U.PAGE_ID) # the official decode state starts at the prompt's <PAGE> count
self.pp = st["n_pages"]
self.expected_pages = ids.count(U.PAGE_ID)
self.ik.zero_()
self.kbar.zero_()
self.allow = None
def qk(self, l: int, r: torch.Tensor, cos, sin):
"""Router query / key rows from r = x @ [Wrq; Wrk]^T [n, 256] (fp32)."""
r = r.float()
iq = U.rotate(U.gemma_rms(r[:, :IDX_D], self.wq[l]), cos, sin)
ik = U.rotate(U.gemma_rms(r[:, IDX_D:2 * IDX_D], self.wk[l]), cos, sin)
return iq, ik
def prefill_layer(self, l: int, r: torch.Tensor):
"""-> sel, bias, valid [L, 12] of layer l from r [L, 256]."""
L = self.L
iq, ik = self.qk(l, r[:L], self.cos, self.sin)
self.ik[l, :L] = ik
kbar, nonempty = U.block_summaries(ik, self.hc[l])
self.kbar[l, :kbar.shape[0]] = kbar
return U.route(iq, kbar, nonempty, torch.arange(L), self.cand)
# ------------------------------------------------------------------ decode
def step_begin(self, token: int, pos: int) -> Tuple[torch.Tensor, torch.Tensor]:
"""Advance the coordinates with the step's input token (at flat position pos); cos / sin [1, 128]."""
self.pos = int(pos)
if self.pos >= self.max_pos:
raise ValueError("KV capacity exceeded")
self.mcum += int(token == U.PAGE_ID)
t, pg = U.decode_coord(self.state, int(token))
cos, sin = U.rope2d(torch.tensor([t]), torch.tensor([pg]))
self.step_cos, self.step_sin = cos, sin
qp = self.mcum - 1 - self.pp
nblk = self.pos // U.BLOCK + 1
self.allow = None
if qp >= 0:
allow = torch.zeros(nblk, dtype=torch.bool)
n = min(self.nb_prefill, nblk)
allow[:n] = ((self.bmin <= qp) & (qp <= self.bmax))[:n]
if bool(allow.any()):
self.allow = allow
return cos, sin
def step_layer(self, l: int, r: torch.Tensor):
"""-> sel, bias, valid [1, 12] of layer l from r [1, 256] at the current step."""
pos = self.pos
iq, ik = self.qk(l, r[:1], self.step_cos, self.step_sin)
self.ik[l, pos] = ik[0]
b = pos // U.BLOCK
kb, _ = U.block_summaries(self.ik[l, b * U.BLOCK:pos + 1], self.hc[l])
self.kbar[l, b] = kb[0]
nblk = b + 1
nonempty = torch.ones(nblk, dtype=torch.bool)
cand = None if self.allow is None else self.allow[None, :nblk]
return U.route(iq, self.kbar[l, :nblk], nonempty, torch.tensor([pos]), cand)
def step_layer_fast(self, l: int, r) -> "np.ndarray":
""":meth:`step_layer` in numpy (one query; ~10x less host time per layer), returning the decode block-bias
row [nbp_dec] directly (NEG where no block is selected). Same math as reference/uocr2.route."""
import numpy as np
if not hasattr(self, "_np"):
self._np = {"hc": [h.numpy() for h in self.hc], "wq": [1.0 + w.numpy() for w in self.wq],
"wk": [1.0 + w.numpy() for w in self.wk]}
self._ik_np = self.ik.numpy() # views of the torch caches (shared memory)
self._kbar_np = self.kbar.numpy()
P, pos = self._np, self.pos
if getattr(self, "_np_pos", None) != pos:
self._np_pos = pos
self._cs = (self.step_cos.numpy().reshape(-1), self.step_sin.numpy().reshape(-1))
cos, sin = self._cs
r = np.asarray(r, np.float32).reshape(-1)
def gemma(x, w1):
x = x * (1.0 / np.sqrt(np.mean(x * x) + 1e-6))
x = np.clip(x, -U.ACT_CLAMP, U.ACT_CLAMP)
return np.clip(x * w1, -U.ACT_CLAMP, U.ACT_CLAMP)
def rot(x):
return x * cos + np.concatenate([-x[64:], x[:64]]) * sin
iq = rot(gemma(r[:IDX_D], P["wq"][l])).astype(np.float32)
ik = rot(gemma(r[IDX_D:2 * IDX_D], P["wk"][l])).astype(np.float32)
self._ik_np[l, pos] = ik
b = pos // U.BLOCK
blk = self._ik_np[l, b * U.BLOCK:pos + 1]
a = np.clip(blk @ P["hc"][l] / math.sqrt(IDX_D), -U.ACT_CLAMP, U.ACT_CLAMP)
e = np.exp(a - a.max())
self._kbar_np[l, b] = (e / max(float(e.sum()), 1e-6)) @ blk
nblk = b + 1
z = np.clip(self._kbar_np[l, :nblk] @ iq / math.sqrt(IDX_D), -U.ACT_CLAMP, U.ACT_CLAMP)
remote = np.arange(nblk) <= b - U.LOCAL_BLOCKS
c = remote if self.allow is None else (remote & self.allow.numpy()[:nblk])
if not c.any():
c = remote
x = np.where(c, z * U.IDX_SCALE, U.ENTMAX_NEG).astype(np.float32)
M = max(1, min(U.TOPM, nblk))
idx = np.argsort(-x, kind="stable")[:M]
xv = x[idx]
X = (xv - xv.max()) / 2
rho = np.arange(1, M + 1, dtype=np.float32)
mean = np.cumsum(X) / rho
msq = np.cumsum(X * X) / rho
tau = mean - np.sqrt(np.maximum((1 - rho * (msq - mean * mean)) / rho, 0))
k = max(1, int((tau <= X).sum()))
prior = np.maximum(X - tau[k - 1], 0) ** 2
K = max(1, min(U.TOPK, M))
sel, prior = idx[:K], prior[:K]
valid = c[sel]
row = np.full(self.nb_dec_pad, NEG, np.float32)
if valid.any():
logp = np.log(np.maximum(prior, U.FLOOR))
mu = logp[valid].sum() / max(int(valid.sum()), 1)
row[sel[valid]] = (logp[valid] - mu) / U.SIGMA
return row
# ------------------------------------------------------------------ output rule
def guard_state(self):
return {"marker_cum": 0, "scanned": 0, "page_len": 0}
|