# /// script # requires-python = ">=3.10" # dependencies = [ # "torch", # "transformers", # "datasets", # "peft", # "accelerate", # "soundfile", # "librosa", # "huggingface_hub", # "requests", # "numpy", # ] # /// """ Step 2: distill the turbo teacher into whisper-small. Uses pre-computed turbo soft targets (top-k logits per token, from precompute_soft_targets.py) so the 1.5GB teacher never has to be shipped. Loss = CE_WEIGHT * cross_entropy(labels) + KL_WEIGHT * T^2 * KL(student || teacher_soft) [content tokens only] The student re-tokenizes each transcript with the whisper-small tokenizer; the KL term is applied only at positions where teacher_label == student_label, which are exactly the shared content (word) tokens — this masks the special/prefix/eot tokens that differ between the large-v3 (51866) and small (51865) vocabularies. Env: HF_TOKEN HF write token HF_PUSH_REPO dataset repo to push the merged student to HF_PUSH_SUBFOLDER path within that repo (default: distill-small-merged) SOFT_TARGETS_REPO dataset repo holding turbo_soft_targets.pkl SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY """ import os, pickle, subprocess, tempfile, logging import numpy as np import requests import soundfile as sf import librosa import torch import torch.nn.functional as F from pathlib import Path from datasets import Dataset from transformers import ( WhisperProcessor, WhisperForConditionalGeneration, Trainer, TrainingArguments, ) from peft import LoraConfig, get_peft_model, TaskType from huggingface_hub import HfApi, hf_hub_download, 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) # ── Config ──────────────────────────────────────────────────────────────────── HF_TOKEN = os.environ["HF_TOKEN"] HF_PUSH_REPO = os.environ.get("HF_PUSH_REPO", "logosaccessibleexpression/training-scripts") HF_PUSH_SUBFOLDER = os.environ.get("HF_PUSH_SUBFOLDER", "distill-small-merged") SOFT_TARGETS_REPO = os.environ.get("SOFT_TARGETS_REPO", "logosaccessibleexpression/training-scripts") SOFT_TARGETS_FILE = os.environ.get("SOFT_TARGETS_FILE", "turbo_soft_targets.pkl") SUPABASE_URL = os.environ["SUPABASE_URL"] SERVICE_ROLE_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"] STUDENT = "openai/whisper-small" LORA_R = 32 LORA_ALPHA = 64 LORA_DROPOUT = 0.05 LORA_TARGETS = ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"] TEMP = 2.0 # distillation temperature CE_WEIGHT = 0.5 KL_WEIGHT = 0.5 TRAIN_EPOCHS = 8 BATCH_SIZE = 8 LEARNING_RATE = 1e-4 SAVE_STEPS = 50 OUTPUT_DIR = "/tmp/logos_distill_small" login(token=HF_TOKEN) # ── Load soft targets ───────────────────────────────────────────────────────── st_path = hf_hub_download(SOFT_TARGETS_REPO, SOFT_TARGETS_FILE, repo_type="dataset", token=HF_TOKEN) with open(st_path, "rb") as f: soft = pickle.load(f) records = soft["records"] log.info(f"Loaded {len(records)} soft-target records (teacher vocab {soft['meta']['vocab_size']})") processor = WhisperProcessor.from_pretrained(STUDENT) processor.tokenizer.set_prefix_tokens(language="en", task="transcribe") STUDENT_VOCAB = len(processor.tokenizer) # full output vocab incl. special tokens (51865) TOPK = soft["meta"]["topk"] # ── Download audio (Supabase) ───────────────────────────────────────────────── WAV_DIR = Path(tempfile.mkdtemp()) hdrs = {"apikey": SERVICE_ROLE_KEY, "Authorization": f"Bearer {SERVICE_ROLE_KEY}"} def download_audio(url, idx): r = requests.get(url.replace("/object/public/", "/object/"), headers=hdrs) if not r.ok: return None ext = url.split("?")[0].rsplit(".", 1)[-1].lower() raw = WAV_DIR / f"{idx}.{ext}" raw.write_bytes(r.content) if ext != "wav": wav = WAV_DIR / f"{idx}.wav" res = subprocess.run(["ffmpeg","-y","-i",str(raw),"-ac","1","-ar","16000","-sample_fmt","s16",str(wav)], capture_output=True) if res.returncode != 0: return None raw = wav try: audio, sr = sf.read(str(raw)) 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) # ── Build student examples with aligned teacher soft targets ────────────────── def build_example(rec, idx): audio = download_audio(rec["audio_url"], idx) if audio is None: return None feats = processor(audio, sampling_rate=16000).input_features[0] # [80, 3000] student_labels = processor.tokenizer(rec["text"]).input_ids # small-vocab ids teacher_labels = rec["label_ids"] L = min(len(student_labels), len(teacher_labels)) topk_idx = rec["topk_idx"][:L].astype(np.int64) # [L, K] (teacher-vocab ids) topk_val = rec["topk_val"][:L].astype(np.float32) # [L, K] (raw logits) slabels = np.array(student_labels[:L], dtype=np.int64) tlabels = np.array(teacher_labels[:L], dtype=np.int64) # distill only where teacher and student agree on the token => content tokens mask = (slabels == tlabels) # any teacher topk id outside student vocab can't be scored => neutralize it oob = topk_idx >= STUDENT_VOCAB topk_idx[oob] = 0 topk_val[oob] = -1e4 return { "input_features": feats, "labels": slabels, "topk_idx": topk_idx, "topk_val": topk_val, "distill_mask": mask, } examples = [] for i, rec in enumerate(records): ex = build_example(rec, i) if ex is not None: examples.append(ex) if (i + 1) % 50 == 0: log.info(f" built {i+1}/{len(records)}") log.info(f"Built {len(examples)} examples") ds = Dataset.from_list(examples) split = ds.train_test_split(test_size=max(1, int(len(ds) * 0.1)), seed=42) train_ds, eval_ds = split["train"], split["test"] log.info(f"Train {len(train_ds)} Eval {len(eval_ds)}") # ── Student model (LoRA) ────────────────────────────────────────────────────── model = WhisperForConditionalGeneration.from_pretrained(STUDENT) 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) model.print_trainable_parameters() # ── Collator ────────────────────────────────────────────────────────────────── class DistillCollator: def __call__(self, feats): x = torch.tensor(np.array([f["input_features"] for f in feats]), dtype=torch.float32) T = max(len(f["labels"]) for f in feats) B, K = len(feats), TOPK labels = torch.full((B, T), -100, dtype=torch.long) tidx = torch.zeros((B, T, K), dtype=torch.long) tval = torch.full((B, T, K), -1e4, dtype=torch.float32) dmask = torch.zeros((B, T), dtype=torch.bool) for i, f in enumerate(feats): L = len(f["labels"]) labels[i, :L] = torch.tensor(f["labels"]) tidx[i, :L] = torch.tensor(f["topk_idx"]) tval[i, :L] = torch.tensor(f["topk_val"]) dmask[i, :L] = torch.tensor(f["distill_mask"]) return {"input_features": x, "labels": labels, "teacher_idx": tidx, "teacher_val": tval, "distill_mask": dmask} # ── Distillation Trainer ────────────────────────────────────────────────────── class DistillTrainer(Trainer): def compute_loss(self, model, inputs, return_outputs=False, **kw): tidx = inputs.pop("teacher_idx") tval = inputs.pop("teacher_val") dmask = inputs.pop("distill_mask") whisper = model.base_model.model if hasattr(model, "base_model") else model out = whisper(input_features=inputs["input_features"], labels=inputs["labels"]) ce = out.loss logits = out.logits # [B, T, Vs] # KL on content positions, over the teacher's top-k indices s_logp = F.log_softmax(logits / TEMP, dim=-1) # [B, T, Vs] s_logp_k = torch.gather(s_logp, 2, tidx) # [B, T, K] t_prob = F.softmax(tval / TEMP, dim=-1) # [B, T, K] soft = -(t_prob * s_logp_k).sum(-1) # [B, T] m = dmask.float() kl = (soft * m).sum() / m.sum().clamp(min=1.0) loss = CE_WEIGHT * ce + KL_WEIGHT * (TEMP ** 2) * kl return (loss, out) if return_outputs else loss 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, remove_unused_columns=False, report_to=[], ) trainer = DistillTrainer( model=model, args=args, train_dataset=train_ds, eval_dataset=eval_ds, data_collator=DistillCollator(), processing_class=processor.feature_extractor, ) trainer.train() # ── Merge + push (transformers; CT2 conversion happens at deploy) ───────────── SAVE_DIR = "/tmp/logos_distill_small_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", path_in_repo=HF_PUSH_SUBFOLDER) log.info(f"Pushed merged student to {HF_PUSH_REPO}/{HF_PUSH_SUBFOLDER}")