Download code/tt_rdt2/tests/test_stress_device.py from changh95/rdt2-base-p150: direct link, hf CLI and curl.
- Browser
- Download file 21.3 kB
-
https://huggingface.co/changh95/rdt2-base-p150/resolve/main/code/tt_rdt2/tests/test_stress_device.py
- Command line
-
hf download hf://changh95/rdt2-base-p150/code/tt_rdt2/tests/test_stress_device.py
-
curl -L -o test_stress_device.py https://huggingface.co/changh95/rdt2-base-p150/resolve/main/code/tt_rdt2/tests/test_stress_device.py
21.3 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """STRESS GATE of the serving path (one p150): N consecutive requests (default 500) through the real HTTP server | |
| in-process (loopback, the real model, every prompt bucket resident), with the shipped defaults. | |
| $ROOT/bin/devrun -t 3600 --reset-on-timeout -- python -u -m pytest -q -s -o faulthandler_timeout=3300 \ | |
| code/tt_rdt2/tests/test_stress_device.py | |
| Environment: RDT2_DISPATCH (eth | worker, default eth), RDT2_STRESS_N (valid requests, default 500), | |
| RDT2_STRESS_JSON (report path; default <tmp>/rdt2_stress_<dispatch>.json), RDT2_STRESS_TIMEOUT_S (per request, 300), | |
| RDT2_VERIFIER_FLOORS_JSON (optional: the verification cases' floors computed beforehand on the CPU with | |
| reference/gatesets.py ``floors_of``, so the device lock is not held for it; computed here otherwise, about 40 s). | |
| The request stream cycles the three prompt buckets (416 / 448 / 512) with varied images (synthetic gradients / noise / | |
| blocks / stripes, the shipped real sample and the official golden cameras; PNG and JPEG), instructions of 3..100 words, | |
| seeds, states (zero, N(0, 1), 10 * N(0, 1)) and forced ``prompt_bucket`` overrides, and mixes in | |
| * every official golden case whose noise is a seeded draw (main 13 + ext 5 + hold-out 8 + the 10 verification cases | |
| of reference/gatesets.py VERIFIER_SETS), twice each: the served chunk must pass the device gates of | |
| tests/test_tt_device.py (floor-anchored A2 verdict, groups primary, where the case has a floor; the main-golden A2 | |
| limits otherwise) and the second answer must equal the first; | |
| * repeats of earlier requests (about one in six): the chunk must be bit-identical to the first answer; | |
| * one malformed request every 50 (wrong camera count, num_steps, special-token text, too-long instruction, broken | |
| base64): it must answer 400 and leave the server healthy (not counted in N). | |
| Gate: no hang (every request answers within RDT2_STRESS_TIMEOUT_S), no error (every valid request 200), identical | |
| outputs for identical requests, every golden request within its gate, every bucket exercised. The report holds the | |
| latency distribution per bucket (server ``timing_ms`` and client round trip: p50 / p99 / max). | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import io | |
| import json | |
| import os | |
| import statistics | |
| import tempfile | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| from typing import Any, Dict, List, Optional, Tuple | |
| import numpy as np | |
| import pytest | |
| import torch | |
| pytestmark = pytest.mark.device | |
| BUCKETS = (416, 448, 512) | |
| MAIN_A2 = dict(min_pcc=0.999, pos_m=0.010, rot=0.02, grip_m=0.003) # tests/test_tt_device.py GATES (main golden) | |
| SEED_CANDIDATES = (list(range(0, 12)) + [42, 777, 1234, 2027, 2525, 4242, 4545, 6262, 31337, 90210] | |
| + [1201, 1919, 3131, 3801, 4120, 4801, 4880, 5050, 5501, 7071]) # the verification cases | |
| WORDS = ("pick up the red cup and place it gently on the white plate near the left edge of the table then move " | |
| "both arms back slowly open the drawer fold the towel pour water from the bottle into the glass wipe " | |
| "stack the blocks push the box toward the shelf grasp handle rotate lid carefully").split() | |
| def _png(a: np.ndarray, fmt: str = "PNG") -> str: | |
| from PIL import Image | |
| b = io.BytesIO() | |
| Image.fromarray(a).save(b, format=fmt, **({"quality": 92} if fmt == "JPEG" else {})) | |
| return base64.b64encode(b.getvalue()).decode("ascii") | |
| def _synthetic(rng: np.random.Generator, kind: int) -> np.ndarray: | |
| h = w = 384 | |
| if kind == 0: # gradients + a disc | |
| y, x = np.mgrid[0:h, 0:w] | |
| img = np.stack([x * 255 // w, y * 255 // h, (x + y) * 255 // (h + w)], -1).astype(np.uint8) | |
| cy, cx, r = rng.integers(60, 320, 2).tolist() + [int(rng.integers(20, 80))] | |
| img[(y - cy) ** 2 + (x - cx) ** 2 < r * r] = rng.integers(0, 256, 3, dtype=np.uint8) | |
| return img | |
| if kind == 1: # uniform noise | |
| return rng.integers(0, 256, (h, w, 3), dtype=np.uint8) | |
| if kind == 2: # colour blocks | |
| img = np.zeros((h, w, 3), np.uint8) | |
| for _ in range(12): | |
| y0, x0 = rng.integers(0, h - 40, 2) | |
| hh, ww = rng.integers(20, 160, 2) | |
| img[y0:y0 + hh, x0:x0 + ww] = rng.integers(0, 256, 3, dtype=np.uint8) | |
| return img | |
| stripes = (np.arange(w)[None, :, None] // int(rng.integers(4, 40)) % 2) * rng.integers(40, 255, 3) # stripes | |
| return np.broadcast_to(stripes, (h, w, 3)).astype(np.uint8).copy() | |
| def _golden_cases() -> List[Dict[str, Any]]: | |
| """Every official golden case whose initial noise is a seeded draw (the HTTP contract carries a seed).""" | |
| from tt_rdt2.reference.config import DEFAULT_DIRS | |
| from tt_rdt2.reference.gatesets import VERIFIER_SETS, HoldoutSet, floors_of, load_floors | |
| from tt_rdt2.reference.golden import GoldenSet | |
| root = DEFAULT_DIRS["golden"] | |
| try: | |
| floors = load_floors() | |
| except FileNotFoundError: | |
| floors = {} | |
| out = [] | |
| def add(name, d, prompt): | |
| noise = d["in.noise"].float().reshape(1, 24, 20) | |
| seed = next((s for s in SEED_CANDIDATES if torch.equal( | |
| torch.randn((1, 24, 20), generator=torch.Generator().manual_seed(s)), noise)), None) | |
| if seed is None: | |
| return | |
| fl = (floors.get(name) or {}).get("floor") | |
| out.append(dict(name=name, left=d["in.left"].numpy(), right=d["in.right"].numpy(), prompt=prompt, seed=seed, | |
| state=[float(x) for x in d["in.state"].float().reshape(-1).tolist()], | |
| nsample=d["exp.nsample"].float().reshape(24, 20), action=d["out.action"].float().reshape(24, 20), | |
| floor=fl)) | |
| if os.path.exists(os.path.join(root, "fp32", "manifest.json")): | |
| g = GoldenSet("fp32") | |
| for c in g.cases: | |
| add(c, g.load(c, with_vlm=False), g.info(c)["prompt"]) | |
| ext = os.path.join(root, "ext") | |
| if os.path.exists(os.path.join(ext, "fp32", "manifest.json")): | |
| g = GoldenSet("fp32", root=ext) | |
| for c in g.cases: | |
| add(c, g.load(c, with_vlm=False), g.info(c)["prompt"]) | |
| try: | |
| h = HoldoutSet() | |
| for c in h.cases: | |
| d = h.load(c) | |
| if "meta.prompt" in d: | |
| add(c, d, str(d["meta.prompt"])) | |
| except FileNotFoundError: | |
| pass | |
| v = HoldoutSet(sets=VERIFIER_SETS) | |
| if v.cases: | |
| cached = os.environ.get("RDT2_VERIFIER_FLOORS_JSON") | |
| if cached and os.path.exists(cached): | |
| with open(cached) as f: | |
| floors.update({c: x for c, x in json.load(f).items() if c in v.cases and c not in floors}) | |
| missing = [c for c in v.cases if c not in floors] | |
| if missing: | |
| floors.update(floors_of(v, missing, os.environ.get("RDT2_EXPERT_DIR"), | |
| os.environ.get("RDT2_NORMALIZER_DIR"))) | |
| for c in v.cases: | |
| d = v.load(c) | |
| if "meta.prompt" in d: | |
| add(c, d, str(d["meta.prompt"])) | |
| return out | |
| def _judge_golden(actions: List[List[float]], case: Dict[str, Any], norm) -> Dict[str, Any]: | |
| from tt_rdt2.reference.gatesets import group_maxabs, judge | |
| from tt_rdt2.reference.golden import pcc | |
| act = torch.tensor(actions, dtype=torch.float32) | |
| ns = act * norm["scale"] + norm["offset"] | |
| pos, rot, grip = group_maxabs(act, case["action"]) | |
| p = pcc(ns, case["nsample"]) | |
| got = dict(one_minus_pcc=1.0 - p, pos_m=pos, rot=rot, grip_m=grip) | |
| if case["floor"]: | |
| v = judge(got, case["floor"]) | |
| return dict(metrics=got, rule="floor", passed=bool(v["passed"]), ratio_to_floor=v["ratio_to_floor"], | |
| limits=v["limits"]) | |
| ok = p >= MAIN_A2["min_pcc"] and pos <= MAIN_A2["pos_m"] and rot <= MAIN_A2["rot"] and grip <= MAIN_A2["grip_m"] | |
| return dict(metrics=got, rule="main_a2", passed=bool(ok), limits=MAIN_A2) | |
| def _post(base: str, payload: Dict[str, Any], timeout: float) -> Tuple[int, Dict[str, Any], float]: | |
| data = json.dumps(payload).encode() | |
| r = urllib.request.Request(base + "/predict", data=data, headers={"Content-Type": "application/json"}) | |
| t0 = time.perf_counter() | |
| try: | |
| with urllib.request.urlopen(r, timeout=timeout) as resp: | |
| body = json.loads(resp.read().decode()) | |
| code = resp.status | |
| except urllib.error.HTTPError as e: | |
| code = e.code | |
| try: | |
| body = json.loads(e.read().decode()) | |
| except ValueError: | |
| body = {} | |
| return code, body, (time.perf_counter() - t0) * 1e3 | |
| def _stats(xs: List[float]) -> Dict[str, Optional[float]]: | |
| if not xs: | |
| return {"n": 0, "p50": None, "p99": None, "max": None, "mean": None} | |
| s = sorted(xs) | |
| p99 = s[min(len(s) - 1, int(round(0.99 * (len(s) - 1))))] | |
| return {"n": len(s), "p50": round(statistics.median(s), 2), "p99": round(p99, 2), "max": round(s[-1], 2), | |
| "mean": round(statistics.fmean(s), 2)} | |
| def test_stress_gate(): | |
| from tt_rdt2.reference.preprocess import tokenize | |
| from tt_rdt2.reference.weights import load_action_normalizer | |
| from tt_rdt2.tests.serving import get_json, local_weight_env, serve_and_run | |
| dispatch = (os.environ.get("RDT2_DISPATCH") or "eth").lower() | |
| n_valid = int(os.environ.get("RDT2_STRESS_N") or 500) | |
| timeout = float(os.environ.get("RDT2_STRESS_TIMEOUT_S") or 300) | |
| out_path = os.environ.get("RDT2_STRESS_JSON") or os.path.join(tempfile.gettempdir(), f"rdt2_stress_{dispatch}.json") | |
| env = local_weight_env() | |
| proc_dir = env.get("RDT2_PROCESSOR_DIR") or os.environ.get("RDT2_PROCESSOR_DIR") | |
| norm = load_action_normalizer(env.get("RDT2_NORMALIZER_DIR") or os.environ.get("RDT2_NORMALIZER_DIR")) | |
| rng = np.random.default_rng(20261118) | |
| # ---------------------------------------------------------------- request material (host, before the server) | |
| golden = _golden_cases() | |
| from tt_rdt2 import api | |
| s = api.load_sample() | |
| images: List[Tuple[str, str]] = [(_png(s["images"][0]), _png(s["images"][1]))] | |
| images.append((_png(s["images"][0], "JPEG"), _png(s["images"][1], "JPEG"))) | |
| for k in range(10): | |
| images.append((_png(_synthetic(rng, k % 4)), _png(_synthetic(rng, (k + 1) % 4)))) | |
| for c in golden[:6]: | |
| images.append((_png(c["left"]), _png(c["right"]))) | |
| instr: Dict[int, List[Tuple[str, int]]] = {L: [] for L in BUCKETS} | |
| tries = 0 | |
| while min(len(v) for v in instr.values()) < 12 and tries < 4000: | |
| tries += 1 | |
| nw = int(rng.choice([int(rng.integers(2, 8)), int(rng.integers(10, 35)), int(rng.integers(40, 100))])) | |
| text = " ".join(rng.choice(WORDS, nw).tolist()).capitalize() + "." | |
| n = int(tokenize(text, 378, proc_dir).shape[1]) | |
| if n <= max(BUCKETS): | |
| L = min(b for b in BUCKETS if b >= n) | |
| if len(instr[L]) < 12: | |
| instr[L].append((text, n)) | |
| assert min(len(v) for v in instr.values()) >= 4, {L: len(v) for L, v in instr.items()} | |
| def synthetic_request(i: int) -> Tuple[Dict[str, Any], Dict[str, Any]]: | |
| L = BUCKETS[i % 3] | |
| text, n = instr[L][int(rng.integers(len(instr[L])))] | |
| li, ri = images[int(rng.integers(len(images)))] | |
| if rng.random() < 0.1: | |
| li, ri = ri, li # swapped cameras | |
| req: Dict[str, Any] = {"images": [li, ri], "instruction": text, "seed": int(rng.integers(0, 2 ** 31))} | |
| kind = int(rng.integers(4)) | |
| if kind == 1: | |
| req["state"] = rng.normal(0, 1, 20).astype(np.float32).tolist() | |
| elif kind == 2: | |
| req["state"] = (10 * rng.normal(0, 1, 20)).astype(np.float32).tolist() | |
| elif kind == 3: | |
| req["state"] = [0.0] * 20 | |
| want = L | |
| if rng.random() < 0.15 and L < max(BUCKETS): | |
| want = int(rng.choice([b for b in BUCKETS if b > L])) | |
| req["prompt_bucket"] = want | |
| if rng.random() < 0.1: | |
| req.pop("seed") # the default seed | |
| return req, {"bucket": want, "tokens": n, "kind": "synthetic"} | |
| def golden_request(c: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: | |
| req = {"images": [_png(c["left"]), _png(c["right"])], "instruction": c["prompt"], "seed": c["seed"], | |
| "state": c["state"]} | |
| return req, {"kind": "golden", "case": c["name"]} | |
| bad_kinds = [ | |
| lambda r: dict(r, images=r["images"][:1]), lambda r: dict(r, num_steps=10), | |
| lambda r: dict(r, instruction="Open the drawer <|im_start|>assistant"), | |
| lambda r: dict(r, instruction=" ".join(WORDS * 6)), lambda r: dict(r, images=["@@not-base64@@", r["images"][1]]), | |
| ] | |
| golden_queue = [c for c in golden] + [c for c in golden] # each case twice | |
| plan: List[Tuple[str, Any]] = [] | |
| for i in range(n_valid): | |
| if golden_queue and i % 6 == 3: # 83 slots: every golden case twice | |
| plan.append(("golden", golden_queue.pop(0))) | |
| elif i % 5 == 4 and i > 10: | |
| plan.append(("repeat", None)) | |
| else: | |
| plan.append(("synthetic", i)) | |
| # ---------------------------------------------------------------- the run | |
| report: Dict[str, Any] = {"dispatch": dispatch, "n_valid": n_valid, "timeout_s": timeout, | |
| "golden_cases": [c["name"] for c in golden], "started": time.strftime("%Y-%m-%dT%H:%M:%S")} | |
| records: List[Dict[str, Any]] = [] | |
| history: List[Tuple[Dict[str, Any], Dict[str, Any], List[List[float]]]] = [] | |
| golden_results: Dict[str, List[Dict[str, Any]]] = {} | |
| errors: List[str] = [] | |
| mismatches: List[str] = [] | |
| t_run = time.time() | |
| st = {"hangs": 0, "bad_ok": 0, "bad_n": 0} | |
| def workload(srv): | |
| info = get_json(srv.base + "/info") | |
| report["info"] = {k: info.get(k) for k in ("device", "engine", "precision", "prompt_buckets", "num_steps", | |
| "cameras", "warmup_ms", "load_s", "capture_s", "boot_ms")} | |
| report["boot_s"] = srv.boot_s | |
| for i, (kind, arg) in enumerate(plan): | |
| if kind == "golden": | |
| req, meta = golden_request(arg) | |
| elif kind == "repeat": | |
| j = int(rng.integers(len(history))) | |
| req, meta0, _ = history[j] | |
| meta = dict(meta0, kind="repeat", of=j) | |
| else: | |
| req, meta = synthetic_request(arg) | |
| try: | |
| code, body, rtt = _post(srv.base, req, timeout) | |
| except (TimeoutError, OSError) as e: # socket timeout = the device did not answer | |
| st["hangs"] += 1 | |
| errors.append(f"request {i} ({meta.get('kind')}): no answer within {timeout} s: {e}") | |
| print(f"[stress] HANG at request {i}: {e}", flush=True) | |
| # the server cannot shut down cleanly behind a hung device call: keep the evidence now | |
| os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) | |
| with open(out_path, "w") as f: | |
| json.dump(dict(report, hang_at=i, request_kind=meta.get("kind"), records=records, errors=errors, | |
| passed=False), f, indent=1, default=str) | |
| break | |
| rec = {"i": i, "kind": meta["kind"], "code": code, "rtt_ms": round(rtt, 2)} | |
| if code != 200: | |
| errors.append(f"request {i} ({meta['kind']}): HTTP {code}: {str(body)[:200]}") | |
| records.append(rec) | |
| continue | |
| tm = body["timing_ms"] | |
| rec.update(bucket=body["prompt_bucket"], tokens=body["num_tokens"], total_ms=tm["total"], | |
| inference_ms=tm["inference"], preprocess_ms=tm["preprocess"]) | |
| if meta["kind"] == "synthetic" and body["prompt_bucket"] != meta["bucket"]: | |
| errors.append(f"request {i}: bucket {body['prompt_bucket']}, expected {meta['bucket']}") | |
| if not np.all(np.isfinite(np.asarray(body["actions"], np.float64))): | |
| errors.append(f"request {i}: non-finite actions") | |
| if meta["kind"] == "repeat": | |
| first = history[meta["of"]][2] | |
| same = body["actions"] == first | |
| rec["identical"] = same | |
| if not same: | |
| mismatches.append(f"request {i} repeats request #{meta['of']} of the history: different chunk") | |
| else: | |
| history.append((req, meta, body["actions"])) | |
| if meta["kind"] == "golden": | |
| case = next(c for c in golden if c["name"] == meta["case"]) | |
| v = _judge_golden(body["actions"], case, norm) | |
| v["bucket"] = body["prompt_bucket"] | |
| prev = golden_results.setdefault(case["name"], []) | |
| if prev and prev[0]["actions"] != body["actions"]: | |
| mismatches.append(f"golden {case['name']}: second answer differs from the first") | |
| prev.append(dict(v, actions=body["actions"])) | |
| rec["golden"] = case["name"] | |
| rec["golden_pass"] = v["passed"] | |
| records.append(rec) | |
| if i % 50 == 49: # a malformed request: 400, and the server stays healthy | |
| st["bad_n"] += 1 | |
| c2, b2, _ = _post(srv.base, bad_kinds[(i // 50) % len(bad_kinds)](req), timeout) | |
| st["bad_ok"] += int(c2 == 400) | |
| if c2 != 400: | |
| errors.append(f"malformed request after {i}: HTTP {c2} (expected 400): {str(b2)[:200]}") | |
| print(f"[stress] {i + 1}/{n_valid} ok, errors {len(errors)}, mismatches {len(mismatches)}, " | |
| f"last total {rec.get('total_ms')} ms", flush=True) | |
| health = get_json(srv.base + "/health") | |
| report["health_after"] = health["status"] | |
| serve_and_run(workload) | |
| hangs, bad_ok, bad_n = st["hangs"], st["bad_ok"], st["bad_n"] | |
| report["wall_s"] = round(time.time() - t_run, 1) | |
| report["ended"] = time.strftime("%Y-%m-%dT%H:%M:%S") | |
| ok = [r for r in records if r["code"] == 200] | |
| report["counts"] = {"sent_valid": len(records), "ok": len(ok), "errors": len(errors), "hangs": hangs, | |
| "malformed_sent": bad_n, "malformed_400": bad_ok, | |
| "by_kind": {k: sum(1 for r in ok if r["kind"] == k) for k in ("synthetic", "golden", "repeat")}, | |
| "by_bucket": {str(L): sum(1 for r in ok if r.get("bucket") == L) for L in BUCKETS}} | |
| report["repeats"] = {"n": sum(1 for r in ok if r["kind"] == "repeat"), | |
| "identical": sum(1 for r in ok if r.get("identical")), "mismatches": mismatches} | |
| g_summary = {} | |
| for name, vs in golden_results.items(): | |
| v = vs[0] | |
| g_summary[name] = {"passed": all(x["passed"] for x in vs), "n": len(vs), "rule": v["rule"], | |
| "bucket": v["bucket"], "metrics": v["metrics"], "ratio_to_floor": v.get("ratio_to_floor")} | |
| report["golden"] = {"cases": g_summary, "n_cases": len(g_summary), | |
| "passed": sum(1 for v in g_summary.values() if v["passed"])} | |
| report["latency_ms"] = {str(L): {"server_total": _stats([r["total_ms"] for r in ok if r.get("bucket") == L]), | |
| "server_inference": _stats([r["inference_ms"] for r in ok if r.get("bucket") == L]), | |
| "server_preprocess": _stats([r["preprocess_ms"] for r in ok | |
| if r.get("bucket") == L]), | |
| "client_rtt": _stats([r["rtt_ms"] for r in ok if r.get("bucket") == L])} | |
| for L in BUCKETS} | |
| report["latency_ms"]["all"] = {"server_total": _stats([r["total_ms"] for r in ok]), | |
| "client_rtt": _stats([r["rtt_ms"] for r in ok])} | |
| report["deterministic"] = not mismatches | |
| report["errors"] = errors[:50] | |
| report["records"] = records | |
| report["passed"] = (hangs == 0 and not errors and not mismatches and len(ok) == n_valid | |
| and report["golden"]["passed"] == report["golden"]["n_cases"] | |
| and all(report["counts"]["by_bucket"][str(L)] > 0 for L in BUCKETS) | |
| and report["health_after"] == "ok") | |
| os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) | |
| with open(out_path, "w") as f: | |
| json.dump(report, f, indent=1) | |
| print(f"[stress] {dispatch}: passed={report['passed']} counts={report['counts']} repeats={report['repeats']['n']}/" | |
| f"{report['repeats']['identical']} golden {report['golden']['passed']}/{report['golden']['n_cases']} " | |
| f"wall {report['wall_s']} s -> {out_path}", flush=True) | |
| for L in BUCKETS: | |
| print(f"[stress] bucket {L}: server total {report['latency_ms'][str(L)]['server_total']} | rtt " | |
| f"{report['latency_ms'][str(L)]['client_rtt']}", flush=True) | |
| assert hangs == 0, errors[:3] | |
| assert not errors, errors[:5] | |
| assert not mismatches, mismatches[:5] | |
| assert len(ok) == n_valid | |
| failed = {k: v for k, v in g_summary.items() if not v["passed"]} | |
| assert not failed, failed | |
| assert all(report["counts"]["by_bucket"][str(L)] > 0 for L in BUCKETS) | |
| assert report["health_after"] == "ok" | |