Spaces:
Running
Running
Bench packed Musci prefill and cache retention on expanded public Open ASR suite
Browse files- README.md +3 -1
- evaluate.py +34 -8
- krokomusci/model.py +15 -5
- krokomusci/packed_prefill.py +115 -0
- krokomusci_backend.py +22 -2
- normalizer/voice_code_data.py +42 -0
- public/index.html +3 -1
- run_eval.py +63 -7
- run_fusion_eval.py +6 -3
- suite.json +12 -1
README.md
CHANGED
|
@@ -10,8 +10,10 @@ short_description: KrokoMusci WER and throughput on one NVIDIA H200
|
|
| 10 |
|
| 11 |
# KrokoMusci Open ASR
|
| 12 |
|
| 13 |
-
This Space evaluates the released Kroko checkpoint with Musci and fusion settings tuned on development and training data. It
|
| 14 |
|
| 15 |
The evaluator reports mean WER by giving each dataset equal weight. RTFx includes audio transport and synchronized inference. Model and dataset revisions are pinned. [Kroko export](https://huggingface.co/Banafo/Kroko-ASR-XL-EN-Offline/tree/8c1fb9b89831c6cd9f63d0295f2ccb2be6da2964/fast-gpu-asr) · [Musci and Qwen revisions](models.json) · [Benchmark suite](suite.json)
|
| 16 |
|
| 17 |
The Space provides the Docker image for the H200 benchmark job. Results are saved to the private bucket, and the app reads progress and the final summary from the configured run directory.
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# KrokoMusci Open ASR
|
| 12 |
|
| 13 |
+
This Space evaluates the released Kroko checkpoint with Musci and fusion settings tuned on development and training data. It uses one NVIDIA H200, batch size 256, one worker and the published beam-6 FP16 Kroko export.
|
| 14 |
|
| 15 |
The evaluator reports mean WER by giving each dataset equal weight. RTFx includes audio transport and synchronized inference. Model and dataset revisions are pinned. [Kroko export](https://huggingface.co/Banafo/Kroko-ASR-XL-EN-Offline/tree/8c1fb9b89831c6cd9f63d0295f2ccb2be6da2964/fast-gpu-asr) · [Musci and Qwen revisions](models.json) · [Benchmark suite](suite.json)
|
| 16 |
|
| 17 |
The Space provides the Docker image for the H200 benchmark job. Results are saved to the private bucket, and the app reads progress and the final summary from the configured run directory.
|
| 18 |
+
|
| 19 |
+
The expanded run includes VoiceCodeBench, Common Voice, TED-LIUM and the original AMI, GigaSpeech, VoxPopuli and Earnings22 splits. It also benchmarks packed Musci prefill and reuses CUDA allocations between calls.
|
evaluate.py
CHANGED
|
@@ -48,6 +48,12 @@ def parse_args(argv=None):
|
|
| 48 |
parser.add_argument("--engine-cache", type=Path, default=Path("/tmp/kroko-engines"))
|
| 49 |
parser.add_argument("--dry-run", action="store_true")
|
| 50 |
args = parser.parse_args(argv)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", args.model_id):
|
| 52 |
parser.error("--model-id must be owner/repository")
|
| 53 |
if not re.fullmatch(r"[0-9a-f]{40}", args.model_revision):
|
|
@@ -69,7 +75,10 @@ def load_suite():
|
|
| 69 |
rows = suite["datasets"]
|
| 70 |
if len(rows) != 10 or len({row["id"] for row in rows}) != 10:
|
| 71 |
raise ValueError("The complete suite must contain ten unique test sets")
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
| 73 |
if not re.fullmatch(r"[0-9a-f]{40}", suite["dataset_revisions"][row["repo"]]):
|
| 74 |
raise ValueError("Every evaluation dataset must have an immutable revision")
|
| 75 |
return suite
|
|
@@ -80,6 +89,12 @@ def build_plan(args):
|
|
| 80 |
rows = suite["datasets"]
|
| 81 |
if args.mode == "smoke":
|
| 82 |
rows = [row for row in rows if row["id"] == "librispeech_clean"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
plan = []
|
| 84 |
for row in rows:
|
| 85 |
command = [sys.executable, str(ROOT / "run_eval.py"),
|
|
@@ -98,6 +113,8 @@ def build_plan(args):
|
|
| 98 |
"--dataset-path", row["repo"], "--dataset", row["config"],
|
| 99 |
"--dataset-revision", suite["dataset_revisions"][row["repo"]],
|
| 100 |
"--split", row["split"], "--max-eval-samples", "3" if args.mode == "smoke" else "-1"]
|
|
|
|
|
|
|
| 101 |
plan.append({"dataset": row, "command": command, "cwd": str(args.output_dir / row["id"])})
|
| 102 |
return plan
|
| 103 |
|
|
@@ -145,6 +162,13 @@ def score_split(item, model_revision):
|
|
| 145 |
rows = read_manifest(manifest)
|
| 146 |
seconds, elapsed = validate_manifest(rows, metadata, model_revision)
|
| 147 |
sessions = merge_chunked_manifest(rows)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
normalizer = EnglishTextNormalizer()
|
| 149 |
refs = [tuple(normalizer(row["text"]).split()) for row in sessions]
|
| 150 |
predictions = [tuple(normalizer(row["pred_text"]).split()) for row in sessions]
|
|
@@ -177,7 +201,7 @@ def execute(args, *, release_check=None, run_command=None, score=None):
|
|
| 177 |
score = score or score_split
|
| 178 |
status = {"state": "preflight", "mode": args.mode, "started_at": now(),
|
| 179 |
"model_id": args.model_id, "model_revision": args.model_revision,
|
| 180 |
-
"completed_datasets": []}
|
| 181 |
write_json(args.output_dir / "status.json", status)
|
| 182 |
write_json(args.output_dir / "plan.json", {"suite": load_suite(), "jobs": plan})
|
| 183 |
try:
|
|
@@ -209,20 +233,22 @@ def execute(args, *, release_check=None, run_command=None, score=None):
|
|
| 209 |
status["completed_datasets"].append(row["id"])
|
| 210 |
write_json(args.output_dir / "status.json", status)
|
| 211 |
print(f"{row['id']}: WER {row['WER_percent']:.4f}%, RTFx {row['RTFx']:.2f}", flush=True)
|
| 212 |
-
if
|
| 213 |
raise ValueError("A partial suite cannot be marked complete")
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
| 216 |
summary = {"model_id": args.model_id, "model_revision": args.model_revision,
|
| 217 |
"mode": args.mode, "complete": True, "completed_at": now(),
|
| 218 |
"scope": "ten public test sets" if args.mode == "full" else "three-clip smoke test; not a benchmark",
|
| 219 |
"official_leaderboard_result": False, "datasets": results,
|
| 220 |
-
"macro_WER_percent": sum(row["WER_percent"] for row in
|
| 221 |
"pooled_RTFx": seconds / elapsed, "audio_seconds": seconds, "inference_seconds": elapsed,
|
| 222 |
"beam": args.beam,
|
| 223 |
"notes": f"RNN-T beam {args.beam}. This explicitly defined public-suite mean is not the live leaderboard default aggregate."}
|
| 224 |
if args.mode == "full":
|
| 225 |
-
default_public = [row for row in
|
| 226 |
if len(default_public) != 7:
|
| 227 |
raise ValueError("Expected seven default public Open ASR splits")
|
| 228 |
summary["open_asr_public"] = {
|
|
@@ -231,7 +257,7 @@ def execute(args, *, release_check=None, run_command=None, score=None):
|
|
| 231 |
"pooled_RTFx": math.fsum(row["audio_seconds"] for row in rows)
|
| 232 |
/ math.fsum(row["inference_seconds"] for row in rows),
|
| 233 |
}
|
| 234 |
-
for name, rows in (("default_seven", default_public), ("all_ten",
|
| 235 |
}
|
| 236 |
write_json(args.output_dir / "summary.json", summary)
|
| 237 |
status.update(state="complete", finished_at=now())
|
|
|
|
| 48 |
parser.add_argument("--engine-cache", type=Path, default=Path("/tmp/kroko-engines"))
|
| 49 |
parser.add_argument("--dry-run", action="store_true")
|
| 50 |
args = parser.parse_args(argv)
|
| 51 |
+
for option in ("voicecode", "extra_public"):
|
| 52 |
+
variable = f"KM_INCLUDE_{option.upper()}"
|
| 53 |
+
enabled = os.environ.get(variable, "0")
|
| 54 |
+
if enabled not in ("0", "1"):
|
| 55 |
+
parser.error(f"{variable} must be 0 or 1")
|
| 56 |
+
setattr(args, f"include_{option}", args.mode == "full" and enabled == "1")
|
| 57 |
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", args.model_id):
|
| 58 |
parser.error("--model-id must be owner/repository")
|
| 59 |
if not re.fullmatch(r"[0-9a-f]{40}", args.model_revision):
|
|
|
|
| 75 |
rows = suite["datasets"]
|
| 76 |
if len(rows) != 10 or len({row["id"] for row in rows}) != 10:
|
| 77 |
raise ValueError("The complete suite must contain ten unique test sets")
|
| 78 |
+
all_rows = rows + suite.get("optional_datasets", [])
|
| 79 |
+
if len({row["id"] for row in all_rows}) != len(all_rows):
|
| 80 |
+
raise ValueError("Dataset IDs must also be unique across optional test sets")
|
| 81 |
+
for row in all_rows:
|
| 82 |
if not re.fullmatch(r"[0-9a-f]{40}", suite["dataset_revisions"][row["repo"]]):
|
| 83 |
raise ValueError("Every evaluation dataset must have an immutable revision")
|
| 84 |
return suite
|
|
|
|
| 89 |
rows = suite["datasets"]
|
| 90 |
if args.mode == "smoke":
|
| 91 |
rows = [row for row in rows if row["id"] == "librispeech_clean"]
|
| 92 |
+
else:
|
| 93 |
+
optional = {row["id"]: row for row in suite.get("optional_datasets", [])}
|
| 94 |
+
voice = [optional["voice_code_bench"]] if getattr(args, "include_voicecode", False) else []
|
| 95 |
+
extra = [row for name, row in optional.items() if name != "voice_code_bench"
|
| 96 |
+
and getattr(args, "include_extra_public", False)]
|
| 97 |
+
rows = [rows[0], *voice, *rows[1:], *extra]
|
| 98 |
plan = []
|
| 99 |
for row in rows:
|
| 100 |
command = [sys.executable, str(ROOT / "run_eval.py"),
|
|
|
|
| 113 |
"--dataset-path", row["repo"], "--dataset", row["config"],
|
| 114 |
"--dataset-revision", suite["dataset_revisions"][row["repo"]],
|
| 115 |
"--split", row["split"], "--max-eval-samples", "3" if args.mode == "smoke" else "-1"]
|
| 116 |
+
if row.get("chunk_long_audio"):
|
| 117 |
+
command.append("--chunk-long-audio")
|
| 118 |
plan.append({"dataset": row, "command": command, "cwd": str(args.output_dir / row["id"])})
|
| 119 |
return plan
|
| 120 |
|
|
|
|
| 162 |
rows = read_manifest(manifest)
|
| 163 |
seconds, elapsed = validate_manifest(rows, metadata, model_revision)
|
| 164 |
sessions = merge_chunked_manifest(rows)
|
| 165 |
+
if item["dataset"]["id"] == "voice_code_bench":
|
| 166 |
+
from normalizer.voice_code_data import DATASET_REVISION, RECORDINGS
|
| 167 |
+
|
| 168 |
+
if (len(sessions) != RECORDINGS or len({row.get("audio_id") for row in sessions}) != RECORDINGS
|
| 169 |
+
or any(not row.get("audio_id") or row.get("voice_code_bench_revision") != DATASET_REVISION
|
| 170 |
+
for row in sessions)):
|
| 171 |
+
raise ValueError("VoiceCodeBench requires one prediction for each of its 300 pinned recordings")
|
| 172 |
normalizer = EnglishTextNormalizer()
|
| 173 |
refs = [tuple(normalizer(row["text"]).split()) for row in sessions]
|
| 174 |
predictions = [tuple(normalizer(row["pred_text"]).split()) for row in sessions]
|
|
|
|
| 201 |
score = score or score_split
|
| 202 |
status = {"state": "preflight", "mode": args.mode, "started_at": now(),
|
| 203 |
"model_id": args.model_id, "model_revision": args.model_revision,
|
| 204 |
+
"completed_datasets": [], "expected_datasets": len(plan)}
|
| 205 |
write_json(args.output_dir / "status.json", status)
|
| 206 |
write_json(args.output_dir / "plan.json", {"suite": load_suite(), "jobs": plan})
|
| 207 |
try:
|
|
|
|
| 233 |
status["completed_datasets"].append(row["id"])
|
| 234 |
write_json(args.output_dir / "status.json", status)
|
| 235 |
print(f"{row['id']}: WER {row['WER_percent']:.4f}%, RTFx {row['RTFx']:.2f}", flush=True)
|
| 236 |
+
if len(results) != len(plan):
|
| 237 |
raise ValueError("A partial suite cannot be marked complete")
|
| 238 |
+
historical_ids = {row["id"] for row in load_suite()["datasets"]}
|
| 239 |
+
historical = [row for row in results if row["id"] in historical_ids]
|
| 240 |
+
seconds = sum(row["audio_seconds"] for row in historical)
|
| 241 |
+
elapsed = sum(row["inference_seconds"] for row in historical)
|
| 242 |
summary = {"model_id": args.model_id, "model_revision": args.model_revision,
|
| 243 |
"mode": args.mode, "complete": True, "completed_at": now(),
|
| 244 |
"scope": "ten public test sets" if args.mode == "full" else "three-clip smoke test; not a benchmark",
|
| 245 |
"official_leaderboard_result": False, "datasets": results,
|
| 246 |
+
"macro_WER_percent": sum(row["WER_percent"] for row in historical) / len(historical),
|
| 247 |
"pooled_RTFx": seconds / elapsed, "audio_seconds": seconds, "inference_seconds": elapsed,
|
| 248 |
"beam": args.beam,
|
| 249 |
"notes": f"RNN-T beam {args.beam}. This explicitly defined public-suite mean is not the live leaderboard default aggregate."}
|
| 250 |
if args.mode == "full":
|
| 251 |
+
default_public = [row for row in historical if row["id"] not in EXTRA_PUBLIC]
|
| 252 |
if len(default_public) != 7:
|
| 253 |
raise ValueError("Expected seven default public Open ASR splits")
|
| 254 |
summary["open_asr_public"] = {
|
|
|
|
| 257 |
"pooled_RTFx": math.fsum(row["audio_seconds"] for row in rows)
|
| 258 |
/ math.fsum(row["inference_seconds"] for row in rows),
|
| 259 |
}
|
| 260 |
+
for name, rows in (("default_seven", default_public), ("all_ten", historical))
|
| 261 |
}
|
| 262 |
write_json(args.output_dir / "summary.json", summary)
|
| 263 |
status.update(state="complete", finished_at=now())
|
krokomusci/model.py
CHANGED
|
@@ -14,6 +14,7 @@ Per call (in blocks of `block` clips, longest first):
|
|
| 14 |
"""
|
| 15 |
import json, os, threading, time
|
| 16 |
from . import _paths # noqa: F401 (makes fast_gpu_asr / cupy / tensorrt importable; must come before them)
|
|
|
|
| 17 |
import numpy as np, torch
|
| 18 |
|
| 19 |
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -55,6 +56,11 @@ class KrokoMusci:
|
|
| 55 |
audio_batched=cfg.get('audio_batched', False), score_batched=cfg.get('score_batched', False),
|
| 56 |
features_gpu=cfg.get('features_gpu', False), fast_step=cfg.get('fast_step', False),
|
| 57 |
fast_step_graphs=cfg.get('fast_step_graphs', False))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
self.asr = fast_gpu_asr.ASR(cfg['kroko_bundle'], device_id=device_id)
|
| 59 |
self.capacity = self.asr.encoder.batch_size; self.max_samples = self.asr.encoder.max_samples
|
| 60 |
j = np.load(cfg['kroko_joiner_output'] if os.path.isabs(cfg['kroko_joiner_output']) else os.path.join(HERE, cfg['kroko_joiner_output']))
|
|
@@ -107,10 +113,13 @@ class KrokoMusci:
|
|
| 107 |
ktext = [t.strip() for t in ktext]
|
| 108 |
self._sync(); t1 = time.perf_counter()
|
| 109 |
cs0 = self.llm.stats['cont_seconds']
|
| 110 |
-
if self.
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
| 114 |
self._sync(); t2 = time.perf_counter() - (self.llm.stats['cont_seconds'] - cs0) # the writing done inside the check loop counts as writing
|
| 115 |
dis = [i for i in range(n) if disputed(chk[i][0], chk[i][1], self.threshold)]
|
| 116 |
if self.writing == 'continue': assert [i for i in range(n) if chk[i][3] is not None] == dis
|
|
@@ -162,7 +171,8 @@ class KrokoMusci:
|
|
| 162 |
out[idx[i]] = d if details else d['text']
|
| 163 |
t6 = time.perf_counter()
|
| 164 |
del encs
|
| 165 |
-
if self.writing == 'continue'
|
|
|
|
| 166 |
T['kroko'] += t1 - t0; T['check'] += t2 - t1; T['write'] += t3 - t2; T['rescore'] += t5 - t4; T['text'] += (t4 - t3) + (t6 - t5); T['total'] += t6 - t0
|
| 167 |
T['audio'] += sum(a.size for a in A) / 16000; T['clips'] += n; T['disputed'] += len(dis); T['disputed_audio'] += sum(A[i].size for i in dis) / 16000
|
| 168 |
if self.verbose:
|
|
|
|
| 14 |
"""
|
| 15 |
import json, os, threading, time
|
| 16 |
from . import _paths # noqa: F401 (makes fast_gpu_asr / cupy / tensorrt importable; must come before them)
|
| 17 |
+
from contextlib import nullcontext
|
| 18 |
import numpy as np, torch
|
| 19 |
|
| 20 |
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
| 56 |
audio_batched=cfg.get('audio_batched', False), score_batched=cfg.get('score_batched', False),
|
| 57 |
features_gpu=cfg.get('features_gpu', False), fast_step=cfg.get('fast_step', False),
|
| 58 |
fast_step_graphs=cfg.get('fast_step_graphs', False))
|
| 59 |
+
self.packed_prefill = None
|
| 60 |
+
if cfg.get('packed_prefill', False):
|
| 61 |
+
from .packed_prefill import PackedPrefill
|
| 62 |
+
self.packed_prefill = PackedPrefill(self.llm)
|
| 63 |
+
self.retain_block_cache = bool(cfg.get('retain_block_cache', False))
|
| 64 |
self.asr = fast_gpu_asr.ASR(cfg['kroko_bundle'], device_id=device_id)
|
| 65 |
self.capacity = self.asr.encoder.batch_size; self.max_samples = self.asr.encoder.max_samples
|
| 66 |
j = np.load(cfg['kroko_joiner_output'] if os.path.isabs(cfg['kroko_joiner_output']) else os.path.join(HERE, cfg['kroko_joiner_output']))
|
|
|
|
| 113 |
ktext = [t.strip() for t in ktext]
|
| 114 |
self._sync(); t1 = time.perf_counter()
|
| 115 |
cs0 = self.llm.stats['cont_seconds']
|
| 116 |
+
check_context = self.packed_prefill.install() if self.packed_prefill is not None else nullcontext()
|
| 117 |
+
with check_context:
|
| 118 |
+
if self.writing == 'continue':
|
| 119 |
+
chk = self.llm.check(A, ktext, self.llm_batch, cont=dict(max_patch_places=self.max_patch_places, cap=self.patch_steps,
|
| 120 |
+
max_new=self.cfg.get('llm_max_new_tokens', 512), threshold=self.threshold, **self.cont_cfg))
|
| 121 |
+
else:
|
| 122 |
+
chk = self.llm.check(A, ktext, self.llm_batch)
|
| 123 |
self._sync(); t2 = time.perf_counter() - (self.llm.stats['cont_seconds'] - cs0) # the writing done inside the check loop counts as writing
|
| 124 |
dis = [i for i in range(n) if disputed(chk[i][0], chk[i][1], self.threshold)]
|
| 125 |
if self.writing == 'continue': assert [i for i in range(n) if chk[i][3] is not None] == dis
|
|
|
|
| 171 |
out[idx[i]] = d if details else d['text']
|
| 172 |
t6 = time.perf_counter()
|
| 173 |
del encs
|
| 174 |
+
if self.writing == 'continue' and not self.retain_block_cache:
|
| 175 |
+
torch.cuda.empty_cache()
|
| 176 |
T['kroko'] += t1 - t0; T['check'] += t2 - t1; T['write'] += t3 - t2; T['rescore'] += t5 - t4; T['text'] += (t4 - t3) + (t6 - t5); T['total'] += t6 - t0
|
| 177 |
T['audio'] += sum(a.size for a in A) / 16000; T['clips'] += n; T['disputed'] += len(dis); T['disputed_audio'] += sum(A[i].size for i in dis) / 16000
|
| 178 |
if self.verbose:
|
krokomusci/packed_prefill.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run Musci's BF16 draft check over the occupied decoder positions only."""
|
| 2 |
+
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from contextvars import ContextVar
|
| 5 |
+
from functools import wraps
|
| 6 |
+
from inspect import unwrap
|
| 7 |
+
from unittest.mock import patch
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from transformers.cache_utils import DynamicCache
|
| 11 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _flash_varlen(query, key, value, offsets, longest, scale):
|
| 15 |
+
output, *_ = torch.ops.aten._flash_attention_forward(
|
| 16 |
+
query, key, value, offsets, offsets, longest, longest, 0.0, True, False, scale=scale,
|
| 17 |
+
)
|
| 18 |
+
return output
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _restore(packed, indices, batch, length):
|
| 22 |
+
dense = packed.new_zeros((batch * length, *packed.shape[1:]))
|
| 23 |
+
dense.index_copy_(0, indices, packed)
|
| 24 |
+
return dense.view(batch, length, *packed.shape[1:])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class PackedPrefill:
|
| 28 |
+
"""Temporarily pack the check decoder, keeping the native dense output interface."""
|
| 29 |
+
|
| 30 |
+
def __init__(self, llm):
|
| 31 |
+
self.llm = llm
|
| 32 |
+
self.decoder = llm.thinker.model
|
| 33 |
+
layers = self.decoder.layers
|
| 34 |
+
if len(layers) != 28 or self.decoder.training or self.decoder.config._attn_implementation != 'sdpa':
|
| 35 |
+
raise ValueError('Expected the released 28-layer Musci text decoder in SDPA eval mode')
|
| 36 |
+
if self.decoder.rotary_emb.rope_type != 'default' or any(not layer.self_attn.is_causal for layer in layers):
|
| 37 |
+
raise ValueError('Expected causal attention and the released position embedding')
|
| 38 |
+
self.apply_rotary = unwrap(layers[0].self_attn.forward).__globals__['apply_rotary_pos_emb']
|
| 39 |
+
self.enabled = True
|
| 40 |
+
self.prefill_groups = 0
|
| 41 |
+
self.occupied_positions = 0
|
| 42 |
+
self.dense_positions = 0
|
| 43 |
+
|
| 44 |
+
def packed(self, embeddings, mask, use_cache):
|
| 45 |
+
batch, length, width = embeddings.shape
|
| 46 |
+
valid = mask.to(torch.bool)
|
| 47 |
+
lengths = valid.sum(dim=1, dtype=torch.int32)
|
| 48 |
+
shortest, longest = torch.aminmax(lengths)
|
| 49 |
+
shortest, longest = torch.stack((shortest, longest)).tolist()
|
| 50 |
+
if not shortest:
|
| 51 |
+
raise ValueError('Every packed clip needs at least one visible decoder position')
|
| 52 |
+
offsets = torch.cat((lengths.new_zeros(1), lengths.cumsum(0, dtype=torch.int32)))
|
| 53 |
+
indices = valid.reshape(-1).nonzero().flatten()
|
| 54 |
+
hidden = embeddings.reshape(-1, width).index_select(0, indices)
|
| 55 |
+
|
| 56 |
+
# The check uses dense absolute positions even for clips with left-padded audio prompts.
|
| 57 |
+
# Gather the native cosines/sines at those positions before removing the padding.
|
| 58 |
+
positions = torch.arange(length, device=embeddings.device).view(1, 1, length).expand(3, batch, length)
|
| 59 |
+
cos, sin = self.decoder.rotary_emb(embeddings, positions)
|
| 60 |
+
cos = cos.flatten(0, 1).index_select(0, indices)
|
| 61 |
+
sin = sin.flatten(0, 1).index_select(0, indices)
|
| 62 |
+
cache = DynamicCache(config=self.decoder.config) if use_cache else None
|
| 63 |
+
|
| 64 |
+
for layer in self.decoder.layers:
|
| 65 |
+
attn = layer.self_attn
|
| 66 |
+
head_shape = (hidden.shape[0], -1, attn.head_dim)
|
| 67 |
+
normalized = layer.input_layernorm(hidden)
|
| 68 |
+
query = attn.q_norm(attn.q_proj(normalized).view(head_shape))
|
| 69 |
+
key = attn.k_norm(attn.k_proj(normalized).view(head_shape))
|
| 70 |
+
value = attn.v_proj(normalized).view(head_shape)
|
| 71 |
+
query, key = self.apply_rotary(query, key, cos, sin)
|
| 72 |
+
attended = _flash_varlen(query, key, value, offsets, longest, attn.scaling)
|
| 73 |
+
hidden = hidden + attn.o_proj(attended.reshape(-1, attn.q_proj.out_features))
|
| 74 |
+
hidden = hidden + layer.mlp(layer.post_attention_layernorm(hidden))
|
| 75 |
+
if cache is not None:
|
| 76 |
+
# FastContinuer expects [clip, KV head, dense position, head channel].
|
| 77 |
+
dense_key = _restore(key, indices, batch, length).transpose(1, 2)
|
| 78 |
+
dense_value = _restore(value, indices, batch, length).transpose(1, 2)
|
| 79 |
+
cache.update(dense_key, dense_value, attn.layer_idx)
|
| 80 |
+
|
| 81 |
+
hidden = _restore(self.decoder.norm(hidden), indices, batch, length)
|
| 82 |
+
self.prefill_groups += 1
|
| 83 |
+
self.occupied_positions += indices.numel()
|
| 84 |
+
self.dense_positions += batch * length
|
| 85 |
+
return BaseModelOutputWithPast(last_hidden_state=hidden, past_key_values=cache)
|
| 86 |
+
|
| 87 |
+
@contextmanager
|
| 88 |
+
def install(self):
|
| 89 |
+
check = self.llm._check_group
|
| 90 |
+
native = self.decoder.forward
|
| 91 |
+
in_check = ContextVar('musci_packed_check', default=False)
|
| 92 |
+
|
| 93 |
+
@wraps(check)
|
| 94 |
+
def check_group(*args, **kwargs):
|
| 95 |
+
scope = in_check.set(True)
|
| 96 |
+
try:
|
| 97 |
+
return check(*args, **kwargs)
|
| 98 |
+
finally:
|
| 99 |
+
in_check.reset(scope)
|
| 100 |
+
|
| 101 |
+
@wraps(native)
|
| 102 |
+
def forward(*args, **kwargs):
|
| 103 |
+
if not self.enabled or not in_check.get() or kwargs.get('past_key_values') is not None:
|
| 104 |
+
return native(*args, **kwargs)
|
| 105 |
+
if args or kwargs.keys() - {'inputs_embeds', 'attention_mask', 'use_cache'}:
|
| 106 |
+
raise ValueError('The Musci draft check changed its decoder call signature')
|
| 107 |
+
embeddings, mask = kwargs['inputs_embeds'], kwargs['attention_mask']
|
| 108 |
+
if (embeddings.ndim != 3 or embeddings.shape[:2] != mask.shape
|
| 109 |
+
or embeddings.dtype != torch.bfloat16 or embeddings.device.type != 'cuda'
|
| 110 |
+
or embeddings.device != mask.device):
|
| 111 |
+
raise ValueError('Expected matching CUDA BF16 embeddings and a dense check mask')
|
| 112 |
+
return self.packed(embeddings, mask, kwargs['use_cache'])
|
| 113 |
+
|
| 114 |
+
with patch.object(self.llm, '_check_group', check_group), patch.object(self.decoder, 'forward', forward):
|
| 115 |
+
yield
|
krokomusci_backend.py
CHANGED
|
@@ -9,6 +9,26 @@ import sys
|
|
| 9 |
import tempfile
|
| 10 |
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
class FusionBackend:
|
| 13 |
def __init__(self, bundle, device_id=0):
|
| 14 |
self.stream = self
|
|
@@ -60,12 +80,12 @@ def serve(bundle, device_id, audio_fd, reply_fd):
|
|
| 60 |
with os.fdopen(reply_fd, "w", buffering=1) as replies:
|
| 61 |
from krokomusci.model import KrokoMusci
|
| 62 |
|
| 63 |
-
root = Path(__file__).resolve().parent
|
| 64 |
models = Path(os.environ["KM_MODELS_DIR"])
|
| 65 |
-
config =
|
| 66 |
config.update(kroko_bundle=str(bundle), kroko_joiner_output=str(bundle / "joiner_output.npz"),
|
| 67 |
llm_base_model=str(models / "qwen"), llm_weights=str(models / "musci/model.safetensors"))
|
| 68 |
backend = KrokoMusci(config, device_id=device_id)
|
|
|
|
| 69 |
print("ready", file=replies, flush=True)
|
| 70 |
for line in sys.stdin:
|
| 71 |
lengths = json.loads(line)
|
|
|
|
| 9 |
import tempfile
|
| 10 |
|
| 11 |
|
| 12 |
+
PROFILE_PATH = Path(__file__).with_name("config") / "krokomusci_rtxpro6000.json"
|
| 13 |
+
SPEED_RECIPES = {
|
| 14 |
+
"baseline": (False, False),
|
| 15 |
+
"retain-cache": (False, True),
|
| 16 |
+
"packed-prefill": (True, False),
|
| 17 |
+
"packed-retain": (True, True),
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def fusion_profile():
|
| 22 |
+
recipe = os.environ.get("KM_SPEED_RECIPE", "baseline")
|
| 23 |
+
try:
|
| 24 |
+
packed, retain = SPEED_RECIPES[recipe]
|
| 25 |
+
except KeyError:
|
| 26 |
+
raise ValueError(f"Unknown KrokoMusci speed recipe: {recipe}") from None
|
| 27 |
+
profile = json.loads(PROFILE_PATH.read_bytes())
|
| 28 |
+
profile.update(packed_prefill=packed, retain_block_cache=retain)
|
| 29 |
+
return profile, recipe
|
| 30 |
+
|
| 31 |
+
|
| 32 |
class FusionBackend:
|
| 33 |
def __init__(self, bundle, device_id=0):
|
| 34 |
self.stream = self
|
|
|
|
| 80 |
with os.fdopen(reply_fd, "w", buffering=1) as replies:
|
| 81 |
from krokomusci.model import KrokoMusci
|
| 82 |
|
|
|
|
| 83 |
models = Path(os.environ["KM_MODELS_DIR"])
|
| 84 |
+
config, recipe = fusion_profile()
|
| 85 |
config.update(kroko_bundle=str(bundle), kroko_joiner_output=str(bundle / "joiner_output.npz"),
|
| 86 |
llm_base_model=str(models / "qwen"), llm_weights=str(models / "musci/model.safetensors"))
|
| 87 |
backend = KrokoMusci(config, device_id=device_id)
|
| 88 |
+
print(f"KrokoMusci speed recipe: {recipe}", flush=True)
|
| 89 |
print("ready", file=replies, flush=True)
|
| 90 |
for line in sys.stdin:
|
| 91 |
lengths = json.loads(line)
|
normalizer/voice_code_data.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load the pinned VoiceCodeBench recordings using the Open ASR protocol."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path, PurePosixPath
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
DATASET_ID = "besimple-ai/voice-code-bench"
|
| 7 |
+
DATASET_REVISION = "bef2824f83ef1c796f3e79731a3b0741708730df"
|
| 8 |
+
RECORDINGS = 300
|
| 9 |
+
MANIFEST_KEYS = ("audio_id", "voice_code_bench_revision")
|
| 10 |
+
MAX_RECORDING_SECONDS = 130
|
| 11 |
+
MAX_CHUNK_SECONDS = 30
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_data(args):
|
| 15 |
+
from datasets import Audio, load_dataset
|
| 16 |
+
from huggingface_hub import snapshot_download
|
| 17 |
+
|
| 18 |
+
if (args.dataset != "default" or args.split != "test" or args.streaming
|
| 19 |
+
or args.dataset_revision != DATASET_REVISION or args.max_eval_samples != -1):
|
| 20 |
+
raise ValueError("Expected the complete pinned VoiceCodeBench default test split")
|
| 21 |
+
|
| 22 |
+
# Upstream protocol: open_asr_leaderboard@4b87692/normalizer/voice_code_bench.py.
|
| 23 |
+
root = Path(snapshot_download(
|
| 24 |
+
DATASET_ID, repo_type="dataset", revision=DATASET_REVISION,
|
| 25 |
+
allow_patterns=["data/metadata.jsonl", "data/audio/*.wav"],
|
| 26 |
+
)) / "data"
|
| 27 |
+
dataset = load_dataset("json", data_files={"test": str(root / "metadata.jsonl")}, split="test")
|
| 28 |
+
ids = dataset["audio_id"]
|
| 29 |
+
if len(ids) != RECORDINGS or len(set(ids)) != RECORDINGS or any(not value for value in ids):
|
| 30 |
+
raise ValueError("VoiceCodeBench metadata does not contain 300 unique audio IDs")
|
| 31 |
+
|
| 32 |
+
def attach_audio(sample):
|
| 33 |
+
relative = PurePosixPath(sample["file_name"])
|
| 34 |
+
if relative.parent != PurePosixPath("audio") or relative.suffix != ".wav":
|
| 35 |
+
raise ValueError("Unexpected VoiceCodeBench audio path")
|
| 36 |
+
audio = root / relative
|
| 37 |
+
if not audio.is_file():
|
| 38 |
+
raise FileNotFoundError(audio)
|
| 39 |
+
return {"audio": str(audio), "id": sample["audio_id"], "text": sample["transcripts"]["acoustic"],
|
| 40 |
+
"voice_code_bench_revision": DATASET_REVISION}
|
| 41 |
+
|
| 42 |
+
return dataset.map(attach_audio, load_from_cache_file=False).cast_column("audio", Audio())
|
public/index.html
CHANGED
|
@@ -78,10 +78,12 @@
|
|
| 78 |
const {lifecycle, benchmark} = await response.json();
|
| 79 |
const state = terminal.has(lifecycle.state) ? lifecycle.state : (benchmark?.state || lifecycle.state);
|
| 80 |
const count = benchmark?.completed_datasets?.length;
|
|
|
|
| 81 |
progress.hidden = count === undefined;
|
|
|
|
| 82 |
progress.value = count || 0;
|
| 83 |
const current = state === "evaluating" && benchmark?.current_dataset ? ` ${benchmark.current_dataset}` : "";
|
| 84 |
-
const progressLabel = count === undefined ? "" : ` · ${count}/
|
| 85 |
status.textContent = (labels[state] || "Checking benchmark status") + current + progressLabel;
|
| 86 |
if (state === "complete") {
|
| 87 |
const result = await fetch("/api/summary", {cache: "no-store"});
|
|
|
|
| 78 |
const {lifecycle, benchmark} = await response.json();
|
| 79 |
const state = terminal.has(lifecycle.state) ? lifecycle.state : (benchmark?.state || lifecycle.state);
|
| 80 |
const count = benchmark?.completed_datasets?.length;
|
| 81 |
+
const total = benchmark?.expected_datasets ?? 10;
|
| 82 |
progress.hidden = count === undefined;
|
| 83 |
+
progress.max = total;
|
| 84 |
progress.value = count || 0;
|
| 85 |
const current = state === "evaluating" && benchmark?.current_dataset ? ` ${benchmark.current_dataset}` : "";
|
| 86 |
+
const progressLabel = count === undefined ? "" : ` · ${count}/${total} datasets`;
|
| 87 |
status.textContent = (labels[state] || "Checking benchmark status") + current + progressLabel;
|
| 88 |
if (state === "complete") {
|
| 89 |
const result = await fetch("/api/summary", {cache: "no-store"});
|
run_eval.py
CHANGED
|
@@ -48,7 +48,7 @@ from librosa import resample
|
|
| 48 |
from scipy.signal import resample_poly
|
| 49 |
from tqdm.auto import tqdm
|
| 50 |
|
| 51 |
-
from normalizer import data_utils
|
| 52 |
from preflight_model import download_release
|
| 53 |
from revision_pins import install as install_dataset_pins
|
| 54 |
|
|
@@ -204,6 +204,8 @@ def parse_args() -> Namespace:
|
|
| 204 |
default=-1,
|
| 205 |
help="Smoke-test limit after reference filtering; -1 evaluates the full split.",
|
| 206 |
)
|
|
|
|
|
|
|
| 207 |
parser.add_argument(
|
| 208 |
"--warmup-steps",
|
| 209 |
type=int,
|
|
@@ -240,7 +242,7 @@ def parse_args() -> Namespace:
|
|
| 240 |
def inspect_audio(
|
| 241 |
audio: dict[str, str | bytes | None],
|
| 242 |
utterance_id: str,
|
| 243 |
-
max_samples: int,
|
| 244 |
model_family: str,
|
| 245 |
) -> dict[str, int | dict[str, int | np.typing.NDArray[np.float32]]]:
|
| 246 |
"""Decode, downmix, validate, and resample a clip before batching.
|
|
@@ -306,7 +308,7 @@ def inspect_audio(
|
|
| 306 |
waveform, SAMPLE_RATE // divisor, sampling_rate // divisor
|
| 307 |
).astype(np.float32)
|
| 308 |
|
| 309 |
-
if waveform.size > max_samples:
|
| 310 |
raise ValueError(
|
| 311 |
f"{utterance_id}: {waveform.size / SAMPLE_RATE:.3f}s exceeds the export profile; "
|
| 312 |
"increase --max-audio-seconds for the whole run."
|
|
@@ -383,6 +385,38 @@ def export_bundle(
|
|
| 383 |
return bundle, metadata
|
| 384 |
|
| 385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
def benchmark(
|
| 387 |
dataset: Dataset, backends: list[ASR], batch_size: int, warmup_steps: int,
|
| 388 |
warmup_seconds: tuple[float, ...] = (0.1, 10.0, 40.0),
|
|
@@ -498,7 +532,8 @@ def benchmark(
|
|
| 498 |
"audio_length_s": [len(audio) / SAMPLE_RATE for audio in audios[index]],
|
| 499 |
"transcription_time_s": [elapsed / len(dataset)] * len(batch["audio"]),
|
| 500 |
"audio_filepaths": data_utils.extract_audio_filepaths_from_batch(batch),
|
| 501 |
-
**{key: batch[key] for key in data_utils.CHUNK_METADATA_KEYS
|
|
|
|
| 502 |
}
|
| 503 |
for key, values in rows.items():
|
| 504 |
results.setdefault(key, []).extend(values)
|
|
@@ -519,8 +554,10 @@ def main() -> None:
|
|
| 519 |
"""
|
| 520 |
|
| 521 |
args = parse_args()
|
|
|
|
| 522 |
with cp.cuda.Device(args.device):
|
| 523 |
-
dataset =
|
|
|
|
| 524 |
# Normalize metadata without copying or decoding the encoded audio column.
|
| 525 |
metadata = dataset.remove_columns("audio").map(data_utils.normalize)
|
| 526 |
indices = [
|
|
@@ -530,6 +567,8 @@ def main() -> None:
|
|
| 530 |
]
|
| 531 |
if args.max_eval_samples > 0:
|
| 532 |
indices = indices[: args.max_eval_samples]
|
|
|
|
|
|
|
| 533 |
|
| 534 |
if not indices:
|
| 535 |
raise ValueError("No evaluable samples remain after upstream filtering.")
|
|
@@ -553,6 +592,11 @@ def main() -> None:
|
|
| 553 |
[dataset.select_columns("audio"), metadata], axis=1
|
| 554 |
).select(indices)
|
| 555 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
dataset = dataset.map(
|
| 557 |
inspect_audio,
|
| 558 |
input_columns=["audio", "utterance_id"],
|
|
@@ -565,7 +609,7 @@ def main() -> None:
|
|
| 565 |
}
|
| 566 |
),
|
| 567 |
fn_kwargs={
|
| 568 |
-
"max_samples":
|
| 569 |
"model_family": args.model_family,
|
| 570 |
},
|
| 571 |
)
|
|
@@ -589,6 +633,10 @@ def main() -> None:
|
|
| 589 |
|
| 590 |
workers = min(args.workers, (len(dataset) + args.batch_size - 1) // args.batch_size)
|
| 591 |
backends = [ASR(bundle, device_id=args.device) for _ in range(workers)]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 592 |
|
| 593 |
results = benchmark(
|
| 594 |
dataset, backends, args.batch_size, args.warmup_steps,
|
|
@@ -598,7 +646,9 @@ def main() -> None:
|
|
| 598 |
raise RuntimeError("Incomplete evaluation: not every sample was transcribed.")
|
| 599 |
|
| 600 |
extra_fields = None
|
| 601 |
-
if
|
|
|
|
|
|
|
| 602 |
extra_fields = {key: results[key] for key in data_utils.CHUNK_METADATA_KEYS}
|
| 603 |
|
| 604 |
manifest = Path(
|
|
@@ -634,6 +684,12 @@ def main() -> None:
|
|
| 634 |
"including text and word timestamps"
|
| 635 |
),
|
| 636 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 637 |
with open(manifest.with_suffix(".metadata.json"), "w", encoding="utf-8") as destination:
|
| 638 |
json.dump(metadata, destination, indent=2, sort_keys=True)
|
| 639 |
|
|
|
|
| 48 |
from scipy.signal import resample_poly
|
| 49 |
from tqdm.auto import tqdm
|
| 50 |
|
| 51 |
+
from normalizer import data_utils, voice_code_data
|
| 52 |
from preflight_model import download_release
|
| 53 |
from revision_pins import install as install_dataset_pins
|
| 54 |
|
|
|
|
| 204 |
default=-1,
|
| 205 |
help="Smoke-test limit after reference filtering; -1 evaluates the full split.",
|
| 206 |
)
|
| 207 |
+
parser.add_argument("--chunk-long-audio", action="store_true",
|
| 208 |
+
help="Split recordings above the export profile when running a supplemental dataset.")
|
| 209 |
parser.add_argument(
|
| 210 |
"--warmup-steps",
|
| 211 |
type=int,
|
|
|
|
| 242 |
def inspect_audio(
|
| 243 |
audio: dict[str, str | bytes | None],
|
| 244 |
utterance_id: str,
|
| 245 |
+
max_samples: int | None,
|
| 246 |
model_family: str,
|
| 247 |
) -> dict[str, int | dict[str, int | np.typing.NDArray[np.float32]]]:
|
| 248 |
"""Decode, downmix, validate, and resample a clip before batching.
|
|
|
|
| 308 |
waveform, SAMPLE_RATE // divisor, sampling_rate // divisor
|
| 309 |
).astype(np.float32)
|
| 310 |
|
| 311 |
+
if max_samples is not None and waveform.size > max_samples:
|
| 312 |
raise ValueError(
|
| 313 |
f"{utterance_id}: {waveform.size / SAMPLE_RATE:.3f}s exceeds the export profile; "
|
| 314 |
"increase --max-audio-seconds for the whole run."
|
|
|
|
| 385 |
return bundle, metadata
|
| 386 |
|
| 387 |
|
| 388 |
+
class ChunkedASR:
|
| 389 |
+
"""Return one raw transcription per original recording, preserving piece order."""
|
| 390 |
+
|
| 391 |
+
def __init__(self, backend, batch_size, chunk_samples, split_above_samples):
|
| 392 |
+
self.backend = backend
|
| 393 |
+
self.stream = backend.stream
|
| 394 |
+
self.batch_size = batch_size
|
| 395 |
+
self.chunk_samples = chunk_samples
|
| 396 |
+
self.split_above_samples = split_above_samples
|
| 397 |
+
|
| 398 |
+
def __call__(self, audios):
|
| 399 |
+
if all(audio.size <= self.split_above_samples for audio in audios):
|
| 400 |
+
return self.backend(audios)
|
| 401 |
+
|
| 402 |
+
# Open ASR's Kroko VoiceCodeBench protocol uses the fewest equal,
|
| 403 |
+
# contiguous nonoverlapping pieces of at most 30 seconds.
|
| 404 |
+
pieces, owners = [], []
|
| 405 |
+
for owner, audio in enumerate(audios):
|
| 406 |
+
count = -(-audio.size // self.chunk_samples) if audio.size > self.split_above_samples else 1
|
| 407 |
+
pieces.extend(np.array_split(audio, count))
|
| 408 |
+
owners.extend([owner] * count)
|
| 409 |
+
joined = [[] for _ in audios]
|
| 410 |
+
for start in range(0, len(pieces), self.batch_size):
|
| 411 |
+
end = start + self.batch_size
|
| 412 |
+
predictions, timestamps = self.backend(pieces[start:end])
|
| 413 |
+
self.stream.synchronize()
|
| 414 |
+
for owner, text, _ in zip(owners[start:end], predictions, timestamps, strict=True):
|
| 415 |
+
if text:
|
| 416 |
+
joined[owner].append(text)
|
| 417 |
+
return [" ".join(texts) for texts in joined], [[] for _ in audios]
|
| 418 |
+
|
| 419 |
+
|
| 420 |
def benchmark(
|
| 421 |
dataset: Dataset, backends: list[ASR], batch_size: int, warmup_steps: int,
|
| 422 |
warmup_seconds: tuple[float, ...] = (0.1, 10.0, 40.0),
|
|
|
|
| 532 |
"audio_length_s": [len(audio) / SAMPLE_RATE for audio in audios[index]],
|
| 533 |
"transcription_time_s": [elapsed / len(dataset)] * len(batch["audio"]),
|
| 534 |
"audio_filepaths": data_utils.extract_audio_filepaths_from_batch(batch),
|
| 535 |
+
**{key: batch[key] for key in (*data_utils.CHUNK_METADATA_KEYS, *voice_code_data.MANIFEST_KEYS)
|
| 536 |
+
if key in batch},
|
| 537 |
}
|
| 538 |
for key, values in rows.items():
|
| 539 |
results.setdefault(key, []).extend(values)
|
|
|
|
| 554 |
"""
|
| 555 |
|
| 556 |
args = parse_args()
|
| 557 |
+
is_voicecode = args.dataset_path.lower() == voice_code_data.DATASET_ID
|
| 558 |
with cp.cuda.Device(args.device):
|
| 559 |
+
dataset = (voice_code_data.load_data(args) if is_voicecode else data_utils.load_data(args))
|
| 560 |
+
dataset = dataset.cast_column("audio", Audio(decode=False))
|
| 561 |
# Normalize metadata without copying or decoding the encoded audio column.
|
| 562 |
metadata = dataset.remove_columns("audio").map(data_utils.normalize)
|
| 563 |
indices = [
|
|
|
|
| 567 |
]
|
| 568 |
if args.max_eval_samples > 0:
|
| 569 |
indices = indices[: args.max_eval_samples]
|
| 570 |
+
if is_voicecode and len(indices) != voice_code_data.RECORDINGS:
|
| 571 |
+
raise ValueError("VoiceCodeBench requires all 300 recording references")
|
| 572 |
|
| 573 |
if not indices:
|
| 574 |
raise ValueError("No evaluable samples remain after upstream filtering.")
|
|
|
|
| 592 |
[dataset.select_columns("audio"), metadata], axis=1
|
| 593 |
).select(indices)
|
| 594 |
|
| 595 |
+
max_samples = round(args.max_audio_seconds * SAMPLE_RATE)
|
| 596 |
+
if is_voicecode:
|
| 597 |
+
max_samples = voice_code_data.MAX_RECORDING_SECONDS * SAMPLE_RATE
|
| 598 |
+
elif args.chunk_long_audio:
|
| 599 |
+
max_samples = None
|
| 600 |
dataset = dataset.map(
|
| 601 |
inspect_audio,
|
| 602 |
input_columns=["audio", "utterance_id"],
|
|
|
|
| 609 |
}
|
| 610 |
),
|
| 611 |
fn_kwargs={
|
| 612 |
+
"max_samples": max_samples,
|
| 613 |
"model_family": args.model_family,
|
| 614 |
},
|
| 615 |
)
|
|
|
|
| 633 |
|
| 634 |
workers = min(args.workers, (len(dataset) + args.batch_size - 1) // args.batch_size)
|
| 635 |
backends = [ASR(bundle, device_id=args.device) for _ in range(workers)]
|
| 636 |
+
if is_voicecode or args.chunk_long_audio:
|
| 637 |
+
chunk_samples = round(min(args.max_audio_seconds, voice_code_data.MAX_CHUNK_SECONDS) * SAMPLE_RATE)
|
| 638 |
+
split_above = chunk_samples if is_voicecode else round(args.max_audio_seconds * SAMPLE_RATE)
|
| 639 |
+
backends = [ChunkedASR(backend, args.batch_size, chunk_samples, split_above) for backend in backends]
|
| 640 |
|
| 641 |
results = benchmark(
|
| 642 |
dataset, backends, args.batch_size, args.warmup_steps,
|
|
|
|
| 646 |
raise RuntimeError("Incomplete evaluation: not every sample was transcribed.")
|
| 647 |
|
| 648 |
extra_fields = None
|
| 649 |
+
if is_voicecode:
|
| 650 |
+
extra_fields = {key: results[key] for key in voice_code_data.MANIFEST_KEYS}
|
| 651 |
+
elif data_utils.is_chunked_dataset(args.dataset_path):
|
| 652 |
extra_fields = {key: results[key] for key in data_utils.CHUNK_METADATA_KEYS}
|
| 653 |
|
| 654 |
manifest = Path(
|
|
|
|
| 684 |
"including text and word timestamps"
|
| 685 |
),
|
| 686 |
}
|
| 687 |
+
if is_voicecode or args.chunk_long_audio:
|
| 688 |
+
metadata["recording_chunking"] = {
|
| 689 |
+
"method": "fewest equal, contiguous nonoverlapping pieces",
|
| 690 |
+
"maximum_chunk_seconds": chunk_samples / SAMPLE_RATE,
|
| 691 |
+
"split_if_longer_than_seconds": split_above / SAMPLE_RATE,
|
| 692 |
+
}
|
| 693 |
with open(manifest.with_suffix(".metadata.json"), "w", encoding="utf-8") as destination:
|
| 694 |
json.dump(metadata, destination, indent=2, sort_keys=True)
|
| 695 |
|
run_fusion_eval.py
CHANGED
|
@@ -8,7 +8,7 @@ import numpy as np
|
|
| 8 |
import onnx
|
| 9 |
|
| 10 |
import run_eval
|
| 11 |
-
from krokomusci_backend import FusionBackend
|
| 12 |
from preflight_model import download_release
|
| 13 |
|
| 14 |
original_export = run_eval.export_bundle
|
|
@@ -33,12 +33,15 @@ def export_fusion_bundle(args, hardware):
|
|
| 33 |
np.savez(temporary, weight=weight, bias=bias)
|
| 34 |
os.replace(temporary, projection)
|
| 35 |
root = Path(__file__).resolve().parent
|
| 36 |
-
|
| 37 |
-
|
| 38 |
metadata["fusion"] = {
|
| 39 |
"name": "KrokoMusci",
|
| 40 |
"version": profile["version"],
|
| 41 |
"profile_sha256": sha256(profile_bytes).hexdigest(),
|
|
|
|
|
|
|
|
|
|
| 42 |
"calibration_sha256": "42b419732d7c9a17967b5b227b8088ca3dd830310fd2034baf199f478e077942",
|
| 43 |
"models": json.loads((root / "models.json").read_text()),
|
| 44 |
"timestamps": "Kroko draft timestamps",
|
|
|
|
| 8 |
import onnx
|
| 9 |
|
| 10 |
import run_eval
|
| 11 |
+
from krokomusci_backend import FusionBackend, fusion_profile
|
| 12 |
from preflight_model import download_release
|
| 13 |
|
| 14 |
original_export = run_eval.export_bundle
|
|
|
|
| 33 |
np.savez(temporary, weight=weight, bias=bias)
|
| 34 |
os.replace(temporary, projection)
|
| 35 |
root = Path(__file__).resolve().parent
|
| 36 |
+
profile, recipe = fusion_profile()
|
| 37 |
+
profile_bytes = json.dumps(profile, sort_keys=True, separators=(",", ":")).encode()
|
| 38 |
metadata["fusion"] = {
|
| 39 |
"name": "KrokoMusci",
|
| 40 |
"version": profile["version"],
|
| 41 |
"profile_sha256": sha256(profile_bytes).hexdigest(),
|
| 42 |
+
"speed_recipe": recipe,
|
| 43 |
+
"packed_prefill": profile["packed_prefill"],
|
| 44 |
+
"retain_block_cache": profile["retain_block_cache"],
|
| 45 |
"calibration_sha256": "42b419732d7c9a17967b5b227b8088ca3dd830310fd2034baf199f478e077942",
|
| 46 |
"models": json.loads((root / "models.json").read_text()),
|
| 47 |
"timestamps": "Kroko draft timestamps",
|
suite.json
CHANGED
|
@@ -5,7 +5,9 @@
|
|
| 5 |
"hf-audio/open-asr-leaderboard": "de79e57adf9983993bcc72586d7313460825f5eb",
|
| 6 |
"ArtificialAnalysis/Earnings22-Cleaned-AA-chunked": "27f7d0056d593231974a752ce03c1e965da69b3f",
|
| 7 |
"ArtificialAnalysis/Earnings22-Cleaned-AA": "5999936ee3d8d3cde160e3c65a8cc6ff5b7c5276",
|
| 8 |
-
"VoiceArena/Monsoon_en_IN_test": "bc1da7b42ef6e2853123c97bf6d22067e4802d11"
|
|
|
|
|
|
|
| 9 |
},
|
| 10 |
"datasets": [
|
| 11 |
{"id": "ami", "repo": "hf-audio/open-asr-leaderboard", "config": "ami_cleaned", "split": "test"},
|
|
@@ -18,5 +20,14 @@
|
|
| 18 |
{"id": "urgent2024_noisy", "repo": "hf-audio/open-asr-leaderboard", "config": "urgent2024", "split": "test"},
|
| 19 |
{"id": "urgent2024_clean", "repo": "hf-audio/open-asr-leaderboard", "config": "urgent2024_clean", "split": "test"},
|
| 20 |
{"id": "monsoon", "repo": "VoiceArena/Monsoon_en_IN_test", "config": "", "split": "test"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
]
|
| 22 |
}
|
|
|
|
| 5 |
"hf-audio/open-asr-leaderboard": "de79e57adf9983993bcc72586d7313460825f5eb",
|
| 6 |
"ArtificialAnalysis/Earnings22-Cleaned-AA-chunked": "27f7d0056d593231974a752ce03c1e965da69b3f",
|
| 7 |
"ArtificialAnalysis/Earnings22-Cleaned-AA": "5999936ee3d8d3cde160e3c65a8cc6ff5b7c5276",
|
| 8 |
+
"VoiceArena/Monsoon_en_IN_test": "bc1da7b42ef6e2853123c97bf6d22067e4802d11",
|
| 9 |
+
"besimple-ai/voice-code-bench": "bef2824f83ef1c796f3e79731a3b0741708730df",
|
| 10 |
+
"huggingworld/open-asr-leaderboard": "f8354547536e59f8410d896e51fa636b4942a2d1"
|
| 11 |
},
|
| 12 |
"datasets": [
|
| 13 |
{"id": "ami", "repo": "hf-audio/open-asr-leaderboard", "config": "ami_cleaned", "split": "test"},
|
|
|
|
| 20 |
{"id": "urgent2024_noisy", "repo": "hf-audio/open-asr-leaderboard", "config": "urgent2024", "split": "test"},
|
| 21 |
{"id": "urgent2024_clean", "repo": "hf-audio/open-asr-leaderboard", "config": "urgent2024_clean", "split": "test"},
|
| 22 |
{"id": "monsoon", "repo": "VoiceArena/Monsoon_en_IN_test", "config": "", "split": "test"}
|
| 23 |
+
],
|
| 24 |
+
"optional_datasets": [
|
| 25 |
+
{"id": "voice_code_bench", "repo": "besimple-ai/voice-code-bench", "config": "default", "split": "test"},
|
| 26 |
+
{"id": "common_voice", "repo": "hf-audio/open-asr-leaderboard", "config": "common_voice", "split": "test", "chunk_long_audio": true},
|
| 27 |
+
{"id": "tedlium", "repo": "huggingworld/open-asr-leaderboard", "config": "tedlium", "split": "test", "chunk_long_audio": true},
|
| 28 |
+
{"id": "ami_original", "repo": "hf-audio/open-asr-leaderboard", "config": "ami", "split": "test"},
|
| 29 |
+
{"id": "gigaspeech_original", "repo": "hf-audio/open-asr-leaderboard", "config": "gigaspeech", "split": "test"},
|
| 30 |
+
{"id": "voxpopuli_original", "repo": "hf-audio/open-asr-leaderboard", "config": "voxpopuli", "split": "test", "chunk_long_audio": true},
|
| 31 |
+
{"id": "earnings22_original", "repo": "hf-audio/open-asr-leaderboard", "config": "earnings22", "split": "test"}
|
| 32 |
]
|
| 33 |
}
|