MOH749 commited on
Commit
8bdf9bc
·
verified ·
1 Parent(s): 64e1e8a

cleanup: training scripts live in deploy/, not the dataset repo

Browse files
Files changed (1) hide show
  1. train_ears_granite.py +0 -160
train_ears_granite.py DELETED
@@ -1,160 +0,0 @@
1
- # /// script
2
- # dependencies = ["transformers>=4.52.1", "peft>=0.13", "accelerate>=0.34",
3
- # "datasets==2.21.0", "soundfile", "librosa", "torchaudio", "jiwer",
4
- # "evaluate", "huggingface_hub>=0.22", "trackio", "wandb"]
5
- # ///
6
- """Fine-tune granite-4.0-1b-speech on MOH749/Bocalantics (LoRA) — HF Jobs uv script.
7
-
8
- Bocalantics-native: loads the unified dataset directly (audio 16k + text + lang),
9
- no manifest/wav extraction. IBM recipe: freeze encoder, train projector, LoRA the
10
- Granite LLM. Pushes the adapter to the Hub (ephemeral job env — must push).
11
-
12
- Config via env vars (HF Jobs injects HF_TOKEN via --secrets):
13
- DATASET (default MOH749/Bocalantics)
14
- PUSH_REPO (default MOH749/yaatal-wa-ears-granite)
15
- EPOCHS, BATCH, LR
16
- SMOKE (>0 → train on only N rows, 1 epoch — a cheap code-validation run)
17
- """
18
- import dataclasses
19
- import io
20
- import os
21
- from typing import Any
22
-
23
- BASE = os.environ.get("BASE_MODEL", "ibm-granite/granite-4.0-1b-speech")
24
- DATASET = os.environ.get("DATASET", "MOH749/Bocalantics")
25
- PUSH_REPO = os.environ.get("PUSH_REPO", "MOH749/yaatal-wa-ears-granite")
26
- EPOCHS = int(os.environ.get("EPOCHS", "3"))
27
- BATCH = int(os.environ.get("BATCH", "4")) # 4 = throughput (BATCH=1 was ~6x slower, ~20h/epoch)
28
- GRAD_ACCUM = int(os.environ.get("GRAD_ACCUM", "4")) # effective batch ~16
29
- MAX_S = float(os.environ.get("MAX_S", "16")) # collator SKIPS clips > MAX_S -> bounds OOM, no truncation
30
- SAVE_STEPS = int(os.environ.get("SAVE_STEPS", "1500")) # push a checkpoint ~hourly so a late fail loses <=1
31
- LR = float(os.environ.get("LR", "2e-4"))
32
- SMOKE = int(os.environ.get("SMOKE", "0"))
33
- # Metrics: "trackio" (HF-native, free dashboard Space) | "wandb" | "none".
34
- # trackio picks up TRACKIO_SPACE_ID + TRACKIO_PROJECT_NAME from env to persist the
35
- # dashboard past the ephemeral job; wandb picks up WANDB_API_KEY (secret) + WANDB_PROJECT.
36
- REPORT = os.environ.get("REPORT", "trackio")
37
- RUN_NAME = os.environ.get("RUN_NAME", f"granite-ears-{'smoke' if SMOKE else 'full'}")
38
- INSTR = "Please transcribe the following audio to text<|audio|>"
39
-
40
-
41
- @dataclasses.dataclass
42
- class Collator:
43
- processor: Any
44
- max_s: float = 30.0
45
-
46
- def __call__(self, examples):
47
- import torch
48
- import soundfile as sf
49
- tok = self.processor.tokenizer
50
- tok.padding_side = "right"
51
- sr_t = self.processor.audio_processor.sampling_rate
52
- prompts, fulls, wavs = [], [], []
53
- for ex in examples:
54
- try:
55
- arr, sr = sf.read(io.BytesIO(ex["audio"]["bytes"]), dtype="float32")
56
- except Exception:
57
- continue
58
- if arr.ndim > 1:
59
- arr = arr.mean(axis=1)
60
- if sr != sr_t:
61
- import librosa
62
- arr = librosa.resample(arr, orig_sr=sr, target_sr=sr_t)
63
- dur = len(arr) / sr_t
64
- if dur < 0.5 or dur > self.max_s: # skip too-short/long: bounds OOM, avoids audio/text mismatch
65
- continue
66
- txt = (ex.get("text") or "").strip()
67
- if not txt:
68
- continue
69
- wavs.append(arr)
70
- prompts.append(tok.apply_chat_template(
71
- [{"role": "user", "content": INSTR}],
72
- tokenize=False, add_generation_prompt=True))
73
- fulls.append(tok.apply_chat_template(
74
- [{"role": "user", "content": INSTR},
75
- {"role": "assistant", "content": txt}], tokenize=False))
76
- if not wavs: # whole batch skipped/bad -> 1-sample silent dummy (never emit a 0-row batch -> no reshape crash)
77
- import numpy as np
78
- wavs = [np.zeros(int(0.5 * sr_t), dtype="float32")]
79
- prompts = [tok.apply_chat_template(
80
- [{"role": "user", "content": INSTR}], tokenize=False, add_generation_prompt=True)]
81
- fulls = [tok.apply_chat_template(
82
- [{"role": "user", "content": INSTR}, {"role": "assistant", "content": "."}], tokenize=False)]
83
- # Let the processor batch + pad input_features and expand the <|audio|>
84
- # placeholders consistently — hand-padding features desyncs the audio-token
85
- # count from the placeholders (the 165-vs-4 failure). Recover labels by
86
- # masking the prompt span, sized from a prompt-only pass (same audio → same
87
- # placeholder expansion, right-padding keeps the prompt a clean prefix).
88
- out = self.processor(text=fulls, audio=wavs, return_tensors="pt", padding=True)
89
- pout = self.processor(text=prompts, audio=wavs, return_tensors="pt", padding=True)
90
- labels = out["input_ids"].clone()
91
- labels[out["attention_mask"] == 0] = -100
92
- for i in range(len(fulls)):
93
- plen = int(pout["attention_mask"][i].sum().item())
94
- labels[i, :plen] = -100
95
- out["labels"] = labels
96
- return dict(out)
97
-
98
-
99
- def main():
100
- import torch
101
- from datasets import load_dataset, Audio
102
- from transformers import (GraniteSpeechForConditionalGeneration,
103
- GraniteSpeechProcessor, Trainer, TrainingArguments)
104
- from peft import LoraConfig, get_peft_model
105
-
106
- epochs = EPOCHS
107
- if SMOKE > 0:
108
- # Stream just the first rows — genuinely avoids the full 25.6GB pull
109
- # (datasets 2.21 split-slicing still downloads every shard first).
110
- from datasets import Dataset
111
- print(f"[load] dataset {DATASET} (smoke stream {SMOKE})")
112
- st = load_dataset(DATASET, split="train", streaming=True).cast_column(
113
- "audio", Audio(decode=False))
114
- sv = load_dataset(DATASET, split="validation", streaming=True).cast_column(
115
- "audio", Audio(decode=False))
116
- train = Dataset.from_list(list(st.take(SMOKE)))
117
- val = Dataset.from_list(list(sv.take(64)))
118
- epochs = 1
119
- print(f"[smoke] train={len(train)} val={len(val)} (1 epoch)")
120
- else:
121
- print(f"[load] dataset {DATASET}")
122
- ds = load_dataset(DATASET).cast_column("audio", Audio(decode=False))
123
- train = ds["train"]
124
- val = ds["validation"] if "validation" in ds else ds["train"]
125
- print(f"[full] train={len(train)} val={len(val)} ({epochs} epochs)")
126
-
127
- print(f"[load] model {BASE}")
128
- proc = GraniteSpeechProcessor.from_pretrained(BASE)
129
- model = GraniteSpeechForConditionalGeneration.from_pretrained(
130
- BASE, torch_dtype=torch.bfloat16)
131
- for p in model.model.encoder.parameters():
132
- p.requires_grad = False
133
- model = get_peft_model(model, LoraConfig(
134
- r=16, lora_alpha=32, lora_dropout=0.05,
135
- target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
136
- "gate_proj", "up_proj", "down_proj"],
137
- bias="none", task_type="CAUSAL_LM"))
138
- model.print_trainable_parameters()
139
-
140
- args = TrainingArguments(
141
- output_dir="out", num_train_epochs=epochs,
142
- per_device_train_batch_size=BATCH, per_device_eval_batch_size=2,
143
- learning_rate=LR, warmup_ratio=0.05, lr_scheduler_type="cosine",
144
- bf16=torch.cuda.is_available(), gradient_accumulation_steps=GRAD_ACCUM,
145
- gradient_checkpointing=False, eval_strategy="no", save_strategy="steps",
146
- save_steps=SAVE_STEPS, save_total_limit=1, logging_steps=20, dataloader_num_workers=2,
147
- remove_unused_columns=False, report_to=REPORT, run_name=RUN_NAME,
148
- label_names=["labels"],
149
- push_to_hub=True, hub_model_id=PUSH_REPO, hub_strategy="every_save",
150
- hub_private_repo=True)
151
- trainer = Trainer(model=model, args=args, train_dataset=train,
152
- eval_dataset=val, data_collator=Collator(processor=proc, max_s=MAX_S))
153
- trainer.train()
154
- trainer.push_to_hub()
155
- proc.push_to_hub(PUSH_REPO, private=True)
156
- print(f"[done] pushed adapter → {PUSH_REPO}")
157
-
158
-
159
- if __name__ == "__main__":
160
- main()