kimbochen commited on
Commit
ac4adb5
1 Parent(s): d55f369

Training in progress, step 200

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