File size: 6,006 Bytes
6a125ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from datasets import load_from_disk
from transformers import WhisperProcessor
import torch
from dataclasses import dataclass
from typing import Any, Dict, List, Union
import evaluate
from transformers import WhisperForConditionalGeneration
from transformers import Seq2SeqTrainingArguments
from transformers import Seq2SeqTrainer


@dataclass
class DataCollatorSpeechSeq2SeqWithPadding:
    processor: Any

    def __call__(
        self, features: List[Dict[str, Union[List[int], torch.Tensor]]]
    ) -> Dict[str, torch.Tensor]:

        input_features = [
            {"input_features": feature["input_features"]} for feature in features
        ]
        batch = self.processor.feature_extractor.pad(
            input_features, return_tensors="pt"
        )

        batch["input_features"] = batch["input_features"].to(torch.bfloat16)

        label_features = [{"input_ids": feature["labels"]} for feature in features]
        labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
        labels = labels_batch["input_ids"].masked_fill(
            labels_batch.attention_mask.ne(1), -100
        )
        if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():
            labels = labels[:, 1:]
        batch["labels"] = labels

        return batch


class FineTuning:
    def __init__(self):
        self.final_dataset = None
        self.dataset_1 = None
        self.dataset_2 = None
        self.model = "/home/ubuntu/Code/Checkpoints/Dataset-6/Best-Model"
        print("Load the processor and wer...")
        self.processor = WhisperProcessor.from_pretrained(
            self.model, language="persian", task="transcribe"
        )
        self.metric = evaluate.load(
            "/home/ubuntu/.cache/huggingface/modules/evaluate_modules/metrics/evaluate-metric--wer/e41eaa77ca7152430cd94704de20946c1b004b5b488ab5d20b26fb81c6c15506/wer.py",
            download_config=None,
        )
        print("Load completed\n")
        self.training_args = None
        self.trainer = None
        self.data_collator = None
        self.final_model_path = "/home/ubuntu/Code/Checkpoints/Dataset-7/Best-Model"

    def load_the_dataset(self):
        print("Load the Fucking dataset\nIt is FUCKING 274 GB ...")
        self.dataset_1 = load_from_disk("/home/ubuntu/Clean-HF-Dataset-7")
        self.final_dataset = self.dataset_1
        del self.dataset_1
        import gc

        gc.collect()

        print(f"Final Dataset train: {len(self.final_dataset['train'])} rows")
        print(f"Final Dataset test: {len(self.final_dataset['test'])} rows")

    def data_collator_func(self):
        print("Data collator is start")
        self.data_collator = DataCollatorSpeechSeq2SeqWithPadding(
            processor=self.processor
        )
        print("Data collator has finished")

    def compute_metrics(self, pred):
        pred_ids = pred.predictions
        label_ids = pred.label_ids
        label_ids[label_ids == -100] = self.processor.tokenizer.pad_token_id
        pred_str = self.processor.tokenizer.batch_decode(
            pred_ids, skip_special_tokens=True, normalize=True
        )
        label_str = self.processor.tokenizer.batch_decode(
            label_ids, skip_special_tokens=True, normalize=True
        )
        wer = 100 * self.metric.compute(predictions=pred_str, references=label_str)
        return {"wer": wer}

    def load_pre_trained_model(self):
        print("Load the pre-trained model")
        self.model = WhisperForConditionalGeneration.from_pretrained(
            self.model,
            torch_dtype=torch.bfloat16,
            # attn_implementation="flash_attention_2",
        )
        self.model.gradient_checkpointing_enable(
            gradient_checkpointing_kwargs={"use_reentrant": False}
        )
        self.model.config.forced_decoder_ids = None
        self.model.config.suppress_tokens = []
        self.model.config.use_cache = False
        self.model.config.gradient_checkpointing = False
        print("Load pre-trained model has completed")

    def configure_training_args(self):
        self.training_args = Seq2SeqTrainingArguments(
            output_dir="/home/ubuntu/Code/Checkpoints/Dataset-7",
            per_device_train_batch_size=2,
            gradient_accumulation_steps=16,
            learning_rate=1e-6,
            warmup_steps=0,
            max_steps=5000,
            gradient_checkpointing=False,
            bf16=True,
            fp16=False,
            eval_strategy="steps",
            per_device_eval_batch_size=2,
            predict_with_generate=True,
            generation_max_length=225,
            save_strategy="steps",
            save_steps=1000,
            logging_steps=25,
            eval_steps=1000,
            report_to=["tensorboard"],
            load_best_model_at_end=True,
            metric_for_best_model="wer",
            greater_is_better=False,
            push_to_hub=False,
            max_grad_norm=1.0,
        )

    def training(self):
        print("\nStart to train the model with FUCKING 274 GB data ...")
        self.trainer = Seq2SeqTrainer(
            args=self.training_args,
            model=self.model,
            train_dataset=self.final_dataset["train"],
            eval_dataset=self.final_dataset["test"],
            data_collator=self.data_collator,
            compute_metrics=self.compute_metrics,
            tokenizer=self.processor.tokenizer,
        )
        self.trainer.train()

    def save_the_model(self):
        print(f"Saving the model in {self.final_model_path}")
        self.trainer.save_model(self.final_model_path)
        self.processor.save_pretrained(self.final_model_path)
        print(f"Final model and processor saved to {self.final_model_path}")


if __name__ == "__main__":
    Obj = FineTuning()
    Obj.load_the_dataset()
    Obj.data_collator_func()
    Obj.load_pre_trained_model()
    Obj.configure_training_args()
    Obj.training()
    Obj.save_the_model()