rdt2-base-p150 / code /tt_rdt2 /tt /common.py
changh95's picture
tt-model push rdt2-base-p150 (container)
9d8d25c verified
Raw History Blame Contribute Delete
16 kB
# SPDX-License-Identifier: Apache-2.0
"""Shared ttnn helpers of the RDT2-FM port: precision policy, compute-kernel configs, uploads, thin op wrappers.
``ttnn`` is imported lazily (inside functions) so the module is importable on a host without a device; the
precision policy and the host weight transforms are CPU-testable.
Precision policy (PORT_LOG.md section 3): every knob is one field of :class:`Precision`; :data:`PRECISION_PRESETS`
holds the measured variants and the three named presets ``baseline`` (default), ``accurate`` and ``fast``.
The named presets keep the ViT and LM residual streams in fp32 (``*_r32``: massive activations up to 1.1e4 in the ViT
and 3.7e3 in the LM, SPEC section 9; sublayer outputs stay bf16 and the add is fused into the next RMSNorm); the
``Precision()`` field defaults (bf16 residuals) are only the starting point of the sweep. RMSNorm statistics in fp32
(HiFi4, fp32 dest acc, approx off), SDPA with exp_approx off and fp32 accumulation.
"""
from __future__ import annotations
import dataclasses
from dataclasses import dataclass
from typing import Any, Dict, Optional, Tuple
import torch
TILE = 32
def round_up(n: int, m: int = TILE) -> int:
return (int(n) + m - 1) // m * m
@dataclass(frozen=True)
class Precision:
"""Weight dtypes ("bf16" | "bfp8" | "bfp4") and matmul fidelities ("HiFi4" | "HiFi2" | "LoFi") per group."""
vit_w: str = "bf16" # ViT qkv / proj / MLP weights
vit_mlp_w: str = "bf16" # ViT gate / up / down
vit_fid: str = "HiFi4"
vit_resid: str = "bf16" # ViT residual stream dtype ("bf16" | "fp32")
merger_w: str = "bf16"
lm_attn_w: str = "bf16" # LM qkv / o
lm_mlp_w: str = "bf16" # LM gate / up / down (2.6 G of the 3.0 G prefix params)
lm_fid: str = "HiFi4"
lm_mlp_fid: str = "HiFi4"
lm_resid: str = "bf16" # LM residual stream dtype ("bf16" | "fp32")
exp_w: str = "bf16" # expert attention / FFN / final
exp_ada_w: str = "bf16" # expert adaLN state half (128 x 1024 x 1024)
exp_fid: str = "HiFi4"
sdpa_fid: str = "HiFi4"
# expert residual stream + adaLN T + S + gates ("bf16" | "fp32"). fp32: the R2-F1 root cause (MK_LOG.md section 1):
# the bf16 residual adds of the device expert carry a step-coherent error (1 - PCC 9.7e-5 -> 3.7e-5 on the hold-out
# case r2_rand_long484 with an fp32 residual, logs/rdt2/mk_expert/rootcause_swaps*.log)
exp_resid: str = "bf16"
# score operand k of the Qwen self-attention (PREFIX; VERIFY_MK_r1 R1-F1, MK_LOG.md section 7):
# "fused": k = bf16(RoPE(bf16(W h + b))) is both the K output and the score operand (round-1 port);
# "table": the k bias leaves the projection; k_nb = RoPE(W h) (small) and the fp32 host tables T = RoPE(b_k),
# D = T - mean_j T give K = bf16(k_nb + T) and score k = bf16(k_nb + D): the bias-dominated, token-
# constant part of k (rms 27 vs 0.6 centred in layer 0) is no longer rounded with the scores (softmax is
# invariant to the constant), which was the systematic PREFIX error on long prompts
# Default "table" since optimization round 3 (VERIFY_MK_r2 R2-F5): every Precision(...) / registry entry gets the
# fixed operand; "fused" only on request (preset baseline_kfused, the A/B).
lm_kscore: str = "table"
def as_dict(self) -> Dict[str, str]:
return dataclasses.asdict(self)
PRECISION_PRESETS: Dict[str, Precision] = {
# accuracy-first: bf16 weights, HiFi4 + fp32 accumulation everywhere
"hifi4_bf16": Precision(),
# big ViT / LM matmuls at HiFi2 (bf16 weights)
"hifi2_bf16": Precision(vit_fid="HiFi2", lm_fid="HiFi2", lm_mlp_fid="HiFi2"),
# + bfp8 LM MLP weights (halves the dominant DRAM traffic)
"hifi2_lmmlp_bfp8": Precision(vit_fid="HiFi2", lm_fid="HiFi2", lm_mlp_fid="HiFi2", lm_mlp_w="bfp8"),
# + bfp8 everywhere except the expert
"hifi2_bfp8": Precision(vit_fid="HiFi2", lm_fid="HiFi2", lm_mlp_fid="HiFi2", lm_mlp_w="bfp8", lm_attn_w="bfp8",
vit_w="bfp8", vit_mlp_w="bfp8", merger_w="bfp8"),
# + bfp8 expert weights
"hifi2_bfp8_all": Precision(vit_fid="HiFi2", lm_fid="HiFi2", lm_mlp_fid="HiFi2", lm_mlp_w="bfp8", lm_attn_w="bfp8",
vit_w="bfp8", vit_mlp_w="bfp8", merger_w="bfp8", exp_w="bfp8", exp_ada_w="bfp8"),
}
for _name, _base in list(PRECISION_PRESETS.items()):
PRECISION_PRESETS[_name + "_r32"] = dataclasses.replace(_base, vit_resid="fp32", lm_resid="fp32", exp_resid="fp32")
# ViT at HiFi2, LM (attention + MLP) at HiFi4 with bf16 weights: the cheapest variant of the round-1 sweep
# (logs/rdt2/fix_r1/precision_sweep.log) that passes the floor-anchored A2 gate on the 492-token ext case.
PRECISION_PRESETS["vit2_lm4_bf16_r32"] = dataclasses.replace(PRECISION_PRESETS["hifi4_bf16_r32"], vit_fid="HiFi2")
# Named presets of the port (PORT_LOG.md section 3), all gated by tests/test_tt_device.py:
# baseline (default): every gate, incl. the per-case floor-anchored A2 on the 448 / 512-bucket ext cases;
# the e2e conditioning V sits below the official bf16 floor (ViT HiFi2; action unaffected)
# accurate : HiFi4 + bf16 everywhere; the reference preset (K / V at or above the official floor)
# fast : the round-0 default (HiFi2, bfp8 LM MLP); FAILS the floor-anchored A2 gate on the 492-token
# case (nsample 0.99972, gripper 2.7 mm vs 0.99989 / 1.5 mm): not for deployment
PRECISION_PRESETS["baseline"] = dataclasses.replace(PRECISION_PRESETS["vit2_lm4_bf16_r32"], lm_kscore="table")
PRECISION_PRESETS["accurate"] = dataclasses.replace(PRECISION_PRESETS["hifi4_bf16_r32"], lm_kscore="table")
PRECISION_PRESETS["fast"] = dataclasses.replace(PRECISION_PRESETS["hifi2_lmmlp_bfp8_r32"], lm_kscore="table")
# the round-1 score operand (A/B of the R1-F1 fix): baseline with k = bf16(RoPE(bf16(W h + b)))
PRECISION_PRESETS["baseline_kfused"] = dataclasses.replace(PRECISION_PRESETS["baseline"], lm_kscore="fused")
DEFAULT_PRECISION = "baseline"
def resolve_precision(p: Any = None) -> Precision:
if p is None:
return PRECISION_PRESETS[DEFAULT_PRECISION]
if isinstance(p, Precision):
return p
if isinstance(p, str):
return PRECISION_PRESETS[p]
if isinstance(p, dict):
return Precision(**p)
raise TypeError(f"precision must be a preset name, a dict or a Precision, got {type(p)}")
# ---------------------------------------------------------------------------------------------------------------
# ttnn objects (lazy)
# ---------------------------------------------------------------------------------------------------------------
def tt_dtype(name: str):
import ttnn
return {"bf16": ttnn.bfloat16, "bfp8": ttnn.bfloat8_b, "bfp4": ttnn.bfloat4_b, "fp32": ttnn.float32}[name]
_CKC: Dict[Tuple[str, bool, bool, bool], Any] = {}
def ckc(fidelity: str = "HiFi4", fp32_acc: bool = True, approx: bool = False, l1_acc: bool = True):
"""Compute-kernel config (cached). ``packer_l1_acc`` on by default: with fp32 dest accumulation the K-block
partials are then accumulated by the packer in L1 instead of being reloaded (2.3x on the ViT qkv matmul)."""
import ttnn
key = (fidelity, fp32_acc, approx, l1_acc)
if key not in _CKC:
_CKC[key] = ttnn.WormholeComputeKernelConfig(math_fidelity=getattr(ttnn.MathFidelity, fidelity),
math_approx_mode=approx, fp32_dest_acc_en=fp32_acc,
packer_l1_acc=l1_acc)
return _CKC[key]
def norm_ckc():
"""RMSNorm: HiFi4, fp32 dest acc, approx off (the op default is approx on / fp32 acc off)."""
return ckc("HiFi4", True, False, False)
def dram():
import ttnn
return ttnn.DRAM_MEMORY_CONFIG
def upload(t: torch.Tensor, device, dtype: str = "bf16", layout: str = "tile", mem=None):
"""Host torch tensor -> device tensor (DRAM interleaved by default). 1-D / 2-D tensors are made 4-D."""
import ttnn
while t.dim() < 4:
t = t.unsqueeze(0)
lay = ttnn.TILE_LAYOUT if layout == "tile" else ttnn.ROW_MAJOR_LAYOUT
if dtype in ("bfp8", "bfp4") and layout != "tile":
raise ValueError("block-float dtypes need TILE layout")
src = t.float() if dtype in ("bfp8", "bfp4", "fp32") else t.to(torch.bfloat16)
return ttnn.from_torch(src.contiguous(), dtype=tt_dtype(dtype), layout=lay, device=device,
memory_config=mem or ttnn.DRAM_MEMORY_CONFIG)
def upload_linear(w: torch.Tensor, device, dtype: str = "bf16", pad_in: Optional[int] = None,
pad_out: Optional[int] = None):
"""torch Linear weight (out, in) -> device (1, 1, in[_pad], out[_pad]) (zero padded)."""
wt = w.t().contiguous()
if pad_in is not None and pad_in > wt.shape[0]:
wt = torch.cat([wt, wt.new_zeros(pad_in - wt.shape[0], wt.shape[1])], 0)
if pad_out is not None and pad_out > wt.shape[1]:
wt = torch.cat([wt, wt.new_zeros(wt.shape[0], pad_out - wt.shape[1])], 1)
return upload(wt, device, dtype)
def upload_bias(b: torch.Tensor, device, pad_out: Optional[int] = None, dtype: str = "bf16"):
b = b.reshape(-1)
if pad_out is not None and pad_out > b.shape[0]:
b = torch.cat([b, b.new_zeros(pad_out - b.shape[0])])
return upload(b.reshape(1, -1), device, dtype)
def to_torch(t) -> torch.Tensor:
import ttnn
return ttnn.to_torch(t).float()
# ---------------------------------------------------------------------------------------------------------------
# op wrappers
# ---------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------------
# matmul program configs (research/rdt2/probes/probe_matmul.py sweep, logs/rdt2/device/probe_matmul.log)
# ---------------------------------------------------------------------------------------------------------------
L1_CB_BUDGET = 1_100_000 # bytes of circular buffers per core a matmul may use (the 2D configs above it fail)
_TILE_BYTES = {"bf16": 2048, "bfp8": 1088, "bfp4": 576, "fp32": 4096}
def _divisors(n: int):
return [d for d in range(1, n + 1) if n % d == 0]
def _subblock(pcm: int, pcn: int, max_dst: int = 4) -> Tuple[int, int]:
best = (1, 1)
for h in _divisors(pcm):
for w in _divisors(pcn):
if h * w <= max_dst and h * w > best[0] * best[1]:
best = (h, w)
return best
def mm_config(kind: Optional[str], M: int, K: int, N: int, grid: Tuple[int, int], *, act: Optional[str] = None,
w_dtype: str = "bf16", out_dtype: str = "bf16", ibw: int = 8, rows: Optional[int] = None,
ncores: Optional[int] = None):
"""Matmul program config: ``None``/"default" (ttnn picks), "2d" (MatmulMultiCoreReuseMultiCast: M over grid rows,
N over the 12 columns) or "1d" (in0 multicast, N over ``ncores``). ``in0_block_w`` is the largest divisor of Kt
<= ``ibw`` whose circular buffers fit :data:`L1_CB_BUDGET`. fp32 dest accumulation -> subblock h * w <= 4."""
if kind in (None, "default"):
return None
import ttnn
gx, gy = grid
mt, kt, nt = -(-M // TILE), -(-K // TILE), -(-N // TILE)
fa = None
if act == "silu":
fa = ttnn.UnaryWithParam(ttnn.UnaryOpType.SILU)
elif act is not None:
raise ValueError(f"unsupported fused activation {act}")
if kind == "2d":
r = min(rows or gy, gy, mt)
pcm, pcn = -(-mt // r), -(-nt // gx)
elif kind == "1d":
nc = ncores or gx * gy
pcm, pcn = mt, -(-nt // nc)
else:
raise ValueError(kind)
tw, to = _TILE_BYTES[w_dtype], _TILE_BYTES[out_dtype]
for b in sorted([d for d in _divisors(kt) if d <= ibw], reverse=True):
cb = 2 * pcm * b * 2048 + 2 * b * pcn * tw + pcm * pcn * (to + 4096)
if cb <= L1_CB_BUDGET:
ibw_ = b
break
else:
return None
sh, sw = _subblock(pcm, pcn)
if kind == "2d":
return ttnn.MatmulMultiCoreReuseMultiCastProgramConfig(
compute_with_storage_grid_size=(gx, -(-mt // pcm)), in0_block_w=ibw_, out_subblock_h=sh,
out_subblock_w=sw, per_core_M=pcm, per_core_N=pcn, transpose_mcast=False, fused_activation=fa,
fuse_batch=True)
nc = -(-nt // pcn)
return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig(
compute_with_storage_grid_size=(gx, -(-nc // gx)), in0_block_w=ibw_, out_subblock_h=sh, out_subblock_w=sw,
per_core_M=pcm, per_core_N=pcn, fuse_batch=True, fused_activation=fa, mcast_in0=True)
def minimal_config(M: int, K: int, N: int, grid: Tuple[int, int], *, kb: int = 8, nb_target: Optional[int] = None):
"""``ttnn.experimental.minimal_matmul`` config for the PREFIX's few-row matmuls (opt round 3, probe
logs/rdt2/opt_r3/probe_prefix_ops_*.log): M over ceil(mt / 2) grid rows (2 row tiles per core: M = 13..16 tiles
cannot fill 10 rows evenly), N over the gx columns, N blocks of the largest divisor of the per-core width <=
``nb_target``, 2 x w sub-blocks (fp32 DST: h * w <= 4), K blocks of ``kb`` tiles."""
import ttnn
gx, gy = grid
mt, nt = -(-M // TILE), -(-N // TILE)
r = min(gy, -(-mt // 2))
pm = -(-mt // r)
pn = -(-nt // gx)
nb = max(d for d in _divisors(pn) if d <= (nb_target or pn))
sh = 2 if pm % 2 == 0 else 1
sw = max(d for d in _divisors(nb) if sh * d <= 4)
return ttnn.MinimalMatmulConfig(M_block_size=pm, K_block_size=kb, N_block_size=nb, subblock_h=sh, subblock_w=sw,
compute_with_storage_grid_size=ttnn.CoreCoord(gx, r))
def linear(x, w, b=None, *, fid: str = "HiFi4", act: Optional[str] = None, out_dtype: str = "bf16", mem=None,
core_grid=None, pc=None):
"""x @ w (+ b). With a program config ``pc`` the activation must already be fused in it (``mm_config(act=)``)."""
import ttnn
kw: Dict[str, Any] = dict(compute_kernel_config=ckc(fid, True), dtype=tt_dtype(out_dtype),
memory_config=mem or ttnn.DRAM_MEMORY_CONFIG)
if pc is not None:
kw["program_config"] = pc
else:
if act is not None:
kw["activation"] = act
if core_grid is not None:
kw["core_grid"] = core_grid
if b is None and (act is None or pc is not None):
return ttnn.matmul(x, w, **kw)
return ttnn.linear(x, w, bias=b, **kw)
def rms_norm(x, w, eps: float, b=None, mem=None, residual=None):
"""``rms_norm(x [+ residual]) * w [+ b]``; the output dtype is x's (bf16 x + fp32 residual -> bf16)."""
import ttnn
return ttnn.rms_norm(x, epsilon=float(eps), weight=w, bias=b, residual_input_tensor=residual,
compute_kernel_config=norm_ckc(), memory_config=mem or ttnn.DRAM_MEMORY_CONFIG)
def sdpa(q, k, v, *, scale: float, grid: Tuple[int, int], chunks: Tuple[int, int], fid: str = "HiFi4",
causal: bool = False, mask=None, cu_window=None, mem=None):
import ttnn
pc = ttnn.SDPAProgramConfig(compute_with_storage_grid_size=grid, q_chunk_size=int(chunks[0]),
k_chunk_size=int(chunks[1]), exp_approx_mode=False)
kw: Dict[str, Any] = dict(is_causal=causal, scale=float(scale), program_config=pc,
compute_kernel_config=ckc(fid, True, False, False),
memory_config=mem or ttnn.DRAM_MEMORY_CONFIG)
if mask is not None:
kw["attn_mask"] = mask
if cu_window is not None:
kw["cu_window_seqlens"] = cu_window
return ttnn.transformer.scaled_dot_product_attention(q, k, v, **kw)
def device_grid(device) -> Tuple[int, int]:
g = device.compute_with_storage_grid_size()
return int(g.x), int(g.y)