Upload trainer.py with huggingface_hub
Browse files- trainer.py +155 -0
trainer.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from datasets import load_from_disk, DatasetDict, concatenate_datasets
|
3 |
+
|
4 |
+
# Get all batch directories
|
5 |
+
batch_dirs = [d for d in os.listdir("processed_dataset") if d.startswith("batch_")]
|
6 |
+
batch_dirs.sort(key=lambda x: int(x.split('_')[1])) # Sort numerically
|
7 |
+
|
8 |
+
# Load each batch and combine them
|
9 |
+
processed_batches = []
|
10 |
+
for batch_dir in batch_dirs:
|
11 |
+
batch_path = os.path.join("processed_dataset", batch_dir)
|
12 |
+
batch_dataset = load_from_disk(batch_path)
|
13 |
+
processed_batches.append(batch_dataset)
|
14 |
+
|
15 |
+
# Combine all batches into one dataset
|
16 |
+
full_dataset = concatenate_datasets(processed_batches)
|
17 |
+
|
18 |
+
# Split into train and test
|
19 |
+
# First shuffle the dataset with a fixed seed for reproducibility
|
20 |
+
shuffled_dataset = full_dataset.shuffle(seed=42)
|
21 |
+
|
22 |
+
# Get the last 975 samples for test
|
23 |
+
test_size = 975
|
24 |
+
processed_test = shuffled_dataset.select(range(test_size))
|
25 |
+
processed_train = shuffled_dataset.select(range(test_size, len(shuffled_dataset)))
|
26 |
+
|
27 |
+
# Create the dataset_dict with the new split
|
28 |
+
dataset_dict = DatasetDict({
|
29 |
+
"train": processed_train,
|
30 |
+
"test": processed_test
|
31 |
+
})
|
32 |
+
|
33 |
+
# Verify the loading and splitting was successful
|
34 |
+
print("\nDataset split information:")
|
35 |
+
print(f"Total examples: {len(shuffled_dataset)}")
|
36 |
+
print(f"Training examples: {len(dataset_dict['train'])}")
|
37 |
+
print(f"Test examples: {len(dataset_dict['test'])}")
|
38 |
+
|
39 |
+
# Optional: Print the first example from each split to verify the structure
|
40 |
+
print("\nFirst training example structure:")
|
41 |
+
print(dataset_dict['train'][0].keys())
|
42 |
+
print("\nFirst test example structure:")
|
43 |
+
print(dataset_dict['test'][0].keys())
|
44 |
+
|
45 |
+
from transformers import WhisperForConditionalGeneration
|
46 |
+
|
47 |
+
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small")
|
48 |
+
|
49 |
+
model.generation_config.language = "malayalam"
|
50 |
+
|
51 |
+
model.generation_config.task = "transcribe"
|
52 |
+
|
53 |
+
model.generation_config.forced_decoder_ids = None
|
54 |
+
|
55 |
+
from transformers import WhisperProcessor
|
56 |
+
|
57 |
+
processor = WhisperProcessor.from_pretrained("openai/whisper-small", language="Malayalam", task="transcribe")
|
58 |
+
|
59 |
+
import torch
|
60 |
+
|
61 |
+
from dataclasses import dataclass
|
62 |
+
from typing import Any, Dict, List, Union
|
63 |
+
|
64 |
+
@dataclass
|
65 |
+
class DataCollatorSpeechSeq2SeqWithPadding:
|
66 |
+
processor: Any
|
67 |
+
decoder_start_token_id: int
|
68 |
+
|
69 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
70 |
+
# split inputs and labels since they have to be of different lengths and need different padding methods
|
71 |
+
# first treat the audio inputs by simply returning torch tensors
|
72 |
+
input_features = [{"input_features": feature["input_features"]} for feature in features]
|
73 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
74 |
+
|
75 |
+
# get the tokenized label sequences
|
76 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
77 |
+
# pad the labels to max length
|
78 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
79 |
+
|
80 |
+
# replace padding with -100 to ignore loss correctly
|
81 |
+
labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
82 |
+
|
83 |
+
# if bos token is appended in previous tokenization step,
|
84 |
+
# cut bos token here as it's append later anyways
|
85 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
86 |
+
labels = labels[:, 1:]
|
87 |
+
|
88 |
+
batch["labels"] = labels
|
89 |
+
|
90 |
+
return batch
|
91 |
+
|
92 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
|
93 |
+
processor=processor,
|
94 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
95 |
+
)
|
96 |
+
|
97 |
+
import evaluate
|
98 |
+
|
99 |
+
metric = evaluate.load("wer")
|
100 |
+
|
101 |
+
def compute_metrics(pred):
|
102 |
+
pred_ids = pred.predictions
|
103 |
+
label_ids = pred.label_ids
|
104 |
+
|
105 |
+
# replace -100 with the pad_token_id
|
106 |
+
label_ids[label_ids == -100] = tokenizer.pad_token_id
|
107 |
+
|
108 |
+
# we do not want to group tokens when computing the metrics
|
109 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
110 |
+
label_str = tokenizer.batch_decode(label_ids, skip_special_tokens=True)
|
111 |
+
|
112 |
+
wer = 100 * metric.compute(predictions=pred_str, references=label_str)
|
113 |
+
|
114 |
+
return {"wer": wer}
|
115 |
+
|
116 |
+
from transformers import Seq2SeqTrainingArguments
|
117 |
+
|
118 |
+
training_args = Seq2SeqTrainingArguments(
|
119 |
+
output_dir="./whisper-small-mal", # change to a repo name of your choice
|
120 |
+
per_device_train_batch_size=16,
|
121 |
+
gradient_accumulation_steps=1, # increase by 2x for every 2x decrease in batch size
|
122 |
+
learning_rate=1e-5,
|
123 |
+
warmup_steps=500,
|
124 |
+
max_steps=4000,
|
125 |
+
gradient_checkpointing=True,
|
126 |
+
fp16=True,
|
127 |
+
evaluation_strategy="steps",
|
128 |
+
per_device_eval_batch_size=8,
|
129 |
+
predict_with_generate=True,
|
130 |
+
generation_max_length=225,
|
131 |
+
save_steps=1000,
|
132 |
+
eval_steps=1000,
|
133 |
+
logging_steps=25,
|
134 |
+
report_to=["tensorboard"],
|
135 |
+
load_best_model_at_end=True,
|
136 |
+
metric_for_best_model="wer",
|
137 |
+
greater_is_better=False,
|
138 |
+
push_to_hub=True,
|
139 |
+
)
|
140 |
+
|
141 |
+
from transformers import Seq2SeqTrainer
|
142 |
+
|
143 |
+
trainer = Seq2SeqTrainer(
|
144 |
+
args=training_args,
|
145 |
+
model=model,
|
146 |
+
train_dataset=dataset_dict["train"],
|
147 |
+
eval_dataset=dataset_dict["test"],
|
148 |
+
data_collator=data_collator,
|
149 |
+
compute_metrics=compute_metrics,
|
150 |
+
tokenizer=processor.feature_extractor,
|
151 |
+
)
|
152 |
+
|
153 |
+
processor.save_pretrained(training_args.output_dir)
|
154 |
+
|
155 |
+
trainer.train()
|