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