aapot commited on
Commit
7db4d10
1 Parent(s): 527719b

Add training files

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