File size: 5,495 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Track A step 4: 1, 2, 4, 8, 16 concurrent streams against the endpoint.

Every stream speaks a question in real time, ends its turn with input.commit (so the
number is the model and the audio path, not an endpointing wait), and listens to the
whole reply. Per turn:
  ttfa_ms     input.commit sent -> first reply audio frame received (client clock)
  underruns   frames that were due while the reply was playing but were not ready (server count)
  max_gap_ms  longest gap between two reply audio frames at the client (80 ms is nominal)

A level PASSES when every turn has ttfa_ms < 800 and no turn has an underrun.
Streams start within a random 2 s of each other; they are not artificially aligned.

  python -m serving.loadtest --wav-dir eval/data/bba --out eval/results/loadtest
"""
import argparse
import asyncio
import random
from pathlib import Path

import aiohttp

import numpy as np

from duplex.spec import OUT_SR, write_json, write_wav
from eval.ws_client import load_16k, open_session, percentiles, run_turn
from serving.probe_baseline import gpu_memory


async def stream(http, args, wavs, idx, level):
    await asyncio.sleep(random.Random(f"{level}-{idx}").uniform(0, 2.0))
    ws = await open_session(http, args.url, args.system, "manual")
    turns = []
    try:
        for k in range(args.turns):
            r = await run_turn(ws, wavs[(idx + k) % len(wavs)], commit=True, max_wait_s=args.max_wait_s)
            done = r["done"] or {}
            if args.save_audio and idx == 0 and r["audio"]:      # one stream's replies, to check the audio with a recogniser
                name = Path(args.save_audio) / f"level{level}_turn{k}"
                write_wav(name.with_suffix(".wav"), np.frombuffer(r["audio"], dtype="<i2").astype(np.float32) / 32768, OUT_SR)
                name.with_suffix(".txt").write_text(r["text"], encoding="utf-8")
            turns.append({
                "stream": idx, "turn": k, "error": r["error"],
                "ttfa_ms": (r["t_first_audio"] - r["t_commit"]) * 1000 if r["t_first_audio"] and "t_commit" in r else None,
                "server_ttfa_ms": done.get("ttfa_ms"), "first_token_ms": done.get("first_token_ms"), "generated_ms": done.get("generated_ms"),
                "audio_ms": done.get("audio_ms"), "underruns": done.get("underruns"), "max_gap_ms": r["max_gap_ms"],
                "decodes": done.get("decodes"), "decode_ms": done.get("decode_ms"),
                # generation time over audio time, under load: below 1 means audio is made faster than it plays
                "real_time_factor": done["generated_ms"] / done["audio_ms"] if done.get("audio_ms") and done.get("generated_ms") else None,
            })
    finally:
        await ws.close()
    return turns


async def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--url", default="http://localhost:8765/ws")
    ap.add_argument("--wav-dir", required=True, help="spoken questions, 16-bit wav")
    ap.add_argument("--out", default="eval/results/loadtest")
    ap.add_argument("--levels", default="1,2,4,8,16")
    ap.add_argument("--turns", type=int, default=3, help="turns per stream")
    ap.add_argument("--max-wait-s", type=float, default=120.0)
    ap.add_argument("--system", default="You are a helpful assistant.")
    ap.add_argument("--save-audio", default=None, help="folder for the first stream's reply audio and text")
    args = ap.parse_args()

    wavs = sorted((load_16k(p) for p in sorted(Path(args.wav_dir).glob("*.wav"))), key=len)[:32]      # the 32 shortest questions
    assert wavs, f"no wav files in {args.wav_dir}"
    out = Path(args.out)
    if args.save_audio:
        Path(args.save_audio).mkdir(parents=True, exist_ok=True)
    summary = []
    async with aiohttp.ClientSession() as http:
        for level in [int(x) for x in args.levels.split(",")]:
            results = await asyncio.gather(*[stream(http, args, wavs, i, level) for i in range(level)], return_exceptions=True)
            turns = [t for r in results if isinstance(r, list) for t in r]
            crashed = [repr(r) for r in results if not isinstance(r, list)]
            ok = [t for t in turns if not t["error"] and t["ttfa_ms"] is not None]
            row = {
                "streams": level, "turns": len(turns), "turns_ok": len(ok), "errors": crashed + [t["error"] for t in turns if t["error"]],
                "ttfa_ms": percentiles([t["ttfa_ms"] for t in ok]), "underruns_total": sum(t["underruns"] or 0 for t in ok),
                "max_gap_ms": max([t["max_gap_ms"] for t in ok], default=None),
                "real_time_factor": percentiles([t["real_time_factor"] for t in ok]), "gpu": gpu_memory(),
            }
            row["pass"] = bool(ok) and len(ok) == level * args.turns and row["ttfa_ms"]["max"] < 800 and row["underruns_total"] == 0
            write_json(out / f"level_{level}.json", {"summary": row, "turns": turns})
            summary.append(row)
            print(f"streams={level:2d} pass={row['pass']} ttfa_ms={row['ttfa_ms']} underruns={row['underruns_total']} max_gap_ms={row['max_gap_ms']}")
    passing = [r["streams"] for r in summary if r["pass"]]
    write_json(out / "summary.json", {"levels": summary, "highest_passing_streams": max(passing) if passing else None,
                                      "criterion": "every turn ttfa_ms < 800 and zero underruns"})
    print("highest passing stream count:", max(passing) if passing else "none")


if __name__ == "__main__":
    asyncio.run(main())