"""How much thinking does the spoken answer need? One arm per thinking budget.
For each of the 100 benchmark questions: the baseline reasons as text for at most
`--budget` tokens (the reasoning is cut there if it has not closed itself), then the reply
is opened for speech with that reasoning in it, exactly as the endpoint's think-then-speak
does. Budget 0 is the plain speech path. The spoken words are scored by the same parser as
every other arm. Audio tokens are generated but not decoded here (the speech decoder adds
nothing to the answer), so "seconds to answer" is the time until the spoken answer's first
audio tokens exist, with one question at a time on a baseline copy of its own.
python -m eval.eval_bba_budget --budget 128 --api-url http://127.0.0.1:9992/v1/chat/completions
"""
import argparse
import asyncio
import json
import time
from collections import defaultdict
from pathlib import Path
import aiohttp
from duplex.spec import write_json
from eval.eval_bba import SYSTEM, parse_answer
from eval.ws_client import load_16k, percentiles
from serving.baseline_client import human_turn, stream_chat
NL = chr(10)
THINK_OPEN, THINK_CLOSE, SPEAK = "" + NL, "", ""
BRIEF = " Before you answer, think it through in a few short steps."
async def ask(http, args, q, sem, out):
pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
base = [{"role": "system", "content": SYSTEM + (BRIEF if args.brief else "")}, human_turn(pcm)]
row = {"id": q["id"], "category": q["category"], "think_tokens": 0, "closed_itself": None, "error": None}
async with sem:
t0 = time.perf_counter()
try:
thought = ""
if args.budget > 0:
n = 0
async for _, text, _ in stream_chat(http, args.api_url, args.model, base + [{"role": "assistant", "content": THINK_OPEN, "eot": False}],
max_tokens=args.budget, temperature=0.7, repetition_penalty=1.0, stop_token_ids=[151665],
stop=[THINK_CLOSE]):
thought += text
n += 1
row["think_tokens"], row["closed_itself"] = n, n < args.budget
if thought and not thought.endswith(NL):
thought += NL # cut mid-sentence by the budget: close the block on a new line
row["think_s"] = time.perf_counter() - t0
opener = (THINK_OPEN + thought + THINK_CLOSE + NL if args.budget > 0 else "") + SPEAK
spoken, first_audio = "", None
async for _, text, tokens in stream_chat(http, args.api_url, args.model, base + [{"role": "assistant", "content": opener, "eot": False}],
max_tokens=512, temperature=0.7, top_p=0.9, repetition_penalty=1.05, stop_token_ids=[151665]):
spoken += text
if tokens and first_audio is None:
first_audio = time.perf_counter() - t0
row["answer_s"], row["total_s"] = first_audio, time.perf_counter() - t0
except Exception as e:
row["error"], spoken, thought = repr(e), "", ""
answer, official = parse_answer(spoken, q["official_answer"])
row.update(official_answer=official, answer=answer, correct=answer is not None and answer == official, spoken=spoken, thought=thought)
write_json(out / f"q_{q['id']}.json", row)
return row
async def main():
ap = argparse.ArgumentParser()
ap.add_argument("--api-url", required=True)
ap.add_argument("--model", default="Step-Audio-R1.1")
ap.add_argument("--data", default="eval/data/bba")
ap.add_argument("--out", default="eval/results/bba_budget")
ap.add_argument("--budget", type=int, required=True, help="most reasoning tokens before the speech; 0 = no reasoning")
ap.add_argument("--brief", action="store_true", help="also ask, in the system prompt, for a few short steps")
ap.add_argument("--concurrency", type=int, default=1)
args = ap.parse_args()
name = f"budget_{args.budget}" + ("_brief" if args.brief else "")
out = Path(args.out) / name
out.mkdir(parents=True, exist_ok=True)
subset = json.loads((Path(args.data) / "subset.json").read_text())
sem = asyncio.Semaphore(args.concurrency)
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
rows = await asyncio.gather(*[ask(http, args, q, sem, out) for q in subset])
by_cat = defaultdict(list)
for r in rows:
by_cat[r["category"]].append(r["correct"])
summary = {
"arm": name, "budget": args.budget, "brief": args.brief, "concurrency": args.concurrency, "questions": len(rows),
"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())},
"no_answer_found": sum(r["answer"] is None for r in rows), "errors": sum(bool(r["error"]) for r in rows),
"reasoning_closed_itself": sum(bool(r["closed_itself"]) for r in rows), "think_tokens": percentiles([r["think_tokens"] for r in rows]),
"seconds_to_spoken_answer": percentiles([r.get("answer_s") for r in rows]),
}
write_json(Path(args.out) / f"summary_{name}.json", summary)
print(json.dumps(summary))
if __name__ == "__main__":
asyncio.run(main())