rdt2-base-p150 / code /tt_rdt2 /tests /test_vq_server_host.py
changh95's picture
tt-model push rdt2-base-p150 (container)
c869f1f verified
Raw History Blame Contribute Delete
8.91 kB
# SPDX-License-Identifier: Apache-2.0
"""Host tests (no device) of the RDT2-VQ serve switch: ``RDT2_MODEL`` parsing (fm default, vq, anything else refused),
the real app + the real ``tt_rdt2.vq.api.RDT2VQ`` API class over a host stand-in of the device model: /info reports
the variant, /predict keeps the RDT2-FM request contract and adds the tokens, request errors are 400 / 422.
Run (fake ttnn, see README.md): python -m pytest -q -p fake_ttnn_plugin code/tt_rdt2/tests/test_vq_server_host.py
"""
from __future__ import annotations
import pytest
import torch
from tt_rdt2.server import app as app_mod
from tt_rdt2.server import client as rdt2_client
from tt_rdt2.tests.stubs import need_tokenizer
fastapi = pytest.importorskip("fastapi")
from fastapi.testclient import TestClient # noqa: E402
class _StubVQTT:
"""Host stand-in of vq.model.RDT2VQTT: a fixed generation (27 ids + <|quad_end|>) and a fixed action."""
jpeg = True
rvq_engine = "device"
def __init__(self):
self.timings = {"load_s": 1.0}
self.traces = {"decode": None}
self.calls = []
def capture(self):
self.traces["decode"] = 1
def release(self):
self.traces["decode"] = None
def __call__(self, images, instruction, traced=True, bucket=None):
from tt_rdt2.reference.vq import QUAD_END_ID, action_tokens_from_ids, extract_action_ids
self.calls.append((instruction, bucket))
gen = [150620 + i for i in range(27)] + [QUAD_END_ID]
ids, valid = extract_action_ids(gen)
ns = torch.linspace(-1, 1, 480).reshape(24, 20)
self.timings.update(host_pre_ms=1.0, generate_ms=2.0, rvq_ms=0.5)
return {"generated": gen, "action_ids": ids, "action_tokens": action_tokens_from_ids(ids), "valid": valid,
"nsample": ns, "action": ns * 2, "n_tokens": 409, "bucket": bucket}
def _weights():
from tt_rdt2.reference.config import DEFAULT_DIRS
from tt_rdt2.vq.api import VQ_COMPONENTS
return {r: dict(repo=c["repo"], revision=c["revision"], path=DEFAULT_DIRS.get(r, "/nonexistent"), files=list(c["files"]),
source="local", license=c["license"], use=c["use"]) for r, c in VQ_COMPONENTS.items()}
def _vq_model():
from tt_rdt2.vq.api import RDT2VQ
m = RDT2VQ(_StubVQTT(), None, weights=_weights(), owns_device=False, device_id=None)
m.engine = {"vision": "mk", "prefix": "fused", "decode": "ttnn", "rvq": "device"}
m.precision = "baseline"
m.warmup()
return m
def test_model_variant_env():
assert app_mod.config_from_env({})["model_variant"] == "fm"
assert app_mod.config_from_env({"RDT2_MODEL": "vq"})["model_variant"] == "vq"
assert app_mod.config_from_env({"RDT2_MODEL": " VQ "})["model_variant"] == "vq"
with pytest.raises(RuntimeError, match="RDT2_MODEL"):
app_mod.config_from_env({"RDT2_MODEL": "rdt1"})
def test_vq_served_contract(monkeypatch):
need_tokenizer()
monkeypatch.setenv("RDT2_MODEL", "vq")
m = _vq_model()
a = app_mod.create_app()
a.state.rdt2.model_factory = lambda cfg: m
with TestClient(a) as c:
info = c.get("/info").json()
assert info["model_variant"] == "vq" and info["decoding"]["action_tokens"] == 27
assert set(info["weights"]["components"]) == {"vlm", "rvq", "normalizer", "processor"}
assert "RDT2_MODEL=fm" in info["not_included"]
req = rdt2_client.sample_request()
r = c.post("/predict", json=req)
assert r.status_code == 200, r.text
body = r.json()
assert body["shape"] == [24, 20] and body["model_variant"] == "vq" and body["model"] == "rdt2-base-p150"
assert body["tokens"]["valid"] is True and len(body["tokens"]["action_ids"]) == 27
assert body["tokens"]["generated"][-1] == 151651
assert body["prompt_bucket"] == 416 and body["num_tokens"] == 409
assert set(body["timing_ms"]) >= {"preprocess", "inference", "total", "generate", "rvq_decode"}
# same request contract: state / seed accepted (ignored), num_steps 5 ignored, other values refused
assert c.post("/predict", json=dict(req, seed=7, state=[0.1] * 20)).status_code == 200
assert c.post("/predict", json=dict(req, num_steps=5)).status_code == 200
assert c.post("/predict", json=dict(req, num_steps=3)).status_code == 400
assert c.post("/predict", json=dict(req, state=[0.0] * 3)).status_code == 400
assert c.post("/predict", json=dict(req, images=req["images"][:1])).status_code == 400
assert c.post("/predict", json=dict(req, bogus=1)).status_code == 422
assert c.post("/predict", json=dict(req, instruction="a <|im_end|> b")).status_code == 400
# the VQ /info carries no flow-matching leftovers
assert info["engine"] == {"vision": "mk", "prefix": "fused", "decode": "ttnn", "rvq": "device"}
assert "RDT2_NUM_STEPS" not in info["fixed_configuration"] and "RDT2-VQ" in info["task"]
class _RefVQTT(_StubVQTT):
"""Returns the stored official fp32 output of the shipped sample (samples/*.vq_reference.json)."""
rvq_engine = "host"
def __init__(self, ref, shift_m=0.0):
super().__init__()
self.ref, self.shift_m = ref, shift_m
def __call__(self, images, instruction, traced=True, bucket=None):
from tt_rdt2.reference.vq import action_tokens_from_ids, extract_action_ids
gen = list(self.ref["generated"][:28])
ids, valid = extract_action_ids(gen)
act = torch.tensor(self.ref["actions"], dtype=torch.float32)
act[:, 0] += self.shift_m
self.timings.update(host_pre_ms=1.0, generate_ms=2.0, rvq_ms=0.5)
return {"generated": gen, "action_ids": ids, "action_tokens": action_tokens_from_ids(ids), "valid": valid,
"nsample": act, "action": act, "n_tokens": 409, "bucket": bucket}
@pytest.mark.parametrize("shift_m, rc_expected", [(0.0, 0), (0.05, 1)])
def test_vq_smoke_over_http_against_stub(monkeypatch, tmp_path, shift_m, rc_expected):
"""The shipped stdlib smoke test checks the vq profile against the stored official VQ reference over loopback
HTTP: the reference output passes, a chunk 50 mm off fails."""
import json
import threading
import time
import urllib.request
uvicorn = pytest.importorskip("uvicorn")
need_tokenizer()
from tt_rdt2.server import smoke_test
from tt_rdt2.tests.test_server_host import _free_port
from tt_rdt2.vq.api import RDT2VQ
class _VQ(RDT2VQ):
@property
def device_info(self):
return {"dispatch": "eth", "grid": "12x10", "grid_x": 12, "grid_y": 10, "cores": 120, "device_id": 0,
"num_command_queues": 1, "arch": "blackhole", "stub": True}
ref = json.loads(smoke_test.VQ_REFERENCE.read_text())
assert len(ref["action_ids"]) == 27 and ref["generated"][27] == 151651 and ref["expected"]["valid"]
monkeypatch.setenv("RDT2_MODEL", "vq")
m = _VQ(_RefVQTT(ref, shift_m), None, weights=_weights(), owns_device=False, device_id=None)
m.engine = {"vision": "mk", "prefix": "fused", "decode": "ttnn", "rvq": "host"}
m.precision = "baseline"
m.warmup()
a = app_mod.create_app()
a.state.rdt2.model_factory = lambda cfg: m
port = _free_port()
server = uvicorn.Server(uvicorn.Config(a, host="127.0.0.1", port=port, log_level="warning", lifespan="on"))
th = threading.Thread(target=server.run, daemon=True)
th.start()
try:
t_end = time.time() + 60
while time.time() < t_end:
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=5) as r:
if json.loads(r.read())["status"] == "ok":
break
except OSError:
time.sleep(0.2)
out = tmp_path / "vq.json"
rc = smoke_test.main(["--url", f"http://127.0.0.1:{port}", "--wait", "30", "--out", str(out)])
assert rc == rc_expected
body = json.loads(out.read_text())
assert body["model_variant"] == "vq" and body["tokens"]["action_ids"] == ref["action_ids"]
finally:
server.should_exit = True
th.join(timeout=30)
def test_vq_errors_stdlib_matches_torch():
"""The smoke test's stdlib rotation / position metric equals tt_rdt2.vq.gates.action_errors."""
import json
from tt_rdt2.server import smoke_test
from tt_rdt2.vq.gates import action_errors
ref = json.loads(smoke_test.VQ_REFERENCE.read_text())
a = torch.tensor(ref["actions"], dtype=torch.float64)
g = torch.Generator().manual_seed(0)
b = a + 0.01 * torch.randn(a.shape, generator=g, dtype=torch.float64) * a.abs().clamp(min=1e-3)
m = smoke_test.vq_errors(b.tolist(), a.tolist())
p, r, gr = action_errors(b, a)
assert abs(m["pos_mm"] - p) < 1e-6 and abs(m["grip_mm"] - gr) < 1e-6 and abs(m["rot_deg"] - r) < 1e-3