marinone94 commited on
Commit
49a13a3
1 Parent(s): 21c2884

Add logic to init env and send email

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