# SPDX-License-Identifier: Apache-2.0 """Host-side helpers of the ENC megakernel tests: weights / golden loading, the float32 reference (embed, blocks, per-block q / k / v / attention output) and the mapping between reference tokens ``[T, 5 + N, C]`` and the megakernel's row tiles ``[Mt, 32, C]`` (geometry.py: prefix tiles, then patch tiles, then the pool tile).""" from __future__ import annotations import os from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from tt_depthpro2.reference import model as R _CODE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # code/ (the package's parent) #: parent of DepthPro2-/ and DepthPro2-focal/ (serve-pkg's host_helpers names; else code/weights) WEIGHTS_ROOT = (os.environ.get("DEPTHPRO2_TEST_WEIGHTS") or os.environ.get("DEPTHPRO2_WEIGHTS_DIR") or os.path.join(_CODE, "weights")) #: Apple's float32 goldens __.safetensors (else code/golden) GOLDEN = os.environ.get("DEPTHPRO2_GOLDEN") or os.path.join(_CODE, "golden") #: optional: the clean-room float32 reference outputs of make_baseline_refs.py (cases without an official golden) BASELINE_REF = os.environ.get("DEPTHPRO2_BASELINE_REF", "") #: optional: where the dev scripts append their jsonl records (unset: print only) LOG_DIR = os.environ.get("DEPTHPRO2_MK_ENC_LOGDIR", "") P = R.NUM_PREFIX def weights_path(size: str) -> str: return os.path.join(WEIGHTS_ROOT, f"DepthPro2-{'focal' if size == 'fov' else size}", "model.safetensors") def load_weights(size: str) -> Dict[str, torch.Tensor]: p = weights_path(size) if not os.path.isfile(p): raise FileNotFoundError(f"{p} not found: set DEPTHPRO2_TEST_WEIGHTS to the parent of DepthPro2-/") return R.load_safetensors(p) def append_log(name: str, rec: dict) -> None: """Append ``rec`` to ``$DEPTHPRO2_MK_ENC_LOGDIR/`` (no-op when the variable is unset).""" if LOG_DIR: import json os.makedirs(LOG_DIR, exist_ok=True) with open(os.path.join(LOG_DIR, name), "a") as f: f.write(json.dumps(rec) + "\n") def load_case(case: str, size: str) -> Dict[str, torch.Tensor]: """The official golden, else the clean-room float32 reference output (``make_baseline_refs.py``, no taps).""" from safetensors.torch import load_file p = os.path.join(GOLDEN, f"{case}__{size}.safetensors") if not os.path.exists(p) and BASELINE_REF: p = os.path.join(BASELINE_REF, f"{case}__{size}.safetensors") if not os.path.exists(p): raise FileNotFoundError(f"no golden {case}__{size}: set DEPTHPRO2_GOLDEN (or DEPTHPRO2_BASELINE_REF)") return load_file(p) def pcc(a: torch.Tensor, b: torch.Tensor) -> float: a, b = a.double().flatten(), b.double().flatten() a, b = a - a.mean(), b - b.mean() return float((a @ b) / (a.norm() * b.norm() + 1e-30)) def rel_err(a: torch.Tensor, b: torch.Tensor) -> float: return float((a.double() - b.double()).norm() / (b.double().norm() + 1e-30)) # ------------------------------------------------------------------------------------------------ token mapping def to_internal(tokens: torch.Tensor, geo) -> torch.Tensor: """``[T, 5 + N, C]`` -> ``[Mt, 32, C]`` (pool tile and padding rows zero).""" t, _, c = tokens.shape out = torch.zeros(geo.Mt, 32, c) out[:t, :P] = tokens[:, :P] pt = torch.zeros(t, geo.Np, c) pt[:, :geo.N] = tokens[:, P:] out[t:t + t * geo.Pt] = pt.reshape(t * geo.Pt, 32, c) return out def from_internal(xi: torch.Tensor, geo) -> torch.Tensor: """``[Mt, 32, C]`` -> ``[T, 5 + N, C]``.""" t, c = geo.T, xi.shape[-1] pre = xi[:t, :P] pat = xi[t:t + t * geo.Pt].reshape(t, geo.Np, c)[:, :geo.N] return torch.cat([pre, pat], 1) def taps_from_device(tap: torch.Tensor, geo) -> torch.Tensor: """depth-mode tap ``[T * Np, C]`` -> ``[T, N, C]``; fov mode ``[T * (32 + Np), C]`` -> ``[T, 5 + N, C]``.""" t, c = geo.T, tap.shape[-1] if geo.mode == "fov": x = tap.reshape(t, 32 + geo.Np, c) return torch.cat([x[:, :P], x[:, 32:32 + geo.N]], 1) return tap.reshape(t, geo.Np, c)[:, :geo.N] # ------------------------------------------------------------------------------------------------ reference def cfg_of(size: str, mode: str) -> R.SizeConfig: return R.FOV_TRUNK if mode == "fov" else R.SIZES[size] def ref_embed(w, x: torch.Tensor, mode: str) -> torch.Tensor: return R.embed(x, w, "trunk." if mode == "fov" else "encoder.") def ref_block(tokens, w, l: int, cfg, rope, mode: str) -> torch.Tensor: pfx = "trunk." if mode == "fov" else "encoder." p = f"{pfx}blocks.{l}" if mode == "fov": out = R.block(tokens, w, p, cfg, rope) if l in cfg.cross_frame_blocks: out = torch.cat([tokens[:, :P], out[:, P:]], dim=1) return out if l in cfg.cross_frame_blocks: return R.cross_frame_block(tokens, w, p, cfg, rope) return R.block(tokens, w, p, cfg, rope) def ref_run(w, x: torch.Tensor, size: str, nl: int, mode: str = "depth") -> Tuple[torch.Tensor, List[torch.Tensor]]: """tokens after ``nl`` blocks and the taps (depth: patch tokens; fov: all tokens) of the blocks run.""" cfg = cfg_of(size, mode) grid = (x.shape[-2] // 16, x.shape[-1] // 16) rope = R.rope_table(*grid) tok = ref_embed(w, x, mode) taps = [] with torch.no_grad(): for l in range(nl): tok = ref_block(tok, w, l, cfg, rope, mode) if l in cfg.reassembled_blocks: taps.append(tok if mode == "fov" else tok[:, P:]) return tok, taps def ref_qkv(tokens, w, l: int, size: str, mode: str, gh: int, gw: int) -> Dict[str, torch.Tensor]: """q (x 1/8) / k / v of block ``l`` (post RoPE) as ``[Mt-like tokens]``: dict of ``[T, 5 + N, C]`` (joint blocks: prefix rows hold the pool tile's k / v in row-tile ``Mt - 1``, returned separately as ``pool_k`` / ``pool_v``).""" cfg = cfg_of(size, mode) pfx = "trunk." if mode == "fov" else "encoder." p = f"{pfx}blocks.{l}" sin, cos = R.rope_table(gh, gw) t = tokens.shape[0] with torch.no_grad(): q, k, v = R.block_qkv(tokens, w, p, cfg.heads, (sin, cos), P) # (T, h, L, d) out = {n: a.permute(0, 2, 1, 3).reshape(t, a.shape[2], -1) for n, a in (("q", q / 8.0), ("k", k), ("v", v))} joint = mode == "depth" and l in cfg.cross_frame_blocks if joint: pool = tokens[:, :P].mean(0, keepdim=True) pq, pk, pv = R.block_qkv(pool, w, p, cfg.heads, None, P) out["pool_k"] = pk.permute(0, 2, 1, 3).reshape(1, P, -1)[0] out["pool_v"] = pv.permute(0, 2, 1, 3).reshape(1, P, -1)[0] return out def ref_attn(tokens, w, l: int, size: str, mode: str, gh: int, gw: int) -> torch.Tensor: """attention output (heads merged, before proj) of block ``l``: ``[T, 5 + N, C]`` (joint: prefix rows 0).""" cfg = cfg_of(size, mode) pfx = "trunk." if mode == "fov" else "encoder." p = f"{pfx}blocks.{l}" sin, cos = R.rope_table(gh, gw) t, n, c = tokens.shape with torch.no_grad(): if mode == "depth" and l in cfg.cross_frame_blocks: x = torch.cat([tokens[:, :P].mean(0, keepdim=True), tokens[:, P:].reshape(1, -1, c)], 1) q, k, v = R.block_qkv(x, w, p, cfg.heads, (sin.repeat(t, 1), cos.repeat(t, 1)), P) a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(1, -1, c) out = torch.zeros(t, n, c) out[:, P:] = a[0, P:].reshape(t, -1, c) return out q, k, v = R.block_qkv(tokens, w, p, cfg.heads, (sin, cos), P) return F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(t, n, c)