LogosAccessibleExpression commited on
Commit
a51a477
·
verified ·
1 Parent(s): 8f0aeb5

Upload voxtral_eval_job.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. voxtral_eval_job.py +112 -0
voxtral_eval_job.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch",
5
+ # "transformers>=4.56",
6
+ # "mistral-common[audio]>=1.8.1",
7
+ # "datasets",
8
+ # "accelerate",
9
+ # "jiwer",
10
+ # "soundfile",
11
+ # "requests",
12
+ # "numpy",
13
+ # ]
14
+ # ///
15
+ """
16
+ Voxtral baseline WER eval — HuggingFace Job script (uv run --script).
17
+
18
+ Transcribes the user's held-out labeled recordings (same seed-42/10% split as
19
+ training and the local eval_voxtral.py) with an open-weights Voxtral model and
20
+ reports WER. No personalization — this is the cold-model baseline.
21
+
22
+ Env: MODEL_ID (default mistralai/Voxtral-Mini-3B-2507), N_CLIPS (default 30),
23
+ USER_ID; secrets: HF_TOKEN, SUPABASE_SERVICE_ROLE_KEY.
24
+ """
25
+ import os, tempfile, time
26
+
27
+ import requests
28
+ import torch
29
+ import jiwer
30
+ from datasets import Dataset
31
+
32
+ MODEL_ID = os.environ.get("MODEL_ID", "mistralai/Voxtral-Mini-3B-2507")
33
+ N_CLIPS = int(os.environ.get("N_CLIPS", "30"))
34
+ USER_ID = os.environ["USER_ID"]
35
+ SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://hehlulmegluxmtlupwgp.supabase.co")
36
+ SB_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"]
37
+
38
+ hdrs = {"apikey": SB_KEY, "Authorization": f"Bearer {SB_KEY}"}
39
+
40
+ recs = requests.get(f"{SUPABASE_URL}/rest/v1/training_recordings", headers=hdrs,
41
+ params={"select": "audio_url,phrase_id", "user_id": f"eq.{USER_ID}"}).json()
42
+ phrases = requests.get(f"{SUPABASE_URL}/rest/v1/training_phrases", headers=hdrs,
43
+ params={"select": "id,text"}).json()
44
+ phrase_map = {p["id"]: p["text"] for p in phrases}
45
+ dataset_all = [{"audio_url": r["audio_url"], "text": phrase_map[r["phrase_id"]]}
46
+ for r in recs if r["phrase_id"] in phrase_map]
47
+ print(f"{len(dataset_all)} labeled recordings")
48
+
49
+ # Same held-out split as training / local eval (seed 42, 10% of the FULL list).
50
+ test_size = max(1, int(len(dataset_all) * 0.1))
51
+ full = Dataset.from_list([{"idx": i} for i in range(len(dataset_all))])
52
+ eval_indices = [r["idx"] for r in full.train_test_split(test_size=test_size, seed=42)["test"]]
53
+ dataset = [dataset_all[i] for i in eval_indices]
54
+
55
+ # WAV clips only (no ffmpeg on the job image; the modern pipeline records WAV).
56
+ wav_ds, skipped = [], 0
57
+ WAV_DIR = tempfile.mkdtemp()
58
+ for i, item in enumerate(dataset):
59
+ url = item["audio_url"]
60
+ if not url.split("?")[0].lower().endswith(".wav"):
61
+ skipped += 1
62
+ continue
63
+ r = requests.get(url.replace("/object/public/", "/object/"), headers=hdrs)
64
+ if not r.ok:
65
+ skipped += 1
66
+ continue
67
+ path = os.path.join(WAV_DIR, f"{i}.wav")
68
+ open(path, "wb").write(r.content)
69
+ wav_ds.append({"path": path, "text": item["text"]})
70
+ if len(wav_ds) >= N_CLIPS:
71
+ break
72
+ print(f"eval clips: {len(wav_ds)} wav ({skipped} non-wav/failed skipped)")
73
+
74
+ from transformers import AutoProcessor, VoxtralForConditionalGeneration
75
+
76
+ print(f"loading {MODEL_ID}…", flush=True)
77
+ processor = AutoProcessor.from_pretrained(MODEL_ID)
78
+ model = VoxtralForConditionalGeneration.from_pretrained(
79
+ MODEL_ID, torch_dtype=torch.bfloat16, device_map="cuda")
80
+ model.eval()
81
+
82
+ # Method name had a typo in early transformers releases — support both.
83
+ _req = getattr(processor, "apply_transcription_request",
84
+ getattr(processor, "apply_transcrition_request", None))
85
+
86
+ norm = jiwer.Compose([jiwer.ToLowerCase(), jiwer.RemovePunctuation(),
87
+ jiwer.RemoveMultipleSpaces(), jiwer.Strip(),
88
+ jiwer.ReduceToListOfListOfWords()])
89
+
90
+ rows = []
91
+ t0 = time.time()
92
+ for i, item in enumerate(wav_ds):
93
+ inputs = _req(language="en", audio=item["path"], model_id=MODEL_ID)
94
+ inputs = inputs.to("cuda", dtype=torch.bfloat16)
95
+ with torch.no_grad():
96
+ out = model.generate(**inputs, max_new_tokens=200)
97
+ hyp = processor.batch_decode(out[:, inputs.input_ids.shape[1]:],
98
+ skip_special_tokens=True)[0].strip()
99
+ wer = jiwer.wer(item["text"], hyp or "",
100
+ reference_transform=norm, hypothesis_transform=norm)
101
+ rows.append((wer, item["text"], hyp))
102
+ print(f"[{i}] wer={wer:.2f} ref={item['text']!r} hyp={hyp!r}", flush=True)
103
+
104
+ mean_wer = sum(w for w, _, _ in rows) / max(1, len(rows))
105
+ print("\n================ RESULTS ================")
106
+ print(f"model: {MODEL_ID}")
107
+ print(f"mean WER: {mean_wer:.3f} over {len(rows)} clips "
108
+ f"({(time.time()-t0)/max(1,len(rows)):.1f}s/clip)")
109
+ print("worst 5:")
110
+ for w, ref, hyp in sorted(rows, reverse=True)[:5]:
111
+ print(f" {w:.2f} ref: {ref!r}")
112
+ print(f" hyp: {hyp!r}")