LogosAccessibleExpression commited on
Commit
758e4d2
Β·
verified Β·
1 Parent(s): f26b180

Upload logos_reward_ft_job.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. logos_reward_ft_job.py +333 -0
logos_reward_ft_job.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch",
5
+ # "transformers",
6
+ # "datasets",
7
+ # "peft",
8
+ # "accelerate",
9
+ # "jiwer",
10
+ # "syllapy",
11
+ # "soundfile",
12
+ # "librosa",
13
+ # "huggingface_hub",
14
+ # "requests",
15
+ # "numpy",
16
+ # ]
17
+ # ///
18
+ """
19
+ Logos Whisper Tiny β€” Reward-Weighted LoRA Fine-Tuning
20
+ HuggingFace Job script (uv run --script)
21
+
22
+ Environment variables (set as job secrets/env):
23
+ HF_TOKEN β€” HuggingFace write token
24
+ HF_PUSH_REPO β€” repo to push the trained adapter to
25
+ SUPABASE_URL β€” Supabase project URL
26
+ SUPABASE_KEY β€” Supabase anon/publishable key
27
+ REFRESH_TOKEN β€” Supabase session refresh token
28
+ USER_ID β€” Supabase user UUID
29
+ """
30
+
31
+ import os, re, subprocess, tempfile, logging
32
+ import numpy as np
33
+ import requests
34
+ import soundfile as sf
35
+ import librosa
36
+ import syllapy
37
+ import torch
38
+ import torch.nn.functional as F
39
+ from pathlib import Path
40
+ from jiwer import process_words
41
+ from datasets import Dataset
42
+ from transformers import (
43
+ WhisperProcessor,
44
+ WhisperForConditionalGeneration,
45
+ Seq2SeqTrainer,
46
+ Seq2SeqTrainingArguments,
47
+ DataCollatorForSeq2Seq,
48
+ )
49
+ from peft import LoraConfig, get_peft_model, TaskType
50
+ from huggingface_hub import login
51
+
52
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
53
+ log = logging.getLogger(__name__)
54
+
55
+ # ── Config ────────────────────────────────────────────────────────────────────
56
+ HF_TOKEN = os.environ["HF_TOKEN"]
57
+ HF_PUSH_REPO = os.environ.get("HF_PUSH_REPO", "logosaccessibleexpression/logos-whisper-tiny-reward-ft")
58
+ SUPABASE_URL = os.environ["SUPABASE_URL"]
59
+ SUPABASE_KEY = os.environ["SUPABASE_KEY"]
60
+ REFRESH_TOKEN = os.environ["REFRESH_TOKEN"]
61
+ USER_ID = os.environ["USER_ID"]
62
+
63
+ WHISPER_BASE = "openai/whisper-tiny"
64
+ LORA_R = 16
65
+ LORA_ALPHA = 32
66
+ LORA_DROPOUT = 0.05
67
+
68
+ REWARD_ALPHA = 1.0 # WER
69
+ REWARD_BETA = 0.5 # positional tail penalty
70
+ REWARD_GAMMA = 0.5 # per-substitution syllable match
71
+ REWARD_DELTA = 0.5 # total syllable count match
72
+ LOSS_SCALE = 2.0 # max loss multiplier for worst examples
73
+
74
+ BEAM_N = 5
75
+ TRAIN_EPOCHS = 5
76
+ BATCH_SIZE = 8
77
+ LEARNING_RATE = 1e-4
78
+ SAVE_STEPS = 50
79
+ OUTPUT_DIR = "/tmp/logos_reward_ft"
80
+
81
+ # ── Supabase auth ─────────────────────────────────────────────────────────────
82
+ def refresh_access_token():
83
+ r = requests.post(
84
+ f"{SUPABASE_URL}/auth/v1/token?grant_type=refresh_token",
85
+ headers={"apikey": SUPABASE_KEY, "Content-Type": "application/json"},
86
+ json={"refresh_token": REFRESH_TOKEN},
87
+ )
88
+ r.raise_for_status()
89
+ return r.json()["access_token"]
90
+
91
+ ACCESS_TOKEN = refresh_access_token()
92
+ log.info("Supabase auth OK")
93
+
94
+ def sb_get(table, select="*", filters=None):
95
+ headers = {"apikey": SUPABASE_KEY, "Authorization": f"Bearer {ACCESS_TOKEN}"}
96
+ params = {"select": select}
97
+ if filters:
98
+ params.update(filters)
99
+ r = requests.get(f"{SUPABASE_URL}/rest/v1/{table}", headers=headers, params=params)
100
+ r.raise_for_status()
101
+ return r.json()
102
+
103
+ # ── Load recordings + phrase texts ───────────────────────────────────────────
104
+ recordings = sb_get("training_recordings", select="audio_url,phrase_id",
105
+ filters={"user_id": f"eq.{USER_ID}"})
106
+ phrases = sb_get("training_phrases", select="id,text")
107
+ phrase_map = {p["id"]: p["text"] for p in phrases}
108
+
109
+ dataset_raw = [
110
+ {"audio_url": r["audio_url"], "text": phrase_map[r["phrase_id"]]}
111
+ for r in recordings if r["phrase_id"] in phrase_map
112
+ ]
113
+ log.info(f"Found {len(dataset_raw)} recordings")
114
+
115
+ # ── Download + decode audio ───────────────────────────────────────────────────
116
+ WAV_DIR = Path(tempfile.mkdtemp())
117
+
118
+ def download_audio(url: str, idx: int) -> np.ndarray | None:
119
+ auth_url = url.replace("/object/public/", "/object/")
120
+ r = requests.get(auth_url, headers={
121
+ "Authorization": f"Bearer {ACCESS_TOKEN}",
122
+ "apikey": SUPABASE_KEY,
123
+ })
124
+ if not r.ok:
125
+ return None
126
+
127
+ ext = url.split("?")[0].rsplit(".", 1)[-1].lower()
128
+ raw_path = WAV_DIR / f"{idx}.{ext}"
129
+ raw_path.write_bytes(r.content)
130
+
131
+ if ext != "wav":
132
+ wav_path = WAV_DIR / f"{idx}.wav"
133
+ result = subprocess.run(
134
+ ["ffmpeg", "-y", "-i", str(raw_path),
135
+ "-ac", "1", "-ar", "16000", "-sample_fmt", "s16", str(wav_path)],
136
+ capture_output=True,
137
+ )
138
+ if result.returncode != 0:
139
+ return None
140
+ raw_path = wav_path
141
+
142
+ try:
143
+ audio, sr = sf.read(str(raw_path))
144
+ except Exception:
145
+ return None
146
+
147
+ if audio.ndim > 1:
148
+ audio = audio.mean(axis=1)
149
+ if sr != 16000:
150
+ audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)
151
+ return audio.astype(np.float32)
152
+
153
+ skipped = 0
154
+ for i, item in enumerate(dataset_raw):
155
+ item["audio"] = download_audio(item["audio_url"], i)
156
+ if item["audio"] is None:
157
+ skipped += 1
158
+
159
+ dataset_raw = [d for d in dataset_raw if d["audio"] is not None]
160
+ log.info(f"Downloaded {len(dataset_raw)} recordings ({skipped} skipped)")
161
+
162
+ # ── Reward function ───────────────────────────────────────────────────────────
163
+ def count_syllables(word: str) -> int:
164
+ word = re.sub(r"[^a-z']", "", word.lower())
165
+ n = syllapy.count(word)
166
+ if n and n > 0:
167
+ return n
168
+ return max(1, len(re.findall(r"[aeiouy]+", word)))
169
+
170
+ def compute_reward(hypothesis: str, ground_truth: str) -> float:
171
+ hyp = hypothesis.strip().lower()
172
+ ref = ground_truth.strip().lower()
173
+ if not hyp:
174
+ return 0.0
175
+ if hyp == ref:
176
+ return 1.0
177
+
178
+ hyp_words = hyp.split()
179
+ ref_words = ref.split()
180
+
181
+ result = process_words(ref, hyp)
182
+ wer_comp = max(0.0, 1.0 - result.wer)
183
+
184
+ n_hyp = len(hyp_words)
185
+ pos_scores, syl_scores = [], []
186
+
187
+ for chunk in result.alignments[0]:
188
+ ctype = chunk.type
189
+ if ctype in ("equal", "substitute"):
190
+ hyp_pos = chunk.hyp_start_idx
191
+ ref_w = ref_words[chunk.ref_start_idx] if chunk.ref_start_idx < len(ref_words) else ""
192
+ hyp_w = hyp_words[hyp_pos] if hyp_pos < n_hyp else ""
193
+ pos_w = 1.0 - 0.5 * (hyp_pos / max(1, n_hyp - 1))
194
+ pos_scores.append(pos_w if ctype == "equal" else 0.0)
195
+ if ctype == "substitute" and ref_w and hyp_w:
196
+ syl_scores.append(1.0 if count_syllables(ref_w) == count_syllables(hyp_w) else 0.0)
197
+ elif ctype == "insert":
198
+ for k in range(chunk.hyp_start_idx, chunk.hyp_end_idx):
199
+ pos_scores.append(0.0)
200
+
201
+ pos_comp = float(np.mean(pos_scores)) if pos_scores else 0.0
202
+ syl_comp = float(np.mean(syl_scores)) if syl_scores else 1.0
203
+
204
+ ref_syl = sum(count_syllables(w) for w in ref_words) if ref_words else 1
205
+ hyp_syl = sum(count_syllables(w) for w in hyp_words) if hyp_words else 0
206
+ syl_count_comp = max(0.0, 1.0 - abs(ref_syl - hyp_syl) / max(ref_syl, 1))
207
+
208
+ score = (
209
+ REWARD_ALPHA * wer_comp +
210
+ REWARD_BETA * pos_comp +
211
+ REWARD_GAMMA * syl_comp +
212
+ REWARD_DELTA * syl_count_comp
213
+ ) / (REWARD_ALPHA + REWARD_BETA + REWARD_GAMMA + REWARD_DELTA)
214
+
215
+ return float(np.clip(score, 0.0, 1.0))
216
+
217
+ # ── Pre-compute reward weights using base model ───────────────────────────────
218
+ processor = WhisperProcessor.from_pretrained(WHISPER_BASE)
219
+ base_model = WhisperForConditionalGeneration.from_pretrained(WHISPER_BASE).cuda()
220
+ base_model.eval()
221
+ forced_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe")
222
+
223
+ def transcribe_audio(audio: np.ndarray, num_beams: int = BEAM_N) -> list:
224
+ feats = processor(audio, sampling_rate=16000, return_tensors="pt").input_features.cuda()
225
+ with torch.no_grad():
226
+ ids = base_model.generate(feats, forced_decoder_ids=forced_ids,
227
+ num_beams=num_beams, num_return_sequences=num_beams)
228
+ return [processor.decode(seq, skip_special_tokens=True) for seq in ids]
229
+
230
+ for i, item in enumerate(dataset_raw):
231
+ hypotheses = transcribe_audio(item["audio"])
232
+ best_score = max(compute_reward(h, item["text"]) for h in hypotheses)
233
+ item["reward_weight"] = 1.0 + LOSS_SCALE * (1.0 - best_score)
234
+ if (i + 1) % 20 == 0:
235
+ log.info(f" scored {i+1}/{len(dataset_raw)}")
236
+
237
+ del base_model
238
+ torch.cuda.empty_cache()
239
+
240
+ weights = [d["reward_weight"] for d in dataset_raw]
241
+ log.info(f"Reward weights β€” min {min(weights):.3f} max {max(weights):.3f} mean {np.mean(weights):.3f}")
242
+
243
+ # ── Build HuggingFace Dataset ─────────────────────────────────────────────────
244
+ def preprocess(item):
245
+ feats = processor(item["audio"], sampling_rate=16000).input_features[0]
246
+ labels = processor.tokenizer(item["text"]).input_ids
247
+ return {"input_features": feats, "labels": labels, "reward_weight": item["reward_weight"]}
248
+
249
+ hf_data = Dataset.from_list([
250
+ {"audio": d["audio"], "text": d["text"], "reward_weight": d["reward_weight"]}
251
+ for d in dataset_raw
252
+ ]).map(preprocess, remove_columns=["audio", "text"])
253
+
254
+ split = hf_data.train_test_split(test_size=max(1, int(len(hf_data) * 0.1)), seed=42)
255
+ train_ds = split["train"]
256
+ eval_ds = split["test"]
257
+ log.info(f"Train: {len(train_ds)} Eval: {len(eval_ds)}")
258
+
259
+ # ── LoRA model ────────────────────────────────────────────────────────────────
260
+ lora_cfg = LoraConfig(
261
+ task_type = TaskType.SEQ_2_SEQ_LM,
262
+ r = LORA_R,
263
+ lora_alpha = LORA_ALPHA,
264
+ lora_dropout = LORA_DROPOUT,
265
+ target_modules = ["q_proj", "v_proj"],
266
+ )
267
+ model = WhisperForConditionalGeneration.from_pretrained(WHISPER_BASE)
268
+ model.config.forced_decoder_ids = None
269
+ model.config.suppress_tokens = []
270
+ model = get_peft_model(model, lora_cfg)
271
+ log.info(str(model.print_trainable_parameters()))
272
+
273
+ # ── Reward-weighted Trainer ───────────────────────────────────────────────────
274
+ class RewardWeightedTrainer(Seq2SeqTrainer):
275
+ def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
276
+ reward_weights = inputs.pop("reward_weight").to(model.device)
277
+ labels = inputs["labels"]
278
+ outputs = model(**inputs)
279
+ logits = outputs.logits
280
+
281
+ B, T, V = logits.shape
282
+ loss_per_token = F.cross_entropy(
283
+ logits.reshape(B * T, V), labels.reshape(B * T),
284
+ ignore_index=-100, reduction="none",
285
+ ).reshape(B, T)
286
+
287
+ valid = (labels != -100).float()
288
+ loss_per_ex = (loss_per_token * valid).sum(dim=1) / valid.sum(dim=1).clamp(min=1)
289
+ weighted_loss = (loss_per_ex * reward_weights).mean()
290
+
291
+ return (weighted_loss, outputs) if return_outputs else weighted_loss
292
+
293
+ collator = DataCollatorForSeq2Seq(processor.tokenizer, model=model, padding=True)
294
+
295
+ training_args = Seq2SeqTrainingArguments(
296
+ output_dir = OUTPUT_DIR,
297
+ per_device_train_batch_size = BATCH_SIZE,
298
+ per_device_eval_batch_size = BATCH_SIZE,
299
+ num_train_epochs = TRAIN_EPOCHS,
300
+ learning_rate = LEARNING_RATE,
301
+ warmup_steps = 50,
302
+ gradient_accumulation_steps = 2,
303
+ fp16 = True,
304
+ evaluation_strategy = "steps",
305
+ eval_steps = SAVE_STEPS,
306
+ save_strategy = "steps",
307
+ save_steps = SAVE_STEPS,
308
+ logging_steps = 10,
309
+ load_best_model_at_end = True,
310
+ metric_for_best_model = "eval_loss",
311
+ greater_is_better = False,
312
+ predict_with_generate = False,
313
+ push_to_hub = False,
314
+ remove_unused_columns = False,
315
+ )
316
+
317
+ trainer = RewardWeightedTrainer(
318
+ model = model,
319
+ args = training_args,
320
+ train_dataset = train_ds,
321
+ eval_dataset = eval_ds,
322
+ data_collator = collator,
323
+ tokenizer = processor.feature_extractor,
324
+ )
325
+
326
+ # ── Train ─────────────────────────────────────────────────────────────────────
327
+ trainer.train()
328
+
329
+ # ── Push to Hub ───────────────────────────────────────────────────────────────
330
+ login(token=HF_TOKEN)
331
+ model.push_to_hub(HF_PUSH_REPO)
332
+ processor.push_to_hub(HF_PUSH_REPO)
333
+ log.info(f"Pushed to https://huggingface.co/{HF_PUSH_REPO}")