File size: 4,820 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 | """The controller on the held-out set (unseen voices, unseen scenarios).
Frame level: precision and recall per label.
Event level, from the events the data builder recorded:
pause handling a mid-sentence pause is handled when no START is predicted in it
turn ends a turn end is caught when START is predicted inside its START window;
the delay is counted from the caller's last frame
interruptions caught when STOP is predicted inside the STOP window
backchannels survived when no STOP is predicted while the caller says "mm-hm"
Whole dialogues are run offline with the banded causal mask, which is the same function
as frame-by-frame serving (tests/test_streaming.py). Raw per-frame predictions are saved.
python -m eval.eval_controller --data data/out/dataset --encoder runs/encoder/final.pt \
--controller runs/controller/final.pt --out eval/results/controller
"""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from controller.encoder.student import load_student
from controller.model.model import load_controller
from duplex.spec import FRAME, LABELS, START, STOP, read_wav, write_json
from duplex.train_utils import confusion, precision_recall
def rate(hits, total):
return {"correct": int(hits), "total": int(total), "accuracy": hits / total if total else None}
@torch.inference_mode()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", required=True)
ap.add_argument("--encoder", required=True)
ap.add_argument("--controller", required=True)
ap.add_argument("--out", default="eval/results/controller")
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--limit", type=int, default=None, help="only the first N held-out dialogues (smoke test)")
args = ap.parse_args()
data, out, device = Path(args.data), Path(args.out), torch.device(args.device)
(out / "pred").mkdir(parents=True, exist_ok=True)
encoder, ctl = load_student(args.encoder, device), load_controller(args.controller, device)
conf = np.zeros((len(LABELS), len(LABELS)), dtype=np.int64)
pauses, turn_ends, stops, backchannels = (np.zeros(2, dtype=np.int64) for _ in range(4)) # [hits, total]
delays, pause_len_ok, pause_len_bad = [], [], []
items = json.loads((data / "index_test.json").read_text())[: args.limit]
for it in items:
wav, _ = read_wav(data / "audio" / f"{it['id']}.wav")
wav = torch.from_numpy(wav[: it["n_frames"] * FRAME].T.copy()).to(device) # [2, T]
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
feats = encoder(wav)
probs = torch.softmax(ctl(feats[0:1], feats[1:2])[0].float(), dim=-1).cpu().numpy()
pred = probs.argmax(-1)
gold = np.load(data / "labels" / f"{it['id']}.npy")
conf += confusion(pred, gold)
np.savez_compressed(out / "pred" / f"{it['id']}.npz", pred=pred.astype(np.uint8), probs=probs.astype(np.float16))
for e in json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]:
window = pred[e["f0"]: e["f1"]] if "f0" in e else None
if e["type"] == "pause" and len(window):
quiet = not (window == START).any()
pauses = pauses + [quiet, 1]
(pause_len_ok if quiet else pause_len_bad).append((e["end"] - e["start"]) / 16000)
elif e["type"] == "start":
hit = np.nonzero(window == START)[0]
turn_ends = turn_ends + [len(hit) > 0, 1]
if len(hit):
delays.append(float(hit[0] + 1) * 80.0) # ms from the caller's last frame to the first START
elif e["type"] == "interrupt" and len(window):
stops = stops + [(window == STOP).any(), 1]
elif e["type"] == "backchannel" and len(window):
backchannels = backchannels + [not (window == STOP).any(), 1]
result = {
"dialogues": len(items), "frames": int(conf.sum()), "per_label": precision_recall(conf), "confusion_rows_true_cols_pred": conf.tolist(),
"pause_handling": rate(*pauses),
"pause_seconds_mean": {"handled": float(np.mean(pause_len_ok)) if pause_len_ok else None,
"started_in_pause": float(np.mean(pause_len_bad)) if pause_len_bad else None},
"turn_end_caught": rate(*turn_ends),
"start_delay_ms": {"p50": float(np.percentile(delays, 50)), "p90": float(np.percentile(delays, 90))} if delays else None,
"interruption_caught": rate(*stops), "backchannel_not_interrupted": rate(*backchannels),
}
write_json(out / "controller.json", result)
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
|