File size: 9,655 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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | """The baseline as end-of-turn judge (serving/judge.py), measured offline.
Cases, all cut from the caller's channel (with its noise), each ending 240 ms into the silence:
finished a caller turn up to its end (the turns that were answered in the data)
pause the same kind of turn, cut at a mid-sentence pause
question Big Bench Audio questions (voices and style nothing here was tuned on):
cut at every inner silence of 400 ms or more (not finished), and at the end (finished)
About half of the data's "pauses" follow a complete sentence ("Thanks for the email.
[pause] I want to make sure ..."): nobody can know from the words that more is coming.
So pauses are also reported in two groups by the words before them:
cut off the last word is a function word (and, but, to, the, my, I ...): clearly unfinished
other everything else, complete-sounding or not
Several variants of the judge (prompt, optional short reasoning) are run on a sample of
TRAIN-split cases and on all held-out cases. The variant to use is the one with the best
balanced accuracy on the TRAIN sample; the held-out numbers of every variant are reported.
python -m eval.eval_judge --data data/out/dataset --dialogues data/out/dialogues.jsonl --bba eval/data/bba --out eval/results/judge
"""
import argparse
import asyncio
import json
import random
import re
import time
from pathlib import Path
import aiohttp
import numpy as np
from duplex.spec import CALLER, FRAME, SR, read_jsonl, read_wav, write_json
from eval.ws_client import load_16k, percentiles
from serving.judge import judge_finished
TAIL = int(0.24 * SR) # the judge is asked 240 ms into the silence
LEAD = int(0.3 * SR)
FUNCTION_WORDS = set("""and but or so because if that which who when while although though unless until
to of in on at for with from by about into onto over under between through during before after
the a an my your our their his her its this these those some any every each no
i we you they he she it there
is are was were am be been being have has had do does did can could will would should might may must
not just than as""".split())
def pause_prefixes(dialogue):
"""The words before each pause of a dialogue, in the order the data builder created the pauses."""
out = []
for turn in dialogue["turns"]:
if turn["spk"] == "caller":
parts = [p.strip() for p in turn["text"].split("[pause]") if p.strip()]
out += [" ".join(parts[: i + 1]) for i in range(len(parts) - 1)]
return out
def cut_off(prefix):
words = re.findall(r"[a-z']+", prefix.lower())
return bool(words) and words[-1] in FUNCTION_WORDS and prefix.rstrip()[-1] not in ".?!"
def dialogue_cases(data, split, limit, seed, dialogues=None):
data, cases = Path(data), []
for it in json.loads((data / f"index_{split}.json").read_text()):
events = json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]
cuts = {e["onset"] for e in events if e["type"] == "interrupt"}
answered = {e["caller_end"] for e in events if e["type"] == "start"}
pauses = [e for e in events if e["type"] == "pause"]
prefixes = pause_prefixes(dialogues[it["id"]]) if dialogues else []
for e in events:
if e["type"] != "caller_turn" or e["start"] in cuts or not 1.0 * SR <= e["end"] - e["start"] <= 25 * SR:
continue
if e["end"] in answered:
cases.append({"kind": "finished", "id": it["id"], "start": e["start"], "cut": e["end"]})
for k, p in enumerate(pauses):
if e["start"] < p["start"] < e["end"] and p["end"] - p["start"] >= TAIL + FRAME:
c = {"kind": "pause", "id": it["id"], "start": e["start"], "cut": p["start"], "pause_index": k}
if len(prefixes) == len(pauses):
c["before"], c["cut_off"] = prefixes[k][-80:], cut_off(prefixes[k])
cases.append(c)
random.Random(seed).shuffle(cases)
return cases[:limit] if limit else cases
def question_cases(bba_dir, db=-45.0, min_gap_s=0.4):
cases = []
for q in json.loads((Path(bba_dir) / "subset.json").read_text()):
pcm = load_16k(Path(bba_dir) / f"q_{q['id']}.wav")
n = len(pcm) // FRAME
rms = np.sqrt(np.mean((pcm[: n * FRAME].reshape(n, FRAME).astype(np.float32) / 32768) ** 2, axis=1))
voiced = 20 * np.log10(rms + 1e-9) > db
last = int(np.nonzero(voiced)[0][-1])
i = 0
while i < last:
if not voiced[i]:
j = i
while j < last and not voiced[j]:
j += 1
if (j - i) * 0.08 >= min_gap_s and voiced[:i].sum() >= 3:
cases.append({"kind": "question_inner", "id": q["id"], "cut": i * FRAME})
i = j
else:
i += 1
cases.append({"kind": "question_end", "id": q["id"], "cut": (last + 1) * FRAME})
return cases
def audio_of(case, data, bba_dir):
if case["kind"].startswith("question"):
pcm = load_16k(Path(bba_dir) / f"q_{case['id']}.wav")[: case["cut"]]
return np.concatenate([pcm, np.zeros(TAIL, np.int16)]) # clean recordings: silence after the cut
a = max(0, case["start"] - LEAD)
x, _ = read_wav(Path(data) / "audio" / f"{case['id']}.wav", a, case["cut"] + TAIL - a)
return (x[:, CALLER] * 32767).astype(np.int16) # the real channel, noise included
async def run(http, args, cases, sem, variant):
prompt, think = variant.split("+")
async def one(c):
pcm = audio_of(c, args.data, args.bba)
async with sem:
t0 = time.perf_counter()
try:
said = await judge_finished(http, args.api_url, args.model, pcm, prompt=prompt, think_tokens=int(think))
except Exception as e:
said, c["error"] = None, repr(e)
c.setdefault("said", {})[variant] = said
c.setdefault("ms", {})[variant] = (time.perf_counter() - t0) * 1000
c["audio_s"] = len(pcm) / SR
await asyncio.gather(*[one(c) for c in cases])
def rate(cases, variant, want, keep=lambda c: True):
rows = [c for c in cases if keep(c) and c["said"][variant] is not None]
hits = sum(c["said"][variant] == want for c in rows)
return {"correct": hits, "total": len(rows), "rate": hits / len(rows) if rows else None}
async def main():
ap = argparse.ArgumentParser()
ap.add_argument("--api-url", default="http://127.0.0.1:9991/v1/chat/completions")
ap.add_argument("--model", default="Step-Audio-R1.1")
ap.add_argument("--data", required=True)
ap.add_argument("--dialogues", required=True)
ap.add_argument("--bba", default="eval/data/bba")
ap.add_argument("--out", default="eval/results/judge")
ap.add_argument("--variants", default="v1+0,v2+0,v2+32", help="prompt+reasoning tokens, comma separated")
ap.add_argument("--train-cases", type=int, default=500)
ap.add_argument("--concurrency", type=int, default=12)
args = ap.parse_args()
dialogues = {d["id"]: d for d in read_jsonl(args.dialogues)}
train = dialogue_cases(args.data, "train", args.train_cases, 0, dialogues)
test = dialogue_cases(args.data, "test", None, 0, dialogues)
quest = question_cases(args.bba)
sem, variants = asyncio.Semaphore(args.concurrency), args.variants.split(",")
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=300)) as http:
for v in variants:
for cases in (train, test, quest):
await run(http, args, cases, sem, v)
is_kind = lambda k: (lambda c: c["kind"] == k)
result = {"cases": {"train": len(train), "held_out": len(test), "question_cuts": len(quest)},
"held_out_pauses": {"all": sum(c["kind"] == "pause" for c in test), "cut_off": sum(c.get("cut_off") is True for c in test)},
"concurrency": args.concurrency, "variants": {}}
for v in variants:
tr_end, tr_pause = rate(train, v, True, is_kind("finished")), rate(train, v, False, is_kind("pause"))
result["variants"][v] = {
"train_balanced_accuracy": (tr_end["rate"] + tr_pause["rate"]) / 2,
"held_out": {
"turn_end_released": rate(test, v, True, is_kind("finished")),
"pause_held_all": rate(test, v, False, is_kind("pause")),
"pause_held_cut_off": rate(test, v, False, lambda c: c.get("cut_off") is True),
"pause_held_other": rate(test, v, False, lambda c: c.get("cut_off") is False),
},
"benchmark_questions": {
"inner_silence_held": rate(quest, v, False, is_kind("question_inner")),
"end_released": rate(quest, v, True, is_kind("question_end")),
"questions_never_released_early": sum(all(c["said"][v] is not True for c in quest if c["id"] == q and c["kind"] == "question_inner")
for q in {c["id"] for c in quest}),
},
"no_answer_word": sum(c["said"][v] is None for c in train + test + quest),
"judge_ms_held_out": percentiles([c["ms"][v] for c in test]),
}
result["chosen_on_train"] = max(variants, key=lambda v: result["variants"][v]["train_balanced_accuracy"])
out = Path(args.out)
write_json(out / "cases.json", {"train": train, "test": test, "questions": quest})
write_json(out / "judge.json", result)
print(json.dumps(result, indent=1))
if __name__ == "__main__":
asyncio.run(main())
|