File size: 7,779 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
 
 
 
 
 
 
 
 
 
b7e49b8
 
 
d5afa0d
 
 
 
b7e49b8
d5afa0d
 
 
 
 
 
 
 
 
 
 
 
 
 
b7e49b8
 
 
 
 
 
 
d5afa0d
 
b7e49b8
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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-<size>/ 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 <case>__<size>.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-<size>/")
    return R.load_safetensors(p)


def append_log(name: str, rec: dict) -> None:
    """Append ``rec`` to ``$DEPTHPRO2_MK_ENC_LOGDIR/<name>`` (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)