training-scripts / finetune_lora_whisper_tiny_300.py
LogosAccessibleExpression's picture
Add whisper-tiny LoRA training script
f26b180 verified
Raw
History Blame Contribute Delete
20.7 kB
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "transformers",
# "datasets",
# "accelerate",
# "soundfile",
# "librosa",
# "supabase",
# "huggingface_hub",
# "evaluate",
# "jiwer",
# "peft",
# "optuna",
# "ctranslate2",
# "torchao>=0.16.0",
# "pandas",
# ]
# ///
"""Optuna LoRA Search β€” Whisper Tiny
Downloads recordings for USER_ID from Supabase, runs Optuna hyperparameter
search (15 trials Γ— 300 steps), retrains best config for 3000 steps on all
recordings, pushes checkpoints to Hub every 500 steps (resumable), converts
to CTranslate2 float16 (faster-whisper compatible), then marks model_versions
status='ready'.
Required env vars (injected by trigger-training via HF Jobs):
SUPABASE_URL Supabase project URL
SUPABASE_SERVICE_ROLE_KEY service role key (bypasses RLS)
USER_ID UUID of the user to train for
HF_TOKEN HF write token
HF_REPO_ID target repo, e.g. "yourname/logos-voice-abc12345"
"""
import gc
import os
import re
import random
import shutil
import subprocess
import sys
os.environ["TQDM_DISABLE"] = "1" # must be before tqdm-using library imports
subprocess.run(['apt-get', 'install', '-y', '-q', 'ffmpeg'], check=False)
import librosa
import optuna
import pandas as pd
import soundfile as sf
import torch
from datasets import Dataset
from dataclasses import dataclass
from typing import Any
from huggingface_hub import login, create_repo, list_repo_files, snapshot_download, upload_folder
from peft import LoraConfig, TaskType, get_peft_model
from supabase import create_client
from transformers import (
Trainer,
TrainerCallback,
TrainingArguments,
WhisperConfig,
WhisperForConditionalGeneration,
WhisperProcessor,
)
import evaluate
# ── Config ────────────────────────────────────────────────────────────────────
SUPABASE_URL = os.environ['SUPABASE_URL']
SUPABASE_SERVICE_ROLE_KEY = os.environ['SUPABASE_SERVICE_ROLE_KEY']
USER_ID = os.environ['USER_ID']
HF_TOKEN = os.environ['HF_TOKEN']
HF_REPO_ID = os.environ['HF_REPO_ID']
MODEL_NAME = 'openai/whisper-tiny'
WORK_DIR = '/tmp/logos_training'
TRIAL_STEPS = 300
FINAL_STEPS = 3000
os.makedirs(WORK_DIR, exist_ok=True)
sb = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)
login(token=HF_TOKEN)
# ── Find or create model_versions training row ────────────────────────────────
_existing = (
sb.table('model_versions')
.select('id, version')
.eq('user_id', USER_ID)
.eq('status', 'training')
.limit(1)
.execute()
)
if _existing.data:
_mv_id = _existing.data[0]['id']
_mv_version = _existing.data[0]['version']
print(f'Using existing model_versions row v{_mv_version}')
else:
_latest = (
sb.table('model_versions')
.select('version')
.eq('user_id', USER_ID)
.order('version', desc=True)
.limit(1)
.execute()
)
_mv_version = ((_latest.data[0]['version']) if _latest.data else 0) + 1
_result = (
sb.table('model_versions')
.insert({'user_id': USER_ID, 'version': _mv_version, 'status': 'training'})
.execute()
)
_mv_id = _result.data[0]['id']
print(f'Inserted model_versions row v{_mv_version}')
def _fail(msg: str):
sb.table('model_versions').update({'status': 'failed'}).eq('id', _mv_id).execute()
sys.exit(f'FATAL: {msg}')
# ── Download recordings from Supabase ─────────────────────────────────────────
response = (
sb.table('training_recordings')
.select('audio_url, phrase_id, training_phrases(text)')
.eq('user_id', USER_ID)
.execute()
)
print(f'Found {len(response.data)} recordings in Supabase')
all_recordings = []
for row in response.data:
phrase_text = (row.get('training_phrases') or {}).get('text', '').strip()
audio_url = row['audio_url']
phrase_id = row['phrase_id']
if not phrase_text or not audio_url:
continue
storage_path = None
for marker in ('/object/public/training-audio/', '/object/authenticated/training-audio/'):
idx = audio_url.find(marker)
if idx != -1:
storage_path = audio_url[idx + len(marker):]
break
if storage_path is None:
print(f' Skipping unexpected URL: {audio_url}')
continue
src_ext = 'wav' if storage_path.lower().endswith('.wav') else 'webm'
raw_path = f'{WORK_DIR}/{phrase_id}_raw.{src_ext}'
local_path = f'{WORK_DIR}/{phrase_id}.wav'
try:
raw_bytes = sb.storage.from_('training-audio').download(storage_path)
with open(raw_path, 'wb') as f:
f.write(raw_bytes)
audio_array, _ = librosa.load(raw_path, sr=16000, mono=True)
sf.write(local_path, audio_array, 16000)
os.remove(raw_path)
all_recordings.append({'phrase': phrase_text, 'audio_path': local_path})
except Exception as e:
print(f' Failed {storage_path}: {e}')
print(f'Downloaded and converted {len(all_recordings)} recordings')
if len(all_recordings) < 100:
_fail(f'Need at least 100 recordings, found {len(all_recordings)}')
# ── Fixed validation split ─────────────────────────────────────────────────────
random.seed(42)
shuffled = all_recordings.copy()
random.shuffle(shuffled)
val_recordings = shuffled[:50]
train_recordings = shuffled[50:]
print(f'Total: {len(all_recordings)} Train: {len(train_recordings)} Val: {len(val_recordings)}')
# ── Preprocess training data once (reused across all trials) ──────────────────
processor = WhisperProcessor.from_pretrained(MODEL_NAME)
processor.tokenizer.set_prefix_tokens(language='english', task='transcribe')
def preprocess(batch):
audio_array, sr = librosa.load(batch['audio_path'], sr=16000, mono=True)
batch['input_features'] = processor.feature_extractor(
audio_array, sampling_rate=sr
).input_features[0]
batch['labels'] = processor.tokenizer(batch['phrase']).input_ids
return batch
train_dataset = Dataset.from_pandas(pd.DataFrame(train_recordings))
train_processed = train_dataset.map(preprocess, remove_columns=train_dataset.column_names)
print('Train dataset preprocessed:', train_processed)
# ── Data collator ─────────────────────────────────────────────────────────────
@dataclass
class DataCollatorSpeechSeq2SeqWithPadding:
processor: Any
decoder_start_token_id: int
def __call__(self, features):
input_features = [{'input_features': f['input_features']} for f in features]
batch = self.processor.feature_extractor.pad(input_features, return_tensors='pt')
label_features = [{'input_ids': f['labels']} for f in features]
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors='pt')
labels = labels_batch['input_ids'].masked_fill(
labels_batch.attention_mask.ne(1), -100
)
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
labels = labels[:, 1:]
batch['labels'] = labels
return batch
_cfg = WhisperConfig.from_pretrained(MODEL_NAME)
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
processor=processor,
decoder_start_token_id=_cfg.decoder_start_token_id,
)
# ── Evaluation ────────────────────────────────────────────────────────────────
wer_metric = evaluate.load('wer')
def score_on_my_recordings(model, verbose=False):
model.eval()
predictions, references = [], []
with torch.no_grad():
for rec in val_recordings:
audio_array, sr = librosa.load(rec['audio_path'], sr=16000, mono=True)
inputs = processor.feature_extractor(audio_array, sampling_rate=sr, return_tensors='pt')
# Match the model's param dtype (LoRA training keeps weights in fp32 under
# fp16=True autocast, so the model is NOT half) β€” force-casting inputs to
# .half() crashes the encoder conv1d with a Half/float bias mismatch.
input_features = inputs.input_features.to(device=model.device, dtype=next(model.parameters()).dtype)
predicted_ids = model.generate(
input_features=input_features,
language='english',
task='transcribe',
max_new_tokens=128,
)
pred = processor.tokenizer.batch_decode(
predicted_ids, skip_special_tokens=True
)[0].strip().lower()
references.append(rec['phrase'].lower())
predictions.append(pred)
wer = wer_metric.compute(predictions=predictions, references=references)
accuracy = max(0.0, 1.0 - wer)
pairs = list(zip(references, predictions))
if verbose:
for ref, pred in pairs:
print(f' [{"OK" if ref == pred else "XX"}] REF: {ref}')
print(f' PRD: {pred}')
return accuracy, wer, pairs
# ── PEFT/Whisper compatibility patch ─────────────────────────────────────────
def _patch_whisper_peft(model):
whisper = model.base_model.model
def _forward(**kwargs):
kwargs.pop('input_ids', None)
return whisper(**kwargs)
model.forward = _forward
return model
# ── Progress callback ─────────────────────────────────────────────────────────
class StepProgressCallback(TrainerCallback):
def on_step_end(self, args, state, control, **kwargs):
if state.global_step % 25 == 0 and state.global_step > 0:
print(f" step {state.global_step}/{state.max_steps}", flush=True)
# ── Hub checkpoint callback (final training only) ─────────────────────────────
class HubCheckpointCallback(TrainerCallback):
def on_save(self, args, state, control, **kwargs):
ckpt_dir = f'{args.output_dir}/checkpoint-{state.global_step}'
if not os.path.exists(ckpt_dir):
return
try:
upload_folder(
folder_path=ckpt_dir,
repo_id=HF_REPO_ID,
path_in_repo=f'checkpoint-{state.global_step}',
repo_type='model',
token=HF_TOKEN,
)
print(f' [hub] pushed checkpoint-{state.global_step}', flush=True)
except Exception as e:
print(f' [hub] checkpoint push failed: {e}', flush=True)
# ── Optuna search ─────────────────────────────────────────────────────────────
TARGET_MODULE_PRESETS = {
'minimal': ['q_proj', 'v_proj'],
'attention': ['q_proj', 'k_proj', 'v_proj', 'out_proj'],
'full': ['q_proj', 'k_proj', 'v_proj', 'out_proj', 'fc1', 'fc2'],
}
def objective(trial):
r = trial.suggest_categorical('r', [8, 16, 32])
lora_dropout = trial.suggest_categorical('lora_dropout', [0.0, 0.05, 0.1])
learning_rate = trial.suggest_float('learning_rate', 5e-5, 1e-3, log=True) # tiny tolerates higher LR
modules_key = trial.suggest_categorical('target_modules', ['minimal', 'attention', 'full'])
warmup_steps = trial.suggest_categorical('warmup_steps', [0, 50, 100])
weight_decay = trial.suggest_categorical('weight_decay', [0.0, 0.01, 0.1])
print(f'\n=== Trial {trial.number} | r={r} dropout={lora_dropout} '
f'lr={learning_rate:.2e} modules={modules_key} warmup={warmup_steps} wd={weight_decay} ===')
base = WhisperForConditionalGeneration.from_pretrained(MODEL_NAME)
base.config.suppress_tokens = None
base.config.forced_decoder_ids = None
base.config.use_cache = False
peft_model = get_peft_model(base, LoraConfig(
r=r, lora_alpha=r * 2,
target_modules=TARGET_MODULE_PRESETS[modules_key],
lora_dropout=lora_dropout, bias='none',
task_type=TaskType.SEQ_2_SEQ_LM,
))
peft_model.enable_input_require_grads()
peft_model.print_trainable_parameters()
_patch_whisper_peft(peft_model)
trainer = Trainer(
args=TrainingArguments(
output_dir=f'{WORK_DIR}/trial_{trial.number}',
per_device_train_batch_size=16, # tiny fits 2x the batch
gradient_accumulation_steps=2,
learning_rate=learning_rate,
weight_decay=weight_decay,
warmup_steps=warmup_steps,
max_steps=TRIAL_STEPS,
gradient_checkpointing=True,
fp16=True,
eval_strategy='no',
save_strategy='no',
logging_steps=50,
push_to_hub=False,
remove_unused_columns=False,
label_names=['labels'],
report_to='none',
),
model=peft_model,
train_dataset=train_processed,
data_collator=data_collator,
callbacks=[StepProgressCallback()],
)
trainer.train()
peft_model.base_model.model.config.use_cache = True
accuracy, wer, samples = score_on_my_recordings(peft_model.cuda())
print(f'Trial {trial.number} β†’ accuracy={accuracy:.3f} WER={wer:.3f}')
for ref, pred in samples[:5]:
print(f' REF: {ref}\n PRD: {pred}')
del peft_model, trainer, base
gc.collect()
torch.cuda.empty_cache()
return accuracy
optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(direction='maximize', study_name='whisper_tiny_lora_search')
study.optimize(objective, n_trials=15)
print(f'\n=== Search complete β€” best accuracy: {study.best_value:.3f} ===')
print(f'Best params: {study.best_params}')
results = []
for t in study.trials:
if t.value is not None:
row = {'trial': t.number, 'accuracy': round(t.value, 3), 'wer': round(1 - t.value, 3)}
row.update(t.params)
results.append(row)
print(pd.DataFrame(results).sort_values('accuracy', ascending=False).to_string(index=False))
# ── Final training on all recordings ─────────────────────────────────────────
best = study.best_params
full_dataset = Dataset.from_pandas(pd.DataFrame(all_recordings))
full_processed = full_dataset.map(preprocess, remove_columns=full_dataset.column_names)
print('Full dataset preprocessed:', full_processed)
print(f'Training best config for {FINAL_STEPS} steps on all {len(all_recordings)} recordings...')
print(f'Best params: {best}')
# Ensure repo exists before checkpoint callback tries to push
create_repo(HF_REPO_ID, repo_type='model', private=True, exist_ok=True, token=HF_TOKEN)
# Check Hub for a resumable checkpoint from a previous interrupted run
def _find_latest_hub_checkpoint():
try:
files = list(list_repo_files(HF_REPO_ID, repo_type='model', token=HF_TOKEN))
steps = [int(m.group(1)) for f in files if (m := re.match(r'checkpoint-(\d+)/', f))]
return max(steps) if steps else None
except Exception:
return None
_latest_step = _find_latest_hub_checkpoint()
resume_path = None
if _latest_step:
print(f'Found Hub checkpoint at step {_latest_step}, downloading...')
snapshot_download(
repo_id=HF_REPO_ID,
allow_patterns=f'checkpoint-{_latest_step}/**',
local_dir=f'{WORK_DIR}/final',
repo_type='model',
token=HF_TOKEN,
)
resume_path = f'{WORK_DIR}/final/checkpoint-{_latest_step}'
print(f'Resuming from step {_latest_step}')
else:
print('No Hub checkpoint found, starting from scratch')
best_base = WhisperForConditionalGeneration.from_pretrained(MODEL_NAME)
best_base.config.suppress_tokens = None
best_base.config.forced_decoder_ids = None
best_base.config.use_cache = False
best_model = get_peft_model(best_base, LoraConfig(
r=best['r'], lora_alpha=best['r'] * 2,
target_modules=TARGET_MODULE_PRESETS[best['target_modules']],
lora_dropout=best['lora_dropout'], bias='none',
task_type=TaskType.SEQ_2_SEQ_LM,
))
best_model.enable_input_require_grads()
best_model.print_trainable_parameters()
_patch_whisper_peft(best_model)
Trainer(
args=TrainingArguments(
output_dir=f'{WORK_DIR}/final',
per_device_train_batch_size=16, # tiny fits 2x the batch
gradient_accumulation_steps=2,
learning_rate=best['learning_rate'],
warmup_steps=best['warmup_steps'],
max_steps=FINAL_STEPS,
gradient_checkpointing=True,
fp16=True,
eval_strategy='no',
save_strategy='steps',
save_steps=500,
logging_steps=50,
push_to_hub=False,
remove_unused_columns=False,
label_names=['labels'],
report_to='none',
),
model=best_model,
train_dataset=full_processed,
data_collator=data_collator,
callbacks=[StepProgressCallback(), HubCheckpointCallback()],
).train(resume_from_checkpoint=resume_path)
best_model.base_model.model.config.use_cache = True
accuracy, wer, _ = score_on_my_recordings(best_model.cuda(), verbose=True)
print(f'\nFinal model β†’ accuracy={accuracy:.3f} WER={wer:.3f}')
# ── Merge LoRA ────────────────────────────────────────────────────────────────
print('Merging LoRA weights...')
merged_path = f'{WORK_DIR}/merged'
final_merged = best_model.merge_and_unload()
final_merged.save_pretrained(merged_path)
processor.save_pretrained(merged_path)
print(f'Saved merged model to {merged_path}')
del best_model, final_merged
gc.collect()
torch.cuda.empty_cache()
# ── Convert to CTranslate2 (faster-whisper) ───────────────────────────────────
ct2_path = f'{WORK_DIR}/ct2'
print('Converting to CTranslate2 float16 (faster-whisper compatible)...')
subprocess.run([
'ct2-transformers-converter',
'--model', merged_path,
'--output_dir', ct2_path,
'--quantization', 'float16',
'--force',
], check=True)
for fname in os.listdir(merged_path):
if fname.endswith('.json') and fname != 'config.json':
src = os.path.join(merged_path, fname)
dst = os.path.join(ct2_path, fname)
if not os.path.exists(dst):
shutil.copy2(src, dst)
print('CTranslate2 conversion complete')
# ── Push CT2 model to Hub ─────────────────────────────────────────────────────
print(f'Pushing faster-whisper model to {HF_REPO_ID}...')
try:
upload_folder(
folder_path=ct2_path,
repo_id=HF_REPO_ID,
repo_type='model',
token=HF_TOKEN,
ignore_patterns=['checkpoint-*/**'],
)
print(f'Model live at https://huggingface.co/{HF_REPO_ID}')
except Exception as e:
_fail(f'push_to_hub failed: {e}')
# ── Mark model ready in Supabase ──────────────────────────────────────────────
sb.table('model_versions').update({
'status': 'ready',
'avg_accuracy': round(accuracy * 100, 2),
'training_samples_count': len(all_recordings),
'model_metadata': {
'hf_repo_id': HF_REPO_ID,
'base_model': MODEL_NAME,
'search_best_params': best,
'search_best_accuracy': round(study.best_value, 3),
'final_wer': round(wer, 4),
'n_trials': 15,
'trial_steps': TRIAL_STEPS,
'final_steps': FINAL_STEPS,
},
}).eq('id', _mv_id).execute()
print(f'model_versions v{_mv_version} β†’ ready (accuracy={accuracy:.3f} repo={HF_REPO_ID})')