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