embeddinggemma-2 / code /tt_embgemma /tt /ttnn_text.py
changh95's picture
tt-model push embeddinggemma-2 (container)
5c33f00 verified
Raw History Blame Contribute Delete
16.1 kB
# SPDX-License-Identifier: Apache-2.0
"""ttnn baseline of the EmbeddingGemma 2 text backbone (24 bidirectional Gemma-4 layers + PLE + final norm +
embedding_projection + mean-pool sums), one program per packed-token bucket S.
Packing (no batch padding): the sequences of a launch are concatenated into one row of S tokens (S = bucket of
the total); attention is block-diagonal per sequence through SDPA ``cu_window_seqlens`` ([0, n1, n1+n2, ..., T, S,
S, ...]: one window per sequence, the padding [T, S) is its own window, unused slots are empty windows). This is
exact for every layer when each sequence has <= 513 tokens (the sliding radius is 512, so sliding == full).
A longer sequence runs alone ("long" mode): full layers use the window [0, n), sliding layers an additive mask =
static band (|i - j| <= 512) + the key-padding row, built on the device.
Per-launch input (one fp32 ROW_MAJOR upload, rows of 8.3 KB): [S, 512 + 1536 + 32] = inputs_embeds | rope tables
(cos/sin sliding 256, cos/sin full 512, per token at its own position) | pooling matrix (column b = 1 on the tokens
of sequence b). Output: per-sequence token-embedding sums [32, 768] fp32 (mean = sum / n on the host) and, on
request, the token embeddings [S, 768]."""
from __future__ import annotations
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
from .. import model_spec as S
from .common import NEG, ckc, knobs, lin, mat, mm_1d_config, norm_w
IN_W = S.HIDDEN + 2 * (S.HEAD_DIM["sliding"] + S.HEAD_DIM["full"]) + 32 # 2080 = 65 tiles
COL_X = 0
COL_CS = S.HIDDEN # cos sliding
COL_SS = COL_CS + S.HEAD_DIM["sliding"]
COL_CF = COL_SS + S.HEAD_DIM["sliding"] # cos full
COL_SF = COL_CF + S.HEAD_DIM["full"]
COL_P = COL_SF + S.HEAD_DIM["full"] # pooling columns (32)
MAX_SEQS = 32
CU_LEN = MAX_SEQS + 2
class RopeTables:
"""Host cos/sin tables (HF default rope, rotate_half layout) up to ``max_pos`` positions, fp32."""
def __init__(self, max_pos: int):
self.tab = {}
for t in ("sliding", "full"):
d, th = S.HEAD_DIM[t], S.ROPE_THETA[t]
inv = 1.0 / (th ** (np.arange(0, d, 2, dtype=np.float64) / d))
f = np.arange(max_pos, dtype=np.float64)[:, None] * inv[None, :]
e = np.concatenate([f, f], axis=1)
self.tab[t] = (np.cos(e).astype(np.float32), np.sin(e).astype(np.float32))
def pack(xs: Sequence[np.ndarray], S_: int, rope: RopeTables) -> Tuple[np.ndarray, np.ndarray]:
"""Sequences [n_b, 512] -> (input rows [S, IN_W] fp32, cu_window_seqlens [CU_LEN] int32)."""
if len(xs) > MAX_SEQS:
raise ValueError(f"at most {MAX_SEQS} sequences per launch")
buf = np.zeros((S_, IN_W), np.float32)
cu = np.full((CU_LEN,), S_, np.int32)
cu[0] = 0
off = 0
for b, x in enumerate(xs):
n = x.shape[0]
buf[off: off + n, COL_X: COL_X + S.HIDDEN] = x
cs, ss = rope.tab["sliding"]
cf, sf = rope.tab["full"]
buf[off: off + n, COL_CS: COL_SS] = cs[:n]
buf[off: off + n, COL_SS: COL_CF] = ss[:n]
buf[off: off + n, COL_CF: COL_SF] = cf[:n]
buf[off: off + n, COL_SF: COL_P] = sf[:n]
buf[off: off + n, COL_P + b] = 1.0
off += n
cu[b + 1] = off
if off > S_:
raise ValueError(f"{off} tokens > bucket {S_}")
cu[len(xs) + 1:] = S_
return buf, cu
class TextWeights:
def __init__(self, device, W: Dict, wdt: str = "bf16", wdt_mlp: Optional[str] = None):
import torch
p = "language_model."
self.layers = []
mlp_dt = wdt_mlp or wdt
ple = W[p + "ple.per_layer_model_projection.weight"].float() * (S.HIDDEN ** -0.5)
# layer_scalar folding: the device keeps z_l = x_l / C_l (C_0 = 1, C_{l+1} = C_l s_l). RMSNorm inputs are
# scale-invariant, the residual adds use w / C_l, the PLE gate (linear in x) uses C_l Wpg; no multiply op.
C = 1.0
for l in range(S.LAYERS):
q = f"{p}layers.{l}."
g = lambda n: W[q + n].float() # noqa: E731
sc = float(W[q + "layer_scalar"].float().item())
qkv = torch.cat([g("self_attn.q_proj.weight"), g("self_attn.k_proj.weight"), g("self_attn.v_proj.weight")], 0)
self.layers.append({
"type": S.LAYER_TYPES[l],
"qkv": mat(device, qkv, wdt),
"o": mat(device, g("self_attn.o_proj.weight"), wdt),
"gate": mat(device, g("mlp.gate_proj.weight"), mlp_dt),
"up": mat(device, g("mlp.up_proj.weight"), mlp_dt),
"down": mat(device, g("mlp.down_proj.weight"), mlp_dt),
"pg": mat(device, g("ple_block.per_layer_input_gate.weight") * C, wdt),
"pp": mat(device, g("ple_block.per_layer_projection.weight"), wdt),
"ple": mat(device, ple[l * S.PLE_DIM:(l + 1) * S.PLE_DIM], wdt),
"n_in": norm_w(device, g("input_layernorm.weight")),
"n_pa": norm_w(device, g("post_attention_layernorm.weight") / C),
"n_pf": norm_w(device, g("pre_feedforward_layernorm.weight")),
"n_pff": norm_w(device, g("post_feedforward_layernorm.weight") / C),
"n_pp": norm_w(device, g("ple_block.post_per_layer_input_norm.weight") / C),
"n_q": norm_w(device, g("self_attn.q_norm.weight")),
"n_k": norm_w(device, g("self_attn.k_norm.weight")),
"scalar": 1.0,
})
C *= sc
self.n_ple = norm_w(device, W[p + "ple.per_layer_projection_norm.weight"])
self.n_final = norm_w(device, W[p + "norm.weight"])
self.proj = mat(device, W[p + "embedding_projection.weight"].float(), "bf16")
class TextProgram:
"""One bucket S and mode ('packed' | 'long'): persistent device inputs, eager forward, optional trace."""
def __init__(self, device, tw: TextWeights, S_: int, mode: str = "packed", act: str = "bf16",
fidelity: str = "HiFi4", want_tokens: bool = False):
import torch
import ttnn
self.device, self.tw, self.S, self.mode = device, tw, int(S_), mode
self.act = {"bf16": ttnn.bfloat16, "fp32": ttnn.float32}[act]
self.ck = ckc(device, knobs()["tfid"] or fidelity)
# SDPA compute: "acc" = HiFi4 + fp32 DST (the op's standard kernel), "fast" = HiFi2 + bf16 DST + approximate
# exp (the op's streaming kernel, its default; ttaw P7: 1.35-1.45x faster, max error 2x)
self.ck_sdpa = ckc(device, "HiFi2", fp32_acc=False, approx=True) if knobs()["sdpa_ck"] == "fast" \
else ckc(device, "HiFi4")
self.want_tokens = want_tokens
self.in_dev = ttnn.allocate_tensor_on_device(ttnn.Shape([1, 1, self.S, IN_W]), ttnn.float32,
ttnn.ROW_MAJOR_LAYOUT, device, ttnn.DRAM_MEMORY_CONFIG)
self.cu_dev = ttnn.allocate_tensor_on_device(ttnn.Shape([CU_LEN]), ttnn.int32, ttnn.ROW_MAJOR_LAYOUT, device,
ttnn.DRAM_MEMORY_CONFIG)
self.band = None
if mode == "long":
i = np.arange(self.S)
band = np.where(np.abs(i[:, None] - i[None, :]) <= S.SLIDING_RADIUS, 0.0, NEG).astype(np.float32)
self.band = ttnn.from_torch(torch.from_numpy(band).reshape(1, 1, self.S, self.S), dtype=ttnn.bfloat16,
layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG)
kn = knobs()
g = device.compute_with_storage_grid_size()
# measured (scripts/op_micro.py): <= 64 tokens: DRAM + the auto matmul config; 128 .. 512: L1 activations +
# matmuls on the full grid; above: DRAM + the full grid
self.grid = ttnn.CoreGrid(y=g.y, x=g.x) if (self.S >= 128 and kn["grid"] == "1") else None
self.mem = ttnn.L1_MEMORY_CONFIG if (128 <= self.S <= 512 and kn["l1"] == "1") else ttnn.DRAM_MEMORY_CONFIG
self.small_mm = self.S <= 64 and kn.get("mm1d", "1") == "1"
self.attn = "cu" if (mode == "packed" and self.S >= 1024 and kn.get("tattn", "") != "mask") else "mask"
self.trace_id = None
self.out = None
def _sdpa_cfg(self, hd: int):
"""64 x 64 chunks (measured: 2-3x faster than 256 x 128 at 128 .. 512 rows: more parallel work units)."""
import ttnn
g = self.device.compute_with_storage_grid_size()
kn = knobs()
qc = int(kn["sdpa"]) if kn.get("sdpa") else 64
q = max(32, min(qc, self.S)) // 32 * 32
k = 128 if self.attn == "cu" else q
grid = ttnn.CoreCoord(min(8, g.x), min(8, g.y)) if hd < 512 else ttnn.CoreCoord(min(8, g.x), min(4, g.y))
return ttnn.SDPAProgramConfig(compute_with_storage_grid_size=grid, q_chunk_size=q, k_chunk_size=k,
exp_approx_mode=False)
def _attention(self, q, k, v, t, hd, masks):
"""<= 512 rows and long mode: SDPA with an additive mask (block-diagonal + key padding [+ band]), 64-row
chunks (2-3x faster than the cu windows at 128 .. 512 rows). >= 1024 packed rows: SDPA cu_window_seqlens,
which skips the cross-sequence blocks (many short sequences: 32 x 64 tokens is 1/32 of the dense work)."""
import ttnn
if self.attn == "cu":
return ttnn.transformer.scaled_dot_product_attention(
q, k, v, is_causal=False, scale=1.0, cu_window_seqlens=self.cu_dev, program_config=self._sdpa_cfg(hd),
compute_kernel_config=self.ck_sdpa)
m = masks["sliding"] if (self.mode == "long" and t == "sliding") else masks["full"]
return ttnn.transformer.scaled_dot_product_attention(
q, k, v, attn_mask=m, is_causal=False, scale=1.0, program_config=self._sdpa_cfg(hd),
compute_kernel_config=self.ck_sdpa)
def forward(self):
import ttnn
tw, S_, act, ck = self.tw, self.S, self.act, self.ck
dram = ttnn.DRAM_MEMORY_CONFIG
inp = ttnn.to_layout(self.in_dev, ttnn.TILE_LAYOUT) # [1, 1, S, IN_W] fp32
x0 = ttnn.slice(inp, [0, 0, 0, COL_X], [1, 1, S_, COL_X + S.HIDDEN])
rope = {
"sliding": (ttnn.typecast(ttnn.slice(inp, [0, 0, 0, COL_CS], [1, 1, S_, COL_SS]), ttnn.bfloat16),
ttnn.typecast(ttnn.slice(inp, [0, 0, 0, COL_SS], [1, 1, S_, COL_CF]), ttnn.bfloat16)),
"full": (ttnn.typecast(ttnn.slice(inp, [0, 0, 0, COL_CF], [1, 1, S_, COL_SF]), ttnn.bfloat16),
ttnn.typecast(ttnn.slice(inp, [0, 0, 0, COL_SF], [1, 1, S_, COL_P]), ttnn.bfloat16)),
}
poolT = ttnn.slice(inp, [0, 0, 0, COL_P], [1, 1, S_, COL_P + 32]) # [1, 1, S, 32] fp32
# same-sequence indicator P P^T (P: the [S, 32] one-hot pooling columns; padding rows are zero) -> 0 / NEG
masks = {}
if self.attn == "mask":
same = ttnn.matmul(poolT, poolT, transpose_b=True, compute_kernel_config=ck, dtype=ttnn.float32) # [S, S]
mfull = ttnn.typecast(ttnn.multiply(ttnn.subtract(same, 1.0), -NEG), ttnn.bfloat16)
masks = {"full": mfull, "sliding": mfull}
if self.mode == "long":
masks["sliding"] = ttnn.add(self.band, mfull, dtype=ttnn.bfloat16)
x = x0 if act == ttnn.float32 else ttnn.typecast(x0, act)
x0b = ttnn.typecast(x0, ttnn.bfloat16)
mem, grid = self.mem, self.grid
bf = ttnn.bfloat16
pcs = {}
def L_(a, w):
pc = None
if self.small_mm:
K, N = int(w.shape[-2]), int(w.shape[-1])
if (K, N) not in pcs:
pcs[(K, N)] = mm_1d_config(S_ // 32, K // 32, N // 32, self.device.compute_with_storage_grid_size().x)
pc = pcs[(K, N)]
return lin(a, w, ck, bf, mem, grid, pc=pc)
def rms(a, w=None):
return ttnn.rms_norm(a, epsilon=S.EPS, weight=w, compute_kernel_config=ck, memory_config=mem)
for L in tw.layers:
t = L["type"]
hd, kvh = S.HEAD_DIM[t], S.KV_HEADS[t]
qkv = L_(rms(x, L["n_in"]), L["qkv"])
q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=S.HEADS, num_kv_heads=kvh,
transpose_k_heads=False, memory_config=mem)
ttnn.deallocate(qkv)
cos, sin = rope[t]
q = ttnn.experimental.rotary_embedding(rms(q, L["n_q"]), cos, sin, compute_kernel_config=ck,
memory_config=mem)
k = ttnn.experimental.rotary_embedding(rms(k, L["n_k"]), cos, sin, compute_kernel_config=ck,
memory_config=mem)
v = rms(v)
a = self._attention(q, k, v, t, hd, masks)
o = L_(ttnn.experimental.nlp_concat_heads(a, memory_config=mem), L["o"])
x = ttnn.add(x, rms(o, L["n_pa"]), dtype=act, memory_config=mem)
h = rms(x, L["n_pf"])
# gelu_tanh(gate) * up (two linears + gelu + multiply measured faster than one fused linear + geglu)
f = ttnn.multiply(ttnn.gelu(L_(h, L["gate"]), variant=ttnn.GeluVariant.Tanh, memory_config=mem),
L_(h, L["up"]), memory_config=mem)
x = ttnn.add(x, rms(L_(f, L["down"]), L["n_pff"]), dtype=act, memory_config=mem)
pl = rms(L_(x0b, L["ple"]), tw.n_ple)
g = ttnn.multiply(ttnn.gelu(L_(x, L["pg"]), variant=ttnn.GeluVariant.Tanh, memory_config=mem), pl,
memory_config=mem)
x = ttnn.add(x, rms(L_(g, L["pp"]), L["n_pp"]), dtype=act, memory_config=mem)
xn = ttnn.rms_norm(x, epsilon=S.EPS, weight=tw.n_final, compute_kernel_config=ck)
# pooled sums: P^T x -> [32, 512] then the projection (linear, so pooling first is exact)
xs = ttnn.matmul(poolT, ttnn.typecast(xn, ttnn.float32), transpose_a=True, compute_kernel_config=ck,
dtype=ttnn.float32)
pooled = ttnn.linear(xs, tw.proj, compute_kernel_config=ck, dtype=ttnn.float32)
toks = ttnn.linear(xn, tw.proj, compute_kernel_config=ck, dtype=ttnn.float32)
return pooled, toks
def load(self, buf: np.ndarray, cu: np.ndarray):
import torch
import ttnn
h = ttnn.from_torch(torch.from_numpy(buf).reshape(1, 1, self.S, IN_W), dtype=ttnn.float32,
layout=ttnn.ROW_MAJOR_LAYOUT)
ttnn.copy_host_to_device_tensor(h, self.in_dev)
c = ttnn.from_torch(torch.from_numpy(cu), dtype=ttnn.int32, layout=ttnn.ROW_MAJOR_LAYOUT)
ttnn.copy_host_to_device_tensor(c, self.cu_dev)
def compile(self):
"""Eager forward (program compile, prepared weights); no trace may have been captured before this on the
device (persistent allocations must not land in a trace's intermediate region)."""
import ttnn
self.forward()
ttnn.synchronize_device(self.device)
def capture(self):
import ttnn
tid = ttnn.begin_trace_capture(self.device, cq_id=0)
self.out = self.forward()
ttnn.end_trace_capture(self.device, tid, cq_id=0)
self.trace_id = tid
def run(self, buf: np.ndarray, cu: np.ndarray, want_tokens: bool = False):
import ttnn
self.load(buf, cu)
if self.trace_id is not None:
ttnn.execute_trace(self.device, self.trace_id, cq_id=0, blocking=False)
pooled, toks = self.out
else:
pooled, toks = self.forward()
p = ttnn.to_torch(pooled).float().reshape(-1, S.EMB_DIM)[:32].numpy()
t = ttnn.to_torch(toks).float().reshape(-1, S.EMB_DIM)[: self.S].numpy() if want_tokens else None
return p, t
def release(self):
import ttnn
if self.trace_id is not None:
ttnn.release_trace(self.device, self.trace_id)
self.trace_id = None