File size: 12,830 Bytes
547c405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""Score SAVA versions against labeled data, on clean audio and through a simulated phone line.

Two of the test sets from the SAVA repository's benchmark, scored the way its scripts score them:

    tenvad    TEN-VAD's 30 hand-labeled recordings: is each 40 ms frame speech?
    pipecat   pipecat's smart-turn test clips: is the turn complete at the clip's end?

Each system is run on every recording as a stream from its start. ``original`` is the PyTorch
model; ONNX files are run one frame at a time by ``sava_onnx``; fine-tuned checkpoints are run as
the original is. The conditions are the lines in ``channels.TEST_CONDITIONS``.
"""

from __future__ import annotations

import argparse
import io
import json
import multiprocessing
import sys
import time
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).parent))  # for sava_onnx when run with python -I

FRAME_SECONDS = 0.04
_systems: dict = {}
_conditions: list[str] = []


def checkpoint_name(path: Path) -> str:
    """``runs/phone-1/best.safetensors`` -> ``phone-1``; other files of a run keep their stem too."""
    return path.parent.name if path.stem == "best" else f"{path.parent.name}-{path.stem}"


def load_systems(args: argparse.Namespace, whole=None) -> dict:
    """``{name: samples -> (speech, turn)}``: the PyTorch original, checkpoints and ONNX files.

    ``whole(model, samples)`` replaces the one-pass run of a PyTorch model, e.g. to bound memory.
    """
    import torch
    from inworld import sava

    import sava_onnx

    torch.set_num_threads(1)

    def pytorch(source: str):
        model = sava.load(source).eval()

        def run(samples: np.ndarray):
            if whole is not None:
                return whole(model, samples)
            curves = sava.run(model, samples)
            return curves.speech, curves.turn

        return run

    systems = {} if args.no_original else {"original": pytorch("inworld/sava")}
    for path in args.checkpoints:
        systems[checkpoint_name(path)] = pytorch(str(path))
    for path in args.versions:
        systems[path.stem.removeprefix("sava.").replace("sava", "onnx")] = sava_onnx.Session(str(path)).run
    return systems


def load_smart_turn(path: Path) -> dict:
    """pipecat smart-turn, run as its own inference code runs it.

    The clip's last 8 s, zero-padded at the front, normalised to zero mean and unit variance, then
    Whisper log-mel features (80 bins, 10 ms hop). Returns the model's end-of-turn probability.
    """
    import onnxruntime as ort
    import torch
    from inworld.sava import mel

    torch.set_num_threads(1)
    options = ort.SessionOptions()
    options.intra_op_num_threads = 1
    session = ort.InferenceSession(str(path), options, providers=["CPUExecutionProvider"])
    window = torch.hann_window(400, dtype=torch.float64)
    filters = mel.mel_filterbank(num_bins=80).double()
    length = 8 * 16000

    def run(samples: np.ndarray):
        tail = samples[-length:] if samples.size >= length else np.pad(samples, (length - samples.size, 0))
        wave = torch.from_numpy(np.ascontiguousarray(tail)).double()
        wave = (wave - wave.mean()) / torch.sqrt(wave.var(unbiased=False) + 1e-7)
        power = torch.stft(wave, 400, 160, window=window, center=True, pad_mode="reflect", return_complex=True).abs() ** 2
        log_spec = torch.clamp(filters @ power[:, :-1], min=1e-10).log10()
        log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
        features = ((log_spec + 4.0) / 4.0).float().numpy()[None]
        probability = session.run(None, {"input_features": features})[0]
        return None, np.array([float(probability.reshape(-1)[0])])

    return {"smart_turn": run}


def conditions_of(samples: np.ndarray, names: list[str]) -> dict[str, np.ndarray]:
    import channels

    return {name: channels.TEST_CONDITIONS[name](samples) for name in names}


# --- TEN-VAD: frame-level speech detection ---------------------------------------------------


def tenvad_recordings(root: Path):
    from inworld.sava import audio

    for label_path in sorted(root.glob("*.scv")):
        fields = label_path.read_text(encoding="utf-8").strip().split(",")
        triples = [fields[i : i + 3] for i in range(1, len(fields) - 2, 3)]
        segments = [(float(s), float(e)) for s, e, label in triples if label.strip() == "1"]
        yield label_path.stem, audio.load(str(label_path.with_suffix(".wav"))), segments


def frame_labels(frames: int, segments: list[tuple[float, float]]) -> np.ndarray:
    """A frame is speech when a labeled segment covers its centre."""
    centres = (np.arange(frames) + 0.5) * FRAME_SECONDS
    labels = np.zeros(frames, dtype=bool)
    for start, end in segments:
        labels |= (centres >= start) & (centres < end)
    return labels


def run_tenvad(args: argparse.Namespace) -> None:
    from sklearn import metrics

    systems = load_systems(args)
    labels, curves = [], {(s, c): [] for s in systems for c in args.conditions}
    for name, samples, segments in tenvad_recordings(args.root):
        for condition, audio in conditions_of(samples, args.conditions).items():
            for system, run in systems.items():
                curves[system, condition].append(run(audio)[0])
        labels.append(frame_labels(next(iter(curves.values()))[-1].size, segments))
        print(f"{name}: {labels[-1].size} frames", file=sys.stderr, flush=True)

    pooled = np.concatenate(labels)
    rng = np.random.default_rng(0)
    draws = [rng.integers(0, len(labels), len(labels)) for _ in range(args.resamples)]

    def auc(curve_list: list[np.ndarray], picks=None) -> float:
        if picks is None:
            return float(metrics.roc_auc_score(pooled, np.concatenate(curve_list)))
        return float(
            metrics.roc_auc_score(
                np.concatenate([labels[i] for i in picks]), np.concatenate([curve_list[i] for i in picks])
            )
        )

    result = {"recordings": len(labels), "frames": int(pooled.size), "speech_fraction": float(pooled.mean()), "systems": {}}
    for (system, condition), curve_list in curves.items():
        probs = np.concatenate(curve_list)
        scores = {
            "auc": auc(curve_list),
            "f1": float(metrics.f1_score(pooled, probs > 0.5)),
            "accuracy": float(((probs > 0.5) == pooled).mean()),
        }
        if system != "original" and ("original", condition) in curves:
            base = curves["original", condition]
            diffs = np.array([auc(curve_list, d) - auc(base, d) for d in draws])
            scores["auc_minus_original"] = scores["auc"] - auc(base)
            scores["auc_minus_original_ci"] = [float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5))]
            scores["frames_flipped"] = float(((probs > 0.5) != (np.concatenate(base) > 0.5)).mean())
        result["systems"][f"{system}/{condition}"] = scores
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8")
    print(json.dumps(result, indent=1))


# --- pipecat smart-turn test: is the turn complete at the clip's end? -------------------------

PIPECAT_COLUMNS = ("id", "language", "endpoint_bool", "synthetic", "dataset", "audio")


def _init_worker(args: argparse.Namespace) -> None:
    _systems.update(load_smart_turn(args.smart_turn) if args.smart_turn else load_systems(args))
    _conditions.extend(args.conditions)


def _score_shard(job: tuple[Path, Path, int | None]) -> int:
    """Score one parquet shard into a JSONL file; clips already in the file are skipped."""
    import soundfile
    from inworld.sava import audio
    from pyarrow import parquet

    shard, out_path, limit = job
    done = set()
    if out_path.exists():
        done = {json.loads(line)["id"] for line in out_path.read_text(encoding="utf-8").splitlines() if line}
    table = parquet.ParquetFile(shard)
    count = 0
    with open(out_path, "a", encoding="utf-8") as out:
        for group in range(table.num_row_groups):
            for row in table.read_row_group(group, columns=list(PIPECAT_COLUMNS)).to_pylist():
                count += 1
                if limit is not None and count > limit:
                    return count - 1
                if row["id"] in done:
                    continue
                samples, rate = soundfile.read(io.BytesIO(row["audio"]["bytes"]), dtype="float32", always_2d=True)
                samples = audio.to_model_rate(samples, rate)
                record = {key: row[key] for key in PIPECAT_COLUMNS if key != "audio"}
                record["seconds"] = samples.size / 16000
                for condition, heard in conditions_of(samples, _conditions).items():
                    for system, run in _systems.items():
                        # The clip's score is the end-of-turn probability at its last frame.
                        record[f"{system}/{condition}"] = float(run(heard)[1][-1])
                out.write(json.dumps(record) + "\n")
                out.flush()
    return count


def run_pipecat(args: argparse.Namespace) -> None:
    shards = sorted(args.root.rglob("*.parquet"))
    if not shards:
        raise FileNotFoundError(f"no parquet shards under {args.root}")
    args.out.mkdir(parents=True, exist_ok=True)
    jobs = [(shard, args.out / f"{shard.stem}.jsonl", args.limit) for shard in shards]
    started = time.time()
    with multiprocessing.Pool(args.workers, _init_worker, (args,)) as pool:
        for clips in pool.imap_unordered(_score_shard, jobs):
            print(f"shard done: {clips} clips, {time.time() - started:.0f} s", file=sys.stderr, flush=True)
    report_pipecat(args)


def report_pipecat(args: argparse.Namespace) -> None:
    from sklearn import metrics

    rows = [json.loads(line) for path in sorted(args.out.glob("*.jsonl")) for line in path.read_text().splitlines() if line]
    labels = np.array([r["endpoint_bool"] for r in rows], dtype=bool)
    keys = [k for k in rows[0] if "/" in k]
    rng = np.random.default_rng(0)
    draws = rng.integers(0, len(rows), (args.resamples, len(rows)))
    result = {"clips": len(rows), "hours": sum(r["seconds"] for r in rows) / 3600, "complete_fraction": float(labels.mean()), "systems": {}}
    correct = {k: (np.array([r[k] for r in rows]) > 0.5) == labels for k in keys}
    for key in keys:
        probs = np.array([r[key] for r in rows])
        scores = {"accuracy": float(correct[key].mean()), "auc": float(metrics.roc_auc_score(labels, probs))}
        system, condition = key.split("/")
        base_key = f"original/{condition}"
        if system != "original" and base_key in correct:
            base = np.array([r[base_key] for r in rows])
            diffs = correct[key][draws].mean(axis=1) - correct[base_key][draws].mean(axis=1)
            scores["accuracy_minus_original"] = scores["accuracy"] - float(correct[base_key].mean())
            scores["accuracy_minus_original_ci"] = [float(np.percentile(diffs, 2.5)), float(np.percentile(diffs, 97.5))]
            scores["clips_flipped"] = float(((probs > 0.5) != (base > 0.5)).mean())
            scores["mean_change"] = float(np.abs(probs - base).mean())
        result["systems"][key] = scores
    (args.out / "summary.json").write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8")
    print(json.dumps(result, indent=1))


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    commands = parser.add_subparsers(dest="command", required=True)
    for name in ("tenvad", "pipecat", "pipecat-report"):
        command = commands.add_parser(name)
        command.add_argument("--root", type=Path, help="the dataset download")
        command.add_argument("--out", type=Path, required=True)
        command.add_argument("--versions", type=Path, nargs="*", default=[Path("build/sava.onnx"), Path("build/sava.int8.onnx")], help="ONNX files")
        command.add_argument("--checkpoints", type=Path, nargs="*", default=[], help="fine-tuned safetensors files")
        command.add_argument("--no-original", action="store_true", help="leave the PyTorch original out")
        command.add_argument("--conditions", nargs="+", default=["clean", "phone"], help="lines from channels.TEST_CONDITIONS")
        command.add_argument("--resamples", type=int, default=2000)
        command.add_argument("--workers", type=int, default=8)
        command.add_argument("--limit", type=int, default=None, help="clips per shard (pipecat)")
        command.add_argument("--smart-turn", type=Path, default=None, help="score pipecat's smart-turn ONNX file instead of SAVA")
    args = parser.parse_args()
    {"tenvad": run_tenvad, "pipecat": run_pipecat, "pipecat-report": report_pipecat}[args.command](args)


if __name__ == "__main__":
    main()