Let evaluation run in batches and on a stratified sample
Browse filesReproducing the Arabic Little STT benchmark means scoring a dozen checkpoints on
the same held-out speakers, and `evaluate` transcribed one clip per forward
pass. The test split is 4,073 utterances; at that rate a single large checkpoint
is most of an hour and the sweep does not fit in a session.
Batch the generate call. Whisper pads every clip to the same 30 s window, so a
batch costs one forward pass rather than `batch_size` of them. Batches are
grouped by language first, because the language token rides in the decoder
prompt and one `generate` call carries a single prompt for the whole batch.
Verified identical: batch_size 1 and 4 produce the same WER, the same CER, and
the same hypothesis for every utterance.
`--limit` takes a speaker-stratified sample instead of the whole manifest.
Uniform sampling would let the child with the most recordings dominate a small
draw, moving the score for reasons unrelated to the model, so it draws from each
speaker in turn. Seeded, since a benchmark whose numbers move between runs
cannot be compared with anything, and the metrics now record how many utterances
were scored out of how many exist -- a subsampled result should never be
readable as a full one.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uis9uRynosX69gefzFQeNN
- src/buddi_asr/cli.py +11 -0
- src/buddi_asr/evaluate.py +89 -29
- tests/test_evaluate_sampling.py +64 -0
|
@@ -198,6 +198,14 @@ def build_parser() -> argparse.ArgumentParser:
|
|
| 198 |
evaluate.add_argument("output_dir")
|
| 199 |
evaluate.add_argument("--device", choices=("auto", "cpu", "cuda", "mps"), default="auto")
|
| 200 |
evaluate.add_argument("--max-new-tokens", type=int, default=128)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
merge = commands.add_parser("merge-lora", help="Merge a LoRA adapter into its Whisper base")
|
| 203 |
merge.add_argument("base_model")
|
|
@@ -304,6 +312,9 @@ def dispatch(args: argparse.Namespace) -> dict[str, Any]:
|
|
| 304 |
args.output_dir,
|
| 305 |
device=args.device,
|
| 306 |
max_new_tokens=args.max_new_tokens,
|
|
|
|
|
|
|
|
|
|
| 307 |
)
|
| 308 |
if args.command == "merge-lora":
|
| 309 |
return merge_lora_adapter(args.base_model, args.adapter_dir, args.output_dir)
|
|
|
|
| 198 |
evaluate.add_argument("output_dir")
|
| 199 |
evaluate.add_argument("--device", choices=("auto", "cpu", "cuda", "mps"), default="auto")
|
| 200 |
evaluate.add_argument("--max-new-tokens", type=int, default=128)
|
| 201 |
+
evaluate.add_argument("--batch-size", type=int, default=1)
|
| 202 |
+
evaluate.add_argument(
|
| 203 |
+
"--limit",
|
| 204 |
+
type=int,
|
| 205 |
+
default=0,
|
| 206 |
+
help="Evaluate a speaker-stratified sample of this size (0 = the whole manifest)",
|
| 207 |
+
)
|
| 208 |
+
evaluate.add_argument("--seed", type=int, default=42, help="Seed for --limit sampling")
|
| 209 |
|
| 210 |
merge = commands.add_parser("merge-lora", help="Merge a LoRA adapter into its Whisper base")
|
| 211 |
merge.add_argument("base_model")
|
|
|
|
| 312 |
args.output_dir,
|
| 313 |
device=args.device,
|
| 314 |
max_new_tokens=args.max_new_tokens,
|
| 315 |
+
batch_size=args.batch_size,
|
| 316 |
+
limit=args.limit,
|
| 317 |
+
seed=args.seed,
|
| 318 |
)
|
| 319 |
if args.command == "merge-lora":
|
| 320 |
return merge_lora_adapter(args.base_model, args.adapter_dir, args.output_dir)
|
|
@@ -3,6 +3,7 @@
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import json
|
|
|
|
| 6 |
from collections import defaultdict
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any
|
|
@@ -25,6 +26,43 @@ def _device_and_dtype(torch: Any, requested: str) -> tuple[str, Any]:
|
|
| 25 |
return requested, torch.float32
|
| 26 |
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
def evaluate_hf_model(
|
| 29 |
model_path: str | Path,
|
| 30 |
manifest_path: str | Path,
|
|
@@ -32,6 +70,9 @@ def evaluate_hf_model(
|
|
| 32 |
*,
|
| 33 |
device: str = "auto",
|
| 34 |
max_new_tokens: int = 128,
|
|
|
|
|
|
|
|
|
|
| 35 |
) -> dict[str, Any]:
|
| 36 |
try:
|
| 37 |
import librosa
|
|
@@ -65,37 +106,53 @@ def evaluate_hf_model(
|
|
| 65 |
model.to(selected_device)
|
| 66 |
model.eval()
|
| 67 |
|
|
|
|
|
|
|
|
|
|
| 68 |
rows: list[dict[str, Any]] = []
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
"
|
| 89 |
-
"
|
| 90 |
-
"age_group": record.age_group,
|
| 91 |
-
"source": record.source,
|
| 92 |
-
"category": record.category,
|
| 93 |
-
"reference": record.text,
|
| 94 |
-
"hypothesis": hypothesis,
|
| 95 |
-
"normalized_reference": normalize_for_metrics(record.text),
|
| 96 |
-
"normalized_hypothesis": normalize_for_metrics(hypothesis),
|
| 97 |
}
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
predictions_path = destination / "predictions.jsonl"
|
| 101 |
with predictions_path.open("w", encoding="utf-8", newline="\n") as handle:
|
|
@@ -119,6 +176,9 @@ def evaluate_hf_model(
|
|
| 119 |
"manifest": str(manifest_location),
|
| 120 |
"device": selected_device,
|
| 121 |
"overall": score(rows),
|
|
|
|
|
|
|
|
|
|
| 122 |
"breakdowns": breakdowns,
|
| 123 |
"predictions": str(predictions_path),
|
| 124 |
"warning": "Review predictions before sharing; transcript text may be sensitive.",
|
|
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import json
|
| 6 |
+
import random
|
| 7 |
from collections import defaultdict
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Any
|
|
|
|
| 26 |
return requested, torch.float32
|
| 27 |
|
| 28 |
|
| 29 |
+
def stratified_sample(records: list[Any], limit: int, seed: int) -> list[Any]:
|
| 30 |
+
"""Take `limit` records, spread evenly across speakers, deterministically.
|
| 31 |
+
|
| 32 |
+
Benchmarking a dozen checkpoints over a full test split costs GPU hours that
|
| 33 |
+
buy no extra confidence, so the split gets subsampled. Sampling uniformly
|
| 34 |
+
would let the loudest speaker dominate a small draw and would move the score
|
| 35 |
+
for reasons that have nothing to do with the model, so take from each
|
| 36 |
+
speaker in turn instead. Seeded, because a benchmark whose numbers shift
|
| 37 |
+
between runs cannot be compared against anything.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
if limit <= 0 or limit >= len(records):
|
| 41 |
+
return records
|
| 42 |
+
by_speaker: dict[str, list[Any]] = defaultdict(list)
|
| 43 |
+
for record in records:
|
| 44 |
+
by_speaker[record.speaker_id].append(record)
|
| 45 |
+
rng = random.Random(seed)
|
| 46 |
+
queues = []
|
| 47 |
+
for speaker in sorted(by_speaker):
|
| 48 |
+
group = by_speaker[speaker][:]
|
| 49 |
+
rng.shuffle(group)
|
| 50 |
+
queues.append(group)
|
| 51 |
+
rng.shuffle(queues)
|
| 52 |
+
picked: list[Any] = []
|
| 53 |
+
position = 0
|
| 54 |
+
while len(picked) < limit:
|
| 55 |
+
available = [queue for queue in queues if position < len(queue)]
|
| 56 |
+
if not available:
|
| 57 |
+
break
|
| 58 |
+
for queue in available:
|
| 59 |
+
picked.append(queue[position])
|
| 60 |
+
if len(picked) == limit:
|
| 61 |
+
break
|
| 62 |
+
position += 1
|
| 63 |
+
return picked
|
| 64 |
+
|
| 65 |
+
|
| 66 |
def evaluate_hf_model(
|
| 67 |
model_path: str | Path,
|
| 68 |
manifest_path: str | Path,
|
|
|
|
| 70 |
*,
|
| 71 |
device: str = "auto",
|
| 72 |
max_new_tokens: int = 128,
|
| 73 |
+
batch_size: int = 1,
|
| 74 |
+
limit: int = 0,
|
| 75 |
+
seed: int = 42,
|
| 76 |
) -> dict[str, Any]:
|
| 77 |
try:
|
| 78 |
import librosa
|
|
|
|
| 106 |
model.to(selected_device)
|
| 107 |
model.eval()
|
| 108 |
|
| 109 |
+
records = list(read_manifest(manifest_location))
|
| 110 |
+
sampled = stratified_sample(records, limit, seed)
|
| 111 |
+
|
| 112 |
rows: list[dict[str, Any]] = []
|
| 113 |
+
# Whisper pads every clip to the same 30 s window, so a batch costs one
|
| 114 |
+
# forward pass instead of `batch_size` of them. Grouping by language keeps
|
| 115 |
+
# that legal: the decoder prompt carries the language token, and one
|
| 116 |
+
# `generate` call takes a single prompt for the whole batch.
|
| 117 |
+
for index in range(0, len(sampled), max(1, batch_size)):
|
| 118 |
+
chunk = sampled[index : index + max(1, batch_size)]
|
| 119 |
+
for language in sorted({record.language for record in chunk}):
|
| 120 |
+
group = [record for record in chunk if record.language == language]
|
| 121 |
+
waveforms = [
|
| 122 |
+
librosa.load(
|
| 123 |
+
resolve_audio_path(record, manifest_location), sr=16000, mono=True
|
| 124 |
+
)[0]
|
| 125 |
+
for record in group
|
| 126 |
+
]
|
| 127 |
+
inputs = processor.feature_extractor(
|
| 128 |
+
waveforms, sampling_rate=16000, return_tensors="pt"
|
| 129 |
+
)
|
| 130 |
+
input_features = inputs.input_features.to(selected_device, dtype=dtype)
|
| 131 |
+
generate_kwargs: dict[str, Any] = {
|
| 132 |
+
"task": "transcribe",
|
| 133 |
+
"max_new_tokens": max_new_tokens,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
}
|
| 135 |
+
if language in {"ar", "en"}:
|
| 136 |
+
generate_kwargs["language"] = language
|
| 137 |
+
with torch.inference_mode():
|
| 138 |
+
generated = model.generate(input_features, **generate_kwargs)
|
| 139 |
+
hypotheses = processor.tokenizer.batch_decode(generated, skip_special_tokens=True)
|
| 140 |
+
for record, hypothesis in zip(group, hypotheses, strict=True):
|
| 141 |
+
rows.append(
|
| 142 |
+
{
|
| 143 |
+
"source_file_id": record.metadata.get("source_file_id"),
|
| 144 |
+
"speaker_id": record.speaker_id,
|
| 145 |
+
"language": record.language,
|
| 146 |
+
"dialect": record.dialect,
|
| 147 |
+
"age_group": record.age_group,
|
| 148 |
+
"source": record.source,
|
| 149 |
+
"category": record.category,
|
| 150 |
+
"reference": record.text,
|
| 151 |
+
"hypothesis": hypothesis,
|
| 152 |
+
"normalized_reference": normalize_for_metrics(record.text),
|
| 153 |
+
"normalized_hypothesis": normalize_for_metrics(hypothesis),
|
| 154 |
+
}
|
| 155 |
+
)
|
| 156 |
|
| 157 |
predictions_path = destination / "predictions.jsonl"
|
| 158 |
with predictions_path.open("w", encoding="utf-8", newline="\n") as handle:
|
|
|
|
| 176 |
"manifest": str(manifest_location),
|
| 177 |
"device": selected_device,
|
| 178 |
"overall": score(rows),
|
| 179 |
+
"evaluated_utterances": len(rows),
|
| 180 |
+
"manifest_utterances": len(records),
|
| 181 |
+
"sample_seed": seed if limit else None,
|
| 182 |
"breakdowns": breakdowns,
|
| 183 |
"predictions": str(predictions_path),
|
| 184 |
"warning": "Review predictions before sharing; transcript text may be sensitive.",
|
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
from collections import Counter
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
from buddi_asr.evaluate import stratified_sample
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class FakeRecord:
|
| 12 |
+
speaker_id: str
|
| 13 |
+
index: int
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def build(speakers: dict[str, int]) -> list[FakeRecord]:
|
| 17 |
+
records = []
|
| 18 |
+
for speaker, count in speakers.items():
|
| 19 |
+
records.extend(FakeRecord(speaker, i) for i in range(count))
|
| 20 |
+
return records
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class StratifiedSampleTests(unittest.TestCase):
|
| 24 |
+
def test_small_limit_spreads_across_speakers(self) -> None:
|
| 25 |
+
# One speaker with ten times the utterances of the others must not take
|
| 26 |
+
# ten times the sample, or the score tracks that child rather than the
|
| 27 |
+
# model.
|
| 28 |
+
records = build({"loud": 100, "a": 10, "b": 10, "c": 10})
|
| 29 |
+
picked = stratified_sample(records, 12, seed=42)
|
| 30 |
+
counts = Counter(record.speaker_id for record in picked)
|
| 31 |
+
self.assertEqual(len(picked), 12)
|
| 32 |
+
self.assertEqual(set(counts), {"loud", "a", "b", "c"})
|
| 33 |
+
self.assertEqual(max(counts.values()) - min(counts.values()), 0)
|
| 34 |
+
|
| 35 |
+
def test_it_is_deterministic(self) -> None:
|
| 36 |
+
records = build({"a": 20, "b": 20, "c": 20})
|
| 37 |
+
first = stratified_sample(records, 15, seed=7)
|
| 38 |
+
second = stratified_sample(records, 15, seed=7)
|
| 39 |
+
self.assertEqual([(r.speaker_id, r.index) for r in first],
|
| 40 |
+
[(r.speaker_id, r.index) for r in second])
|
| 41 |
+
|
| 42 |
+
def test_a_different_seed_draws_differently(self) -> None:
|
| 43 |
+
records = build({"a": 20, "b": 20, "c": 20})
|
| 44 |
+
first = stratified_sample(records, 15, seed=7)
|
| 45 |
+
second = stratified_sample(records, 15, seed=8)
|
| 46 |
+
self.assertNotEqual([(r.speaker_id, r.index) for r in first],
|
| 47 |
+
[(r.speaker_id, r.index) for r in second])
|
| 48 |
+
|
| 49 |
+
def test_no_limit_returns_everything_untouched(self) -> None:
|
| 50 |
+
records = build({"a": 5, "b": 5})
|
| 51 |
+
self.assertIs(stratified_sample(records, 0, seed=1), records)
|
| 52 |
+
self.assertIs(stratified_sample(records, 99, seed=1), records)
|
| 53 |
+
|
| 54 |
+
def test_limit_larger_than_a_speakers_supply_still_fills(self) -> None:
|
| 55 |
+
# "b" runs out after 2; the sample must keep drawing from "a" rather
|
| 56 |
+
# than stopping short of the requested size.
|
| 57 |
+
records = build({"a": 20, "b": 2})
|
| 58 |
+
picked = stratified_sample(records, 10, seed=3)
|
| 59 |
+
self.assertEqual(len(picked), 10)
|
| 60 |
+
|
| 61 |
+
def test_it_never_repeats_a_record(self) -> None:
|
| 62 |
+
records = build({"a": 20, "b": 20, "c": 20})
|
| 63 |
+
picked = stratified_sample(records, 40, seed=5)
|
| 64 |
+
self.assertEqual(len({id(record) for record in picked}), 40)
|