Upload logos_reward_ft_job.py with huggingface_hub
Browse files- logos_reward_ft_job.py +89 -55
logos_reward_ft_job.py
CHANGED
|
@@ -19,13 +19,25 @@
|
|
| 19 |
Logos Whisper Tiny β Reward-Weighted LoRA Fine-Tuning
|
| 20 |
HuggingFace Job script (uv run --script)
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
Environment variables (set as job secrets/env):
|
| 23 |
-
HF_TOKEN
|
| 24 |
-
HF_PUSH_REPO
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
| 29 |
"""
|
| 30 |
|
| 31 |
import os, re, subprocess, tempfile, logging
|
|
@@ -45,8 +57,8 @@ from transformers import (
|
|
| 45 |
Trainer,
|
| 46 |
TrainingArguments,
|
| 47 |
)
|
| 48 |
-
from peft import LoraConfig, get_peft_model, TaskType
|
| 49 |
-
from huggingface_hub import login
|
| 50 |
|
| 51 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
|
| 52 |
log = logging.getLogger(__name__)
|
|
@@ -56,35 +68,38 @@ subprocess.run(["apt-get", "update", "-q"], check=True)
|
|
| 56 |
subprocess.run(["apt-get", "install", "-y", "-q", "ffmpeg"], check=True)
|
| 57 |
|
| 58 |
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
-
HF_TOKEN
|
| 60 |
-
HF_PUSH_REPO
|
|
|
|
|
|
|
| 61 |
SUPABASE_URL = os.environ["SUPABASE_URL"]
|
| 62 |
SUPABASE_KEY = os.environ["SUPABASE_KEY"]
|
| 63 |
SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY")
|
| 64 |
REFRESH_TOKEN = os.environ.get("REFRESH_TOKEN")
|
| 65 |
USER_ID = os.environ["USER_ID"]
|
| 66 |
|
| 67 |
-
WHISPER_BASE
|
| 68 |
-
LORA_R
|
| 69 |
-
LORA_ALPHA
|
| 70 |
-
LORA_DROPOUT
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
| 84 |
|
| 85 |
# ββ Supabase auth βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 86 |
if SERVICE_ROLE_KEY:
|
| 87 |
-
# Service role key is a long-lived JWT β use directly, bypasses RLS.
|
| 88 |
ACCESS_TOKEN = SERVICE_ROLE_KEY
|
| 89 |
SUPABASE_KEY = SERVICE_ROLE_KEY
|
| 90 |
else:
|
|
@@ -220,17 +235,24 @@ def compute_reward(hypothesis: str, ground_truth: str) -> float:
|
|
| 220 |
|
| 221 |
return float(np.clip(score, 0.0, 1.0))
|
| 222 |
|
| 223 |
-
# ββ Pre-compute reward weights using
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
forced_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe")
|
| 228 |
|
| 229 |
def transcribe_audio(audio: np.ndarray, num_beams: int = BEAM_N) -> list:
|
| 230 |
feats = processor(audio, sampling_rate=16000, return_tensors="pt").input_features.cuda()
|
| 231 |
with torch.no_grad():
|
| 232 |
-
ids =
|
| 233 |
-
|
| 234 |
return [processor.decode(seq, skip_special_tokens=True) for seq in ids]
|
| 235 |
|
| 236 |
for i, item in enumerate(dataset_raw):
|
|
@@ -240,7 +262,7 @@ for i, item in enumerate(dataset_raw):
|
|
| 240 |
if (i + 1) % 20 == 0:
|
| 241 |
log.info(f" scored {i+1}/{len(dataset_raw)}")
|
| 242 |
|
| 243 |
-
del
|
| 244 |
torch.cuda.empty_cache()
|
| 245 |
|
| 246 |
weights = [d["reward_weight"] for d in dataset_raw]
|
|
@@ -262,17 +284,22 @@ train_ds = split["train"]
|
|
| 262 |
eval_ds = split["test"]
|
| 263 |
log.info(f"Train: {len(train_ds)} Eval: {len(eval_ds)}")
|
| 264 |
|
| 265 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
lora_cfg = LoraConfig(
|
| 267 |
task_type = TaskType.SEQ_2_SEQ_LM,
|
| 268 |
r = LORA_R,
|
| 269 |
lora_alpha = LORA_ALPHA,
|
| 270 |
lora_dropout = LORA_DROPOUT,
|
| 271 |
-
target_modules =
|
| 272 |
)
|
| 273 |
-
model = WhisperForConditionalGeneration.from_pretrained(WHISPER_BASE)
|
| 274 |
-
model.config.forced_decoder_ids = None
|
| 275 |
-
model.config.suppress_tokens = []
|
| 276 |
model = get_peft_model(model, lora_cfg)
|
| 277 |
log.info(str(model.print_trainable_parameters()))
|
| 278 |
|
|
@@ -281,12 +308,12 @@ class RewardWeightedTrainer(Trainer):
|
|
| 281 |
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 282 |
reward_weights = inputs.pop("reward_weight").to(model.device)
|
| 283 |
labels = inputs["labels"]
|
| 284 |
-
# Bypass PeftModelForSeq2SeqLM.forward
|
| 285 |
-
#
|
| 286 |
-
#
|
| 287 |
whisper = model.base_model.model if hasattr(model, 'base_model') else model
|
| 288 |
outputs = whisper(**inputs)
|
| 289 |
-
logits
|
| 290 |
|
| 291 |
B, T, V = logits.shape
|
| 292 |
loss_per_token = F.cross_entropy(
|
|
@@ -307,7 +334,7 @@ class WhisperRewardCollator:
|
|
| 307 |
np.array([f["input_features"] for f in features]), dtype=torch.float32
|
| 308 |
)
|
| 309 |
max_len = max(len(f["labels"]) for f in features)
|
| 310 |
-
labels
|
| 311 |
for i, f in enumerate(features):
|
| 312 |
ids = torch.tensor(f["labels"], dtype=torch.long)
|
| 313 |
labels[i, :len(ids)] = ids
|
|
@@ -340,19 +367,26 @@ training_args = TrainingArguments(
|
|
| 340 |
)
|
| 341 |
|
| 342 |
trainer = RewardWeightedTrainer(
|
| 343 |
-
model
|
| 344 |
-
args
|
| 345 |
-
train_dataset
|
| 346 |
-
eval_dataset
|
| 347 |
-
data_collator
|
| 348 |
processing_class = processor.feature_extractor,
|
| 349 |
)
|
| 350 |
|
| 351 |
# ββ Train βββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 352 |
trainer.train()
|
| 353 |
|
| 354 |
-
# ββ
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
Logos Whisper Tiny β Reward-Weighted LoRA Fine-Tuning
|
| 20 |
HuggingFace Job script (uv run --script)
|
| 21 |
|
| 22 |
+
Scores each training example against the *existing* fine-tuned model
|
| 23 |
+
(logos-voice-tiny-d43df745 checkpoint-3000), so the reward signal is
|
| 24 |
+
discriminative: examples the current model handles well get low weight,
|
| 25 |
+
hard/hallucinated ones get up to 3Γ weight.
|
| 26 |
+
|
| 27 |
+
Fine-tuning starts from the same merged fine-tuned checkpoint and adds a
|
| 28 |
+
fresh LoRA delta. The final merged model (base + old LoRA + reward LoRA)
|
| 29 |
+
is pushed as a dataset repo (org token lacks model-create permission).
|
| 30 |
+
|
| 31 |
Environment variables (set as job secrets/env):
|
| 32 |
+
HF_TOKEN β HuggingFace write token
|
| 33 |
+
HF_PUSH_REPO β dataset repo to push the trained model to
|
| 34 |
+
HF_FINETUNE_REPO β adapter repo to score/start from
|
| 35 |
+
HF_FINETUNE_SUBFOLDER β checkpoint subfolder (default: checkpoint-3000)
|
| 36 |
+
SUPABASE_URL β Supabase project URL
|
| 37 |
+
SUPABASE_KEY β Supabase anon/publishable key
|
| 38 |
+
SUPABASE_SERVICE_ROLE_KEY β long-lived service role JWT (preferred over REFRESH_TOKEN)
|
| 39 |
+
REFRESH_TOKEN β Supabase session refresh token (fallback)
|
| 40 |
+
USER_ID β Supabase user UUID
|
| 41 |
"""
|
| 42 |
|
| 43 |
import os, re, subprocess, tempfile, logging
|
|
|
|
| 57 |
Trainer,
|
| 58 |
TrainingArguments,
|
| 59 |
)
|
| 60 |
+
from peft import LoraConfig, PeftModel, get_peft_model, TaskType
|
| 61 |
+
from huggingface_hub import HfApi, login
|
| 62 |
|
| 63 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
|
| 64 |
log = logging.getLogger(__name__)
|
|
|
|
| 68 |
subprocess.run(["apt-get", "install", "-y", "-q", "ffmpeg"], check=True)
|
| 69 |
|
| 70 |
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 71 |
+
HF_TOKEN = os.environ["HF_TOKEN"]
|
| 72 |
+
HF_PUSH_REPO = os.environ.get("HF_PUSH_REPO", "logosaccessibleexpression/logos-whisper-tiny-reward-ft")
|
| 73 |
+
HF_FINETUNE_REPO = os.environ.get("HF_FINETUNE_REPO", "logosaccessibleexpression/logos-voice-tiny-d43df745")
|
| 74 |
+
HF_FINETUNE_SUB = os.environ.get("HF_FINETUNE_SUBFOLDER", "checkpoint-3000")
|
| 75 |
SUPABASE_URL = os.environ["SUPABASE_URL"]
|
| 76 |
SUPABASE_KEY = os.environ["SUPABASE_KEY"]
|
| 77 |
SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY")
|
| 78 |
REFRESH_TOKEN = os.environ.get("REFRESH_TOKEN")
|
| 79 |
USER_ID = os.environ["USER_ID"]
|
| 80 |
|
| 81 |
+
WHISPER_BASE = "openai/whisper-tiny"
|
| 82 |
+
LORA_R = 16
|
| 83 |
+
LORA_ALPHA = 32
|
| 84 |
+
LORA_DROPOUT = 0.05
|
| 85 |
+
# Match target modules from logos-voice-tiny-d43df745 for maximum coverage.
|
| 86 |
+
LORA_TARGETS = ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"]
|
| 87 |
+
|
| 88 |
+
REWARD_ALPHA = 1.0 # WER
|
| 89 |
+
REWARD_BETA = 0.5 # positional tail penalty
|
| 90 |
+
REWARD_GAMMA = 0.5 # per-substitution syllable match
|
| 91 |
+
REWARD_DELTA = 0.5 # total syllable count match
|
| 92 |
+
LOSS_SCALE = 2.0 # max additional loss multiplier (worst β 3Γ, best β 1Γ)
|
| 93 |
+
|
| 94 |
+
BEAM_N = 5
|
| 95 |
+
TRAIN_EPOCHS = 5
|
| 96 |
+
BATCH_SIZE = 8
|
| 97 |
+
LEARNING_RATE = 1e-4
|
| 98 |
+
SAVE_STEPS = 50
|
| 99 |
+
OUTPUT_DIR = "/tmp/logos_reward_ft"
|
| 100 |
|
| 101 |
# ββ Supabase auth βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 102 |
if SERVICE_ROLE_KEY:
|
|
|
|
| 103 |
ACCESS_TOKEN = SERVICE_ROLE_KEY
|
| 104 |
SUPABASE_KEY = SERVICE_ROLE_KEY
|
| 105 |
else:
|
|
|
|
| 235 |
|
| 236 |
return float(np.clip(score, 0.0, 1.0))
|
| 237 |
|
| 238 |
+
# ββ Pre-compute reward weights using the existing fine-tuned model ββββββββββββ
|
| 239 |
+
# Score against the production model so the reward is discriminative:
|
| 240 |
+
# examples it already handles well get low weight, hard ones get up to 3Γ.
|
| 241 |
+
login(token=HF_TOKEN)
|
| 242 |
+
processor = WhisperProcessor.from_pretrained(WHISPER_BASE)
|
| 243 |
+
|
| 244 |
+
log.info(f"Loading scorer from {HF_FINETUNE_REPO}/{HF_FINETUNE_SUB}")
|
| 245 |
+
_scorer_base = WhisperForConditionalGeneration.from_pretrained(WHISPER_BASE)
|
| 246 |
+
_scorer_peft = PeftModel.from_pretrained(_scorer_base, HF_FINETUNE_REPO,
|
| 247 |
+
subfolder=HF_FINETUNE_SUB)
|
| 248 |
+
scorer = _scorer_peft.merge_and_unload().cuda().eval()
|
| 249 |
forced_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe")
|
| 250 |
|
| 251 |
def transcribe_audio(audio: np.ndarray, num_beams: int = BEAM_N) -> list:
|
| 252 |
feats = processor(audio, sampling_rate=16000, return_tensors="pt").input_features.cuda()
|
| 253 |
with torch.no_grad():
|
| 254 |
+
ids = scorer.generate(feats, forced_decoder_ids=forced_ids,
|
| 255 |
+
num_beams=num_beams, num_return_sequences=num_beams)
|
| 256 |
return [processor.decode(seq, skip_special_tokens=True) for seq in ids]
|
| 257 |
|
| 258 |
for i, item in enumerate(dataset_raw):
|
|
|
|
| 262 |
if (i + 1) % 20 == 0:
|
| 263 |
log.info(f" scored {i+1}/{len(dataset_raw)}")
|
| 264 |
|
| 265 |
+
del scorer
|
| 266 |
torch.cuda.empty_cache()
|
| 267 |
|
| 268 |
weights = [d["reward_weight"] for d in dataset_raw]
|
|
|
|
| 284 |
eval_ds = split["test"]
|
| 285 |
log.info(f"Train: {len(train_ds)} Eval: {len(eval_ds)}")
|
| 286 |
|
| 287 |
+
# ββ Model: merge existing fine-tune, then add fresh reward-shaping LoRA βββββββ
|
| 288 |
+
log.info(f"Loading training base from {HF_FINETUNE_REPO}/{HF_FINETUNE_SUB}")
|
| 289 |
+
_train_base = WhisperForConditionalGeneration.from_pretrained(WHISPER_BASE)
|
| 290 |
+
_train_peft = PeftModel.from_pretrained(_train_base, HF_FINETUNE_REPO,
|
| 291 |
+
subfolder=HF_FINETUNE_SUB)
|
| 292 |
+
model = _train_peft.merge_and_unload()
|
| 293 |
+
model.config.forced_decoder_ids = None
|
| 294 |
+
model.config.suppress_tokens = []
|
| 295 |
+
|
| 296 |
lora_cfg = LoraConfig(
|
| 297 |
task_type = TaskType.SEQ_2_SEQ_LM,
|
| 298 |
r = LORA_R,
|
| 299 |
lora_alpha = LORA_ALPHA,
|
| 300 |
lora_dropout = LORA_DROPOUT,
|
| 301 |
+
target_modules = LORA_TARGETS,
|
| 302 |
)
|
|
|
|
|
|
|
|
|
|
| 303 |
model = get_peft_model(model, lora_cfg)
|
| 304 |
log.info(str(model.print_trainable_parameters()))
|
| 305 |
|
|
|
|
| 308 |
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 309 |
reward_weights = inputs.pop("reward_weight").to(model.device)
|
| 310 |
labels = inputs["labels"]
|
| 311 |
+
# Bypass PeftModelForSeq2SeqLM.forward β it injects input_ids=None which
|
| 312 |
+
# collides with Whisper's input_features path. LoRA is baked into the
|
| 313 |
+
# linear layers so gradients still flow correctly.
|
| 314 |
whisper = model.base_model.model if hasattr(model, 'base_model') else model
|
| 315 |
outputs = whisper(**inputs)
|
| 316 |
+
logits = outputs.logits
|
| 317 |
|
| 318 |
B, T, V = logits.shape
|
| 319 |
loss_per_token = F.cross_entropy(
|
|
|
|
| 334 |
np.array([f["input_features"] for f in features]), dtype=torch.float32
|
| 335 |
)
|
| 336 |
max_len = max(len(f["labels"]) for f in features)
|
| 337 |
+
labels = torch.full((len(features), max_len), -100, dtype=torch.long)
|
| 338 |
for i, f in enumerate(features):
|
| 339 |
ids = torch.tensor(f["labels"], dtype=torch.long)
|
| 340 |
labels[i, :len(ids)] = ids
|
|
|
|
| 367 |
)
|
| 368 |
|
| 369 |
trainer = RewardWeightedTrainer(
|
| 370 |
+
model = model,
|
| 371 |
+
args = training_args,
|
| 372 |
+
train_dataset = train_ds,
|
| 373 |
+
eval_dataset = eval_ds,
|
| 374 |
+
data_collator = collator,
|
| 375 |
processing_class = processor.feature_extractor,
|
| 376 |
)
|
| 377 |
|
| 378 |
# ββ Train βββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 379 |
trainer.train()
|
| 380 |
|
| 381 |
+
# ββ Merge LoRA and push full model βββββββββββββββββββββββββββββββββββββββββββ
|
| 382 |
+
# Push as a dataset repo β the org token has dataset write access but not model-create.
|
| 383 |
+
# Load as: WhisperForConditionalGeneration.from_pretrained(HF_PUSH_REPO)
|
| 384 |
+
SAVE_DIR = "/tmp/logos_reward_ft_final"
|
| 385 |
+
merged = model.merge_and_unload()
|
| 386 |
+
merged.save_pretrained(SAVE_DIR)
|
| 387 |
+
processor.save_pretrained(SAVE_DIR)
|
| 388 |
+
|
| 389 |
+
api = HfApi(token=HF_TOKEN)
|
| 390 |
+
api.create_repo(HF_PUSH_REPO, repo_type="dataset", private=True, exist_ok=True)
|
| 391 |
+
api.upload_folder(folder_path=SAVE_DIR, repo_id=HF_PUSH_REPO, repo_type="dataset")
|
| 392 |
+
log.info(f"Pushed merged model to https://huggingface.co/datasets/{HF_PUSH_REPO}")
|