versae commited on
Commit
7fde432
·
1 Parent(s): 0a7c458

Create run_speech_recognition_whisper.py

Browse files
Files changed (1) hide show
  1. run_speech_recognition_whisper.py +796 -0
run_speech_recognition_whisper.py ADDED
@@ -0,0 +1,796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+
15
+ """ Fine-tuning a 🤗 Transformers Whisper model for automatic speech recognition"""
16
+
17
+ import functools
18
+ import json
19
+ import logging
20
+ import os
21
+ import re
22
+ import sys
23
+ import warnings
24
+ from dataclasses import dataclass, field
25
+ from typing import Dict, List, Optional, Union
26
+
27
+ import datasets
28
+ import numpy as np
29
+ import torch
30
+ import evaluate
31
+ from datasets import DatasetDict, load_dataset
32
+
33
+ import transformers
34
+ from transformers import (
35
+ AutoConfig,
36
+ AutoFeatureExtractor,
37
+ AutoModelForCTC,
38
+ AutoProcessor,
39
+ AutoTokenizer,
40
+ HfArgumentParser,
41
+ Trainer,
42
+ TrainingArguments,
43
+ Wav2Vec2Processor,
44
+ set_seed,
45
+
46
+ WhisperFeatureExtractor,
47
+ WhisperTokenizer,
48
+ WhisperForConditionalGeneration,
49
+ WhisperProcessor,
50
+ Seq2SeqTrainer,
51
+ Seq2SeqTrainingArguments,
52
+ )
53
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
54
+ from transformers.utils import check_min_version
55
+ from transformers.utils.versions import require_version
56
+
57
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
58
+ check_min_version("4.24.0.dev0")
59
+
60
+ require_version("datasets>=2.6.1", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
61
+
62
+ logger = logging.getLogger(__name__)
63
+
64
+
65
+ def list_field(default=None, metadata=None):
66
+ return field(default_factory=lambda: default, metadata=metadata)
67
+
68
+
69
+ @dataclass
70
+ class ModelArguments:
71
+ """
72
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
73
+ """
74
+
75
+ model_name_or_path: str = field(
76
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
77
+ )
78
+ language: str = field(
79
+ metadata={"help": "Whisper specific language"}
80
+ )
81
+ task: str = field(
82
+ metadata={"help": "Whisper specific task, i.e., 'transcribe' or 'translate'"}
83
+ )
84
+ tokenizer_name_or_path: Optional[str] = field(
85
+ default=None,
86
+ metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
87
+ )
88
+ cache_dir: Optional[str] = field(
89
+ default=None,
90
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
91
+ )
92
+ freeze_feature_encoder: bool = field(
93
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
94
+ )
95
+ attention_dropout: float = field(
96
+ default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."}
97
+ )
98
+ activation_dropout: float = field(
99
+ default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."}
100
+ )
101
+ feat_proj_dropout: float = field(default=0.0, metadata={"help": "The dropout ratio for the projected features."})
102
+ hidden_dropout: float = field(
103
+ default=0.0,
104
+ metadata={
105
+ "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
106
+ },
107
+ )
108
+ final_dropout: float = field(
109
+ default=0.0,
110
+ metadata={"help": "The dropout probability for the final projection layer."},
111
+ )
112
+ mask_time_prob: float = field(
113
+ default=0.05,
114
+ metadata={
115
+ "help": "Probability of each feature vector along the time axis to be chosen as the start of the vector"
116
+ "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
117
+ "vectors will be masked along the time axis."
118
+ },
119
+ )
120
+ mask_time_length: int = field(
121
+ default=10,
122
+ metadata={"help": "Length of vector span to mask along the time axis."},
123
+ )
124
+ mask_feature_prob: float = field(
125
+ default=0.0,
126
+ metadata={
127
+ "help": "Probability of each feature vector along the feature axis to be chosen as the start of the vector"
128
+ "span to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature bins will be masked along the time axis."
129
+ },
130
+ )
131
+ mask_feature_length: int = field(
132
+ default=10,
133
+ metadata={"help": "Length of vector span to mask along the feature axis."},
134
+ )
135
+ layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
136
+ ctc_loss_reduction: Optional[str] = field(
137
+ default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
138
+ )
139
+ ctc_zero_infinity: Optional[bool] = field(
140
+ default=False, metadata={"help": "If True, will try yo aboud the CTC loss goinf to infinity."}
141
+ )
142
+
143
+
144
+ @dataclass
145
+ class DataTrainingArguments:
146
+ """
147
+ Arguments pertaining to what data we are going to input our model for training and eval.
148
+
149
+ Using `HfArgumentParser` we can turn this class
150
+ into argparse arguments to be able to specify them on
151
+ the command line.
152
+ """
153
+
154
+ dataset_name: str = field(
155
+ metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
156
+ )
157
+ dataset_config_name: str = field(
158
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
159
+ )
160
+ train_split_name: str = field(
161
+ default="train",
162
+ metadata={
163
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
164
+ },
165
+ )
166
+ eval_split_name: str = field(
167
+ default="test",
168
+ metadata={
169
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
170
+ },
171
+ )
172
+ audio_column_name: str = field(
173
+ default="audio",
174
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
175
+ )
176
+ text_column_name: str = field(
177
+ default="text",
178
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
179
+ )
180
+ overwrite_cache: bool = field(
181
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
182
+ )
183
+ preprocessing_num_workers: Optional[int] = field(
184
+ default=None,
185
+ metadata={"help": "The number of processes to use for the preprocessing."},
186
+ )
187
+ max_train_samples: Optional[int] = field(
188
+ default=None,
189
+ metadata={
190
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
191
+ "value if set."
192
+ },
193
+ )
194
+ max_eval_samples: Optional[int] = field(
195
+ default=None,
196
+ metadata={
197
+ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this "
198
+ "value if set."
199
+ },
200
+ )
201
+ chars_to_ignore: Optional[List[str]] = list_field(
202
+ default=None,
203
+ metadata={"help": "A list of characters to remove from the transcripts."},
204
+ )
205
+ eval_metrics: List[str] = list_field(
206
+ default=["wer"],
207
+ metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
208
+ )
209
+ max_duration_in_seconds: float = field(
210
+ default=20.0,
211
+ metadata={
212
+ "help": "Filter audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
213
+ },
214
+ )
215
+ min_duration_in_seconds: float = field(
216
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
217
+ )
218
+ preprocessing_only: bool = field(
219
+ default=False,
220
+ metadata={
221
+ "help": "Whether to only do data preprocessing and skip training. "
222
+ "This is especially useful when data preprocessing errors out in distributed training due to timeout. "
223
+ "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
224
+ "so that the cached datasets can consequently be loaded in distributed training"
225
+ },
226
+ )
227
+ use_auth_token: bool = field(
228
+ default=False,
229
+ metadata={
230
+ "help": "If :obj:`True`, will use the token generated when running"
231
+ ":obj:`transformers-cli login` as HTTP bearer authorization for remote files."
232
+ },
233
+ )
234
+ unk_token: str = field(
235
+ default="[UNK]",
236
+ metadata={"help": "The unk token for the tokenizer"},
237
+ )
238
+ pad_token: str = field(
239
+ default="[PAD]",
240
+ metadata={"help": "The padding token for the tokenizer"},
241
+ )
242
+ word_delimiter_token: str = field(
243
+ default="|",
244
+ metadata={"help": "The word delimiter token for the tokenizer"},
245
+ )
246
+ phoneme_language: Optional[str] = field(
247
+ default=None,
248
+ metadata={
249
+ "help": "The target language that should be used be"
250
+ " passed to the tokenizer for tokenization. Note that"
251
+ " this is only relevant if the model classifies the"
252
+ " input audio to a sequence of phoneme sequences."
253
+ },
254
+ )
255
+
256
+
257
+ @dataclass
258
+ class DataCollatorSpeechSeq2SeqWithPadding:
259
+ processor: Any
260
+
261
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
262
+ # split inputs and labels since they have to be of different lengths and need different padding methods
263
+ # first treat the audio inputs by simply returning torch tensors
264
+ input_features = [{"input_features": feature["input_features"]} for feature in features]
265
+ batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
266
+
267
+ # get the tokenized label sequences
268
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
269
+ # pad the labels to max length
270
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
271
+
272
+ # replace padding with -100 to ignore loss correctly
273
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
274
+
275
+ # if bos token is appended in previous tokenization step,
276
+ # cut bos token here as it's append later anyways
277
+ if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():
278
+ labels = labels[:, 1:]
279
+
280
+ batch["labels"] = labels
281
+
282
+ return batch
283
+
284
+
285
+ def create_vocabulary_from_data(
286
+ datasets: DatasetDict,
287
+ word_delimiter_token: Optional[str] = None,
288
+ unk_token: Optional[str] = None,
289
+ pad_token: Optional[str] = None,
290
+ ):
291
+ # Given training and test labels create vocabulary
292
+ alphabet = set()
293
+
294
+ def extract_all_chars(batch):
295
+ all_text = " ".join(batch["target_text"])
296
+ alphabet.update(all_text)
297
+
298
+ datasets.map(
299
+ extract_all_chars,
300
+ batched=True,
301
+ batch_size=-1,
302
+ keep_in_memory=True,
303
+ remove_columns=datasets["train"].column_names,
304
+ )
305
+
306
+ # # take union of all unique characters in each dataset
307
+ # vocab_set = functools.reduce(
308
+ # lambda vocab_1, vocab_2: {"vocab": list(set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]))}, vocabs.values()
309
+ # )["vocab"][0]
310
+
311
+ vocab_dict = {v: k for k, v in enumerate(sorted(list(alphabet)))}
312
+
313
+ # replace white space with delimiter token
314
+ if word_delimiter_token is not None:
315
+ vocab_dict[word_delimiter_token] = vocab_dict[" "]
316
+ del vocab_dict[" "]
317
+
318
+ # add unk and pad token
319
+ if unk_token is not None:
320
+ vocab_dict[unk_token] = len(vocab_dict)
321
+
322
+ if pad_token is not None:
323
+ vocab_dict[pad_token] = len(vocab_dict)
324
+
325
+ return vocab_dict
326
+
327
+
328
+ def make_dataset(training_args, data_args):
329
+ seed = training_args.seed or 42
330
+ # Pre-processing dataset
331
+ # import re
332
+
333
+ # def map_nst(entry):
334
+ # text = entry["text"].lower()
335
+ # text = text.replace("(...Vær stille under dette opptaket...)", "")
336
+ # text = re.sub('[áàâ]', 'a', text)
337
+ # text = re.sub('[ä]', 'æ', text)
338
+ # text = re.sub('[éèëê]', 'e', text)
339
+ # text = re.sub('[íìïî]', 'i', text)
340
+ # text = re.sub('[óòöô]', 'o', text)
341
+ # text = re.sub('[ö]', 'ø', text)
342
+ # text = re.sub('[ç]', 'c', text)
343
+ # text = re.sub('[úùüû]', 'u', text)
344
+ # # text = re.sub('\\(?=(Punktum|Komma|Utropstegn|Spørsmålstegn))', ' ', text)
345
+ # text = re.sub('\s+', ' ', text)
346
+ # return {"text": text}
347
+
348
+ # def filter_nst(entry):
349
+ # if not ((len(entry["text"]) <= len(entry["audio"]["array"]) // 320) and (len(entry["text"].strip()) >= 3)):
350
+ # return False # Too short
351
+ # if re.match(entry["type"], "pIW|CA"):
352
+ # return False # Spelling out words
353
+ # return True
354
+
355
+ # def filter_npsc(entry):
356
+ # # False if there are digits in the text
357
+ # if not ((len(entry["text"]) <= len(entry["audio"]["array"]) // 320) and (len(entry["text"].strip()) >= 3)):
358
+ # return False # Too short
359
+ # if re.search("\d", entry["text"]):
360
+ # return False
361
+ # return True
362
+
363
+ # def map_npsc(entry):
364
+ # batch = {"text": entry["text"].lower()}
365
+ # batch["text"] = re.sub('[áàâ]', 'a', batch["text"])
366
+ # batch["text"] = re.sub('[ä]', 'æ', batch["text"])
367
+ # batch["text"] = re.sub('[éèëê]', 'e', batch["text"])
368
+ # batch["text"] = re.sub('[íìïî]', 'i', batch["text"])
369
+ # batch["text"] = re.sub('[óòöô]', 'o', batch["text"])
370
+ # batch["text"] = re.sub('[ö]', 'ø', batch["text"])
371
+ # batch["text"] = re.sub('[ç]', 'c', batch["text"])
372
+ # batch["text"] = re.sub('[úùüû]', 'u', batch["text"])
373
+ # batch["text"] = re.sub('\s', ' ', batch["text"])
374
+ # batch["text"] = re.sub('<ee>', 'eee', batch["text"])
375
+ # batch["text"] = re.sub('<qq>', 'qqq', batch["text"])
376
+ # batch["text"] = re.sub('<mm>', 'mmm', batch["text"])
377
+ # batch["text"] = re.sub('<inaudible>', 'xxx', batch["text"])
378
+ # # batch["text"] = re.sub('<inaudible>', '?', batch["text"])
379
+ # if "<" in batch["text"]:
380
+ # raise ValueError(batch["text"])
381
+ # return batch
382
+
383
+ # nst = datasets.load_dataset("NbAiLab/NST", "no-close")
384
+ # npsc = datasets.load_dataset("NbAiLab/NPSC", "16K_mp3")
385
+ # # TODO NST_hesitate
386
+
387
+ # split = len(npsc["train"]) / (len(npsc["train"]) + len(npsc["validation"])) # Use same train/val ratio as NPSC
388
+ # nst_train = nst["train"].train_test_split(train_size=split, seed=seed)
389
+ # nst["train"] = nst_train["train"]
390
+ # nst["validation"] = nst_train["test"]
391
+
392
+ # nst = nst.filter(filter_nst).map(map_nst).shuffle(seed=seed)
393
+ # npsc = npsc.filter(filter_npsc).map(map_npsc).shuffle(seed=seed)
394
+
395
+ # npsc_base = npsc.remove_columns([col for col in npsc["train"].column_names if col not in ["text", "audio"]])
396
+ # nst_base = nst.remove_columns([col for col in nst["train"].column_names if col not in ["text", "audio"]])
397
+
398
+ # combined = {}
399
+ # for split in "train", "validation", "test":
400
+ # probs = np.array([len(nst_base[split]), len(npsc_base[split])]) # Weight by number of examples
401
+ # probs = (probs / probs.sum()).tolist()
402
+ # comb = datasets.interleave_datasets([nst_base[split], npsc_base[split]], probabilities=probs, seed=seed)
403
+ # combined[split] = comb
404
+
405
+ # return datasets.DatasetDict(**combined)
406
+
407
+ dataset = datasets.load_dataset(training_args.dataset_name, training_args.dataset_config_name, use_auth_token=data_args.use_auth_token)
408
+ return dataset
409
+
410
+
411
+
412
+ def main():
413
+ # See all possible arguments in src/transformers/training_args.py
414
+ # or by passing the --help flag to this script.
415
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
416
+
417
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
418
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
419
+ # If we pass only one argument to the script and it's the path to a json file,
420
+ # let's parse it to get our arguments.
421
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
422
+ else:
423
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
424
+
425
+ # Detecting last checkpoint.
426
+ last_checkpoint = None
427
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
428
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
429
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
430
+ raise ValueError(
431
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
432
+ "Use --overwrite_output_dir to overcome."
433
+ )
434
+ elif last_checkpoint is not None:
435
+ logger.info(
436
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
437
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
438
+ )
439
+
440
+ # Setup logging
441
+ logging.basicConfig(
442
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
443
+ datefmt="%m/%d/%Y %H:%M:%S",
444
+ handlers=[logging.StreamHandler(sys.stdout)],
445
+ )
446
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
447
+
448
+ # Log on each process the small summary:
449
+ logger.warning(
450
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
451
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
452
+ )
453
+ # Set the verbosity to info of the Transformers logger (on main process only):
454
+ if is_main_process(training_args.local_rank):
455
+ transformers.utils.logging.set_verbosity_info()
456
+ logger.info("Training/evaluation parameters %s", training_args)
457
+
458
+ # Set seed before initializing model.
459
+ set_seed(training_args.seed)
460
+
461
+ # 1. First, let's load the dataset
462
+ raw_datasets = make_dataset(training_args, data_args)
463
+
464
+ if training_args.do_train:
465
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
466
+ raise ValueError(
467
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
468
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
469
+ f"{', '.join(raw_datasets['train'].column_names)}."
470
+ )
471
+
472
+ if data_args.text_column_name not in raw_datasets["train"].column_names:
473
+ raise ValueError(
474
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
475
+ "Make sure to set `--text_column_name` to the correct text column - one of "
476
+ f"{', '.join(raw_datasets['train'].column_names)}."
477
+ )
478
+
479
+ if data_args.max_train_samples is not None:
480
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
481
+
482
+ if training_args.do_eval:
483
+ if data_args.max_eval_samples is not None:
484
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
485
+
486
+ # 2. We remove some special characters from the datasets
487
+ # that make training complicated and do not help in transcribing the speech
488
+ # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
489
+ # that could be easily picked up by the model
490
+ # chars_to_ignore_regex = (
491
+ # f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
492
+ # )
493
+ chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]'
494
+
495
+ text_column_name = data_args.text_column_name
496
+
497
+ def remove_special_characters(batch):
498
+ if chars_to_ignore_regex is not None:
499
+ batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[text_column_name]).lower() + " "
500
+ else:
501
+ batch["target_text"] = batch[text_column_name].lower() + " "
502
+ return batch
503
+
504
+ with training_args.main_process_first(desc="dataset map special characters removal"):
505
+ raw_datasets = raw_datasets.map(
506
+ remove_special_characters,
507
+ remove_columns=[text_column_name],
508
+ desc="remove special characters from datasets",
509
+ )
510
+
511
+ # save special tokens for tokenizer
512
+ word_delimiter_token = data_args.word_delimiter_token
513
+ unk_token = data_args.unk_token
514
+ pad_token = data_args.pad_token
515
+
516
+ # 3. Next, let's load the config as we might need it to create
517
+ # the tokenizer
518
+ # load config
519
+ config = WhisperCon.from_pretrained(
520
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
521
+ )
522
+
523
+ # 4. Next, if no tokenizer file is defined,
524
+ # we create the vocabulary of the model by extracting all unique characters from
525
+ # the training and evaluation datasets
526
+ # We need to make sure that only first rank saves vocabulary
527
+ # make sure all processes wait until vocab is created
528
+ tokenizer_name_or_path = model_args.tokenizer_name_or_path
529
+ tokenizer_kwargs = {}
530
+ if tokenizer_name_or_path is None:
531
+ # save vocab in training output dir
532
+ tokenizer_name_or_path = training_args.output_dir
533
+
534
+ vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
535
+
536
+ with training_args.main_process_first():
537
+ if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
538
+ os.remove(vocab_file)
539
+
540
+ with training_args.main_process_first(desc="dataset map vocabulary creation"):
541
+ if not os.path.isfile(vocab_file):
542
+ os.makedirs(tokenizer_name_or_path, exist_ok=True)
543
+ vocab_dict = create_vocabulary_from_data(
544
+ raw_datasets,
545
+ word_delimiter_token=word_delimiter_token,
546
+ unk_token=unk_token,
547
+ pad_token=pad_token,
548
+ )
549
+
550
+ # save vocab dict to be loaded into tokenizer
551
+ with open(vocab_file, "w") as file:
552
+ json.dump(vocab_dict, file)
553
+
554
+ # if tokenizer has just been created
555
+ # it is defined by `tokenizer_class` if present in config else by `model_type`
556
+ tokenizer_kwargs = {
557
+ "config": config if config.tokenizer_class is not None else None,
558
+ "tokenizer_type": config.model_type if config.tokenizer_class is None else None,
559
+ "unk_token": unk_token,
560
+ "pad_token": pad_token,
561
+ "word_delimiter_token": word_delimiter_token,
562
+ }
563
+
564
+ # 5. Now we can instantiate the feature extractor, tokenizer and model
565
+ # Note for distributed training, the .from_pretrained methods guarantee that only
566
+ # one local process can concurrently download model & vocab.
567
+
568
+ # load feature_extractor and tokenizer
569
+ tokenizer = WhisperTokenizer.from_pretrained(
570
+ tokenizer_name_or_path,
571
+ use_auth_token=data_args.use_auth_token,
572
+ language=model_args.language,
573
+ task=model_args.task
574
+ **tokenizer_kwargs,
575
+ )
576
+ feature_extractor = WhisperFeatureExtractor.from_pretrained(
577
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token,
578
+ language=model_args.language, task=model_args.task,
579
+ )
580
+
581
+ # adapt config
582
+ config.update(
583
+ {
584
+ "forced_decoder_ids": None,
585
+ "suppress_tokens": [],
586
+ # "feat_proj_dropout": model_args.feat_proj_dropout,
587
+ # "attention_dropout": model_args.attention_dropout,
588
+ # "hidden_dropout": model_args.hidden_dropout,
589
+ # "final_dropout": model_args.final_dropout,
590
+ # "mask_time_prob": model_args.mask_time_prob,
591
+ # "mask_time_length": model_args.mask_time_length,
592
+ # "mask_feature_prob": model_args.mask_feature_prob,
593
+ # "mask_feature_length": model_args.mask_feature_length,
594
+ # "gradient_checkpointing": training_args.gradient_checkpointing,
595
+ # "layerdrop": model_args.layerdrop,
596
+ # "ctc_loss_reduction": model_args.ctc_loss_reduction,
597
+ # "ctc_zero_infinity": model_args.ctc_zero_infinity,
598
+ # "pad_token_id": tokenizer.pad_token_id,
599
+ # "vocab_size": len(tokenizer),
600
+ # "activation_dropout": model_args.activation_dropout,
601
+ }
602
+ )
603
+
604
+ # create model
605
+ model = WhisperForConditionalGeneration.from_pretrained(
606
+ model_args.model_name_or_path,
607
+ cache_dir=model_args.cache_dir,
608
+ config=config,
609
+ use_auth_token=data_args.use_auth_token,
610
+ )
611
+
612
+ # freeze encoder
613
+ if model_args.freeze_feature_encoder:
614
+ model.freeze_feature_encoder()
615
+
616
+ # 6. Now we preprocess the datasets including loading the audio, resampling and normalization
617
+ # Thankfully, `datasets` takes care of automatically loading and resampling the audio,
618
+ # so that we just need to set the correct target sampling rate and normalize the input
619
+ # via the `feature_extractor`
620
+
621
+ # make sure that dataset decodes audio with correct sampling rate
622
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
623
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
624
+ raw_datasets = raw_datasets.cast_column(
625
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
626
+ )
627
+
628
+ # derive max & min input length for sample rate & max duration
629
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
630
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
631
+ audio_column_name = data_args.audio_column_name
632
+ num_workers = data_args.preprocessing_num_workers
633
+
634
+ # `phoneme_language` is only relevant if the model is fine-tuned on phoneme classification
635
+ phoneme_language = data_args.phoneme_language
636
+
637
+ # Preprocessing the datasets.
638
+ # We need to read the audio files as arrays and tokenize the targets.
639
+ def prepare_dataset(batch):
640
+ # load and resample audio data from 48 to 16kHz
641
+ audio = batch[audio_column_name]
642
+
643
+ # compute log-Mel input features from input audio array
644
+ batch["input_features"] = feature_extractor(audio["array"], sampling_rate=audio["sampling_rate"]).input_features[0]
645
+
646
+ # encode target text to label ids
647
+ batch["labels"] = tokenizer(batch["sentence"]).input_ids
648
+ return batch
649
+
650
+
651
+ with training_args.main_process_first(desc="dataset map preprocessing"):
652
+ vectorized_datasets = raw_datasets.map(
653
+ prepare_dataset,
654
+ remove_columns=next(iter(raw_datasets.values())).column_names,
655
+ num_proc=num_workers,
656
+ desc="preprocess datasets",
657
+ )
658
+
659
+ def is_audio_in_length_range(length):
660
+ return length > min_input_length and length < max_input_length
661
+
662
+ # filter data that is shorter than min_input_length
663
+ vectorized_datasets = vectorized_datasets.filter(
664
+ is_audio_in_length_range,
665
+ num_proc=num_workers,
666
+ input_columns=["input_length"],
667
+ )
668
+
669
+ # 7. Next, we can prepare the training.
670
+ # Let's use word error rate (WER) as our evaluation metric,
671
+ # instantiate a data collator and the trainer
672
+
673
+ # Define evaluation metrics during training, *i.e.* word error rate, character error rate
674
+ eval_metrics = {metric: evaluate.load(metric) for metric in data_args.eval_metrics}
675
+
676
+ # for large datasets it is advised to run the preprocessing on a
677
+ # single machine first with ``args.preprocessing_only`` since there will mostly likely
678
+ # be a timeout when running the script in distributed mode.
679
+ # In a second step ``args.preprocessing_only`` can then be set to `False` to load the
680
+ # cached dataset
681
+ if data_args.preprocessing_only:
682
+ logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}")
683
+ return
684
+
685
+ def compute_metrics(pred):
686
+ pred_ids = pred.predictions
687
+ label_ids = pred.label_ids
688
+
689
+ # replace -100 with the pad_token_id
690
+ label_ids[label_ids == -100] = tokenizer.pad_token_id
691
+
692
+ # we do not want to group tokens when computing the metrics
693
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
694
+ label_str = tokenizer.batch_decode(label_ids, skip_special_tokens=True)
695
+
696
+ metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}
697
+
698
+ return metrics
699
+
700
+ # Now save everything to be able to create a single processor later
701
+ if is_main_process(training_args.local_rank):
702
+ # save feature extractor, tokenizer and config
703
+ feature_extractor.save_pretrained(training_args.output_dir)
704
+ tokenizer.save_pretrained(training_args.output_dir)
705
+ config.save_pretrained(training_args.output_dir)
706
+
707
+ try:
708
+ processor = AutoProcessor.from_pretrained(training_args.output_dir, language=model_args.language, task=model_args.task)
709
+ except (OSError, KeyError):
710
+ warnings.warn(
711
+ "Loading a processor from a feature extractor config that does not"
712
+ " include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
713
+ " attribute to your `preprocessor_config.json` file to suppress this warning: "
714
+ " `'processor_class': 'Wav2Vec2Processor'`",
715
+ FutureWarning,
716
+ )
717
+ processor = WhisperProcessor.from_pretrained(model_args.model_name_or_path, training_args.output_dir, language=model_args.language, task=model_args.task)
718
+
719
+ # Instantiate custom data collator
720
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)
721
+
722
+ # Initialize Trainer
723
+ trainer = Seq2SeqTrainer(
724
+ model=model,
725
+ data_collator=data_collator,
726
+ args=training_args,
727
+ compute_metrics=compute_metrics,
728
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
729
+ eval_dataset=vectorized_datasets["validation"] if training_args.do_eval else None,
730
+ tokenizer=feature_extractor,
731
+ )
732
+
733
+ # 8. Finally, we can start training
734
+
735
+ # Training
736
+ if training_args.do_train:
737
+
738
+ # use last checkpoint if exist
739
+ if last_checkpoint is not None:
740
+ checkpoint = last_checkpoint
741
+ elif os.path.isdir(model_args.model_name_or_path):
742
+ checkpoint = model_args.model_name_or_path
743
+ else:
744
+ checkpoint = None
745
+
746
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
747
+ trainer.save_model()
748
+
749
+ metrics = train_result.metrics
750
+ max_train_samples = (
751
+ data_args.max_train_samples
752
+ if data_args.max_train_samples is not None
753
+ else len(vectorized_datasets["train"])
754
+ )
755
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
756
+
757
+ trainer.log_metrics("train", metrics)
758
+ trainer.save_metrics("train", metrics)
759
+ trainer.save_state()
760
+
761
+ # Evaluation
762
+ results = {}
763
+ if training_args.do_eval:
764
+ logger.info("*** Evaluate ***")
765
+ metrics = trainer.evaluate()
766
+ max_eval_samples = (
767
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
768
+ )
769
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
770
+
771
+ trainer.log_metrics("eval", metrics)
772
+ trainer.save_metrics("eval", metrics)
773
+
774
+ # Write model card and (optionally) push to hub
775
+ config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
776
+ kwargs = {
777
+ "finetuned_from": model_args.model_name_or_path,
778
+ "tasks": "automatic-speech-recognition",
779
+ "tags": ["hf-asr-leaderboard", "automatic-speech-recognition", data_args.dataset_name],
780
+ "dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}",
781
+ "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
782
+ "language": model_args.language,
783
+ }
784
+ if "common_voice" in data_args.dataset_name:
785
+ kwargs["language"] = config_name
786
+
787
+ if training_args.push_to_hub:
788
+ trainer.push_to_hub(**kwargs)
789
+ else:
790
+ trainer.create_model_card(**kwargs)
791
+
792
+ return results
793
+
794
+
795
+ if __name__ == "__main__":
796
+ main()