LogosAccessibleExpression commited on
Commit
d4e0f11
Β·
verified Β·
1 Parent(s): 627e164

Upload logos_distill_small_job.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. logos_distill_small_job.py +261 -0
logos_distill_small_job.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch",
5
+ # "transformers",
6
+ # "datasets",
7
+ # "peft",
8
+ # "accelerate",
9
+ # "soundfile",
10
+ # "librosa",
11
+ # "huggingface_hub",
12
+ # "requests",
13
+ # "numpy",
14
+ # ]
15
+ # ///
16
+ """
17
+ Step 2: distill the turbo teacher into whisper-small.
18
+
19
+ Uses pre-computed turbo soft targets (top-k logits per token, from
20
+ precompute_soft_targets.py) so the 1.5GB teacher never has to be shipped.
21
+
22
+ Loss = CE_WEIGHT * cross_entropy(labels)
23
+ + KL_WEIGHT * T^2 * KL(student || teacher_soft) [content tokens only]
24
+
25
+ The student re-tokenizes each transcript with the whisper-small tokenizer; the KL
26
+ term is applied only at positions where teacher_label == student_label, which are
27
+ exactly the shared content (word) tokens β€” this masks the special/prefix/eot tokens
28
+ that differ between the large-v3 (51866) and small (51865) vocabularies.
29
+
30
+ Env:
31
+ HF_TOKEN HF write token
32
+ HF_PUSH_REPO dataset repo to push the merged student to
33
+ HF_PUSH_SUBFOLDER path within that repo (default: distill-small-merged)
34
+ SOFT_TARGETS_REPO dataset repo holding turbo_soft_targets.pkl
35
+ SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY
36
+ """
37
+ import os, pickle, subprocess, tempfile, logging
38
+ import numpy as np
39
+ import requests
40
+ import soundfile as sf
41
+ import librosa
42
+ import torch
43
+ import torch.nn.functional as F
44
+ from pathlib import Path
45
+ from datasets import Dataset
46
+ from transformers import (
47
+ WhisperProcessor,
48
+ WhisperForConditionalGeneration,
49
+ Trainer,
50
+ TrainingArguments,
51
+ )
52
+ from peft import LoraConfig, get_peft_model, TaskType
53
+ from huggingface_hub import HfApi, hf_hub_download, login
54
+
55
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
56
+ log = logging.getLogger(__name__)
57
+
58
+ subprocess.run(["apt-get", "update", "-q"], check=True)
59
+ subprocess.run(["apt-get", "install", "-y", "-q", "ffmpeg"], check=True)
60
+
61
+ # ── Config ────────────────────────────────────────────────────────────────────
62
+ HF_TOKEN = os.environ["HF_TOKEN"]
63
+ HF_PUSH_REPO = os.environ.get("HF_PUSH_REPO", "logosaccessibleexpression/training-scripts")
64
+ HF_PUSH_SUBFOLDER = os.environ.get("HF_PUSH_SUBFOLDER", "distill-small-merged")
65
+ SOFT_TARGETS_REPO = os.environ.get("SOFT_TARGETS_REPO", "logosaccessibleexpression/training-scripts")
66
+ SOFT_TARGETS_FILE = os.environ.get("SOFT_TARGETS_FILE", "turbo_soft_targets.pkl")
67
+ SUPABASE_URL = os.environ["SUPABASE_URL"]
68
+ SERVICE_ROLE_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"]
69
+
70
+ STUDENT = "openai/whisper-small"
71
+ LORA_R = 32
72
+ LORA_ALPHA = 64
73
+ LORA_DROPOUT = 0.05
74
+ LORA_TARGETS = ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"]
75
+
76
+ TEMP = 2.0 # distillation temperature
77
+ CE_WEIGHT = 0.5
78
+ KL_WEIGHT = 0.5
79
+
80
+ TRAIN_EPOCHS = 8
81
+ BATCH_SIZE = 8
82
+ LEARNING_RATE = 1e-4
83
+ SAVE_STEPS = 50
84
+ OUTPUT_DIR = "/tmp/logos_distill_small"
85
+
86
+ login(token=HF_TOKEN)
87
+
88
+ # ── Load soft targets ─────────────────────────────────────────────────────────
89
+ st_path = hf_hub_download(SOFT_TARGETS_REPO, SOFT_TARGETS_FILE, repo_type="dataset", token=HF_TOKEN)
90
+ with open(st_path, "rb") as f:
91
+ soft = pickle.load(f)
92
+ records = soft["records"]
93
+ log.info(f"Loaded {len(records)} soft-target records (teacher vocab {soft['meta']['vocab_size']})")
94
+
95
+ processor = WhisperProcessor.from_pretrained(STUDENT)
96
+ processor.tokenizer.set_prefix_tokens(language="en", task="transcribe")
97
+ STUDENT_VOCAB = len(processor.tokenizer) # full output vocab incl. special tokens (51865)
98
+ TOPK = soft["meta"]["topk"]
99
+
100
+ # ── Download audio (Supabase) ─────────────────────────────────────────────────
101
+ WAV_DIR = Path(tempfile.mkdtemp())
102
+ hdrs = {"apikey": SERVICE_ROLE_KEY, "Authorization": f"Bearer {SERVICE_ROLE_KEY}"}
103
+
104
+ def download_audio(url, idx):
105
+ r = requests.get(url.replace("/object/public/", "/object/"), headers=hdrs)
106
+ if not r.ok:
107
+ return None
108
+ ext = url.split("?")[0].rsplit(".", 1)[-1].lower()
109
+ raw = WAV_DIR / f"{idx}.{ext}"
110
+ raw.write_bytes(r.content)
111
+ if ext != "wav":
112
+ wav = WAV_DIR / f"{idx}.wav"
113
+ res = subprocess.run(["ffmpeg","-y","-i",str(raw),"-ac","1","-ar","16000","-sample_fmt","s16",str(wav)],
114
+ capture_output=True)
115
+ if res.returncode != 0:
116
+ return None
117
+ raw = wav
118
+ try:
119
+ audio, sr = sf.read(str(raw))
120
+ except Exception:
121
+ return None
122
+ if audio.ndim > 1:
123
+ audio = audio.mean(axis=1)
124
+ if sr != 16000:
125
+ audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)
126
+ return audio.astype(np.float32)
127
+
128
+ # ── Build student examples with aligned teacher soft targets ��─────────────────
129
+ def build_example(rec, idx):
130
+ audio = download_audio(rec["audio_url"], idx)
131
+ if audio is None:
132
+ return None
133
+ feats = processor(audio, sampling_rate=16000).input_features[0] # [80, 3000]
134
+ student_labels = processor.tokenizer(rec["text"]).input_ids # small-vocab ids
135
+ teacher_labels = rec["label_ids"]
136
+ L = min(len(student_labels), len(teacher_labels))
137
+
138
+ topk_idx = rec["topk_idx"][:L].astype(np.int64) # [L, K] (teacher-vocab ids)
139
+ topk_val = rec["topk_val"][:L].astype(np.float32) # [L, K] (raw logits)
140
+ slabels = np.array(student_labels[:L], dtype=np.int64)
141
+ tlabels = np.array(teacher_labels[:L], dtype=np.int64)
142
+
143
+ # distill only where teacher and student agree on the token => content tokens
144
+ mask = (slabels == tlabels)
145
+
146
+ # any teacher topk id outside student vocab can't be scored => neutralize it
147
+ oob = topk_idx >= STUDENT_VOCAB
148
+ topk_idx[oob] = 0
149
+ topk_val[oob] = -1e4
150
+
151
+ return {
152
+ "input_features": feats,
153
+ "labels": slabels,
154
+ "topk_idx": topk_idx,
155
+ "topk_val": topk_val,
156
+ "distill_mask": mask,
157
+ }
158
+
159
+ examples = []
160
+ for i, rec in enumerate(records):
161
+ ex = build_example(rec, i)
162
+ if ex is not None:
163
+ examples.append(ex)
164
+ if (i + 1) % 50 == 0:
165
+ log.info(f" built {i+1}/{len(records)}")
166
+ log.info(f"Built {len(examples)} examples")
167
+
168
+ ds = Dataset.from_list(examples)
169
+ split = ds.train_test_split(test_size=max(1, int(len(ds) * 0.1)), seed=42)
170
+ train_ds, eval_ds = split["train"], split["test"]
171
+ log.info(f"Train {len(train_ds)} Eval {len(eval_ds)}")
172
+
173
+ # ── Student model (LoRA) ──────────────────────────────────────────────────────
174
+ model = WhisperForConditionalGeneration.from_pretrained(STUDENT)
175
+ model.config.forced_decoder_ids = None
176
+ model.config.suppress_tokens = []
177
+ lora_cfg = LoraConfig(task_type=TaskType.SEQ_2_SEQ_LM, r=LORA_R, lora_alpha=LORA_ALPHA,
178
+ lora_dropout=LORA_DROPOUT, target_modules=LORA_TARGETS)
179
+ model = get_peft_model(model, lora_cfg)
180
+ model.print_trainable_parameters()
181
+
182
+ # ── Collator ──────────────────────────────────────────────────────────────────
183
+ class DistillCollator:
184
+ def __call__(self, feats):
185
+ x = torch.tensor(np.array([f["input_features"] for f in feats]), dtype=torch.float32)
186
+ T = max(len(f["labels"]) for f in feats)
187
+ B, K = len(feats), TOPK
188
+ labels = torch.full((B, T), -100, dtype=torch.long)
189
+ tidx = torch.zeros((B, T, K), dtype=torch.long)
190
+ tval = torch.full((B, T, K), -1e4, dtype=torch.float32)
191
+ dmask = torch.zeros((B, T), dtype=torch.bool)
192
+ for i, f in enumerate(feats):
193
+ L = len(f["labels"])
194
+ labels[i, :L] = torch.tensor(f["labels"])
195
+ tidx[i, :L] = torch.tensor(f["topk_idx"])
196
+ tval[i, :L] = torch.tensor(f["topk_val"])
197
+ dmask[i, :L] = torch.tensor(f["distill_mask"])
198
+ return {"input_features": x, "labels": labels,
199
+ "teacher_idx": tidx, "teacher_val": tval, "distill_mask": dmask}
200
+
201
+ # ── Distillation Trainer ──────────────────────────────────────────────────────
202
+ class DistillTrainer(Trainer):
203
+ def compute_loss(self, model, inputs, return_outputs=False, **kw):
204
+ tidx = inputs.pop("teacher_idx")
205
+ tval = inputs.pop("teacher_val")
206
+ dmask = inputs.pop("distill_mask")
207
+ whisper = model.base_model.model if hasattr(model, "base_model") else model
208
+ out = whisper(input_features=inputs["input_features"], labels=inputs["labels"])
209
+ ce = out.loss
210
+ logits = out.logits # [B, T, Vs]
211
+
212
+ # KL on content positions, over the teacher's top-k indices
213
+ s_logp = F.log_softmax(logits / TEMP, dim=-1) # [B, T, Vs]
214
+ s_logp_k = torch.gather(s_logp, 2, tidx) # [B, T, K]
215
+ t_prob = F.softmax(tval / TEMP, dim=-1) # [B, T, K]
216
+ soft = -(t_prob * s_logp_k).sum(-1) # [B, T]
217
+ m = dmask.float()
218
+ kl = (soft * m).sum() / m.sum().clamp(min=1.0)
219
+
220
+ loss = CE_WEIGHT * ce + KL_WEIGHT * (TEMP ** 2) * kl
221
+ return (loss, out) if return_outputs else loss
222
+
223
+ args = TrainingArguments(
224
+ output_dir=OUTPUT_DIR,
225
+ per_device_train_batch_size=BATCH_SIZE,
226
+ per_device_eval_batch_size=BATCH_SIZE,
227
+ num_train_epochs=TRAIN_EPOCHS,
228
+ learning_rate=LEARNING_RATE,
229
+ warmup_steps=50,
230
+ gradient_accumulation_steps=2,
231
+ fp16=True,
232
+ eval_strategy="steps",
233
+ eval_steps=SAVE_STEPS,
234
+ save_strategy="steps",
235
+ save_steps=SAVE_STEPS,
236
+ logging_steps=10,
237
+ load_best_model_at_end=True,
238
+ metric_for_best_model="eval_loss",
239
+ greater_is_better=False,
240
+ remove_unused_columns=False,
241
+ report_to=[],
242
+ )
243
+
244
+ trainer = DistillTrainer(
245
+ model=model, args=args,
246
+ train_dataset=train_ds, eval_dataset=eval_ds,
247
+ data_collator=DistillCollator(),
248
+ processing_class=processor.feature_extractor,
249
+ )
250
+ trainer.train()
251
+
252
+ # ── Merge + push (transformers; CT2 conversion happens at deploy) ─────────────
253
+ SAVE_DIR = "/tmp/logos_distill_small_final"
254
+ merged = model.merge_and_unload()
255
+ merged.save_pretrained(SAVE_DIR)
256
+ processor.save_pretrained(SAVE_DIR)
257
+
258
+ api = HfApi(token=HF_TOKEN)
259
+ api.upload_folder(folder_path=SAVE_DIR, repo_id=HF_PUSH_REPO, repo_type="dataset",
260
+ path_in_repo=HF_PUSH_SUBFOLDER)
261
+ log.info(f"Pushed merged student to {HF_PUSH_REPO}/{HF_PUSH_SUBFOLDER}")