bjelkenhed commited on
Commit
5579ec1
1 Parent(s): 6e2fea2

initial commit

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