#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Smoke test of a running laya server (standard library only: runs with the host's python3). python3 smoke_test.py --url http://127.0.0.1:20000 [--wait 900] [--manifest /tt_kernel_manifest.json] [--profile NAME] [--out smoke.json] [--expect-engine mk] Checks (each failure is listed; exit 0 = PASS): - readiness (/health), /info: ETH dispatch, 12x10 grid, the pinned configuration of the package (manifest serve env); - /v1/systemone on the shipped requests (samples/smoke_reference.json: the official laya 0.5.8 float32 answers): same top answer for every question, every probability within 0.03, usage tokens identical; - /v1/systemone/batch of the same requests == the single requests; 12 concurrent requests == the single ones; - min_confidence gate fields; served latency of one 1-question and one 4-question request; - LAYA_MAX_LEN > 512: one ~600-token state with 8 questions (one 8-row long-row launch) == each question alone; - refusals: malformed JSON (400), an unknown question type (422), max_len above the server's (422), a lone UTF-16 surrogate (400), a state over LAYA_MAX_STATE_CHARS (413); max_len below the head budget is answered (200). """ from __future__ import annotations import argparse import concurrent.futures import json import sys import time from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import client as C # noqa: E402 MODEL = "laya" MAX_DP = 0.03 def _load_ttaw(name): import importlib.util p = HERE.parent / "ttaw" / "server" / f"{name}.py" spec = importlib.util.spec_from_file_location(f"laya_ttaw_{name}", p) m = importlib.util.module_from_spec(spec) spec.loader.exec_module(m) return m def wait_ready(url: str, wait_s: float): t0 = time.time() last = None while True: try: h = C.get_json(url + "/health") last = h if h.get("status") in ("ok", "error"): return h except Exception as e: # noqa: BLE001 last = {"status": f"unreachable: {e}"} if time.time() - t0 > wait_s: return last time.sleep(5) def top(a): if a["type"] == "choice": return a["choice"] if a["type"] == "score": return max(a["probabilities"], key=lambda k: a["probabilities"][k]) return a["noul"] >= 0.5 def probs(a): return [a["noul"]] if a["type"] == "noul" else list(a["probabilities"].values()) def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--url", default="http://127.0.0.1:20000") ap.add_argument("--wait", type=float, default=900) ap.add_argument("--manifest", default=None) ap.add_argument("--profile", default=None) ap.add_argument("--out", default=None) ap.add_argument("--expect-engine", default=None) a = ap.parse_args() url = a.url.rstrip("/") fails, metrics = [], {} h = wait_ready(url, a.wait) if h.get("status") != "ok": print(f"SMOKE FAIL {MODEL}: not ready: {h}") return 1 info = C.get_json(url + "/info") dev = info.get("device", {}) if dev.get("dispatch") != "eth" or dev.get("grid") != "12x10": fails.append(f"device {dev.get('dispatch')} {dev.get('grid')} (expected eth 12x10)") engine = info.get("engine") metrics["engine"] = engine cfg = info.get("config", {}) profile = cfg.get("profile") metrics["profile"] = profile if a.expect_engine and engine != a.expect_engine: fails.append(f"engine {engine} (expected {a.expect_engine})") if a.manifest: smoke = _load_ttaw("smoke") pins = smoke.pinned_config(a.manifest, a.profile) env = pins.get("env", {}) for k, field, conv in (("LAYA_PROFILE", "profile", str), ("LAYA_ENGINE", "engine", str), ("LAYA_MAX_BATCH", "max_batch", int), ("LAYA_DISPATCH", "dispatch", str), ("LAYA_FIDELITY", "fidelity", str)): if k in env and conv(env[k]) != cfg.get(field): fails.append(f"/info config {field}={cfg.get(field)!r}, package pins {k}={env[k]!r}") rev = (pins.get("weights") or {}).get("revision") got_rev = info.get("model_info", {}).get("checkpoint", {}).get("revision") if rev and rev != got_rev: fails.append(f"checkpoint revision {got_rev!r} != pinned {rev}") ref = json.loads((HERE.parent / "samples" / "smoke_reference.json").read_text()) cases = [c for c in ref["cases"] if c["profile"] == profile] if not cases: fails.append(f"no shipped reference requests for profile {profile!r}") single = [] worst = 0.0 for c in cases: t0 = time.perf_counter() code, body = C.post(url + "/v1/systemone", {"state": c["state"], "questions": c["questions"], **c["kwargs"]}) if code != 200: fails.append(f"{c['id']}: HTTP {code} {body}") single.append(None) continue single.append(body) for qid, want in c["official"]["answers"].items(): got = body["answers"][qid] if top(got) != top(want): fails.append(f"{c['id']}/{qid}: answer {top(got)!r} != official {top(want)!r}") dp = max(abs(x - y) for x, y in zip(probs(got), probs(want))) worst = max(worst, dp) if dp > MAX_DP: fails.append(f"{c['id']}/{qid}: probability differs by {dp:.4f} > {MAX_DP}") for f in ("abstention", "low_confidence"): if want.get(f) != got.get(f): fails.append(f"{c['id']}/{qid}: {f} {got.get(f)!r} != official {want.get(f)!r}") if body["usage"]["input_tokens"] != c["official"]["usage"]["input_tokens"]: fails.append(f"{c['id']}: usage {body['usage']} != official {c['official']['usage']}") metrics["max_dp_vs_official"] = round(worst, 5) # batch + concurrency equal the single requests for c, s in zip(cases, single): if s is None: continue code, body = C.post(url + "/v1/systemone/batch", {"states": [c["state"]] * 3, "questions": c["questions"], **c["kwargs"]}) if code != 200 or len(body.get("results", [])) != 3: fails.append(f"batch {c['id']}: HTTP {code}") continue if "total_usage" not in body: fails.append(f"batch {c['id']}: no total_usage (the official batch key)") for r in body["results"]: for qid in s["answers"]: if top(r["answers"][qid]) != top(s["answers"][qid]): fails.append(f"batch {c['id']}/{qid}: answer differs from the single request") if cases: c = cases[0] with concurrent.futures.ThreadPoolExecutor(12) as ex: res = list(ex.map(lambda _: C.post(url + "/v1/systemone", {"state": c["state"], "questions": c["questions"]}), range(12))) for code, body in res: if code != 200 or any(top(body["answers"][q]) != top(single[0]["answers"][q]) for q in single[0]["answers"]): fails.append(f"concurrent request: HTTP {code} or a different answer") break # served latency (client round trip on loopback) q1 = {k: v for k, v in list(c["questions"].items())[:1]} for name, qs in (("1q", q1), ("all_q", c["questions"])): lat = [] for _ in range(20): t0 = time.perf_counter() C.post(url + "/v1/systemone", {"state": c["state"], "questions": qs}) lat.append(1e3 * (time.perf_counter() - t0)) lat.sort() metrics[f"served_{name}_ms_p50"] = round(lat[len(lat) // 2], 3) # long rows (LAYA_MAX_LEN > 512: the tt-nn long-row engine): one ~600-token state with 8 questions is ONE launch # of 8 rows (batch slots 0-7); every answer must equal the same question asked alone (batch 1) if (cfg.get("max_len") or 0) > 512: para = ("The customer of workspace {i} reports that the March invoice was charged twice, that the support " "portal failed to load the receipt, and asks for a refund before the end of the quarter. ") long_state = "".join(para.format(i=i) for i in range(18)) lq = {"department": {"type": "choice", "instructions": "Which department should handle this?", "criteria": {"billing": "invoices, refunds", "technical": "bugs", "other": None}}, "urgency": {"type": "score", "instructions": "How urgent is it?", "criteria": ["low", "mid", "high"]}, "refund": {"type": "noul", "instructions": "Does the customer ask for a refund?"}, "cancel": {"type": "noul", "instructions": "Does the customer threaten to cancel?"}, "topic": {"type": "choice", "instructions": "What is the topic?", "criteria": ["payment", "outage", "account", "other"]}, "anger": {"type": "score", "instructions": "How angry is the customer?", "criteria": ["calm", "annoyed", "angry"]}, "pii": {"type": "noul", "instructions": "Does the text contain personal data?"}, "area": {"type": "choice", "instructions": "Which product area is affected?", "criteria": {"billing": None, "portal": None, "api": None}}} code, allq = C.post(url + "/v1/systemone", {"state": long_state, "questions": lq}) if code != 200: fails.append(f"long state, 8 questions: HTTP {code}") else: tokens = allq["usage"]["input_tokens"] metrics["long8_tokens_per_row"] = tokens // 8 if tokens // 8 <= 512: fails.append(f"long state: {tokens // 8} tokens per row, expected > 512 (the long-row engine)") worst8 = 0.0 for qid, qdef in lq.items(): code, one = C.post(url + "/v1/systemone", {"state": long_state, "questions": {qid: qdef}}) if code != 200: fails.append(f"long state, {qid} alone: HTTP {code}") continue a8, a1 = allq["answers"][qid], one["answers"][qid] d = max(abs(x - y) for x, y in zip(probs(a8), probs(a1))) worst8 = max(worst8, d) if top(a8) != top(a1) or d > 0.01: fails.append(f"long state: {qid} in the 8-question launch differs from alone (|dp| {d:.4f})") metrics["long8_max_dp_vs_alone"] = round(worst8, 5) # refusals code, _ = C.post(url + "/v1/systemone", {"state": "x", "questions": {"q": {"type": "maybe", "instructions": "i"}}}) if code != 422: fails.append(f"unknown question type: HTTP {code}, expected 422") code, _ = C.post(url + "/v1/systemone", {"state": "x", "questions": {"q": {"type": "noul", "instructions": "i"}}, "max_len": 100000}) if code != 422: fails.append(f"max_len 100000: HTTP {code}, expected 422") # as officially: max_len below the head budget is answered; a lone UTF-16 surrogate is a 400; a state over # LAYA_MAX_STATE_CHARS a 413 code, _ = C.post(url + "/v1/systemone", {"state": "a short ticket", "max_len": 64, "questions": {"q": {"type": "noul", "instructions": "Is it short?"}}}) if code != 200: fails.append(f"max_len 64 (below the head budget): HTTP {code}, expected 200") code, _ = C.post(url + "/v1/systemone", {"state": "bad \ud800 text", "questions": {"q": {"type": "noul", "instructions": "i"}}}) if code != 400: fails.append(f"lone surrogate: HTTP {code}, expected 400") cap = (info.get("config") or {}).get("max_state_chars") or 0 if cap: code, _ = C.post(url + "/v1/systemone", {"state": "x" * (cap + 1), "questions": {"q": {"type": "noul", "instructions": "i"}}}) if code != 413: fails.append(f"state of {cap + 1} chars: HTTP {code}, expected 413") import urllib.request req = urllib.request.Request(url + "/v1/systemone", data=b"{bad", headers={"Content-Type": "application/json"}) try: urllib.request.urlopen(req, timeout=10) fails.append("malformed JSON accepted") except urllib.error.HTTPError as e: if e.code != 400: fails.append(f"malformed JSON: HTTP {e.code}, expected 400") if a.out: Path(a.out).write_text(json.dumps({"metrics": metrics, "failures": fails, "info": info}, indent=1)) print(json.dumps(metrics)) print(("SMOKE PASS" if not fails else "SMOKE FAIL") + f" {MODEL}: engine={engine} profile={profile} " f"max_dp={metrics.get('max_dp_vs_official')}" + ("" if not fails else f" {fails[:10]}")) return 0 if not fails else 1 if __name__ == "__main__": sys.exit(main())