File size: 6,826 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
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
"""100 Big Bench Audio questions through the endpoint, with and without the controller.

  without  endpointing "manual": the question is committed the instant its audio ends,
           so nothing but the model decides the answer.
  with     endpointing "controller": the controller alone decides when to answer. If it
           starts early, the model answers a cut-off question and that shows up here.

Scoring is ours, not Artificial Analysis's judge model: the reply text after the last
"</think>" is searched for the last valid/invalid, yes/no or number, and compared with
the official answer. Scores are comparable between the two modes of this run, not with
the public leaderboard. Raw replies (text and audio) are saved so they can be re-scored.

  python -m eval.eval_bba --data eval/data/bba --out eval/results/bba --modes manual,controller
"""
import argparse
import asyncio
import json
import re
from collections import defaultdict
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

SYSTEM = ('Listen to the question and answer it. Reply with only "valid" or "invalid", "yes" or "no", '
          "or a number. Do not add anything else.")

# Third run: Whisper recognised only 71 of 94 one-word spoken answers (the model gives a lone word very little
# audio, down to 0.16 s). "sentence" asks for the answer inside one short sentence instead.
SYSTEMS = {"word": SYSTEM,
           "sentence": ('Listen to the question and answer it in one short spoken sentence that states the answer: "valid" or "invalid", '
                        '"yes" or "no", or the number. Do not add anything else.')}

UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
TENS = "twenty thirty forty fifty sixty seventy eighty ninety".split()
# digits, "twenty", "twenty one" / "twenty-one", or a single word from zero to nineteen
NUMBER = rf"\d+|(?:{'|'.join(TENS)})(?:[\s-](?:{'|'.join(UNITS[1:10])}))?|(?:{'|'.join(UNITS)})"


def to_number(s):
    words = re.split(r"[\s-]+", s.strip().lower())
    if len(words) == 1 and words[0].isdigit():
        return int(words[0])
    if len(words) == 1 and words[0] in UNITS:
        return UNITS.index(words[0])
    if words[0] in TENS and (len(words) == 1 or (len(words) == 2 and words[1] in UNITS[1:10])):
        return 10 * (TENS.index(words[0]) + 2) + (UNITS.index(words[1]) if len(words) == 2 else 0)
    return None


def parse_answer(text, official):
    """The last answer of the right kind in the spoken part of the reply, or None."""
    say = re.sub(r"<[^>]+>", " ", text.split("</think>")[-1]).lower()
    official = official.strip().lower()
    if official in ("valid", "invalid"):
        found = re.findall(r"\b(invalid|valid)\b", say)
    elif official in ("yes", "no"):
        found = re.findall(r"\b(yes|no)\b", say)
    else:
        found = [str(n) for n in (to_number(m) for m in re.findall(rf"\b({NUMBER})\b", say)) if n is not None]
        official = str(to_number(official)) if to_number(official) is not None else official
    return (found[-1] if found else None), official


async def ask(http, args, q, mode, sem, out):
    async with sem:
        pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
        ws = await open_session(http, args.url, SYSTEMS[args.system], mode)
        try:
            r = await run_turn(ws, pcm, commit=(mode == "manual"), until="done_after_audio", max_wait_s=args.max_wait_s)
        finally:
            await ws.close()
    answer, official = parse_answer(r["text"], q["official_answer"])
    row = {
        "id": q["id"], "category": q["category"], "official_answer": official, "answer": answer,
        "correct": answer is not None and answer == official, "replied": r["done"] is not None and r["done"]["reason"] == "done",
        "started_early": r["started_early"], "replies_cut_off": sum(1 for d in r["replies"] if d["reason"] != "done"),
        "latency_ms": r["latency_ms"], "question_s": len(pcm) / 16000, "text": r["text"], "error": r["error"],
        "events": [e for e in r["events"] if e["type"] != "transcript.delta"],
    }
    write_json(out / f"q_{q['id']}.json", row)
    if r["audio"]:
        write_wav(out / f"q_{q['id']}.wav", np.frombuffer(r["audio"], dtype="<i2").astype(np.float32) / 32768, OUT_SR)
    return row


async def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--url", default="http://localhost:8765/ws")
    ap.add_argument("--data", default="eval/data/bba")
    ap.add_argument("--out", default="eval/results/bba")
    ap.add_argument("--modes", default="manual,controller")
    ap.add_argument("--concurrency", type=int, default=4)
    ap.add_argument("--max-wait-s", type=float, default=90.0)
    ap.add_argument("--system", default="word", choices=list(SYSTEMS), help="how the answer is asked for")
    ap.add_argument("--shard", type=int, default=0, help="ask only questions with index % num-shards == shard (an arm split over several baseline copies)")
    ap.add_argument("--num-shards", type=int, default=1)
    args = ap.parse_args()

    subset = [q for i, q in enumerate(json.loads((Path(args.data) / "subset.json").read_text())) if i % args.num_shards == args.shard]
    summary = {"questions": len(subset), "scoring": "last valid/invalid, yes/no or number in the reply text; not the leaderboard's judge"}
    async with aiohttp.ClientSession() as http:
        for mode in args.modes.split(","):
            out = Path(args.out) / mode
            out.mkdir(parents=True, exist_ok=True)
            sem = asyncio.Semaphore(args.concurrency)
            rows = await asyncio.gather(*[ask(http, args, q, mode, sem, out) for q in subset])
            by_cat = defaultdict(list)
            for row in rows:
                by_cat[row["category"]].append(row["correct"])
            summary[mode] = {
                "accuracy": sum(r["correct"] for r in rows) / len(rows),
                "accuracy_by_category": {c: sum(v) / len(v) for c, v in sorted(by_cat.items())},
                "replied": sum(r["replied"] for r in rows), "no_answer_found": sum(r["answer"] is None for r in rows),
                "started_early": sum(r["started_early"] for r in rows), "replies_cut_off": sum(r["replies_cut_off"] for r in rows),
                "errors": sum(bool(r["error"]) for r in rows), "latency_ms": percentiles([r["latency_ms"] for r in rows if r["replied"]]),
            }
            print(mode, json.dumps(summary[mode]))
    write_json(Path(args.out) / f"summary_{args.modes.replace(',', '_')}{f'_shard{args.shard}' if args.num_shards > 1 else ''}.json", summary)


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