| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """ |
| Logos Whisper Tiny β Reward-Weighted LoRA Fine-Tuning |
| HuggingFace Job script (uv run --script) |
| |
| Scores each training example against the *existing* fine-tuned model |
| (logos-voice-tiny-d43df745 checkpoint-3000), so the reward signal is |
| discriminative: examples the current model handles well get low weight, |
| hard/hallucinated ones get up to 3Γ weight. |
| |
| Fine-tuning starts from the same merged fine-tuned checkpoint and adds a |
| fresh LoRA delta. The final merged model (base + old LoRA + reward LoRA) |
| is pushed as a dataset repo (org token lacks model-create permission). |
| |
| Environment variables (set as job secrets/env): |
| HF_TOKEN β HuggingFace write token |
| HF_PUSH_REPO β dataset repo to push the trained model to |
| HF_FINETUNE_REPO β adapter repo to score/start from |
| HF_FINETUNE_SUBFOLDER β checkpoint subfolder (default: checkpoint-3000) |
| SUPABASE_URL β Supabase project URL |
| SUPABASE_KEY β Supabase anon/publishable key |
| SUPABASE_SERVICE_ROLE_KEY β long-lived service role JWT (preferred over REFRESH_TOKEN) |
| REFRESH_TOKEN β Supabase session refresh token (fallback) |
| USER_ID β Supabase user UUID |
| """ |
|
|
| import os, re, subprocess, tempfile, logging |
| import numpy as np |
| import requests |
| import soundfile as sf |
| import librosa |
| import syllapy |
| import torch |
| import torch.nn.functional as F |
| from pathlib import Path |
| from jiwer import process_words |
| from datasets import Dataset |
| from transformers import ( |
| WhisperProcessor, |
| WhisperForConditionalGeneration, |
| Trainer, |
| TrainingArguments, |
| ) |
| from peft import LoraConfig, PeftModel, get_peft_model, TaskType |
| from huggingface_hub import HfApi, login |
|
|
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s") |
| log = logging.getLogger(__name__) |
|
|
| |
| subprocess.run(["apt-get", "update", "-q"], check=True) |
| subprocess.run(["apt-get", "install", "-y", "-q", "ffmpeg"], check=True) |
|
|
| |
| HF_TOKEN = os.environ["HF_TOKEN"] |
| HF_PUSH_REPO = os.environ.get("HF_PUSH_REPO", "logosaccessibleexpression/logos-whisper-tiny-reward-ft") |
| HF_FINETUNE_REPO = os.environ.get("HF_FINETUNE_REPO", "logosaccessibleexpression/logos-voice-tiny-d43df745") |
| HF_FINETUNE_SUB = os.environ.get("HF_FINETUNE_SUBFOLDER", "checkpoint-3000") |
| SUPABASE_URL = os.environ["SUPABASE_URL"] |
| SUPABASE_KEY = os.environ["SUPABASE_KEY"] |
| SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY") |
| REFRESH_TOKEN = os.environ.get("REFRESH_TOKEN") |
| USER_ID = os.environ["USER_ID"] |
|
|
| WHISPER_BASE = "openai/whisper-tiny" |
| LORA_R = 16 |
| LORA_ALPHA = 32 |
| LORA_DROPOUT = 0.05 |
| |
| LORA_TARGETS = ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"] |
|
|
| REWARD_ALPHA = 1.0 |
| REWARD_BETA = 0.5 |
| REWARD_GAMMA = 0.5 |
| REWARD_DELTA = 0.5 |
| LOSS_SCALE = 2.0 |
|
|
| BEAM_N = 5 |
| TRAIN_EPOCHS = 5 |
| BATCH_SIZE = 8 |
| LEARNING_RATE = 1e-4 |
| SAVE_STEPS = 50 |
| OUTPUT_DIR = "/tmp/logos_reward_ft" |
|
|
| |
| if SERVICE_ROLE_KEY: |
| ACCESS_TOKEN = SERVICE_ROLE_KEY |
| SUPABASE_KEY = SERVICE_ROLE_KEY |
| else: |
| r = requests.post( |
| f"{SUPABASE_URL}/auth/v1/token?grant_type=refresh_token", |
| headers={"apikey": SUPABASE_KEY, "Content-Type": "application/json"}, |
| json={"refresh_token": REFRESH_TOKEN}, |
| ) |
| r.raise_for_status() |
| ACCESS_TOKEN = r.json()["access_token"] |
| log.info("Supabase auth OK") |
|
|
| def sb_get(table, select="*", filters=None): |
| headers = {"apikey": SUPABASE_KEY, "Authorization": f"Bearer {ACCESS_TOKEN}"} |
| params = {"select": select} |
| if filters: |
| params.update(filters) |
| r = requests.get(f"{SUPABASE_URL}/rest/v1/{table}", headers=headers, params=params) |
| r.raise_for_status() |
| return r.json() |
|
|
| |
| recordings = sb_get("training_recordings", select="audio_url,phrase_id", |
| filters={"user_id": f"eq.{USER_ID}"}) |
| phrases = sb_get("training_phrases", select="id,text") |
| phrase_map = {p["id"]: p["text"] for p in phrases} |
|
|
| dataset_raw = [ |
| {"audio_url": r["audio_url"], "text": phrase_map[r["phrase_id"]]} |
| for r in recordings if r["phrase_id"] in phrase_map |
| ] |
| log.info(f"Found {len(dataset_raw)} recordings") |
|
|
| |
| WAV_DIR = Path(tempfile.mkdtemp()) |
|
|
| def download_audio(url: str, idx: int) -> np.ndarray | None: |
| auth_url = url.replace("/object/public/", "/object/") |
| r = requests.get(auth_url, headers={ |
| "Authorization": f"Bearer {ACCESS_TOKEN}", |
| "apikey": SUPABASE_KEY, |
| }) |
| if not r.ok: |
| return None |
|
|
| ext = url.split("?")[0].rsplit(".", 1)[-1].lower() |
| raw_path = WAV_DIR / f"{idx}.{ext}" |
| raw_path.write_bytes(r.content) |
|
|
| if ext != "wav": |
| wav_path = WAV_DIR / f"{idx}.wav" |
| result = subprocess.run( |
| ["ffmpeg", "-y", "-i", str(raw_path), |
| "-ac", "1", "-ar", "16000", "-sample_fmt", "s16", str(wav_path)], |
| capture_output=True, |
| ) |
| if result.returncode != 0: |
| return None |
| raw_path = wav_path |
|
|
| try: |
| audio, sr = sf.read(str(raw_path)) |
| except Exception: |
| return None |
|
|
| if audio.ndim > 1: |
| audio = audio.mean(axis=1) |
| if sr != 16000: |
| audio = librosa.resample(audio, orig_sr=sr, target_sr=16000) |
| return audio.astype(np.float32) |
|
|
| skipped = 0 |
| for i, item in enumerate(dataset_raw): |
| item["audio"] = download_audio(item["audio_url"], i) |
| if item["audio"] is None: |
| skipped += 1 |
|
|
| dataset_raw = [d for d in dataset_raw if d["audio"] is not None] |
| log.info(f"Downloaded {len(dataset_raw)} recordings ({skipped} skipped)") |
|
|
| |
| def count_syllables(word: str) -> int: |
| word = re.sub(r"[^a-z']", "", word.lower()) |
| n = syllapy.count(word) |
| if n and n > 0: |
| return n |
| return max(1, len(re.findall(r"[aeiouy]+", word))) |
|
|
| def compute_reward(hypothesis: str, ground_truth: str) -> float: |
| hyp = hypothesis.strip().lower() |
| ref = ground_truth.strip().lower() |
| if not hyp: |
| return 0.0 |
| if hyp == ref: |
| return 1.0 |
|
|
| hyp_words = hyp.split() |
| ref_words = ref.split() |
|
|
| result = process_words(ref, hyp) |
| wer_comp = max(0.0, 1.0 - result.wer) |
|
|
| n_hyp = len(hyp_words) |
| pos_scores, syl_scores = [], [] |
|
|
| for chunk in result.alignments[0]: |
| ctype = chunk.type |
| if ctype in ("equal", "substitute"): |
| hyp_pos = chunk.hyp_start_idx |
| ref_w = ref_words[chunk.ref_start_idx] if chunk.ref_start_idx < len(ref_words) else "" |
| hyp_w = hyp_words[hyp_pos] if hyp_pos < n_hyp else "" |
| pos_w = 1.0 - 0.5 * (hyp_pos / max(1, n_hyp - 1)) |
| pos_scores.append(pos_w if ctype == "equal" else 0.0) |
| if ctype == "substitute" and ref_w and hyp_w: |
| syl_scores.append(1.0 if count_syllables(ref_w) == count_syllables(hyp_w) else 0.0) |
| elif ctype == "insert": |
| for k in range(chunk.hyp_start_idx, chunk.hyp_end_idx): |
| pos_scores.append(0.0) |
|
|
| pos_comp = float(np.mean(pos_scores)) if pos_scores else 0.0 |
| syl_comp = float(np.mean(syl_scores)) if syl_scores else 1.0 |
|
|
| ref_syl = sum(count_syllables(w) for w in ref_words) if ref_words else 1 |
| hyp_syl = sum(count_syllables(w) for w in hyp_words) if hyp_words else 0 |
| syl_count_comp = max(0.0, 1.0 - abs(ref_syl - hyp_syl) / max(ref_syl, 1)) |
|
|
| score = ( |
| REWARD_ALPHA * wer_comp + |
| REWARD_BETA * pos_comp + |
| REWARD_GAMMA * syl_comp + |
| REWARD_DELTA * syl_count_comp |
| ) / (REWARD_ALPHA + REWARD_BETA + REWARD_GAMMA + REWARD_DELTA) |
|
|
| return float(np.clip(score, 0.0, 1.0)) |
|
|
| |
| |
| |
| login(token=HF_TOKEN) |
| processor = WhisperProcessor.from_pretrained(WHISPER_BASE) |
|
|
| log.info(f"Loading scorer from {HF_FINETUNE_REPO}/{HF_FINETUNE_SUB}") |
| _scorer_base = WhisperForConditionalGeneration.from_pretrained(WHISPER_BASE) |
| _scorer_peft = PeftModel.from_pretrained(_scorer_base, HF_FINETUNE_REPO, |
| subfolder=HF_FINETUNE_SUB) |
| scorer = _scorer_peft.merge_and_unload().cuda().eval() |
| forced_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe") |
|
|
| def transcribe_audio(audio: np.ndarray, num_beams: int = BEAM_N) -> list: |
| feats = processor(audio, sampling_rate=16000, return_tensors="pt").input_features.cuda() |
| with torch.no_grad(): |
| ids = scorer.generate(feats, forced_decoder_ids=forced_ids, |
| num_beams=num_beams, num_return_sequences=num_beams) |
| return [processor.decode(seq, skip_special_tokens=True) for seq in ids] |
|
|
| for i, item in enumerate(dataset_raw): |
| hypotheses = transcribe_audio(item["audio"]) |
| best_score = max(compute_reward(h, item["text"]) for h in hypotheses) |
| item["reward_weight"] = 1.0 + LOSS_SCALE * (1.0 - best_score) |
| if (i + 1) % 20 == 0: |
| log.info(f" scored {i+1}/{len(dataset_raw)}") |
|
|
| del scorer |
| torch.cuda.empty_cache() |
|
|
| weights = [d["reward_weight"] for d in dataset_raw] |
| log.info(f"Reward weights β min {min(weights):.3f} max {max(weights):.3f} mean {np.mean(weights):.3f}") |
|
|
| |
| def preprocess(item): |
| feats = processor(item["audio"], sampling_rate=16000).input_features[0] |
| labels = processor.tokenizer(item["text"]).input_ids |
| return {"input_features": feats, "labels": labels, "reward_weight": item["reward_weight"]} |
|
|
| hf_data = Dataset.from_list([ |
| {"audio": d["audio"], "text": d["text"], "reward_weight": d["reward_weight"]} |
| for d in dataset_raw |
| ]).map(preprocess, remove_columns=["audio", "text"]) |
|
|
| split = hf_data.train_test_split(test_size=max(1, int(len(hf_data) * 0.1)), seed=42) |
| train_ds = split["train"] |
| eval_ds = split["test"] |
| log.info(f"Train: {len(train_ds)} Eval: {len(eval_ds)}") |
|
|
| |
| log.info(f"Loading training base from {HF_FINETUNE_REPO}/{HF_FINETUNE_SUB}") |
| _train_base = WhisperForConditionalGeneration.from_pretrained(WHISPER_BASE) |
| _train_peft = PeftModel.from_pretrained(_train_base, HF_FINETUNE_REPO, |
| subfolder=HF_FINETUNE_SUB) |
| model = _train_peft.merge_and_unload() |
| model.config.forced_decoder_ids = None |
| model.config.suppress_tokens = [] |
|
|
| lora_cfg = LoraConfig( |
| task_type = TaskType.SEQ_2_SEQ_LM, |
| r = LORA_R, |
| lora_alpha = LORA_ALPHA, |
| lora_dropout = LORA_DROPOUT, |
| target_modules = LORA_TARGETS, |
| ) |
| model = get_peft_model(model, lora_cfg) |
| log.info(str(model.print_trainable_parameters())) |
|
|
| |
| class RewardWeightedTrainer(Trainer): |
| def compute_loss(self, model, inputs, return_outputs=False, **kwargs): |
| reward_weights = inputs.pop("reward_weight").to(model.device) |
| labels = inputs["labels"] |
| |
| |
| |
| whisper = model.base_model.model if hasattr(model, 'base_model') else model |
| outputs = whisper(**inputs) |
| logits = outputs.logits |
|
|
| B, T, V = logits.shape |
| loss_per_token = F.cross_entropy( |
| logits.reshape(B * T, V), labels.reshape(B * T), |
| ignore_index=-100, reduction="none", |
| ).reshape(B, T) |
|
|
| valid = (labels != -100).float() |
| loss_per_ex = (loss_per_token * valid).sum(dim=1) / valid.sum(dim=1).clamp(min=1) |
| weighted_loss = (loss_per_ex * reward_weights).mean() |
|
|
| return (weighted_loss, outputs) if return_outputs else weighted_loss |
|
|
| class WhisperRewardCollator: |
| """Stack input_features, pad labels with -100, pass reward_weight through.""" |
| def __call__(self, features): |
| input_features = torch.tensor( |
| np.array([f["input_features"] for f in features]), dtype=torch.float32 |
| ) |
| max_len = max(len(f["labels"]) for f in features) |
| labels = torch.full((len(features), max_len), -100, dtype=torch.long) |
| for i, f in enumerate(features): |
| ids = torch.tensor(f["labels"], dtype=torch.long) |
| labels[i, :len(ids)] = ids |
| reward_weight = torch.tensor( |
| [f["reward_weight"] for f in features], dtype=torch.float32 |
| ) |
| return {"input_features": input_features, "labels": labels, "reward_weight": reward_weight} |
|
|
| collator = WhisperRewardCollator() |
|
|
| training_args = TrainingArguments( |
| output_dir = OUTPUT_DIR, |
| per_device_train_batch_size = BATCH_SIZE, |
| per_device_eval_batch_size = BATCH_SIZE, |
| num_train_epochs = TRAIN_EPOCHS, |
| learning_rate = LEARNING_RATE, |
| warmup_steps = 50, |
| gradient_accumulation_steps = 2, |
| fp16 = True, |
| eval_strategy = "steps", |
| eval_steps = SAVE_STEPS, |
| save_strategy = "steps", |
| save_steps = SAVE_STEPS, |
| logging_steps = 10, |
| load_best_model_at_end = True, |
| metric_for_best_model = "eval_loss", |
| greater_is_better = False, |
| push_to_hub = False, |
| remove_unused_columns = False, |
| ) |
|
|
| trainer = RewardWeightedTrainer( |
| model = model, |
| args = training_args, |
| train_dataset = train_ds, |
| eval_dataset = eval_ds, |
| data_collator = collator, |
| processing_class = processor.feature_extractor, |
| ) |
|
|
| |
| trainer.train() |
|
|
| |
| |
| |
| SAVE_DIR = "/tmp/logos_reward_ft_final" |
| merged = model.merge_and_unload() |
| merged.save_pretrained(SAVE_DIR) |
| processor.save_pretrained(SAVE_DIR) |
|
|
| api = HfApi(token=HF_TOKEN) |
| |
| api.upload_folder(folder_path=SAVE_DIR, repo_id=HF_PUSH_REPO, repo_type="dataset") |
| log.info(f"Pushed merged model to https://huggingface.co/datasets/{HF_PUSH_REPO}") |
|
|