AlexN commited on
Commit
f1dc28b
1 Parent(s): 37f8bf6

adding running script

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