nefasto commited on
Commit
3530ad0
1 Parent(s): 5307009

add main script with data augm and freeze encoder

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