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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
Colab-ready Knowledge Distillation script
|
| 4 |
+
Teacher : maya-research/veena-tts (4-bit)
|
| 5 |
+
Student : HuggingFaceTB/SmolLM-135M
|
| 6 |
+
Dataset : ArunKr/tts-hindi (HF Hub)
|
| 7 |
+
Output : push to hub -> ArunKr/smol-tts
|
| 8 |
+
|
| 9 |
+
How to run on Colab (single GPU):
|
| 10 |
+
-------------------------------------------------
|
| 11 |
+
1) !apt-get -y install libsndfile1
|
| 12 |
+
2) !pip install -U torch torchvision torchaudio transformers accelerate bitsandbytes snac soundfile wandb datasets einops sentencepiece
|
| 13 |
+
3) !huggingface-cli login # paste your token with write access to ArunKr
|
| 14 |
+
4) Save this file as distill_colab.py and run:
|
| 15 |
+
!accelerate launch distill_colab.py \
|
| 16 |
+
--hf_dataset ArunKr/tts-hindi \
|
| 17 |
+
--split train \
|
| 18 |
+
--text_key text \
|
| 19 |
+
--output_dir /content/outputs \
|
| 20 |
+
--push_to_hub True \
|
| 21 |
+
--hub_model_id ArunKr/smol-tts
|
| 22 |
+
"""
|
| 23 |
+
import os
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import random
|
| 27 |
+
import argparse
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
import torch.nn.functional as F
|
| 32 |
+
from torch.utils.data import Dataset, DataLoader
|
| 33 |
+
from accelerate import Accelerator
|
| 34 |
+
from transformers import (
|
| 35 |
+
AutoModelForCausalLM,
|
| 36 |
+
AutoTokenizer,
|
| 37 |
+
BitsAndBytesConfig,
|
| 38 |
+
get_cosine_schedule_with_warmup,
|
| 39 |
+
)
|
| 40 |
+
from datasets import load_dataset
|
| 41 |
+
from huggingface_hub import HfApi
|
| 42 |
+
|
| 43 |
+
# -----------------------------
|
| 44 |
+
# Teacher code from the prompt
|
| 45 |
+
# -----------------------------
|
| 46 |
+
from snac import SNAC # not used for KD but imported to satisfy trust_remote_code deps
|
| 47 |
+
import soundfile as sf # idem
|
| 48 |
+
|
| 49 |
+
START_OF_SPEECH_TOKEN = 128257
|
| 50 |
+
END_OF_SPEECH_TOKEN = 128258
|
| 51 |
+
START_OF_HUMAN_TOKEN = 128259
|
| 52 |
+
END_OF_HUMAN_TOKEN = 128260
|
| 53 |
+
START_OF_AI_TOKEN = 128261
|
| 54 |
+
END_OF_AI_TOKEN = 128262
|
| 55 |
+
AUDIO_CODE_BASE_OFFSET = 128266
|
| 56 |
+
|
| 57 |
+
SPEAKERS = ["kavya", "agastya", "maitri", "vinaya"]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def load_teacher(device_map="auto"):
|
| 61 |
+
quant_cfg = BitsAndBytesConfig(
|
| 62 |
+
load_in_4bit=True,
|
| 63 |
+
bnb_4bit_quant_type="nf4",
|
| 64 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 65 |
+
bnb_4bit_use_double_quant=True,
|
| 66 |
+
)
|
| 67 |
+
teacher = AutoModelForCausalLM.from_pretrained(
|
| 68 |
+
"maya-research/veena-tts",
|
| 69 |
+
quantization_config=quant_cfg,
|
| 70 |
+
device_map=device_map,
|
| 71 |
+
trust_remote_code=True,
|
| 72 |
+
)
|
| 73 |
+
teacher_tok = AutoTokenizer.from_pretrained("maya-research/veena-tts", trust_remote_code=True)
|
| 74 |
+
return teacher, teacher_tok
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# -----------------------------
|
| 78 |
+
# HF dataset wrapper
|
| 79 |
+
# -----------------------------
|
| 80 |
+
class HFDataset(Dataset):
|
| 81 |
+
def __init__(self, hf_ds, text_key, tokenizer, max_len):
|
| 82 |
+
self.ds = hf_ds
|
| 83 |
+
self.key = text_key
|
| 84 |
+
self.tok = tokenizer
|
| 85 |
+
self.max_len = max_len
|
| 86 |
+
if self.key not in self.ds.features:
|
| 87 |
+
raise ValueError(f"Column '{self.key}' not in dataset columns: {self.ds.features}")
|
| 88 |
+
|
| 89 |
+
def __len__(self):
|
| 90 |
+
return len(self.ds)
|
| 91 |
+
|
| 92 |
+
def __getitem__(self, idx):
|
| 93 |
+
text = self.ds[idx][self.key]
|
| 94 |
+
enc = self.tok(text, truncation=True, max_length=self.max_len, return_tensors="pt", add_special_tokens=True)
|
| 95 |
+
return {"input_ids": enc.input_ids[0], "attention_mask": enc.attention_mask[0], "text": text}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def collate(batch, pad_id):
|
| 99 |
+
input_ids = [b["input_ids"] for b in batch]
|
| 100 |
+
attn = [b["attention_mask"] for b in batch]
|
| 101 |
+
maxlen = max(x.size(0) for x in input_ids)
|
| 102 |
+
def pad(x, val):
|
| 103 |
+
if x.size(0) == maxlen:
|
| 104 |
+
return x
|
| 105 |
+
return torch.cat([x, torch.full((maxlen - x.size(0),), val, dtype=x.dtype)], dim=0)
|
| 106 |
+
input_ids = torch.stack([pad(x, pad_id) for x in input_ids])
|
| 107 |
+
attn = torch.stack([pad(x, 0) for x in attn])
|
| 108 |
+
return {"input_ids": input_ids, "attention_mask": attn}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# -----------------------------
|
| 112 |
+
# Distillation utils
|
| 113 |
+
# -----------------------------
|
| 114 |
+
@torch.no_grad()
|
| 115 |
+
def teacher_forward(teacher, teacher_tok, batch_text, device):
|
| 116 |
+
prompts = []
|
| 117 |
+
for txt in batch_text:
|
| 118 |
+
spk = random.choice(SPEAKERS)
|
| 119 |
+
p = f"<spk_{spk}> {txt}"
|
| 120 |
+
prompt_tokens = teacher_tok.encode(p, add_special_tokens=False)
|
| 121 |
+
seq = [START_OF_HUMAN_TOKEN, *prompt_tokens, END_OF_HUMAN_TOKEN, START_OF_AI_TOKEN]
|
| 122 |
+
prompts.append(seq)
|
| 123 |
+
|
| 124 |
+
max_len = max(len(p) for p in prompts)
|
| 125 |
+
input_ids = torch.full((len(prompts), max_len), teacher_tok.pad_token_id, dtype=torch.long, device=device)
|
| 126 |
+
attn_mask = torch.zeros_like(input_ids)
|
| 127 |
+
for i, seq in enumerate(prompts):
|
| 128 |
+
input_ids[i, : len(seq)] = torch.tensor(seq, device=device)
|
| 129 |
+
attn_mask[i, : len(seq)] = 1
|
| 130 |
+
|
| 131 |
+
out = teacher(input_ids=input_ids, attention_mask=attn_mask, output_logits=True)
|
| 132 |
+
return out.logits
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def kl_divergence(student_logits, teacher_logits, mask):
|
| 136 |
+
student_log_probs = F.log_softmax(student_logits, dim=-1)
|
| 137 |
+
teacher_probs = F.softmax(teacher_logits, dim=-1)
|
| 138 |
+
kl = F.kl_div(student_log_probs, teacher_probs, reduction='none').sum(-1)
|
| 139 |
+
kl = kl * mask
|
| 140 |
+
return kl.sum() / mask.sum().clamp(min=1)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# -----------------------------
|
| 144 |
+
# Main
|
| 145 |
+
# -----------------------------
|
| 146 |
+
|
| 147 |
+
def main():
|
| 148 |
+
parser = argparse.ArgumentParser()
|
| 149 |
+
parser.add_argument('--hf_dataset', type=str, default='ArunKr/tts-hindi')
|
| 150 |
+
parser.add_argument('--split', type=str, default='train')
|
| 151 |
+
parser.add_argument('--text_key', type=str, default='text')
|
| 152 |
+
parser.add_argument('--output_dir', type=str, required=True)
|
| 153 |
+
parser.add_argument('--epochs', type=int, default=3)
|
| 154 |
+
parser.add_argument('--batch_size', type=int, default=8)
|
| 155 |
+
parser.add_argument('--lr', type=float, default=2e-4)
|
| 156 |
+
parser.add_argument('--warmup_steps', type=int, default=500)
|
| 157 |
+
parser.add_argument('--max_len', type=int, default=512)
|
| 158 |
+
parser.add_argument('--seed', type=int, default=42)
|
| 159 |
+
parser.add_argument('--weight_ce', type=float, default=0.1)
|
| 160 |
+
parser.add_argument('--weight_kl', type=float, default=1.0)
|
| 161 |
+
parser.add_argument('--gradient_accumulation_steps', type=int, default=1)
|
| 162 |
+
parser.add_argument('--log_every', type=int, default=50)
|
| 163 |
+
parser.add_argument('--push_to_hub', type=lambda x: x.lower()=='true', default=False)
|
| 164 |
+
parser.add_argument('--hub_model_id', type=str, default='ArunKr/smol-tts')
|
| 165 |
+
args = parser.parse_args()
|
| 166 |
+
|
| 167 |
+
random.seed(args.seed)
|
| 168 |
+
torch.manual_seed(args.seed)
|
| 169 |
+
|
| 170 |
+
accelerator = Accelerator(log_with="wandb")
|
| 171 |
+
accelerator.init_trackers("distill-smollm135m", config=vars(args))
|
| 172 |
+
|
| 173 |
+
# Teacher
|
| 174 |
+
teacher, teacher_tok = load_teacher()
|
| 175 |
+
teacher.eval()
|
| 176 |
+
|
| 177 |
+
# Student
|
| 178 |
+
student_name = "HuggingFaceTB/SmolLM-135M"
|
| 179 |
+
student = AutoModelForCausalLM.from_pretrained(student_name)
|
| 180 |
+
student_tok = AutoTokenizer.from_pretrained(student_name)
|
| 181 |
+
if student_tok.pad_token is None:
|
| 182 |
+
student_tok.pad_token = student_tok.eos_token
|
| 183 |
+
|
| 184 |
+
# Dataset from HF Hub
|
| 185 |
+
raw_ds = load_dataset(args.hf_dataset, split=args.split)
|
| 186 |
+
ds = HFDataset(raw_ds, args.text_key, tokenizer=student_tok, max_len=args.max_len)
|
| 187 |
+
dl = DataLoader(ds, batch_size=args.batch_size, shuffle=True,
|
| 188 |
+
collate_fn=lambda b: collate(b, pad_id=student_tok.pad_token_id))
|
| 189 |
+
|
| 190 |
+
# Optimizer & scheduler
|
| 191 |
+
optim = torch.optim.AdamW(student.parameters(), lr=args.lr)
|
| 192 |
+
total_steps = args.epochs * math.ceil(len(ds) / (args.batch_size * args.gradient_accumulation_steps))
|
| 193 |
+
sched = get_cosine_schedule_with_warmup(optim, num_warmup_steps=args.warmup_steps, num_training_steps=total_steps)
|
| 194 |
+
|
| 195 |
+
student, optim, dl, sched = accelerator.prepare(student, optim, dl, sched)
|
| 196 |
+
|
| 197 |
+
global_step = 0
|
| 198 |
+
for epoch in range(args.epochs):
|
| 199 |
+
for step, batch in enumerate(dl):
|
| 200 |
+
student.train()
|
| 201 |
+
|
| 202 |
+
# Get original texts back
|
| 203 |
+
pad_id = student_tok.pad_token_id
|
| 204 |
+
texts = []
|
| 205 |
+
for ids in batch['input_ids']:
|
| 206 |
+
valid = ids[ids != pad_id].tolist()
|
| 207 |
+
texts.append(student_tok.decode(valid, skip_special_tokens=True))
|
| 208 |
+
|
| 209 |
+
with torch.no_grad():
|
| 210 |
+
t_logits = teacher_forward(teacher, teacher_tok, texts, device=accelerator.device)
|
| 211 |
+
|
| 212 |
+
s_in = batch['input_ids']
|
| 213 |
+
attn = batch['attention_mask']
|
| 214 |
+
B, L = s_in.shape
|
| 215 |
+
|
| 216 |
+
# align teacher length
|
| 217 |
+
if t_logits.size(1) < L:
|
| 218 |
+
pad = torch.zeros(B, L - t_logits.size(1), t_logits.size(2), device=t_logits.device)
|
| 219 |
+
t_logits = torch.cat([t_logits, pad], dim=1)
|
| 220 |
+
elif t_logits.size(1) > L:
|
| 221 |
+
t_logits = t_logits[:, :L]
|
| 222 |
+
|
| 223 |
+
outputs = student(input_ids=s_in, attention_mask=attn)
|
| 224 |
+
s_logits = outputs.logits
|
| 225 |
+
|
| 226 |
+
loss_mask = attn.clone()
|
| 227 |
+
loss_mask[:, 0] = 0
|
| 228 |
+
|
| 229 |
+
kd_loss = kl_divergence(s_logits, t_logits, loss_mask) * args.weight_kl
|
| 230 |
+
|
| 231 |
+
shift_logits = s_logits[:, :-1].contiguous()
|
| 232 |
+
shift_labels = s_in[:, 1:].contiguous()
|
| 233 |
+
shift_mask = loss_mask[:, 1:]
|
| 234 |
+
ce_loss = torch.nn.functional.cross_entropy(
|
| 235 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 236 |
+
shift_labels.view(-1),
|
| 237 |
+
reduction='none'
|
| 238 |
+
)
|
| 239 |
+
ce_loss = (ce_loss.view(B, -1) * shift_mask).sum() / shift_mask.sum().clamp(min=1)
|
| 240 |
+
ce_loss = ce_loss * args.weight_ce
|
| 241 |
+
|
| 242 |
+
loss = (kd_loss + ce_loss) / args.gradient_accumulation_steps
|
| 243 |
+
accelerator.backward(loss)
|
| 244 |
+
|
| 245 |
+
if (step + 1) % args.gradient_accumulation_steps == 0:
|
| 246 |
+
optim.step(); sched.step(); optim.zero_grad(); global_step += 1
|
| 247 |
+
|
| 248 |
+
if accelerator.is_main_process and global_step % args.log_every == 0:
|
| 249 |
+
accelerator.log({"loss": loss.item(), "kd_loss": kd_loss.item(), "ce_loss": ce_loss.item(), "lr": sched.get_last_lr()[0]}, step=global_step)
|
| 250 |
+
|
| 251 |
+
if accelerator.is_main_process:
|
| 252 |
+
save_dir = Path(args.output_dir) / f"epoch_{epoch}"
|
| 253 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 254 |
+
accelerator.unwrap_model(student).save_pretrained(save_dir)
|
| 255 |
+
student_tok.save_pretrained(save_dir)
|
| 256 |
+
|
| 257 |
+
# Final save & (optional) push to hub
|
| 258 |
+
if accelerator.is_main_process:
|
| 259 |
+
final_dir = Path(args.output_dir) / "final"
|
| 260 |
+
final_dir.mkdir(parents=True, exist_ok=True)
|
| 261 |
+
accelerator.unwrap_model(student).save_pretrained(final_dir)
|
| 262 |
+
student_tok.save_pretrained(final_dir)
|
| 263 |
+
if args.push_to_hub:
|
| 264 |
+
from transformers import AutoModelForCausalLM
|
| 265 |
+
AutoModelForCausalLM.from_pretrained(final_dir).push_to_hub(args.hub_model_id)
|
| 266 |
+
student_tok.push_to_hub(args.hub_model_id)
|
| 267 |
+
|
| 268 |
+
accelerator.end_training()
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
if __name__ == "__main__":
|
| 272 |
+
main()
|