File size: 16,783 Bytes
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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# SPDX-License-Identifier: Apache-2.0
"""ttnn baseline of DepthPro2 on the device: stage-level PCC (ENC / DEC / FOV, S) and end-to-end gates (SPEC §5)
for every size through ``DepthPro2Device`` (traced), plus trace-replay determinism.

Run through the workspace lock, naming this file:
``bin/devrun -t 5400 -- python -m pytest -q -s -o faulthandler_timeout=3000 \
    bundles/depthpro2/code/tt_depthpro2/tests/test_device_baseline.py``
(``-k "stage"`` / ``-k "e2e and S"`` select subsets). Results are appended to
``logs/depthpro2/baseline/results.jsonl`` (``DEPTHPRO2_BASELINE_RESULTS`` overrides).
"""

from __future__ import annotations

import json
import os
import sys
import time

import pytest
import torch

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import baseline_helpers as H  # noqa: E402

from tt_depthpro2.reference import model as ref  # noqa: E402
from tt_depthpro2.tt import StageShape  # noqa: E402
from tt_depthpro2.tt.weights import load_weights, unfold_patches  # noqa: E402

pytestmark = pytest.mark.device

RESULTS = os.environ.get("DEPTHPRO2_BASELINE_RESULTS", os.path.join(H.ROOT, "logs/depthpro2/baseline/results.jsonl"))
E2E_CASES = ("img_vga", "clip4_240x320", "img_375x500_pad")


def record(kind: str, **kw) -> None:
    kw = {"kind": kind, "time": time.strftime("%Y-%m-%d %H:%M:%S"), **kw}
    os.makedirs(os.path.dirname(RESULTS), exist_ok=True)
    with open(RESULTS, "a") as f:
        f.write(json.dumps(kw) + "\n")
    print(json.dumps(kw))


_W = {}


def weights(name: str):
    if name not in _W:
        _W[name] = load_weights(H.fov_dir() if name == "fov" else H.size_dir(name))
    return _W[name]


def to_dev(t: torch.Tensor, device):
    import ttnn

    return ttnn.from_torch(t.to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device,
                           memory_config=ttnn.DRAM_MEMORY_CONFIG)


# ----------------------------------------------------------------------------------------------- stage level (S)


@pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320"])
def test_enc_stage(device, case):
    import ttnn

    from tt_depthpro2.tt import ttnn_enc

    g, _ = H.load_golden(case, "S")
    x = ref.pad_to_multiple(g["x_norm"])
    t, _, hp, wp = x.shape
    shape = StageShape(t, hp, wp)
    eng = ttnn_enc.Engine(device, ttnn_enc.Engine.prepare_weights(device, weights("S"), "S"), shape)
    blocks = {}
    eng.trunk.hook = lambda i, xt: blocks.__setitem__(i, ttnn.to_torch(xt).float())
    taps = eng.run(to_dev(unfold_patches(x, shape.np_).reshape(1, 1, -1, 768), device))
    n = shape.n
    blk = []
    for i, xb in sorted(blocks.items()):
        dev_b = torch.cat([xb[:, 0, n:n + 5], xb[:, 0, :n]], dim=1)
        blk.append(round(H.pcc(dev_b, g[f"enc.block{i:02d}.out"]), 6))
    res = []
    for i, tp in enumerate(taps):
        d = ttnn.to_torch(tp).float().reshape(t, shape.np_, -1)[:, :n]
        res.append({"pcc": H.pcc(d, g[f"tap{i}"]), "max_rel": H.max_rel(d, g[f"tap{i}"])})
    record("stage_enc", size="S", case=case, taps=res, block_pcc=blk)
    assert min(r["pcc"] for r in res) >= 0.999, res
    assert min(blk) >= 0.999, blk


@pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320", "img_vga"])
def test_dec_stage(device, case):
    import ttnn

    from tt_depthpro2.tt import ttnn_dec

    g, _ = H.load_golden(case, "S")
    x = ref.pad_to_multiple(g["x_norm"])
    t, _, hp, wp = x.shape
    shape = StageShape(t, hp, wp)
    eng = ttnn_dec.Engine(device, ttnn_dec.Engine.prepare_weights(device, weights("S"), "S"), shape)
    taps = []
    for i in range(4):
        tp = torch.zeros(t, shape.np_, g[f"tap{i}"].shape[-1])
        tp[:, :shape.n] = g[f"tap{i}"]
        taps.append(to_dev(tp.reshape(1, 1, -1, tp.shape[-1]), device))
    out = ttnn.to_torch(eng.run(taps)).float().reshape(t, hp, wp)
    ref_o = g["head.out"][:, 0]
    r = {"pcc": H.pcc(out, ref_o), "max_rel": H.max_rel(out, ref_o)}
    record("stage_dec", size="S", case=case, inv=r)
    assert r["pcc"] >= 0.9999, r


@pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320", "img_375x500_pad"])
def test_fov_stage(device, case):
    import ttnn

    from tt_depthpro2.tt import ttnn_fov

    g, _ = H.load_golden(case, "S")
    x = g["x_norm"]
    y = ref.fov_resize(x)
    t, _, h, w = y.shape
    shape = StageShape(t, h, w)
    fw = weights("fov")
    with torch.no_grad():
        tok, grid = ref.fov_trunk(y, fw)
        lg_ref = ref.fov_head(tok, grid, fw)
    eng = ttnn_fov.Engine(device, ttnn_fov.Engine.prepare_weights(device, fw), shape)
    lg = ttnn.to_torch(eng.run(to_dev(unfold_patches(y, shape.np_).reshape(1, 1, -1, 768), device))).float().reshape(t, 2)
    deg = ref.fov_logits_to_deg(lg, tuple(x.shape[-2:]), (h, w))
    f = float(ref.median_focal_length_px(deg, *x.shape[-2:]))
    f_ref = float(g["focallength_px"])
    r = {"logit_maxabs": float((lg - lg_ref).abs().max()), "fov_deg_maxabs": float((deg - g["fov_deg"]).abs().max()),
         "f_px": f, "f_px_golden": f_ref, "f_rel": abs(f / f_ref - 1)}
    fbud, fwhy = H.fov_budget(case)
    r.update(f_rel_budget=fbud, f_budget_from=fwhy)
    record("stage_fov", case=case, fov=r)
    assert r["f_rel"] <= fbud, r


# ----------------------------------------------------------------------------------------------- end to end


def _cases(size: str):
    return [c for c in E2E_CASES if H.golden_path(c, size) is not None]


@pytest.mark.parametrize("size", ["S", "B", "L", "H"])
def test_e2e(device, size):
    """DepthPro2Device (traced ENC + DEC, traced FOV) on every golden case of ``size``; SPEC §5 gates."""
    from tt_depthpro2.tt.model import DepthPro2Device

    cases = _cases(size)
    goldens = {c: H.load_golden(c, size)[0] for c in cases}
    shapes = {c: ref.pad_to_multiple(g["x_norm"]).shape for c, g in goldens.items()}
    buckets = sorted({(s[-2], s[-1]) for s in shapes.values()})
    fov_shapes = sorted({tuple(ref.fov_resize(g["x_norm"][:1]).shape[-2:]) for g in goldens.values()})
    t0 = time.perf_counter()
    # T=1 everywhere up front; the clip (T=4) compiles on first use (exercises the release / recapture path)
    m = DepthPro2Device(device, size, weights(size), weights("fov"), buckets=buckets, max_frames=1, fov_shapes=fov_shapes)
    build_s = time.perf_counter() - t0
    failures = []
    try:
        for c in cases:
            g = goldens[c]
            x = g["x_norm"]
            t, _, h, w = x.shape
            t1 = time.perf_counter()
            inv = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w]
            first_ms = (time.perf_counter() - t1) * 1e3
            t1 = time.perf_counter()
            inv2 = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w]
            call_ms = (time.perf_counter() - t1) * 1e3
            met = H.drift_metrics(inv, g["inverse_depth"].reshape(t, h, w))
            budget, why = H.absrel_budget(c, size)
            y = ref.fov_resize(x)
            lg = m.fov_logits(y)
            deg = ref.fov_logits_to_deg(lg, (h, w), tuple(y.shape[-2:]))
            f = float(ref.median_focal_length_px(deg, h, w))
            f_rel = abs(f / float(g["focallength_px"]) - 1)
            fbud, fwhy = H.fov_budget(c)
            ok = met["pcc"] >= 0.999 and met["absrel_valid"] <= budget and f_rel <= fbud and torch.equal(inv, inv2)
            record("e2e", size=size, case=c, golden=os.path.basename(os.path.dirname(H.golden_path(c, size))), metrics=met, absrel_budget=budget, budget_from=why, f_px=f,
                   f_px_golden=float(g["focallength_px"]), f_rel=f_rel, f_rel_budget=fbud, f_budget_from=fwhy, fov_deg_maxabs=float((deg - g["fov_deg"]).abs().max()),
                   repeat_bitexact=bool(torch.equal(inv, inv2)), first_call_ms=first_ms, call_ms=call_ms, build_s=build_s,
                   passed=ok)
            if not ok:
                failures.append(c)
    finally:
        m.close()
    assert not failures, failures


def test_trace_determinism(device):
    """50 back-to-back replays of one traced configuration are bit-identical (the 500-run stress is in the bench)."""
    from tt_depthpro2.tt.model import DepthPro2Device

    g, _ = H.load_golden("img_vga", "S")
    x = ref.pad_to_multiple(g["x_norm"])
    m = DepthPro2Device(device, "S", weights("S"), None, buckets=[tuple(x.shape[-2:])], max_frames=1)
    try:
        first = m.inverse_depth(x)
        diffs = sum(int(not torch.equal(first, m.inverse_depth(x))) for _ in range(50))
    finally:
        m.close()
    record("determinism", size="S", case="img_vga", replays=50, mismatches=diffs)
    assert diffs == 0


@pytest.mark.parametrize("n", [2, 3])
def test_valid_frames(device, n):
    """One T=4 program serving an n-frame clip (runtime valid-frame count) == the exact T=n program."""
    import ttnn

    from tt_depthpro2.tt import ttnn_dec, ttnn_enc

    g, _ = H.load_golden("clip4_240x320", "S")
    x = ref.pad_to_multiple(g["x_norm"])[:n]
    we = ttnn_enc.Engine.prepare_weights(device, weights("S"), "S")
    wd = ttnn_dec.Engine.prepare_weights(device, weights("S"), "S")

    def run(t):
        sh = StageShape(t, 256, 320)
        enc, dec = ttnn_enc.Engine(device, we, sh), ttnn_dec.Engine(device, wd, sh)
        xp = torch.cat([x, x.new_zeros(t - n, 3, 256, 320)]) if t > n else x
        enc.set_valid_frames(n)
        return ttnn.to_torch(dec.run(enc.run(to_dev(unfold_patches(xp, sh.np_).reshape(1, 1, -1, 768), device)))).float()[:n]

    exact, padded = run(n), run(4)
    r = {"pcc": H.pcc(padded, exact), "max_rel": H.max_rel(padded, exact)}
    record("valid_frames", size="S", case="clip4_240x320", n=n, program_T=4, vs_exact=r)
    assert r["pcc"] >= 0.99999, r


def test_fov_any_t(device):
    """fov_logits on 1 frame and on the window (4) with the programs T in {1, 4}; 3 frames run in the T=4 program."""
    from tt_depthpro2.tt.model import DepthPro2Device

    g, _ = H.load_golden("clip4_240x320", "S")
    y = ref.fov_resize(g["x_norm"])
    fw = weights("fov")
    with torch.no_grad():
        lg_ref = ref.fov_head(*ref.fov_trunk(y, fw), fw)
    m = DepthPro2Device(device, "S", weights("S"), fw, buckets=[(256, 320)], max_frames=4, frames=(1,))
    try:
        res = {t: float((m.fov_logits(y[:t]) - lg_ref[:t]).abs().max()) for t in (1, 3, 4)}
    finally:
        m.close()
    record("fov_any_t", case="clip4_240x320", logit_maxabs=res)
    assert max(res.values()) < 0.02, res


def test_kv_stream(device):
    """Unbuffered video (KV cache, window 4) through tt_depthpro2.streaming on stream_unbuf_w4_n6 (S): per frame
    PCC >= 0.999 and AbsRel <= max(2 x official clip4 drift, 0.01); a 2nd interleaved stream is bit-identical."""
    from tt_depthpro2.streaming import DepthStream
    from tt_depthpro2.tt.model import DepthPro2Device

    g, _ = H.load_golden("stream_unbuf_w4_n6", "S")
    frames = ref.preprocess(g["input_u8"].round().to(torch.uint8).numpy())
    m = DepthPro2Device(device, "S", weights("S"), None, buckets=[(256, 320)], max_frames=4, frames=(1,), kv_cache=True,
                        kv_streams=2)
    times = []

    def step(clip, cache):
        t0 = time.perf_counter()
        out = m.inverse_depth_step(ref.pad_to_multiple(clip), cache)[:, :240, :320]
        times.append((time.perf_counter() - t0) * 1e3)
        return out

    def run_stream():
        st = DepthStream(lambda c: None, window=4, overlap=0, f_px=float(g["focallength_px"]), mode="unbuffered",
                         predict_step=step, open_cache=lambda: m.kv_cache((256, 320), 4))
        return st

    try:
        a, b = run_stream(), run_stream()  # two open caches, steps interleaved
        pa, pb = [], []
        for f in frames:
            pa += a.step(f)
            pb += b.step(f)
        pa += a.flush()
        pb += b.flush()
        a.close()
        b.close()
        nbytes = m.kv_cache_bytes()
    finally:
        m.close()
    d, src = H.official_drift_absrel("clip4_240x320", "S")
    budget = max(2 * (d or 0.0), 0.01)
    per = []
    for p in pa:
        met = H.drift_metrics(p.inverse_depth, g["inverse_depth"][p.index])
        per.append({"frame": p.index, "pcc": met["pcc"], "absrel_valid": met["absrel_valid"]})
    same = all(torch.equal(x.inverse_depth, y.inverse_depth) for x, y in zip(pa, pb))
    record("kv_stream", size="S", case="stream_unbuf_w4_n6", window=4, frames=per, absrel_budget=budget,
           budget_from=src, interleaved_bitexact=same, cache_bytes=nbytes, step_ms=times)
    assert len(per) == len(frames) and same
    assert all(r["pcc"] >= 0.999 and r["absrel_valid"] <= budget for r in per), per


@pytest.mark.parametrize("size", ["S", "B", "L", "H"])
def test_vga_t16(device, size):
    """Regression (round 3): a 16-frame 480x640 clip on the T=16 program (n = 16) and its first 5 frames through
    the valid-frame path (n = 5), against the float32 reference (tests/make_clip16_refs.py). Every frame: finite,
    PCC >= 0.999."""
    from safetensors.torch import load_file

    from tt_depthpro2.tt.model import DepthPro2Device

    path = os.path.join(H.BASELINE_REF, f"clip16_480x640__{size}.safetensors")
    if not os.path.exists(path):
        pytest.skip(f"{path} missing (tests/make_clip16_refs.py)")
    r = load_file(path)
    x = r["x_norm"]
    m = DepthPro2Device(device, size, weights(size), None, buckets=[(480, 640)], max_frames=16)
    res = {}
    try:
        for n, key in ((16, "inverse_depth"), (5, "inverse_depth_n5")):
            inv = m.inverse_depth(x[:n])
            ref_inv = r[key]
            per = [H.pcc(inv[f], ref_inv[f]) for f in range(n)]
            met = [H.drift_metrics(inv[f], ref_inv[f]) for f in range(n)]
            # AbsRel (depth) is not gated: a few valid pixels (ref >= 1% of the max) at the seams of the rolled frames
            # come out 0 after the final ReLU, and 1 / 1e-9 dominates the mean; the inverse-depth p99 is reported.
            res[n] = {"finite": bool(torch.isfinite(inv).all()), "absmax": float(inv.abs().max()), "pcc_min": min(per),
                      "pcc_frames": [round(p, 6) for p in per],
                      "absrel_valid_median": float(torch.tensor([m["absrel_valid"] for m in met]).median()),
                      "inv_rel_p99_valid_max": max(m["inv_rel_p99_valid"] for m in met)}
    finally:
        m.close()
    record("vga_t16", size=size, program_T=16, results=res)
    for n, v in res.items():
        assert v["finite"] and v["pcc_min"] >= 0.999, (n, v)


@pytest.mark.parametrize("size", ["L", "H"])
def test_startup_3buckets_kv(device, size):
    """Regression (round 3): start-up with 3 buckets (480x640, 640x480, 256x320), window 16, images, FOV and the KV
    cache (serve's DepthPro2 configuration), then one call per bucket and one KV step. Needs a trace region of
    ``trace_region_bytes`` (run with DEPTHPRO2_TRACE_REGION set accordingly)."""
    from tt_depthpro2.tt.model import DepthPro2Device, planned_frames, trace_region_bytes

    buckets = [(480, 640), (640, 480), (256, 320)]
    need = trace_region_bytes(size, buckets, planned_frames(16, clip_lengths="all"), kv_cache=True)
    have = int(os.environ.get("DEPTHPRO2_TRACE_REGION", "0") or 0)
    if have < need:
        pytest.skip(f"needs DEPTHPRO2_TRACE_REGION >= {need} (trace_region_bytes), have {have}")
    t0 = time.perf_counter()
    m = DepthPro2Device(device, size, weights(size), weights("fov"), buckets=buckets, max_frames=16, frames=(1,),
                        clip_lengths="all", kv_cache=True)
    build = time.perf_counter() - t0
    out = {}
    try:
        for hp, wp in buckets:
            inv = m.inverse_depth(torch.randn(1, 3, hp, wp) * 0.5)
            out[f"{hp}x{wp}"] = bool(torch.isfinite(inv).all())
        c = m.kv_cache((256, 320), 4)
        st = m.inverse_depth_step(torch.randn(1, 3, 256, 320) * 0.5, c)
        out["kv_step"] = bool(torch.isfinite(st).all())
        c.close()
    finally:
        m.close()
    record("startup_3buckets_kv", size=size, build_s=build, finite=out, trace_region_estimate_mb=need >> 20)
    assert all(out.values()), out


def test_engine_switch():
    from tt_depthpro2.tt import model as M

    assert M.parse_engine(None) == {"enc": "ttnn", "dec": "ttnn", "fov": "ttnn"}
    assert M.parse_engine("enc=mk,dec=ttnn") == {"enc": "mk", "dec": "ttnn", "fov": "ttnn"}
    assert M.parse_engine({"fov": "mk"})["fov"] == "mk"
    with pytest.raises(ValueError):
        M.parse_engine("enc=foo")
    for stage in ("enc", "dec", "fov"):
        assert M.engine_class(stage, "ttnn").__name__ == "Engine"
        try:
            cls = M.engine_class(stage, "mk")
            assert hasattr(cls, "run")
        except RuntimeError as e:  # mk module absent / incomplete: a clear error naming the module
            assert f"mk_{stage}" in str(e)