File size: 8,618 Bytes
9d8d25c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests (no device) of the optimization round 3 / stage Opt2 host changes:
  * the fast ``host_pixels`` is bit-identical to the reference implementation (random / structured images, every
    accepted camera geometry class, the shipped sample);
  * parallel camera decoding returns the serial result and the same error;
  * the tokenizer cache returns fresh, equal tensors;
  * ``Precision.lm_kscore`` defaults to "table" (VERIFY_MK_r2 R2-F5);
  * the floors pin the torch thread count (R2-F3);
  * the replay's memory check: addresses before ``execute_trace``, the allocator state overlapped with the device run
    but before ``replay`` returns (R2-F4), "pre" keeps the package-time order.
Run: TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_rdt2/tests/test_host_opt2.py
"""
from __future__ import annotations

import io
import os
import sys
import types

import numpy as np
import pytest
import torch

SAMPLES = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "samples")


def _images(kind: int, h: int, w: int, g: np.random.Generator):
    shape = (2, h, w, 3)
    if kind == 0:
        a = g.integers(0, 256, shape, dtype=np.uint8)
    elif kind == 1:
        a = np.where(g.random(shape) > 0.5, 255, 0).astype(np.uint8)
    elif kind == 2:
        a = np.sort(g.integers(0, 256, shape, dtype=np.uint8), axis=2)
    elif kind == 3:
        a = np.clip(g.normal(128, 60, shape), 0, 255).astype(np.uint8)
    else:
        a = np.full(shape, int(g.integers(0, 256)), np.uint8)
    return [a[0], a[1]]


@pytest.mark.parametrize("hw", [(384, 384), (392, 378), (400, 380)])
def test_fast_host_pixels_bit_identical(hw):
    from tt_rdt2.tt.vision import host_pixels, host_pixels_reference

    g = np.random.default_rng(hw[0] * 1000 + hw[1])
    for k in range(10):
        ims = _images(k % 5, *hw, g)
        assert torch.equal(host_pixels(ims), host_pixels_reference(ims)), (hw, k)


def test_fast_host_pixels_sample_and_layouts():
    from PIL import Image

    from tt_rdt2.tt.vision import host_pixels, host_pixels_reference

    ims = [np.asarray(Image.open(os.path.join(SAMPLES, f"ur5e_bimanual_example_0_{c}.png")).convert("RGB"))
           for c in ("left_stereo", "right_stereo")]
    ref = host_pixels_reference(ims)
    assert torch.equal(host_pixels(ims), ref)
    # non-contiguous inputs (views) give the same rows
    views = []
    for im in ims:
        big = np.zeros((im.shape[0], 2 * im.shape[1], 3), np.uint8)
        big[:, ::2] = im
        views.append(big[:, ::2])
    assert not views[0].flags["C_CONTIGUOUS"]
    assert torch.equal(host_pixels(views), ref)
    out = host_pixels(ims)
    assert out.shape == (1, 1, 1536, 608) and out.dtype == torch.float32
    assert not out[0, 0, 1512:].any() and not out[0, 0, :, 588:].any()


def test_parallel_decode_matches_serial_and_errors():
    from tt_rdt2 import api

    raw = [open(os.path.join(SAMPLES, f"ur5e_bimanual_example_0_{c}.png"), "rb").read()
           for c in ("left_stereo", "right_stereo")]
    par = api.decode_images(raw)
    ser = [api._decode_image(x, i) for i, x in enumerate(raw)]
    assert all(np.array_equal(a, b) for a, b in zip(par, ser))
    from PIL import Image

    jpg = []
    for a in ser:
        b = io.BytesIO()
        Image.fromarray(a).save(b, format="JPEG", quality=90)
        jpg.append(b.getvalue())
    assert all(np.array_equal(a, api._decode_image(x, i)) for i, (a, x) in enumerate(zip(api.decode_images(jpg), jpg)))
    with pytest.raises(api.InputError, match="right_stereo"):
        api.decode_images([raw[0], b"not an image"])
    with pytest.raises(api.InputError, match="left_stereo"):
        api.decode_images([b"junk", b"junk too"])  # the first bad camera is reported, as in the serial loop


def test_tokenize_cache_returns_fresh_tensors(dirs):
    from tt_rdt2.reference import preprocess as pp

    if not os.path.exists(os.path.join(dirs["processor"], "tokenizer.json")):
        pytest.skip("processor files not found")
    a = pp.tokenize("pick up the cup", 378)
    b = pp.tokenize("pick up the cup", 378)
    assert torch.equal(a, b) and a.data_ptr() != b.data_ptr() and a.dtype == torch.int64
    a[0, 0] = -1
    assert torch.equal(pp.tokenize("pick up the cup", 378), b)
    tok = pp._tokenizer(dirs["processor"])
    ids = tok.encode(pp.build_prompt("pick up the cup", 378), add_special_tokens=True).ids
    assert b[0].tolist() == ids


def test_precision_kscore_default_is_table():
    from tt_rdt2.tt.common import PRECISION_PRESETS, Precision

    assert Precision().lm_kscore == "table"
    assert PRECISION_PRESETS["baseline_kfused"].lm_kscore == "fused"
    assert all(p.lm_kscore == "table" for n, p in PRECISION_PRESETS.items() if n != "baseline_kfused")


def test_floor_threads_pinned():
    from tt_rdt2.reference import gatesets

    before = torch.get_num_threads()
    with gatesets._pinned_threads(gatesets.FLOOR_THREADS):
        assert torch.get_num_threads() == gatesets.FLOOR_THREADS
    assert torch.get_num_threads() == before


class _FakeTTNN(types.SimpleNamespace):
    pass


def _fake_model(monkeypatch, calls, mem):
    from tt_rdt2.tt.model import RDT2FMTT

    fake = _FakeTTNN(execute_trace=lambda dev, tid, cq_id, blocking: calls.append(("exec", blocking)),
                     synchronize_device=lambda dev: calls.append(("sync",)))
    monkeypatch.setitem(sys.modules, "ttnn", fake)
    m = RDT2FMTT.__new__(RDT2FMTT)
    monkeypatch.setattr(RDT2FMTT, "memory_totals", lambda self: calls.append(("alloc",)) or dict(mem))
    monkeypatch.setattr(RDT2FMTT, "_persistent_addresses", lambda self: calls.append(("addr",)) or {"a": 1})
    m._persist_addr, m.strict_memory, m._sealed, m.device, m._check_pool = {"a": 1}, True, True, None, None
    m.inputs, m.buckets, m.traces = {416: {}}, (416,), {416: 3}
    m._mem_seal = dict(mem)
    return m


def test_replay_refuses_before_execute(monkeypatch):
    """replay(): both halves of the memory contract before execute_trace (a violation refuses the replay)."""
    calls, mem = [], {"dram": 100, "l1": 0}
    m = _fake_model(monkeypatch, calls, mem)
    m.replay(416, blocking=False)
    assert calls == [("addr",), ("alloc",), ("exec", False)]
    calls.clear()
    mem["dram"] += 2048  # a live allocation after the capture
    with pytest.raises(RuntimeError, match="memory contract"):
        m.replay(416, blocking=False)
    assert calls == [("addr",), ("alloc",)]
    calls.clear()
    m.replay(416, blocking=True, allocator_checked=True)  # the caller checked the allocator itself
    assert calls == [("addr",), ("exec", True)]
    calls.clear()
    mem["dram"] -= 2048
    m._persist_addr = {"a": 2}  # a persistent buffer moved
    with pytest.raises(RuntimeError, match="moved"):
        m.replay(416, blocking=True, allocator_checked=True)
    assert calls == [("addr",)]


@pytest.mark.parametrize("mode", ["overlap", "pre"])
def test_call_checks_allocator_before_any_device_work(monkeypatch, mode):
    """__call__: "overlap" runs the allocator check on a helper thread during host_inputs and joins it before
    write_inputs; a violation raises before any write / replay. "pre": the check runs inside replay()."""
    from tt_rdt2.tt.model import RDT2FMTT

    calls, mem = [], {"dram": 100, "l1": 0}
    m = _fake_model(monkeypatch, calls, mem)
    m.memory_check, m.norm, m.timings = mode, None, {}
    monkeypatch.setattr(RDT2FMTT, "host_inputs", lambda self, *a, **k: calls.append(("host",)) or
                        {"bucket": 416, "n_tokens": torch.tensor(5)})
    monkeypatch.setattr(RDT2FMTT, "write_inputs", lambda self, host: calls.append(("write",)))
    monkeypatch.setattr(RDT2FMTT, "read_action_normalized", lambda self, L=None: torch.zeros(1, 24, 20))
    import tt_rdt2.tt.model as model_mod

    monkeypatch.setattr(model_mod, "unnormalize_action", lambda ns, norm: ns)
    m(None, "x", state=np.zeros(20, np.float32), noise=torch.zeros(1, 24, 20))
    seq = [c for c in calls if c[0] != "host"]
    if mode == "overlap":
        assert seq == [("alloc",), ("write",), ("addr",), ("exec", False)]
    else:
        assert seq == [("write",), ("addr",), ("alloc",), ("exec", False)]
    calls.clear()
    mem["dram"] += 2048
    with pytest.raises(RuntimeError, match="memory contract"):
        m(None, "x", state=np.zeros(20, np.float32), noise=torch.zeros(1, 24, 20))
    assert ("write",) not in calls or mode == "pre"
    assert ("exec", False) not in calls
    m.release_stage_traces = lambda: None
    if m._check_pool is not None:
        m._check_pool.shutdown(wait=True)