farsipal commited on
Commit
508f25b
1 Parent(s): 52ed255

Upload 2 files

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