sanchit-gandhi commited on
Commit
fe434bd
·
1 Parent(s): 0c13a60

Add final checkpoint

Browse files
medium.en.whisper ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25dc027dabc4a05113307724a954d42a572f858adcf93bbbfe387d800c8dbf37
3
+ size 3055768923
run_common_voice_9.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ CUDA_VISIBLE_DEVICES=0 python run_speech_recognition_whisper.py \
3
+ --model_name_or_path="medium.en" \
4
+ --dataset_name="mozilla-foundation/common_voice_9_0" \
5
+ --dataset_config_name="en" \
6
+ --train_split_name="train" \
7
+ --eval_split_name="validation" \
8
+ --test_split_name="test" \
9
+ --text_column_name="sentence" \
10
+ --max_steps="2500" \
11
+ --output_dir="./" \
12
+ --run_name="whisper-cv9" \
13
+ --wandb_project="whisper" \
14
+ --per_device_train_batch_size="64" \
15
+ --per_device_eval_batch_size="16" \
16
+ --logging_steps="25" \
17
+ --learning_rate="1e-4" \
18
+ --warmup_steps="500" \
19
+ --report_to="wandb" \
20
+ --preprocessing_num_workers="16" \
21
+ --evaluation_strategy="steps" \
22
+ --eval_steps="500" \
23
+ --save_strategy="steps" \
24
+ --save_steps="500" \
25
+ --generation_max_length="128" \
26
+ --length_column_name="input_lengths" \
27
+ --do_lower_case="False" \
28
+ --push_to_hub="False" \
29
+ --max_eval_duration_in_seconds="20" \
30
+ --gradient_checkpointing \
31
+ --group_by_length \
32
+ --freeze_encoder \
33
+ --fp16 \
34
+ --overwrite_output_dir \
35
+ --do_train \
36
+ --do_eval \
37
+ --do_predict \
38
+ --predict_with_generate \
39
+ --use_auth_token
run_speech_recognition_whisper.py ADDED
@@ -0,0 +1,944 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OpenAI Whisper models for speech recognition.
18
+ """
19
+ # You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
20
+ # flake8: noqa: E501
21
+ import logging
22
+ import os
23
+ import re
24
+ import string
25
+
26
+ import torchaudio
27
+ import whisper
28
+ import sys
29
+ from dataclasses import dataclass, field
30
+
31
+ from typing import Optional, Dict, Union, List
32
+
33
+ import numpy as np
34
+ import torch
35
+
36
+ import datasets
37
+ from datasets import DatasetDict, load_dataset
38
+ import transformers
39
+ from torch import nn
40
+ from transformers import (
41
+ HfArgumentParser,
42
+ Seq2SeqTrainingArguments,
43
+ set_seed,
44
+ Seq2SeqTrainer,
45
+ )
46
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
47
+ from transformers.utils import check_min_version
48
+ from transformers.utils.versions import require_version
49
+
50
+ import wandb
51
+
52
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
53
+ check_min_version("4.17.0.dev0")
54
+
55
+ require_version("datasets>=1.18.0", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ @dataclass
61
+ class ModelArguments:
62
+ """
63
+ Arguments pertaining to which model/tokenizer we are going to fine-tune from.
64
+ """
65
+ model_name_or_path: Optional[str] = field(
66
+ default=None,
67
+ metadata={"help": "Path to pretrained model or model identifier from OpenAI Whisper NGC."}
68
+ )
69
+ cache_dir: Optional[str] = field(
70
+ default=None,
71
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co or OpenAI Whisper NGC."},
72
+ )
73
+ use_auth_token: bool = field(
74
+ default=False,
75
+ metadata={
76
+ "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script "
77
+ "with private models)."
78
+ },
79
+ )
80
+ manifest_path: str = field(
81
+ default="data",
82
+ metadata={
83
+ "help": "Manifest path."
84
+ },
85
+ )
86
+ tokenizer_path: str = field(
87
+ default="tokenizers",
88
+ metadata={
89
+ "help": "Tokenizer path."
90
+ },
91
+ )
92
+ freeze_encoder: bool = field(
93
+ default=False,
94
+ metadata={"help": "Freeze the acoustic encoder of the model. Recommend when fine-tuning on small datasets."}
95
+ )
96
+ use_adam8bit: bool = field(
97
+ default=False,
98
+ metadata={"help": "Whether to use bitsandbytes 8bit AdamW optimiser."}
99
+ )
100
+ dropout_rate: float = field(
101
+ default=0.0,
102
+ metadata={"help": "The dropout ratio for all dropout layers (default=0)."}
103
+ )
104
+
105
+
106
+ class SuppressBlank:
107
+ def __init__(self, tokenizer, sample_begin: int = 1):
108
+ self.tokenizer = tokenizer
109
+ self.sample_begin = sample_begin
110
+
111
+ def __call__(self, input_ids, scores):
112
+ tokens = input_ids
113
+ logits = scores
114
+ if tokens.shape[1] == self.sample_begin:
115
+ logits[:, self.tokenizer.encode(" ") + [self.tokenizer.eot]] = -np.inf
116
+ return logits
117
+
118
+
119
+ class SuppressTokens:
120
+ def __init__(self, suppress_tokens):
121
+ self.suppress_tokens = list(suppress_tokens)
122
+
123
+ def __call__(self, input_ids, scores):
124
+ logits = scores
125
+ logits[:, self.suppress_tokens] = -np.inf
126
+ return logits
127
+
128
+
129
+ class ApplyTimestampRules:
130
+ def __init__(
131
+ self, tokenizer, sample_begin: int = 1, max_initial_timestamp_index: Optional[int] = None
132
+ ):
133
+ self.tokenizer = tokenizer
134
+ self.sample_begin = sample_begin
135
+ self.max_initial_timestamp_index = max_initial_timestamp_index
136
+
137
+ def __call__(self, input_ids, scores):
138
+ tokens = input_ids
139
+ logits = scores
140
+ # suppress <|notimestamps|> which is handled by without_timestamps
141
+ if self.tokenizer.no_timestamps is not None:
142
+ logits[:, self.tokenizer.no_timestamps] = -np.inf
143
+
144
+ # timestamps have to appear in pairs, except directly before EOT; mask logits accordingly
145
+ for k in range(tokens.shape[0]):
146
+ seq = [t for t in tokens[k, self.sample_begin :].tolist()]
147
+ last_was_timestamp = len(seq) >= 1 and seq[-1] >= self.tokenizer.timestamp_begin
148
+ penultimate_was_timestamp = len(seq) < 2 or seq[-2] >= self.tokenizer.timestamp_begin
149
+
150
+ if last_was_timestamp:
151
+ if penultimate_was_timestamp: # has to be non-timestamp
152
+ logits[k, self.tokenizer.timestamp_begin :] = -np.inf
153
+ else: # cannot be normal text tokens
154
+ logits[k, : self.tokenizer.eot] = -np.inf
155
+
156
+ # apply the `max_initial_timestamp` option
157
+ if tokens.shape[1] == self.sample_begin and self.max_initial_timestamp_index is not None:
158
+ last_allowed = self.tokenizer.timestamp_begin + self.max_initial_timestamp_index
159
+ logits[:, last_allowed + 1 :] = -np.inf
160
+
161
+ # if sum of probability over timestamps is above any other token, sample timestamp
162
+ logprobs = torch.nn.functional.log_softmax(logits.float(), dim=-1)
163
+ for k in range(tokens.shape[0]):
164
+ timestamp_logprob = logprobs[k, self.tokenizer.timestamp_begin :].logsumexp(dim=-1)
165
+ max_text_token_logprob = logprobs[k, : self.tokenizer.timestamp_begin].max()
166
+ if timestamp_logprob > max_text_token_logprob:
167
+ logits[k, : self.tokenizer.timestamp_begin] = -np.inf
168
+ return logits
169
+
170
+
171
+ @dataclass
172
+ class DataTrainingArguments:
173
+ """
174
+ Arguments pertaining to what data we are going to input our model for training and eval.
175
+ """
176
+
177
+ dataset_name: str = field(
178
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
179
+ )
180
+ dataset_config_name: Optional[str] = field(
181
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
182
+ )
183
+ text_column: Optional[str] = field(
184
+ default=None,
185
+ metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
186
+ )
187
+ dataset_cache_dir: Optional[str] = field(
188
+ default=None, metadata={"help": "Path to cache directory for saving and loading datasets"}
189
+ )
190
+ overwrite_cache: bool = field(
191
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
192
+ )
193
+ preprocessing_num_workers: Optional[int] = field(
194
+ default=None,
195
+ metadata={"help": "The number of processes to use for the preprocessing."},
196
+ )
197
+ max_train_samples: Optional[int] = field(
198
+ default=None,
199
+ metadata={
200
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
201
+ "value if set."
202
+ },
203
+ )
204
+ max_eval_samples: Optional[int] = field(
205
+ default=None,
206
+ metadata={
207
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
208
+ "value if set."
209
+ },
210
+ )
211
+ max_predict_samples: Optional[int] = field(
212
+ default=None,
213
+ metadata={
214
+ "help": "For debugging purposes or quicker training, truncate the number of test examples to this "
215
+ "value if set."
216
+ },
217
+ )
218
+ audio_column_name: str = field(
219
+ default="audio",
220
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
221
+ )
222
+ text_column_name: str = field(
223
+ default="text",
224
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
225
+ )
226
+ max_duration_in_seconds: float = field(
227
+ default=20.0,
228
+ metadata={
229
+ "help": "Truncate training audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
230
+ },
231
+ )
232
+ min_duration_in_seconds: float = field(
233
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
234
+ )
235
+ max_eval_duration_in_seconds: float = field(
236
+ default=None,
237
+ metadata={
238
+ "help": "Truncate eval/test audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
239
+ },
240
+ )
241
+ max_target_length: Optional[int] = field(
242
+ default=128,
243
+ metadata={
244
+ "help": "The maximum total sequence length for target text after tokenization. Sequences longer "
245
+ "than this will be truncated, sequences shorter will be padded."
246
+ },
247
+ )
248
+ min_target_length: Optional[int] = field(
249
+ default=0,
250
+ metadata={
251
+ "help": "The minimum total sequence length for target text after tokenization. Sequences shorter "
252
+ "than this will be filtered."
253
+ },
254
+ )
255
+ preprocessing_only: bool = field(
256
+ default=False,
257
+ metadata={
258
+ "help": "Whether to only do data preprocessing and skip training. "
259
+ "This is especially useful when data preprocessing errors out in distributed training due to timeout. "
260
+ "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
261
+ "so that the cached datasets can consequently be loaded in distributed training"
262
+ },
263
+ )
264
+ train_split_name: str = field(
265
+ default="train",
266
+ metadata={
267
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
268
+ },
269
+ )
270
+ eval_split_name: str = field(
271
+ default="validation",
272
+ metadata={
273
+ "help": "The name of the evaluation data set split to use (via the datasets library). Defaults to 'validation'"
274
+ },
275
+ )
276
+ test_split_name: str = field(
277
+ default="test",
278
+ metadata={"help": "The name of the test data set split to use (via the datasets library). Defaults to 'test'"},
279
+ )
280
+ do_lower_case: bool = field(
281
+ default=True,
282
+ metadata={"help": "Whether the target text should be lower cased."},
283
+ )
284
+ wandb_project: str = field(
285
+ default="speech-recognition-whisper",
286
+ metadata={"help": "The name of the wandb project."},
287
+ )
288
+ ignore_verifications: bool = field(
289
+ default=False,
290
+ metadata={
291
+ "help": "Ignore the verifications of the downloaded/processed dataset information in `load_dataset` (checksums/size/splits/...)."
292
+ }
293
+ )
294
+ torchaudio_resampler: bool = field(
295
+ default=False,
296
+ metadata={
297
+ "help": "Whether to use torchaudio to resample. If `False` (default) will use the default datataset backed."
298
+ }
299
+ )
300
+
301
+
302
+ def write_wandb_pred(pred_str, label_str, prefix="eval"):
303
+ # convert str data to a wandb compatible format
304
+ str_data = [[label_str[i], pred_str[i]] for i in range(len(pred_str))]
305
+ # we'll log all predictions for the last epoch
306
+ wandb.log(
307
+ {
308
+ f"{prefix}/predictions": wandb.Table(
309
+ columns=["label_str", "pred_str"], data=str_data
310
+ )
311
+ },
312
+ )
313
+
314
+
315
+ def transform(array):
316
+ """Static function which:
317
+ 1. Pads/trims a list of audio arrays to a max length of 30s
318
+ 2. Computes log-mel filter coefficients from padded/trimmed audio sequences
319
+ Inputs:
320
+ array: list of audio arrays
321
+ Returns:
322
+ input_ids: torch.tensor of log-mel filter bank coefficients
323
+ """
324
+ padded_input = whisper.pad_or_trim(np.asarray(array, dtype=np.float32))
325
+ input_ids = whisper.log_mel_spectrogram(padded_input)
326
+ return input_ids
327
+
328
+
329
+ @dataclass
330
+ class WhisperDataCollatorWithPadding:
331
+ """
332
+ Data collator that dynamically pads the audio inputs received. An EOS token is appended to the labels sequences.
333
+ They are then dynamically padded to max length.
334
+ Args:
335
+ eos_token_id (`int`)
336
+ The end-of-sentence token for the Whisper tokenizer. Ensure to set for sequences to terminate before
337
+ generation max length.
338
+ """
339
+
340
+ eos_token_id: int
341
+
342
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
343
+ """
344
+ Since Whisper models don't have a HF processor defined (feature extractor + tokenizer), we'll pad by hand...
345
+ """
346
+ # split inputs and labels since they have to be of different lengths
347
+ # and need different padding methods
348
+ input_ids = [feature["input_ids"] for feature in features]
349
+ labels = [feature["labels"] for feature in features]
350
+
351
+ # first, pad the audio inputs to max_len
352
+ input_ids = torch.concat([transform(input_val)[None, :] for input_val in input_ids])
353
+
354
+ # next, append the eos token to our sequence of labels
355
+ labels = [lab + [self.eos_token_id] for lab in labels]
356
+ # finally, pad the target labels to max_len
357
+ label_lengths = [len(lab) for lab in labels]
358
+ max_label_len = max(label_lengths)
359
+ labels = [np.pad(lab, (0, max_label_len - lab_len), 'constant', constant_values=-100) for lab, lab_len in zip(labels, label_lengths)]
360
+
361
+ batch = {"labels": labels}
362
+ batch = {k: torch.tensor(np.array(v), requires_grad=False) for k, v in batch.items()}
363
+
364
+ batch["input_ids"] = input_ids
365
+
366
+ return batch
367
+
368
+
369
+ def main():
370
+ # See all possible arguments in src/transformers/training_args.py
371
+ # or by passing the --help flag to this script.
372
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
373
+
374
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
375
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
376
+ # If we pass only one argument to the script and it's the path to a json file,
377
+ # let's parse it to get our arguments.
378
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
379
+ else:
380
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
381
+
382
+ # Set wandb project ID before instantiating the Trainer
383
+ os.environ["WANDB_PROJECT"] = data_args.wandb_project
384
+ report_to_wandb = "wandb" in training_args.report_to
385
+
386
+ sample_rate = 16_000
387
+
388
+ # Detecting last checkpoint.
389
+ last_checkpoint = None
390
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
391
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
392
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
393
+ raise ValueError(
394
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
395
+ "Use --overwrite_output_dir to overcome."
396
+ )
397
+ elif last_checkpoint is not None:
398
+ logger.info(
399
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
400
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
401
+ )
402
+
403
+ # Setup logging
404
+ logging.basicConfig(
405
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
406
+ datefmt="%m/%d/%Y %H:%M:%S",
407
+ handlers=[logging.StreamHandler(sys.stdout)],
408
+ )
409
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
410
+
411
+ # Log on each process the small summary:
412
+ logger.warning(
413
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
414
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
415
+ )
416
+ # Set the verbosity to info of the Transformers logger (on main process only):
417
+ if is_main_process(training_args.local_rank):
418
+ transformers.utils.logging.set_verbosity_info()
419
+ logger.info("Training/evaluation parameters %s", training_args)
420
+
421
+ # Set seed before initializing model.
422
+ set_seed(training_args.seed)
423
+
424
+ # load the model
425
+ model = whisper.load_model(model_args.model_name_or_path, dropout_rate=model_args.dropout_rate)
426
+
427
+ # set the dropout for the MLP layers -> we do this here as the MLP layers are written as a 'sequential'
428
+ # so changing the modelling code gives mis-matches in the state-dict
429
+ for block_idx in range(len(model.encoder.blocks)):
430
+ mlp_layer = model.encoder.blocks[block_idx].mlp
431
+ # going very verbose to explain what we're doing here!
432
+ fc1 = mlp_layer[0]
433
+ act_fn = mlp_layer[1]
434
+ dropout = nn.Dropout(p=model_args.dropout_rate)
435
+ fc2 = mlp_layer[2]
436
+ model.encoder.blocks[block_idx].mlp = nn.Sequential(fc1, act_fn, dropout, fc2, dropout)
437
+
438
+ for block_idx in range(len(model.decoder.blocks)):
439
+ mlp_layer = model.decoder.blocks[block_idx].mlp
440
+ fc1 = mlp_layer[0]
441
+ act_fn = mlp_layer[1]
442
+ dropout = nn.Dropout(p=model_args.dropout_rate)
443
+ fc2 = mlp_layer[2]
444
+ model.decoder.blocks[block_idx].mlp = nn.Sequential(fc1, act_fn, dropout, fc2, dropout)
445
+
446
+ # load the tokenizer
447
+ whisper_tok = whisper.tokenizer.get_tokenizer(False, task="transcribe", language="en")
448
+ decoding_options = whisper.decoding.DecodingOptions(task="transcribe", language="en")
449
+ task = whisper.decoding.DecodingTask(model, decoding_options)
450
+ suppress_tokens = task._get_suppress_tokens()
451
+
452
+ logits_processors = [SuppressBlank(whisper_tok), SuppressTokens(suppress_tokens), ApplyTimestampRules(whisper_tok)]
453
+ tokenizer = whisper_tok.tokenizer
454
+ tokenizer.pad_token = tokenizer.eos_token
455
+
456
+ # 4. Load dataset
457
+ raw_datasets = DatasetDict()
458
+
459
+ if training_args.do_train:
460
+ raw_datasets["train"] = load_dataset(
461
+ data_args.dataset_name,
462
+ data_args.dataset_config_name,
463
+ split=data_args.train_split_name,
464
+ cache_dir=data_args.dataset_cache_dir,
465
+ use_auth_token=True if model_args.use_auth_token else None,
466
+ )
467
+
468
+ if training_args.do_eval:
469
+ raw_datasets["eval"] = load_dataset(
470
+ data_args.dataset_name,
471
+ data_args.dataset_config_name,
472
+ split=data_args.eval_split_name,
473
+ cache_dir=data_args.dataset_cache_dir,
474
+ use_auth_token=True if model_args.use_auth_token else None,
475
+ )
476
+
477
+ if training_args.do_predict:
478
+ test_split = data_args.test_split_name.split("+")
479
+ for split in test_split:
480
+ raw_datasets[split] = load_dataset(
481
+ data_args.dataset_name,
482
+ data_args.dataset_config_name,
483
+ split=split,
484
+ cache_dir=data_args.dataset_cache_dir,
485
+ use_auth_token=True if model_args.use_auth_token else None,
486
+ )
487
+
488
+ if not training_args.do_train and not training_args.do_eval and not training_args.do_predict:
489
+ raise ValueError(
490
+ "Cannot not train, not do evaluation and not do prediction. At least one of "
491
+ "training, evaluation or prediction has to be done."
492
+ )
493
+
494
+ # if not training, there is no need to run multiple epochs
495
+ if not training_args.do_train:
496
+ training_args.num_train_epochs = 1
497
+
498
+ if data_args.audio_column_name not in next(iter(raw_datasets.values())).column_names:
499
+ raise ValueError(
500
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
501
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
502
+ f"{', '.join(next(iter(raw_datasets.values())).column_names)}."
503
+ )
504
+
505
+ if data_args.text_column_name not in next(iter(raw_datasets.values())).column_names:
506
+ raise ValueError(
507
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
508
+ "Make sure to set `--text_column_name` to the correct text column - one of "
509
+ f"{', '.join(next(iter(raw_datasets.values())).column_names)}."
510
+ )
511
+
512
+ # 6. Resample speech dataset ALWAYS
513
+ if data_args.torchaudio_resampler:
514
+ # TODO: remove hardcoding of orig sr
515
+ resampler = torchaudio.transforms.Resample(8_000, sample_rate)
516
+ else:
517
+ raw_datasets = raw_datasets.cast_column(
518
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=sample_rate)
519
+ )
520
+ resampler = None
521
+
522
+ # 7. Preprocessing the datasets.
523
+ # We need to read the audio files as arrays and tokenize the targets.
524
+ max_input_length = int(data_args.max_duration_in_seconds * sample_rate)
525
+ min_input_length = min(int(data_args.min_duration_in_seconds * sample_rate), 1)
526
+ max_eval_input_length = int(data_args.max_eval_duration_in_seconds * sample_rate) if data_args.max_eval_duration_in_seconds else None
527
+ max_target_length = data_args.max_target_length
528
+ min_target_length = data_args.min_target_length
529
+ audio_column_name = data_args.audio_column_name
530
+ num_workers = data_args.preprocessing_num_workers
531
+ text_column_name = data_args.text_column_name
532
+ do_lower_case = data_args.do_lower_case
533
+ dataset_name = data_args.dataset_name
534
+
535
+ # Define tokens to ignore/replace
536
+ tedlium_contractions = [" 's", " 't", " 're", " 've", " 'm", " 'll", " 'd", " 'clock", " 'all"]
537
+ gigaspeech_punctuation = {" <comma>": ",", " <period>": ".", " <questionmark>": "?", " <exclamationpoint>": "!"}
538
+ gigaspeech_disfluencies = ["<other>", "<sil>"]
539
+ swb_disfluencies = ["[noise]", "[laughter]", "[silence]", "[vocalized-noise]", "<a_aside>", "<b_aside>", "<e_aside>",
540
+ "[laughter-", "_1", "[laugh]", "[sigh]", "[cough]", "[mn]", "[breath]", "[lipsmack]",
541
+ "[sneeze]", "[skip]", "[pause]", "(%hesitation)", "(%HESITATION)"]
542
+ swb_punctuations = ["{", "}", "[", "]-", "]", "((", "))", "(", ")"]
543
+ earnings_disfluencies = ["<noise>", "<crosstalk>", "<affirmative>", "<inaudible>", "inaudible", "<laugh>", "<silence>"]
544
+ ignore_segments = ["ignore_time_segment_in_scoring", "<noise>", "<music>", "[noise]", "[laughter]", "[silence]",
545
+ "[vocalized-noise]", "<crosstalk>", "<affirmative>", "<inaudible>", "<laugh>", ""]
546
+ ignore_segments = ignore_segments + gigaspeech_disfluencies + swb_disfluencies + earnings_disfluencies
547
+
548
+ if training_args.do_train and data_args.max_train_samples is not None:
549
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
550
+
551
+ if training_args.do_eval and data_args.max_eval_samples is not None:
552
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
553
+
554
+ if training_args.do_predict and data_args.max_predict_samples is not None:
555
+ for split in test_split:
556
+ raw_datasets[split] = raw_datasets[split].select(range(data_args.max_predict_samples))
557
+
558
+ # filter data where the targets are ignored in scoring
559
+ def is_target_labels(input_str):
560
+ return input_str.lower() not in ignore_segments
561
+
562
+ raw_datasets = raw_datasets.filter(
563
+ is_target_labels,
564
+ num_proc=num_workers,
565
+ input_columns=[text_column_name],
566
+ desc="filtering data where the targets are ignored in scoring",
567
+ )
568
+
569
+ def prepare_dataset(batch):
570
+ # pre-process audio
571
+ try:
572
+ sample = batch[audio_column_name]
573
+ except ValueError:
574
+ # E22: some samples are empty (no audio). Reading the empty audio array will trigger
575
+ # a soundfile ValueError. For now, we'll manually set these arrays to a zero array.
576
+ # They will be filtered in the subsequent filtering stage and so are
577
+ # explicitly ignored during training.
578
+ sample = {"array": np.array([0.]), "sampling_rate": sample_rate}
579
+
580
+ if resampler is not None:
581
+ speech_tensor = torch.FloatTensor(sample["array"])
582
+ speech_tensor = speech_tensor.squeeze()
583
+ speech_tensor = resampler(speech_tensor)
584
+ sample["array"] = speech_tensor.numpy()
585
+ sample["sampling_rate"] = resampler.new_freq
586
+
587
+ # For training Whisper we perform the audio preprocessing in the WhisperDataCollator
588
+ # => we only need to supply it with the raw audio values
589
+ batch["input_ids"] = sample["array"]
590
+ batch["input_lengths"] = len(batch["input_ids"])
591
+
592
+ # 'Error correction' of targets
593
+ input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
594
+
595
+ # LibriSpeech ASR
596
+ if dataset_name == "librispeech_asr":
597
+ pass # no error correction necessary
598
+
599
+ # VoxPopuli
600
+ if dataset_name == "google/xtreme_s":
601
+ pass # no error correction necessary
602
+
603
+ # Common Voice 9
604
+ if dataset_name == "mozilla-foundation/common_voice_9_0":
605
+ if input_str.startswith('"') and input_str.endswith('"'):
606
+ # we can remove trailing quotation marks as they do not affect the transcription
607
+ input_str = input_str[1:-1]
608
+ # replace double quotation marks with single
609
+ input_str = input_str.replace('""', '"')
610
+
611
+ # TED-LIUM (Release 3)
612
+ if dataset_name == "LIUM/tedlium":
613
+ # delete the <unk> token from the text
614
+ input_str = input_str.replace("<unk>", "")
615
+ # replace spaced apostrophes with un-spaced (it 's -> it's)
616
+ for contraction in tedlium_contractions:
617
+ input_str = input_str.replace(contraction, contraction[1:])
618
+
619
+ # GigaSpeech
620
+ if dataset_name == "speechcolab/gigaspeech":
621
+ for disfluency in gigaspeech_disfluencies:
622
+ input_str = input_str.replace(disfluency, "")
623
+ # convert spelled out punctuation to symbolic form
624
+ for punctuation, replacement in gigaspeech_punctuation.items():
625
+ input_str = input_str.replace(punctuation, replacement)
626
+
627
+ # SWB: hide the path to the private HF dataset
628
+ if "switchboard" in dataset_name:
629
+ # In one conversation people speak some German phrases that are tagged as
630
+ # <german (( ja wohl )) > -- we remove these
631
+ input_str = re.sub("<[^>]*>", "", input_str)
632
+
633
+ # Remove junk tokens
634
+ for disfluency in swb_disfluencies:
635
+ input_str = input_str.replace(disfluency, "")
636
+
637
+ # normalise acronyms (Fisher: u_.c_.l_.a., SWBD: u c l a)
638
+ input_str = input_str.replace("_.", " ")
639
+
640
+ # Replace partially pronounced words (square brackets + hyphen): westmin[ster]- to westmin- or -[go]ing to -ing
641
+ # Replace anomalous words (square brackets + backslack): [lemguini/linguini] to linguini
642
+ # Replace the combo of the two: [lem[guini]-/linguini] to lem-
643
+ # Example: we [ah/are] -[go]ing to westmin[ster]- for [lem[guini]-/linguini]
644
+ # Target: we ah -ing to westmin- for lem-
645
+ # Treat anomalous words first then destroy the content of all square brackets (partially pronounced words)
646
+
647
+ # First treat partially pronounced anomalous words by removing correct word: [lem[guini]-/linguini] to [lem[guini]-
648
+ input_str = re.sub(r"\-\/.*?\]", "-", input_str)
649
+
650
+ # Now replace anomalous words with their correct transcriptions: [lemguini/linguini] to linguini
651
+ split_str = input_str.split("/")
652
+ if len(split_str) > 1:
653
+ input_str = " ".join(
654
+ [" ".join([" ".join(i.split(" ")[:-1]) for i in split_str])] + [split_str[-1].split(" ")[-1]])
655
+
656
+ # Remove the trailing brackets on the start/end of words
657
+ processed_str = []
658
+ for word in input_str.split():
659
+ if word[0] == "[":
660
+ processed_str.append(word[1:])
661
+ elif word[-1] == "]":
662
+ processed_str.append(word[:-1])
663
+ else:
664
+ processed_str.append(word)
665
+
666
+ # Stick the processed words back together
667
+ input_str = " ".join(processed_str)
668
+
669
+ # Now we can remove all words in square brackets: -[go]ing to -ing
670
+ input_str = re.sub(r"\-\[(.*?)\]", "-", input_str)
671
+
672
+ # westmin[ster]- to westmin-
673
+ input_str = re.sub(r"\[(.*?)\]\-", "-", input_str)
674
+
675
+ # tech[n]ology to tech-ology
676
+ input_str = re.sub(r"\[(.*?)\]", "-", input_str)
677
+
678
+ # partially pronounced words are now done!
679
+ # remove erroneous punctuations (curly braces, trailing square brackets, etc.)
680
+ for punctuation in swb_punctuations:
681
+ input_str = input_str.replace(punctuation, "")
682
+
683
+ # Earnings 22: still figuring out best segmenting method. Thus, dataset name subject to change
684
+ if "earnings22" in dataset_name:
685
+ # Remove the 100ms offset at the end of the sample
686
+ sampling_rate = sample["sampling_rate"]
687
+ offset = int(100 * (10 ** -3) * sampling_rate)
688
+ batch["input_ids"] = sample["array"][:-offset]
689
+ batch["input_lengths"] = len(batch["input_ids"])
690
+ # Remove junk tokens
691
+ for disfluency in earnings_disfluencies:
692
+ input_str = input_str.replace(disfluency, "")
693
+
694
+ # SPGISpeech
695
+ if dataset_name == "kensho/spgispeech":
696
+ pass # no error correction necessary
697
+
698
+ # JIWER compliance (for WER/CER calc.)
699
+ # remove multiple spaces
700
+ input_str = re.sub(r"\s\s+", " ", input_str)
701
+ # strip trailing spaces
702
+ input_str = input_str.strip()
703
+
704
+ # Finally, we tokenize the processed text
705
+ batch["labels"] = tokenizer(input_str).input_ids
706
+ return batch
707
+
708
+ vectorized_datasets = raw_datasets.map(
709
+ prepare_dataset,
710
+ remove_columns=next(iter(raw_datasets.values())).column_names,
711
+ num_proc=num_workers,
712
+ desc="preprocess train dataset",
713
+ )
714
+
715
+ # filter training data with inputs longer than max_input_length
716
+ def is_audio_in_length_range(input_length):
717
+ return min_input_length < input_length < max_input_length
718
+
719
+ if training_args.do_train:
720
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
721
+ is_audio_in_length_range,
722
+ num_proc=num_workers,
723
+ input_columns=["input_lengths"],
724
+ )
725
+
726
+ if max_eval_input_length is not None:
727
+ # filter training data with inputs longer than max_input_length
728
+ def is_eval_audio_in_length_range(input_length):
729
+ return min_input_length < input_length < max_eval_input_length
730
+
731
+ if training_args.do_eval:
732
+ vectorized_datasets["eval"] = vectorized_datasets["eval"].filter(
733
+ is_eval_audio_in_length_range,
734
+ num_proc=num_workers,
735
+ input_columns=["input_lengths"],
736
+ )
737
+
738
+ if training_args.do_predict:
739
+ for split in test_split:
740
+ vectorized_datasets[split] = vectorized_datasets[split].filter(
741
+ is_eval_audio_in_length_range,
742
+ num_proc=num_workers,
743
+ input_columns=["input_lengths"],
744
+ )
745
+
746
+ # filter training data with targets shorter than min_target_length or longer than max_target_length
747
+ def is_labels_in_length_range(labels):
748
+ return min_target_length < len(labels) < max_target_length
749
+
750
+ if training_args.do_train:
751
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
752
+ is_labels_in_length_range,
753
+ num_proc=num_workers,
754
+ input_columns=["labels"],
755
+ )
756
+
757
+ # filter data with targets empty sentences
758
+ def is_labels_greater_than_min(labels):
759
+ return len(labels) > 0
760
+
761
+ vectorized_datasets = vectorized_datasets.filter(
762
+ is_labels_greater_than_min,
763
+ num_proc=num_workers,
764
+ input_columns=["labels"],
765
+ )
766
+
767
+ # for large datasets it is advised to run the preprocessing on a
768
+ # single machine first with `args.preprocessing_only` since there will mostly likely
769
+ # be a timeout when running the script in distributed mode.
770
+ # In a second step `args.preprocessing_only` can then be set to `False` to load the
771
+ # cached dataset
772
+ if data_args.preprocessing_only:
773
+ cache = {k: v.cache_files for k, v in vectorized_datasets.items()}
774
+ logger.info(f"Data preprocessing finished. Files cached at {cache}.")
775
+ return
776
+
777
+ if model_args.freeze_encoder:
778
+ model.freeze_encoder()
779
+ logging.info("Model encoder has been frozen")
780
+
781
+ # 8. Load Metric
782
+ #metric_wer = evaluate.load("wer")
783
+ #metric_cer = evaluate.load("cer")
784
+ metric_wer = datasets.load_metric("wer")
785
+ metric_cer = datasets.load_metric("cer")
786
+
787
+ def compute_metrics(pred):
788
+ pred_ids = pred.predictions
789
+ pred.label_ids[pred.label_ids == -100] = tokenizer.eos_token_id
790
+
791
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
792
+ pred_str = [x.lstrip().strip() for x in pred_str]
793
+
794
+ # we do not want to group tokens when computing the metrics
795
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
796
+
797
+ wer = metric_wer.compute(predictions=pred_str, references=label_str)
798
+ cer = metric_cer.compute(predictions=pred_str, references=label_str)
799
+
800
+ return {"wer": wer, "cer": cer}
801
+
802
+ def compute_metrics_and_predictions(pred):
803
+ pred_ids = pred.predictions
804
+ pred.label_ids[pred.label_ids == -100] = tokenizer.eos_token_id
805
+
806
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
807
+ pred_str = [x.lstrip().strip() for x in pred_str]
808
+
809
+ # we do not want to group tokens when computing the metrics
810
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
811
+
812
+ wer = metric_wer.compute(predictions=pred_str, references=label_str)
813
+ cer = metric_cer.compute(predictions=pred_str, references=label_str)
814
+
815
+ return {"wer": wer, "cer": cer, "pred_str": pred_str, "label_str": label_str}
816
+
817
+ class WhisperTrainer(Seq2SeqTrainer):
818
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
819
+ # If we are executing this function, we are the process zero, so we don't check for that.
820
+ output_dir = output_dir if output_dir is not None else self.args.output_dir
821
+ os.makedirs(output_dir, exist_ok=True)
822
+ logger.info(f"Saving model checkpoint to {output_dir}")
823
+ # Save a trained model and configuration using `save_pretrained()`.
824
+ # They can then be reloaded using `from_pretrained()`
825
+ self.model.save_to(save_path=os.path.join(output_dir, model_args.model_name_or_path + ".whisper"))
826
+ # Good practice: save your training arguments together with the trained model
827
+ torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
828
+
829
+ # Define data collator
830
+ whisper_data_collator = WhisperDataCollatorWithPadding(eos_token_id=tokenizer.eos_token_id)
831
+
832
+ # Initialize Trainer
833
+ trainer = WhisperTrainer(
834
+ model=model,
835
+ args=training_args,
836
+ compute_metrics=compute_metrics,
837
+ train_dataset=vectorized_datasets['train'] if training_args.do_train else None,
838
+ eval_dataset=vectorized_datasets['eval'] if training_args.do_eval else None,
839
+ data_collator=whisper_data_collator,
840
+ )
841
+
842
+ # 8. Finally, we can start training
843
+
844
+ # Training
845
+ if training_args.do_train:
846
+
847
+ # use last checkpoint if exist
848
+ if last_checkpoint is not None:
849
+ checkpoint = last_checkpoint
850
+ elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path):
851
+ checkpoint = model_args.model_name_or_path
852
+ else:
853
+ checkpoint = None
854
+
855
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
856
+ trainer.save_model()
857
+
858
+ metrics = train_result.metrics
859
+ max_train_samples = (
860
+ data_args.max_train_samples
861
+ if data_args.max_train_samples is not None
862
+ else len(vectorized_datasets["train"])
863
+ )
864
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
865
+
866
+ trainer.log_metrics("train", metrics)
867
+ trainer.save_metrics("train", metrics)
868
+ trainer.save_state()
869
+
870
+ # Change decoding strategy for final eval/predict
871
+ # if training_args.do_eval or training_args.do_predict:
872
+ # trainer.model.num_beams = 2
873
+
874
+ trainer.compute_metrics = compute_metrics_and_predictions
875
+
876
+ results = {}
877
+ if training_args.do_eval:
878
+ if not training_args.do_train and report_to_wandb:
879
+ # manually init wandb
880
+ wandb.init(project=data_args.wandb_project, name=training_args.run_name)
881
+ # Have to run this as a predict step, otherwise trainer will try to log the pred/label strings to wandb
882
+ eval_results = trainer.predict(vectorized_datasets["eval"], metric_key_prefix="eval", logits_processor=logits_processors)
883
+ metrics = eval_results.metrics
884
+ max_eval_samples = (
885
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
886
+ )
887
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
888
+ pred_str = metrics.pop("eval_pred_str", None)
889
+ label_str = metrics.pop("eval_label_str", None)
890
+
891
+ trainer.log_metrics("eval", metrics)
892
+ trainer.save_metrics("eval", metrics)
893
+
894
+ if report_to_wandb:
895
+ metrics = {os.path.join("eval", k[len("eval") + 1:]): v for k, v in metrics.items()}
896
+ wandb.log(metrics)
897
+ write_wandb_pred(pred_str, label_str, prefix="eval")
898
+
899
+ if training_args.do_predict:
900
+ if not training_args.do_train and not training_args.do_eval and report_to_wandb:
901
+ # manually init wandb
902
+ wandb.init(project=data_args.wandb_project, name=training_args.run_name)
903
+ for split in test_split:
904
+ predict_results = trainer.predict(
905
+ vectorized_datasets[split], metric_key_prefix=split, logits_processor=logits_processors)
906
+ metrics = predict_results.metrics
907
+ max_predict_samples = (
908
+ data_args.max_predict_samples if data_args.max_predict_samples is not None else len(vectorized_datasets[split])
909
+ )
910
+ metrics[f"{split}_samples"] = min(max_predict_samples, len(vectorized_datasets[split]))
911
+ pred_str = metrics.pop(f"{split}_pred_str", None)
912
+ label_str = metrics.pop(f"{split}_label_str", None)
913
+
914
+ trainer.log_metrics(split, metrics)
915
+ trainer.save_metrics(split, metrics)
916
+
917
+ if report_to_wandb:
918
+ metrics = {os.path.join(split, k[len(split)+1:]): v for k, v in metrics.items()}
919
+ wandb.log(metrics)
920
+ write_wandb_pred(pred_str, label_str, prefix=split)
921
+
922
+ # Write model card and (optionally) push to hub
923
+ config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
924
+ kwargs = {
925
+ "finetuned_from": model_args.model_name_or_path,
926
+ "tasks": "speech-recognition",
927
+ "tags": ["automatic-speech-recognition", data_args.dataset_name],
928
+ "dataset_args": (
929
+ f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split:"
930
+ f" {data_args.eval_split_name}"
931
+ ),
932
+ "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
933
+ }
934
+ if "common_voice" in data_args.dataset_name:
935
+ kwargs["language"] = config_name
936
+
937
+ if training_args.push_to_hub:
938
+ trainer.push_to_hub(**kwargs)
939
+
940
+ return results
941
+
942
+
943
+ if __name__ == "__main__":
944
+ main()