farsipal commited on
Commit
eea944c
1 Parent(s): e710579

Upload run_speech_recognition_seq2seq_streaming.py

Browse files
run_speech_recognition_seq2seq_streaming.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace 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
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition
18
+ with 🤗 Datasets' streaming mode.
19
+ """
20
+ # You can also adapt this script for your own sequence to sequence speech
21
+ # recognition task. Pointers for this are left as comments.
22
+
23
+ import logging
24
+ import os
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Union
28
+
29
+ import datasets
30
+ import torch
31
+ from datasets import IterableDatasetDict, interleave_datasets, load_dataset
32
+ from torch.utils.data import IterableDataset
33
+
34
+ import evaluate
35
+ import transformers
36
+ from transformers import (
37
+ AutoConfig,
38
+ AutoFeatureExtractor,
39
+ AutoModelForSpeechSeq2Seq,
40
+ AutoProcessor,
41
+ AutoTokenizer,
42
+ HfArgumentParser,
43
+ Seq2SeqTrainer,
44
+ Seq2SeqTrainingArguments,
45
+ TrainerCallback,
46
+ set_seed,
47
+ )
48
+ from transformers.trainer_pt_utils import IterableDatasetShard
49
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
50
+ from transformers.utils import check_min_version, send_example_telemetry
51
+ from transformers.utils.versions import require_version
52
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
53
+
54
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
55
+ check_min_version("4.25.0.dev0")
56
+
57
+ require_version("datasets>=1.18.2", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ @dataclass
63
+ class ModelArguments:
64
+ """
65
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
66
+ """
67
+
68
+ model_name_or_path: str = field(
69
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
70
+ )
71
+ config_name: Optional[str] = field(
72
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
73
+ )
74
+ tokenizer_name: Optional[str] = field(
75
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
76
+ )
77
+ feature_extractor_name: Optional[str] = field(
78
+ default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
79
+ )
80
+ cache_dir: Optional[str] = field(
81
+ default=None,
82
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
83
+ )
84
+ use_fast_tokenizer: bool = field(
85
+ default=True,
86
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
87
+ )
88
+ model_revision: str = field(
89
+ default="main",
90
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
91
+ )
92
+ use_auth_token: bool = field(
93
+ default=False,
94
+ metadata={
95
+ "help": (
96
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
97
+ "with private models)."
98
+ )
99
+ },
100
+ )
101
+ freeze_feature_encoder: bool = field(
102
+ default=True, metadata={"help": "Deprecated - Whether to freeze the feature encoder layers of the model."}
103
+ )
104
+ freeze_encoder: bool = field(
105
+ default=False, metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."}
106
+ )
107
+ forced_decoder_ids: List[List[int]] = field(
108
+ default=None,
109
+ metadata={
110
+ "help": (
111
+ "A list of pairs of integers which indicates a mapping from generation indices to token indices "
112
+ "that will be forced before sampling. For example, [[0, 123]] means the first generated token "
113
+ "will always be a token of index 123."
114
+ )
115
+ },
116
+ )
117
+ suppress_tokens: List[int] = field(
118
+ default=None, metadata={"help": "A list of tokens that will be suppressed at generation."}
119
+ )
120
+ model_index_name: str = field(default=None, metadata={"help": "Pretty name for the model card."})
121
+
122
+ ## added by Michael Kamfonas
123
+ use_cache: bool = field(
124
+ default=False, metadata={"help": "Whether to use cache."}
125
+ )
126
+
127
+
128
+
129
+ @dataclass
130
+ class DataTrainingArguments:
131
+ """
132
+ Arguments pertaining to what data we are going to input our model for training and eval.
133
+ """
134
+
135
+ dataset_name: str = field(
136
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
137
+ )
138
+ dataset_config_name: Optional[str] = field(
139
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
140
+ )
141
+ text_column: Optional[str] = field(
142
+ default=None,
143
+ metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
144
+ )
145
+ max_train_samples: Optional[int] = field(
146
+ default=None,
147
+ metadata={
148
+ "help": (
149
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
150
+ "value if set."
151
+ )
152
+ },
153
+ )
154
+ max_eval_samples: Optional[int] = field(
155
+ default=None,
156
+ metadata={
157
+ "help": (
158
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
159
+ "value if set."
160
+ )
161
+ },
162
+ )
163
+ audio_column_name: str = field(
164
+ default="audio",
165
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
166
+ )
167
+ text_column_name: str = field(
168
+ default="text",
169
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
170
+ )
171
+ max_duration_in_seconds: float = field(
172
+ default=20.0,
173
+ metadata={
174
+ "help": (
175
+ "Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
176
+ " 'max_duration_in_seconds`"
177
+ )
178
+ },
179
+ )
180
+ min_duration_in_seconds: float = field(
181
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
182
+ )
183
+ train_split_name: str = field(
184
+ default="train",
185
+ metadata={
186
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
187
+ },
188
+ )
189
+ eval_split_name: str = field(
190
+ default="test",
191
+ metadata={
192
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
193
+ },
194
+ )
195
+ do_lower_case: bool = field(
196
+ default=False,
197
+ metadata={"help": "Whether the target text should be lower cased."},
198
+ )
199
+ do_remove_punctuation: bool = field(
200
+ default=False,
201
+ metadata={"help": "Whether the target text should be striped of punctuation."},
202
+ )
203
+ do_normalize_eval: bool = field(
204
+ default=True,
205
+ metadata={"help": "Whether to normalise the references and predictions in the eval WER calculation."},
206
+ )
207
+ language: str = field(
208
+ default=None,
209
+ metadata={
210
+ "help": (
211
+ "Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
212
+ "only. For English speech recognition, it should be set to `None`."
213
+ )
214
+ },
215
+ )
216
+ task: str = field(
217
+ default="transcribe",
218
+ metadata={"help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."},
219
+ )
220
+ shuffle_buffer_size: Optional[int] = field(
221
+ default=500,
222
+ metadata={
223
+ "help": (
224
+ "The number of streamed examples to download before shuffling them. The large the buffer, "
225
+ "the closer it is to real offline shuffling."
226
+ )
227
+ },
228
+ )
229
+
230
+
231
+ @dataclass
232
+ class DataCollatorSpeechSeq2SeqWithPadding:
233
+ """
234
+ Data collator that will dynamically pad the inputs received.
235
+ Args:
236
+ processor ([`WhisperProcessor`])
237
+ The processor used for processing the data.
238
+ decoder_start_token_id (`int`)
239
+ The begin-of-sentence of the decoder.
240
+ """
241
+
242
+ processor: Any
243
+ decoder_start_token_id: int
244
+
245
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
246
+ # split inputs and labels since they have to be of different lengths and need
247
+ # different padding methods
248
+ model_input_name = self.processor.model_input_names[0]
249
+ input_features = [{model_input_name: feature[model_input_name]} for feature in features]
250
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
251
+
252
+ batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
253
+
254
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
255
+
256
+ # replace padding with -100 to ignore loss correctly
257
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
258
+
259
+ # if bos token is appended in previous tokenization step,
260
+ # cut bos token here as it's append later anyways
261
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
262
+ labels = labels[:, 1:]
263
+
264
+ batch["labels"] = labels
265
+
266
+ return batch
267
+
268
+
269
+ def load_streaming_dataset(dataset_name, dataset_config_name, split="train", **kwargs):
270
+ """
271
+ Utility function to load a dataset in streaming mode. For datasets with multiple splits,
272
+ each split is loaded individually and then splits combined by taking alternating examples from
273
+ each (interleaving).
274
+ """
275
+ if "+" in split:
276
+ # load multiple splits separated by the `+` symbol with streaming mode
277
+ dataset_splits = [
278
+ load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=True, **kwargs)
279
+ for split_name in split.split("+")
280
+ ]
281
+ # interleave multiple splits to form one dataset
282
+ interleaved_dataset = interleave_datasets(dataset_splits)
283
+ return interleaved_dataset
284
+ else:
285
+ # load a single split *with* streaming mode
286
+ dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=True, **kwargs)
287
+ return dataset
288
+
289
+
290
+ def main():
291
+ # 1. Parse input arguments
292
+ # See all possible arguments in src/transformers/training_args.py
293
+ # or by passing the --help flag to this script.
294
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
295
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
296
+
297
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
298
+ # If we pass only one argument to the script and it's the path to a json file,
299
+ # let's parse it to get our arguments.
300
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
301
+ else:
302
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
303
+
304
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
305
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
306
+ send_example_telemetry("run_speech_recognition_seq2seq_streaming", model_args, data_args)
307
+
308
+ # 2. Setup logging
309
+ logging.basicConfig(
310
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
311
+ datefmt="%m/%d/%Y %H:%M:%S",
312
+ handlers=[logging.StreamHandler(sys.stdout)],
313
+ )
314
+ log_level = training_args.get_process_log_level()
315
+ logger.setLevel(log_level)
316
+ datasets.utils.logging.set_verbosity(log_level)
317
+ transformers.utils.logging.set_verbosity(log_level)
318
+ transformers.utils.logging.enable_default_handler()
319
+ transformers.utils.logging.enable_explicit_format()
320
+
321
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
322
+
323
+ # Log on each process the small summary:
324
+ logger.warning(
325
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
326
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
327
+ )
328
+ logger.info(f"Training/evaluation parameters {training_args}")
329
+
330
+ # Set the verbosity to info of the Transformers logger (on main process only):
331
+ if is_main_process(training_args.local_rank):
332
+ transformers.utils.logging.set_verbosity_info()
333
+ logger.info("Training/evaluation parameters %s", training_args)
334
+
335
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
336
+ last_checkpoint = None
337
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
338
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
339
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
340
+ raise ValueError(
341
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
342
+ "Use --overwrite_output_dir to overcome."
343
+ )
344
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
345
+ logger.info(
346
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
347
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
348
+ )
349
+
350
+ # Set seed before initializing model.
351
+ set_seed(training_args.seed)
352
+
353
+ # 4. Load dataset
354
+ raw_datasets = IterableDatasetDict()
355
+
356
+ if training_args.do_train:
357
+ raw_datasets["train"] = load_streaming_dataset(
358
+ data_args.dataset_name,
359
+ data_args.dataset_config_name,
360
+ split=data_args.train_split_name,
361
+ use_auth_token=True if model_args.use_auth_token else None,
362
+ )
363
+
364
+ if training_args.do_eval:
365
+ raw_datasets["eval"] = load_streaming_dataset(
366
+ data_args.dataset_name,
367
+ data_args.dataset_config_name,
368
+ split=data_args.eval_split_name,
369
+ use_auth_token=True if model_args.use_auth_token else None,
370
+ )
371
+
372
+ raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
373
+
374
+ if data_args.audio_column_name not in raw_datasets_features:
375
+ raise ValueError(
376
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
377
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
378
+ f"{', '.join(raw_datasets_features)}."
379
+ )
380
+
381
+ if data_args.text_column_name not in raw_datasets_features:
382
+ raise ValueError(
383
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
384
+ "Make sure to set `--text_column_name` to the correct text column - one of "
385
+ f"{', '.join(raw_datasets_features)}."
386
+ )
387
+
388
+ # 5. Load pretrained model, tokenizer, and feature extractor
389
+ #
390
+ # Distributed training:
391
+ # The .from_pretrained methods guarantee that only one local process can concurrently
392
+ config = AutoConfig.from_pretrained(
393
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
394
+ cache_dir=model_args.cache_dir,
395
+ revision=model_args.model_revision,
396
+ use_auth_token=True if model_args.use_auth_token else None,
397
+ )
398
+
399
+ config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
400
+
401
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
402
+ model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
403
+ cache_dir=model_args.cache_dir,
404
+ revision=model_args.model_revision,
405
+ use_auth_token=True if model_args.use_auth_token else None,
406
+ )
407
+ tokenizer = AutoTokenizer.from_pretrained(
408
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
409
+ cache_dir=model_args.cache_dir,
410
+ use_fast=model_args.use_fast_tokenizer,
411
+ revision=model_args.model_revision,
412
+ use_auth_token=True if model_args.use_auth_token else None,
413
+ )
414
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
415
+ model_args.model_name_or_path,
416
+ config=config,
417
+ cache_dir=model_args.cache_dir,
418
+ revision=model_args.model_revision,
419
+ use_auth_token=True if model_args.use_auth_token else None,
420
+ )
421
+
422
+ model.config.use_cache = model_args.use_cache
423
+
424
+ if model.config.decoder_start_token_id is None:
425
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
426
+
427
+ # depricated
428
+ #if model_args.freeze_feature_encoder:
429
+ # model.freeze_feature_encoder()
430
+
431
+ if model_args.freeze_encoder:
432
+ model.freeze_encoder()
433
+ model.model.encoder.gradient_checkpointing = False
434
+
435
+ if data_args.language is not None:
436
+ # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
437
+ tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
438
+
439
+ # 6. Resample speech dataset if necessary
440
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
441
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
442
+ raw_datasets = raw_datasets.cast_column(
443
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
444
+ )
445
+
446
+ # 7. Preprocessing the datasets.
447
+ # We need to read the audio files as arrays and tokenize the targets.
448
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
449
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
450
+ audio_column_name = data_args.audio_column_name
451
+ text_column_name = data_args.text_column_name
452
+ model_input_name = feature_extractor.model_input_names[0]
453
+ do_lower_case = data_args.do_lower_case
454
+ do_remove_punctuation = data_args.do_remove_punctuation
455
+ normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
456
+
457
+ if data_args.max_train_samples is not None:
458
+ raw_datasets["train"] = raw_datasets["train"].take(data_args.max_train_samples)
459
+
460
+ if data_args.max_eval_samples is not None:
461
+ raw_datasets["eval"] = raw_datasets["eval"].take(data_args.max_eval_samples)
462
+
463
+ def prepare_dataset(batch):
464
+ # process audio
465
+ sample = batch[audio_column_name]
466
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
467
+ # process audio length
468
+ batch[model_input_name] = inputs.get(model_input_name)[0]
469
+ batch["input_length"] = len(sample["array"])
470
+
471
+ # process targets
472
+ input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
473
+ if do_remove_punctuation:
474
+ input_str = normalizer(input_str).strip()
475
+ batch["labels"] = tokenizer(input_str).input_ids
476
+ return batch
477
+
478
+ with training_args.main_process_first(desc="dataset map pre-processing"):
479
+ vectorized_datasets = raw_datasets.map(
480
+ prepare_dataset,
481
+ remove_columns=raw_datasets_features,
482
+ ).with_format("torch")
483
+
484
+ if training_args.do_train:
485
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
486
+ buffer_size=data_args.shuffle_buffer_size,
487
+ seed=training_args.seed,
488
+ )
489
+
490
+ # filter training data that is shorter than min_input_length or longer than
491
+ # max_input_length
492
+ def is_audio_in_length_range(length):
493
+ return min_input_length < length < max_input_length
494
+
495
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
496
+ is_audio_in_length_range,
497
+ input_columns=["input_length"],
498
+ )
499
+
500
+ # 8. Load Metric
501
+ metric = evaluate.load("wer")
502
+ do_normalize_eval = data_args.do_normalize_eval
503
+
504
+ def compute_metrics(pred):
505
+ pred_ids = pred.predictions
506
+
507
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
508
+
509
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
510
+ # we do not want to group tokens when computing the metrics
511
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
512
+
513
+ if do_normalize_eval:
514
+ pred_str = [normalizer(pred) for pred in pred_str]
515
+ label_str = [normalizer(label) for label in label_str]
516
+
517
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
518
+
519
+ return {"wer": wer}
520
+
521
+ # 9. Create a single speech processor
522
+ if is_main_process(training_args.local_rank):
523
+ # save feature extractor, tokenizer and config
524
+ feature_extractor.save_pretrained(training_args.output_dir)
525
+ tokenizer.save_pretrained(training_args.output_dir)
526
+ config.save_pretrained(training_args.output_dir)
527
+
528
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
529
+
530
+ # 10. Define data collator
531
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
532
+ processor=processor,
533
+ decoder_start_token_id=model.config.decoder_start_token_id,
534
+ )
535
+
536
+ # 11. Configure Trainer
537
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
538
+ class ShuffleCallback(TrainerCallback):
539
+ def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
540
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
541
+ pass # set_epoch() is handled by the Trainer
542
+ elif isinstance(train_dataloader.dataset, IterableDataset):
543
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
544
+
545
+ # Initialize Trainer
546
+ trainer = Seq2SeqTrainer(
547
+ model=model,
548
+ args=training_args,
549
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
550
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
551
+ tokenizer=feature_extractor,
552
+ data_collator=data_collator,
553
+ compute_metrics=compute_metrics if training_args.predict_with_generate else None,
554
+ callbacks=[ShuffleCallback()],
555
+ )
556
+
557
+ # 12. Training
558
+ if training_args.do_train:
559
+ checkpoint = None
560
+ if training_args.resume_from_checkpoint is not None:
561
+ checkpoint = training_args.resume_from_checkpoint
562
+ elif last_checkpoint is not None:
563
+ checkpoint = last_checkpoint
564
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
565
+ trainer.save_model() # Saves the feature extractor too for easy upload
566
+
567
+ metrics = train_result.metrics
568
+ if data_args.max_train_samples:
569
+ metrics["train_samples"] = data_args.max_train_samples
570
+ trainer.log_metrics("train", metrics)
571
+ trainer.save_metrics("train", metrics)
572
+ trainer.save_state()
573
+
574
+ # 13. Evaluation
575
+ results = {}
576
+ if training_args.do_eval:
577
+ logger.info("*** Evaluate ***")
578
+ metrics = trainer.evaluate(
579
+ metric_key_prefix="eval",
580
+ max_length=training_args.generation_max_length,
581
+ num_beams=training_args.generation_num_beams,
582
+ )
583
+ if data_args.max_eval_samples:
584
+ metrics["eval_samples"] = data_args.max_eval_samples
585
+
586
+ trainer.log_metrics("eval", metrics)
587
+ trainer.save_metrics("eval", metrics)
588
+
589
+ # 14. Write Training Stats
590
+ kwargs = {
591
+ "finetuned_from": model_args.model_name_or_path,
592
+ "tasks": "automatic-speech-recognition",
593
+ "tags": "whisper-event",
594
+ }
595
+ if data_args.dataset_name is not None:
596
+ kwargs["dataset_tags"] = data_args.dataset_name
597
+ if data_args.dataset_config_name is not None:
598
+ kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
599
+ else:
600
+ kwargs["dataset"] = data_args.dataset_name
601
+ if "common_voice" in data_args.dataset_name:
602
+ kwargs["language"] = data_args.dataset_config_name
603
+ if model_args.model_index_name is not None:
604
+ kwargs["model_name"] = model_args.model_index_name
605
+
606
+ if training_args.push_to_hub:
607
+ trainer.push_to_hub(**kwargs)
608
+ else:
609
+ trainer.create_model_card(**kwargs)
610
+
611
+ return results
612
+
613
+
614
+ if __name__ == "__main__":
615
+ main()