File size: 10,953 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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the video streaming (no device): the buffered ``DepthStream`` semantics on synthetic clips (which
frames each clip predicts, the cross-fade weights, the flush of the tail with and without an overlap, the focal
length over the frames so far), ``plan_buffered_clips`` against the stream, the unbuffered mode's requirements, and
-- with the weights and goldens -- the API's buffered and unbuffered video on the CPU engine against Apple's float32
``stream_buf_w4o1_n10`` / ``stream_unbuf_w4_n6`` goldens.

    PYTHONPATH=<workspace>/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \
        python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_streaming.py
"""
from __future__ import annotations

import random

import pytest
import torch

from tt_depthpro2.api import plan_buffered_clips
from tt_depthpro2.streaming import DepthStream, blend_weights
from tt_depthpro2.tests.host_helpers import cpu_model, depth_rel_err_valid, golden, pcc, rel_err


class Spy:
    """A fake clip predictor: frame k (a 3 x 2 x 2 tensor filled with k) predicts k + 1000 * (its clip number)."""

    def __init__(self):
        self.clips = []

    def __call__(self, clip):
        self.clips.append([int(v) for v in clip[:, 0, 0, 0].tolist()])
        return clip[:, 0] + 1000.0 * len(self.clips)


def frame(k):
    return torch.full((3, 2, 2), float(k))


def run(n, window, overlap, **kw):
    spy = Spy()
    s = DepthStream(spy, window=window, overlap=overlap, **kw)
    out = []
    for k in range(n):
        out += s.step(frame(k))
    out += s.flush()
    return spy, out, s


def test_blend_weights():
    assert blend_weights(1, torch.zeros(1)).flatten().tolist() == [0.5]
    assert torch.allclose(blend_weights(3, torch.zeros(1)).flatten(), torch.tensor([0.75, 0.5, 0.25]))


def test_buffered_w4_o1_n10():
    spy, out, _ = run(10, 4, 1)
    assert spy.clips == [[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9]]
    assert [p.index for p in out] == list(range(10))
    vals = [float(p.inverse_depth[0, 0]) for p in out]
    want = [1000, 1001, 1002, 0.5 * 1003 + 0.5 * 2003, 2004, 2005, 0.5 * 2006 + 0.5 * 3006, 3007, 3008, 3009]
    assert vals == pytest.approx(want)


def test_buffered_overlap2_crossfade():
    spy, out, _ = run(6, 4, 2)
    # clip 1: 0..3 (returns 0, 1; holds 2, 3); flush: pulled back to a full window 2..5
    assert spy.clips == [[0, 1, 2, 3], [2, 3, 4, 5]]
    vals = [float(p.inverse_depth[0, 0]) for p in out]
    w = [2 / 3, 1 / 3]
    want = [1000, 1001, w[0] * 1002 + (1 - w[0]) * 2002, w[1] * 1003 + (1 - w[1]) * 2003, 2004, 2005]
    assert vals == pytest.approx(want)


def test_flush_tails():
    spy, out, _ = run(5, 4, 1)  # tail pulled back over frames already returned (1..4); 3 cross-faded, 4 new
    assert spy.clips == [[0, 1, 2, 3], [1, 2, 3, 4]] and [p.index for p in out] == [0, 1, 2, 3, 4]
    spy, out, _ = run(6, 4, 0)  # no overlap: the tail is just the new frames
    assert spy.clips == [[0, 1, 2, 3], [4, 5]] and len(out) == 6
    spy, out, _ = run(3, 4, 2)  # shorter than the window: one short clip at flush
    assert spy.clips == [[0, 1, 2]] and len(out) == 3
    spy, out, _ = run(8, 4, 1)  # one new frame at flush: a full window pulled back over 4..7
    assert spy.clips == [[0, 1, 2, 3], [3, 4, 5, 6], [4, 5, 6, 7]] and [p.index for p in out] == list(range(8))
    spy, out, _ = run(7, 4, 1)  # nothing new at flush: the held frame is returned without another clip
    assert spy.clips == [[0, 1, 2, 3], [3, 4, 5, 6]] and [p.index for p in out] == list(range(7))
    assert float(out[-1].inverse_depth[0, 0]) == 2006.0
    spy, out, _ = run(0, 4, 1)
    assert spy.clips == [] and out == []


def test_window_one_and_returns_in_order():
    spy, out, _ = run(5, 1, 0)
    assert spy.clips == [[k] for k in range(5)] and [p.index for p in out] == list(range(5))


def test_plan_matches_the_stream():
    rng = random.Random(0)
    for _ in range(200):
        w = rng.randint(1, 16)
        o = rng.randint(0, w - 1)
        n = rng.randint(0, 50)
        spy, out, _ = run(n, w, o)
        assert [len(c) for c in spy.clips] == plan_buffered_clips(n, w, o), (n, w, o)
        assert [p.index for p in out] == list(range(n))


def test_step_after_flush_continues():
    spy = Spy()
    s = DepthStream(spy, window=4, overlap=1)
    out = []
    for k in range(5):
        out += s.step(frame(k))
    out += s.flush()
    for k in range(5, 9):
        out += s.step(frame(k))
    out += s.flush()
    assert [p.index for p in out] == list(range(9))


def test_focal_over_frames_so_far():
    calls = []

    def fov(clip):
        calls.append(clip.shape[0])
        return torch.stack([clip[:, 0, 0, 0] + 60.0, clip[:, 0, 0, 0] + 45.0], dim=1)

    def focal(fov_deg, h, w):
        return fov_deg[:, 1].median()

    spy = Spy()
    s = DepthStream(spy, window=4, overlap=1, fov_deg=fov, focal_from_fov=focal)
    out = []
    for k in range(10):
        out += s.step(frame(k))
    out += s.flush()
    assert calls == [4]  # the first clip's frames; fixed once a window of estimates is in
    # clip 1: median of vfov 45..48 (lower median) -> 46; fixed once 4 estimates are in
    assert float(out[0].f_px) == 46.0 and float(out[-1].f_px) == 46.0 and float(s.f_px) == 46.0
    s2 = DepthStream(Spy(), window=4, overlap=1, f_px=123.0, fov_deg=fov, focal_from_fov=focal)
    calls.clear()
    got = [p for k in range(4) for p in s2.step(frame(k))]
    assert calls == [] and all(float(p.f_px) == 123.0 for p in got)


def test_errors():
    with pytest.raises(ValueError):
        DepthStream(Spy(), window=4, overlap=4)
    with pytest.raises(ValueError):
        DepthStream(Spy(), window=0, overlap=0)
    with pytest.raises(ValueError):
        DepthStream(Spy(), window=4, overlap=1, mode="live")
    with pytest.raises(NotImplementedError):
        DepthStream(Spy(), window=4, overlap=0, mode="unbuffered")
    s = DepthStream(Spy(), window=4, overlap=1)
    s.step(frame(0))
    with pytest.raises(ValueError):
        s.step(torch.zeros(3, 4, 4))
    with pytest.raises(ValueError):
        s.step(torch.zeros(1, 3, 2, 2))
    s.close()
    with pytest.raises(RuntimeError):
        s.step(frame(1))


def test_unbuffered_with_a_cache():
    opened = []

    def step(clip, cache):
        cache.append(int(clip[0, 0, 0, 0]))
        return clip[:, 0] + 10.0 * len(cache)

    def open_cache():
        opened.append([])
        return opened[-1]

    s = DepthStream(Spy(), window=3, overlap=2, mode="unbuffered", predict_step=step, open_cache=open_cache)
    out = []
    for k in range(5):
        got = s.step(frame(k))
        assert [p.index for p in got] == [k]  # returned at once
        out += got
    assert s.flush() == [] and opened == [[0, 1, 2, 3, 4]]
    assert [float(p.inverse_depth[0, 0]) for p in out] == [10, 21, 32, 43, 54]


# ---------------------------------------------------------------------------------------------- Apple's goldens


def test_buffered_video_matches_the_official_golden():
    g = golden("stream_buf_w4o1_n10__S")
    m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all")
    outs = list(m.infer_video(list(g["input_u8"].numpy())))
    assert [o.frame_index for o in outs] == list(range(10))
    inv = torch.stack([o.inverse_depth for o in outs])
    depth = torch.stack([o.depth for o in outs])
    assert rel_err(inv, g["inverse_depth"]) < 1e-5 and pcc(inv, g["inverse_depth"]) > 0.999999
    # the focal length comes from the reference FOV (within 1e-4 of Apple's float32 here)
    f_rel = abs(outs[0].focallength_px - float(g["focallength_px"])) / float(g["focallength_px"])
    assert f_rel < 1e-3
    # depth where it is well defined (see depth_rel_err_valid): <= 100 x the inverse-depth bound (1e-5) + f_rel
    assert depth_rel_err_valid(depth, g["depth"], g["inverse_depth"]) < 1e-3 + f_rel + 1e-4  # + 1e-4 margin
    assert all(o.focal_source == "fov" and o.focallength_px == outs[0].focallength_px for o in outs)


def test_unbuffered_video_matches_the_official_golden():
    g = golden("stream_unbuf_w4_n6__S")
    m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all",
                  video_modes="buffered,unbuffered")
    assert m.supports_unbuffered
    outs = list(m.infer_video(list(g["input_u8"].numpy()), mode="unbuffered"))
    inv = torch.stack([o.inverse_depth for o in outs])
    assert [o.frame_index for o in outs] == list(range(6))
    assert rel_err(inv, g["inverse_depth"]) < 1e-5
    f_rel = abs(outs[0].focallength_px - float(g["focallength_px"])) / float(g["focallength_px"])
    assert f_rel < 1e-3
    # depth where it is well defined: near the sky (inverse depth ~0) the depth of the float32 CPU engine moves with
    # the torch thread count (5 % at 4 threads, while the inverse depth stays within 1e-5); on the valid pixels it is
    # bounded by 100 x the inverse-depth bound (1e-5) + the focal length's error
    depth = torch.stack([o.depth for o in outs])
    assert depth_rel_err_valid(depth, g["depth"], g["inverse_depth"]) < 1e-3 + f_rel + 1e-4  # + 1e-4 margin


def test_buffered_video_given_f_px_and_resized_frames():
    g = golden("stream_buf_w4o1_n10__S")
    m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all")
    u8 = g["input_u8"].numpy()
    outs = list(m.infer_video(list(u8), f_px=300.0))
    assert all(o.focal_source == "request" and o.focallength_px == 300.0 for o in outs)
    inv = torch.stack([o.inverse_depth for o in outs])
    assert rel_err(inv, g["inverse_depth"]) < 1e-5
    assert rel_err(torch.stack([o.depth for o in outs]), 300.0 / (320 * g["inverse_depth"])) < 1e-5
    # frames twice the bucket size: resized to the bucket and back; the focal length scales with the width
    big = u8.repeat(2, axis=1).repeat(2, axis=2)
    outs2 = list(m.infer_video(list(big)))
    assert outs2[0].inverse_depth.shape == (480, 640) and outs2[0].resized
    f2 = outs2[0].focallength_px
    assert abs(f2 / (2 * float(g["focallength_px"])) - 1) < 0.02
    small = torch.nn.functional.avg_pool2d(torch.stack([o.inverse_depth for o in outs2])[:, None], 2)[:, 0]
    assert pcc(small, g["inverse_depth"]) > 0.995


def test_live_stream_session_matches_infer_video():
    g = golden("stream_buf_w4o1_n10__S")
    m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all")
    u8 = g["input_u8"].numpy()
    s = m.stream()
    got = []
    for k in range(10):
        got += s.step(u8[k])
        if k < 3:
            assert got == []  # nothing until a window is full
    got += s.flush()
    s.close()
    inv = torch.stack([o.inverse_depth for o in got])
    assert [o.frame_index for o in got] == list(range(10))
    assert rel_err(inv, g["inverse_depth"]) < 1e-5  # inverse depth does not depend on the focal length
    assert s.focallength_px is not None and all(o.focallength_px for o in got)