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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 DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset, Audio
|
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.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 |
+
# dataset_splits = [dataset.cast_column("audio", Audio(sampling_rate))
|
282 |
+
# for dataset in dataset_splits]
|
283 |
+
|
284 |
+
# interleave multiple splits to form one dataset
|
285 |
+
interleaved_dataset = interleave_datasets(dataset_splits)
|
286 |
+
return interleaved_dataset
|
287 |
+
else:
|
288 |
+
# load a single split *with* streaming mode
|
289 |
+
dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=streaming, **kwargs)
|
290 |
+
# dataset = dataset.cast_column("audio", Audio(sampling_rate))
|
291 |
+
return dataset
|
292 |
+
|
293 |
+
def load_multiple_streaming_datasets(
|
294 |
+
dataset_names: List,
|
295 |
+
dataset_config_names: List,
|
296 |
+
splits: Optional[List] = None,
|
297 |
+
text_column_names: Optional[List] = None,
|
298 |
+
sampling_rate: Optional[int] = 16000,
|
299 |
+
stopping_strategy: Optional[str] = "all_exhausted",
|
300 |
+
**kwargs
|
301 |
+
) -> IterableDataset:
|
302 |
+
|
303 |
+
if len(dataset_names) != len(dataset_config_names):
|
304 |
+
raise ValueError(
|
305 |
+
f"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and"
|
306 |
+
f" {len(dataset_config_names)} configs."
|
307 |
+
)
|
308 |
+
|
309 |
+
if splits is not None and len(splits) != len(dataset_names):
|
310 |
+
raise ValueError(
|
311 |
+
f"Ensure one split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits."
|
312 |
+
)
|
313 |
+
|
314 |
+
if text_column_names is not None and len(text_column_names) != len(dataset_names):
|
315 |
+
raise ValueError(
|
316 |
+
f"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and"
|
317 |
+
f" {len(text_column_names)} text column names."
|
318 |
+
)
|
319 |
+
|
320 |
+
splits = splits if splits is not None else ["train" for i in range(len(dataset_names))]
|
321 |
+
text_column_names = (
|
322 |
+
text_column_names if text_column_names is not None else ["text" for i in range(len(dataset_names))]
|
323 |
+
)
|
324 |
+
|
325 |
+
all_datasets = []
|
326 |
+
# iterate over the datasets we want to interleave
|
327 |
+
for i, dataset_name in enumerate(dataset_names):
|
328 |
+
dataset = load_dataset(dataset_name, dataset_config_names[i], split=splits[i], streaming=True, **kwargs)
|
329 |
+
# resample to specified sampling rate
|
330 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate))
|
331 |
+
# normalise columns to ["audio", "sentence"]
|
332 |
+
if text_column_names[i] != "sentence":
|
333 |
+
dataset = dataset.rename_column(text_column_names[i], "sentence")
|
334 |
+
dataset = dataset.remove_columns(set(dataset.features.keys()) - set(["audio", "sentence"]))
|
335 |
+
all_datasets.append(dataset)
|
336 |
+
|
337 |
+
interleaved_dataset = interleave_datasets(all_datasets, stopping_strategy=stopping_strategy)
|
338 |
+
return interleaved_dataset
|
339 |
+
|
340 |
+
def main():
|
341 |
+
# 1. Parse input arguments
|
342 |
+
# See all possible arguments in src/transformers/training_args.py
|
343 |
+
# or by passing the --help flag to this script.
|
344 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
345 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
346 |
+
|
347 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
348 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
349 |
+
# let's parse it to get our arguments.
|
350 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
351 |
+
else:
|
352 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
353 |
+
|
354 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
355 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
356 |
+
send_example_telemetry("run_speech_recognition_seq2seq_streaming", model_args, data_args)
|
357 |
+
|
358 |
+
# 2. Setup logging
|
359 |
+
logging.basicConfig(
|
360 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
361 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
362 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
363 |
+
)
|
364 |
+
log_level = training_args.get_process_log_level()
|
365 |
+
logger.setLevel(log_level)
|
366 |
+
datasets.utils.logging.set_verbosity(log_level)
|
367 |
+
transformers.utils.logging.set_verbosity(log_level)
|
368 |
+
transformers.utils.logging.enable_default_handler()
|
369 |
+
transformers.utils.logging.enable_explicit_format()
|
370 |
+
|
371 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
372 |
+
|
373 |
+
# Log on each process the small summary:
|
374 |
+
logger.warning(
|
375 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
376 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
377 |
+
)
|
378 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
379 |
+
|
380 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
381 |
+
if is_main_process(training_args.local_rank):
|
382 |
+
transformers.utils.logging.set_verbosity_info()
|
383 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
384 |
+
|
385 |
+
# 3. Detecting last checkpoint and eventually continue from last checkpoint
|
386 |
+
last_checkpoint = None
|
387 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
388 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
389 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
390 |
+
raise ValueError(
|
391 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
392 |
+
"Use --overwrite_output_dir to overcome."
|
393 |
+
)
|
394 |
+
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
|
395 |
+
logger.info(
|
396 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
397 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
398 |
+
)
|
399 |
+
|
400 |
+
# Set seed before initializing model.
|
401 |
+
set_seed(training_args.seed)
|
402 |
+
|
403 |
+
# # 4. Load dataset
|
404 |
+
# raw_datasets = IterableDatasetDict() if data_args.streaming else DatasetDict()
|
405 |
+
|
406 |
+
# if training_args.do_train:
|
407 |
+
# raw_datasets["train"] = load_maybe_streaming_dataset(
|
408 |
+
# data_args.dataset_name,
|
409 |
+
# data_args.dataset_config_name,
|
410 |
+
# split=data_args.train_split_name,
|
411 |
+
# use_auth_token=True if model_args.use_auth_token else None,
|
412 |
+
# streaming=data_args.streaming,
|
413 |
+
# )
|
414 |
+
|
415 |
+
# 4. Load dataset
|
416 |
+
dataset_names = ["mozilla-foundation/common_voice_11_0", "mozilla-foundation/common_voice_11_0", "google/fleurs", "google/fleurs", "google/fleurs", "vivos", "vivos"]
|
417 |
+
dataset_config_names = ["vi", "vi", "vi_vn", "vi_vn", "vi_vn", "", ""]
|
418 |
+
text_column_names = ["sentence", "sentence", "raw_transcription", "raw_transcription", "raw_transcription", "sentence", "sentence"]
|
419 |
+
splits = ['train', 'validation', 'train', 'validation', 'test', 'train', 'test']
|
420 |
+
|
421 |
+
raw_datasets = IterableDatasetDict()
|
422 |
+
|
423 |
+
if training_args.do_train:
|
424 |
+
raw_datasets["train"] = load_multiple_streaming_datasets(
|
425 |
+
dataset_names,
|
426 |
+
splits=splits,
|
427 |
+
dataset_config_names=dataset_config_names,
|
428 |
+
text_column_names=text_column_names,
|
429 |
+
sampling_rate=16000,
|
430 |
+
use_auth_token=True)
|
431 |
+
|
432 |
+
if training_args.do_eval:
|
433 |
+
# raw_datasets["eval"] = load_maybe_streaming_dataset(
|
434 |
+
# data_args.dataset_name,
|
435 |
+
# data_args.dataset_config_name,
|
436 |
+
# split=data_args.eval_split_name,
|
437 |
+
# use_auth_token=True if model_args.use_auth_token else None,
|
438 |
+
# streaming=data_args.streaming,
|
439 |
+
# )
|
440 |
+
|
441 |
+
raw_datasets["eval"] = load_multiple_streaming_datasets(
|
442 |
+
["mozilla-foundation/common_voice_11_0"],
|
443 |
+
splits=['test'],
|
444 |
+
dataset_config_names=["vi"],
|
445 |
+
text_column_names=["sentence"],
|
446 |
+
sampling_rate=16000,
|
447 |
+
use_auth_token=True if model_args.use_auth_token else None)
|
448 |
+
|
449 |
+
raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
|
450 |
+
|
451 |
+
if data_args.audio_column_name not in raw_datasets_features:
|
452 |
+
raise ValueError(
|
453 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
|
454 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
455 |
+
f"{', '.join(raw_datasets_features)}."
|
456 |
+
)
|
457 |
+
|
458 |
+
if data_args.text_column_name not in raw_datasets_features:
|
459 |
+
raise ValueError(
|
460 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
|
461 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
462 |
+
f"{', '.join(raw_datasets_features)}."
|
463 |
+
)
|
464 |
+
|
465 |
+
# 5. Load pretrained model, tokenizer, and feature extractor
|
466 |
+
#
|
467 |
+
# Distributed training:
|
468 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
469 |
+
config = AutoConfig.from_pretrained(
|
470 |
+
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
|
471 |
+
cache_dir=model_args.cache_dir,
|
472 |
+
revision=model_args.model_revision,
|
473 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
474 |
+
)
|
475 |
+
|
476 |
+
config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
|
477 |
+
|
478 |
+
if training_args.gradient_checkpointing:
|
479 |
+
config.update({"use_cache": False})
|
480 |
+
|
481 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
482 |
+
model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
|
483 |
+
cache_dir=model_args.cache_dir,
|
484 |
+
revision=model_args.model_revision,
|
485 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
486 |
+
)
|
487 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
488 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
489 |
+
cache_dir=model_args.cache_dir,
|
490 |
+
use_fast=model_args.use_fast_tokenizer,
|
491 |
+
revision=model_args.model_revision,
|
492 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
493 |
+
)
|
494 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
495 |
+
model_args.model_name_or_path,
|
496 |
+
config=config,
|
497 |
+
cache_dir=model_args.cache_dir,
|
498 |
+
revision=model_args.model_revision,
|
499 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
500 |
+
)
|
501 |
+
|
502 |
+
if model.config.decoder_start_token_id is None:
|
503 |
+
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
|
504 |
+
|
505 |
+
if model_args.freeze_feature_encoder:
|
506 |
+
model.freeze_feature_encoder()
|
507 |
+
|
508 |
+
if model_args.freeze_encoder:
|
509 |
+
model.freeze_encoder()
|
510 |
+
|
511 |
+
if data_args.language is not None:
|
512 |
+
# We only need to set the task id when the language is specified (i.e. in a multilingual setting)
|
513 |
+
tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
|
514 |
+
|
515 |
+
# 6. Resample speech dataset if necessary
|
516 |
+
dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
|
517 |
+
if dataset_sampling_rate != feature_extractor.sampling_rate:
|
518 |
+
raw_datasets = raw_datasets.cast_column(
|
519 |
+
data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
|
520 |
+
)
|
521 |
+
|
522 |
+
# 7. Preprocessing the datasets.
|
523 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
524 |
+
max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
525 |
+
min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
526 |
+
audio_column_name = data_args.audio_column_name
|
527 |
+
text_column_name = data_args.text_column_name
|
528 |
+
model_input_name = feature_extractor.model_input_names[0]
|
529 |
+
do_lower_case = data_args.do_lower_case
|
530 |
+
do_remove_punctuation = data_args.do_remove_punctuation
|
531 |
+
normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
|
532 |
+
|
533 |
+
if data_args.max_train_samples is not None:
|
534 |
+
raw_datasets["train"] = (
|
535 |
+
raw_datasets["train"].take(data_args.max_train_samples)
|
536 |
+
if data_args.streaming
|
537 |
+
else raw_datasets["train"].select(range(data_args.max_train_samples))
|
538 |
+
)
|
539 |
+
|
540 |
+
if data_args.max_eval_samples is not None:
|
541 |
+
raw_datasets["eval"] = (
|
542 |
+
raw_datasets["eval"].take(data_args.max_eval_samples)
|
543 |
+
if data_args.streaming
|
544 |
+
else raw_datasets["eval"].select(range(data_args.max_eval_samples))
|
545 |
+
)
|
546 |
+
|
547 |
+
def prepare_dataset(batch):
|
548 |
+
# process audio
|
549 |
+
sample = batch[audio_column_name]
|
550 |
+
inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
|
551 |
+
# process audio length
|
552 |
+
batch[model_input_name] = inputs.get(model_input_name)[0]
|
553 |
+
batch["input_length"] = len(sample["array"])
|
554 |
+
|
555 |
+
# process targets
|
556 |
+
input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
|
557 |
+
if do_remove_punctuation:
|
558 |
+
input_str = normalizer(input_str).strip()
|
559 |
+
batch["labels"] = tokenizer(input_str).input_ids
|
560 |
+
return batch
|
561 |
+
|
562 |
+
with training_args.main_process_first(desc="dataset map pre-processing"):
|
563 |
+
vectorized_datasets = raw_datasets.map(
|
564 |
+
prepare_dataset,
|
565 |
+
remove_columns=raw_datasets_features,
|
566 |
+
).with_format("torch")
|
567 |
+
|
568 |
+
if training_args.do_train and data_args.streaming:
|
569 |
+
# manually shuffle if streaming (done by the trainer for non-streaming)
|
570 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
|
571 |
+
buffer_size=data_args.shuffle_buffer_size,
|
572 |
+
seed=training_args.seed,
|
573 |
+
)
|
574 |
+
|
575 |
+
# filter training data that is shorter than min_input_length or longer than
|
576 |
+
# max_input_length
|
577 |
+
def is_audio_in_length_range(length):
|
578 |
+
return min_input_length < length < max_input_length
|
579 |
+
|
580 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].filter(
|
581 |
+
is_audio_in_length_range,
|
582 |
+
input_columns=["input_length"],
|
583 |
+
)
|
584 |
+
|
585 |
+
# 8. Load Metric
|
586 |
+
wer_metric = evaluate.load("wer")
|
587 |
+
cer_metric = evaluate.load("cer")
|
588 |
+
do_normalize_eval = data_args.do_normalize_eval
|
589 |
+
|
590 |
+
def compute_metrics(pred):
|
591 |
+
pred_ids = pred.predictions
|
592 |
+
|
593 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
594 |
+
|
595 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
596 |
+
# we do not want to group tokens when computing the metrics
|
597 |
+
label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
|
598 |
+
|
599 |
+
if do_normalize_eval:
|
600 |
+
pred_str = [normalizer(pred) for pred in pred_str]
|
601 |
+
label_str = [normalizer(label) for label in label_str]
|
602 |
+
|
603 |
+
wer = 100 * wer_metric.compute(predictions=pred_str, references=label_str)
|
604 |
+
cer = 100 * cer_metric.compute(predictions=pred_str, references=label_str)
|
605 |
+
|
606 |
+
return {"wer": wer, "cer": cer}
|
607 |
+
|
608 |
+
# 9. Create a single speech processor
|
609 |
+
if is_main_process(training_args.local_rank):
|
610 |
+
# save feature extractor, tokenizer and config
|
611 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
612 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
613 |
+
config.save_pretrained(training_args.output_dir)
|
614 |
+
|
615 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
616 |
+
|
617 |
+
# 10. Define data collator
|
618 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
|
619 |
+
processor=processor,
|
620 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
621 |
+
)
|
622 |
+
|
623 |
+
# 11. Configure Trainer
|
624 |
+
# Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
|
625 |
+
# Only required for streaming: Trainer automatically shuffles non-streaming datasets
|
626 |
+
class ShuffleCallback(TrainerCallback):
|
627 |
+
def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
|
628 |
+
if isinstance(train_dataloader.dataset, IterableDatasetShard):
|
629 |
+
pass # set_epoch() is handled by the Trainer
|
630 |
+
elif isinstance(train_dataloader.dataset, IterableDataset):
|
631 |
+
train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
|
632 |
+
|
633 |
+
# Initialize Trainer
|
634 |
+
trainer = Seq2SeqTrainer(
|
635 |
+
model=model,
|
636 |
+
args=training_args,
|
637 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
638 |
+
eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
|
639 |
+
tokenizer=feature_extractor,
|
640 |
+
data_collator=data_collator,
|
641 |
+
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
|
642 |
+
callbacks=[ShuffleCallback()] if data_args.streaming else None,
|
643 |
+
)
|
644 |
+
|
645 |
+
# 12. Training
|
646 |
+
if training_args.do_train:
|
647 |
+
checkpoint = None
|
648 |
+
if training_args.resume_from_checkpoint is not None:
|
649 |
+
checkpoint = training_args.resume_from_checkpoint
|
650 |
+
elif last_checkpoint is not None:
|
651 |
+
checkpoint = last_checkpoint
|
652 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
653 |
+
trainer.save_model() # Saves the feature extractor too for easy upload
|
654 |
+
|
655 |
+
metrics = train_result.metrics
|
656 |
+
if data_args.max_train_samples:
|
657 |
+
metrics["train_samples"] = data_args.max_train_samples
|
658 |
+
trainer.log_metrics("train", metrics)
|
659 |
+
trainer.save_metrics("train", metrics)
|
660 |
+
trainer.save_state()
|
661 |
+
|
662 |
+
# 13. Evaluation
|
663 |
+
results = {}
|
664 |
+
if training_args.do_eval:
|
665 |
+
logger.info("*** Evaluate ***")
|
666 |
+
metrics = trainer.evaluate(
|
667 |
+
metric_key_prefix="eval",
|
668 |
+
max_length=training_args.generation_max_length,
|
669 |
+
num_beams=training_args.generation_num_beams,
|
670 |
+
)
|
671 |
+
if data_args.max_eval_samples:
|
672 |
+
metrics["eval_samples"] = data_args.max_eval_samples
|
673 |
+
|
674 |
+
trainer.log_metrics("eval", metrics)
|
675 |
+
trainer.save_metrics("eval", metrics)
|
676 |
+
|
677 |
+
# 14. Write Training Stats
|
678 |
+
kwargs = {
|
679 |
+
"finetuned_from": model_args.model_name_or_path,
|
680 |
+
"tasks": "automatic-speech-recognition",
|
681 |
+
"tags": "whisper-event",
|
682 |
+
}
|
683 |
+
if data_args.dataset_name is not None:
|
684 |
+
kwargs["dataset_tags"] = data_args.dataset_name
|
685 |
+
if data_args.dataset_config_name is not None:
|
686 |
+
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
|
687 |
+
else:
|
688 |
+
kwargs["dataset"] = data_args.dataset_name
|
689 |
+
if "common_voice" in data_args.dataset_name:
|
690 |
+
kwargs["language"] = data_args.dataset_config_name[:2]
|
691 |
+
if model_args.model_index_name is not None:
|
692 |
+
kwargs["model_name"] = model_args.model_index_name
|
693 |
+
|
694 |
+
if training_args.push_to_hub:
|
695 |
+
trainer.push_to_hub(**kwargs)
|
696 |
+
else:
|
697 |
+
trainer.create_model_card(**kwargs)
|
698 |
+
|
699 |
+
return results
|
700 |
+
|
701 |
+
|
702 |
+
if __name__ == "__main__":
|
703 |
+
main()
|
pytorch_model.bin
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
size 6173655480
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:12f292f88d9506f92caebc9f3c451c528db43aad08a1597c1d039d382b46ef95
|
3 |
size 6173655480
|
run_speech_recognition_seq2seq_streaming.py
CHANGED
@@ -413,10 +413,10 @@ def main():
|
|
413 |
# )
|
414 |
|
415 |
# 4. Load dataset
|
416 |
-
dataset_names = ["mozilla-foundation/common_voice_11_0", "mozilla-foundation/common_voice_11_0", "google/fleurs", "google/fleurs", "google/fleurs"]
|
417 |
-
dataset_config_names = ["vi", "vi", "vi_vn", "vi_vn", "vi_vn"]
|
418 |
-
text_column_names = ["sentence", "sentence", "raw_transcription", "raw_transcription", "raw_transcription"]
|
419 |
-
splits = ['train', 'validation', 'train', 'validation', 'test']
|
420 |
|
421 |
raw_datasets = IterableDatasetDict()
|
422 |
|
|
|
413 |
# )
|
414 |
|
415 |
# 4. Load dataset
|
416 |
+
dataset_names = ["mozilla-foundation/common_voice_11_0", "mozilla-foundation/common_voice_11_0", "google/fleurs", "google/fleurs", "google/fleurs", "vivos", "vivos"]
|
417 |
+
dataset_config_names = ["vi", "vi", "vi_vn", "vi_vn", "vi_vn", "", ""]
|
418 |
+
text_column_names = ["sentence", "sentence", "raw_transcription", "raw_transcription", "raw_transcription", "sentence", "sentence"]
|
419 |
+
splits = ['train', 'validation', 'train', 'validation', 'test', 'train', 'test']
|
420 |
|
421 |
raw_datasets = IterableDatasetDict()
|
422 |
|
runs/Dec09_13-54-47_132-145-179-103/events.out.tfevents.1670594111.132-145-179-103.2897147.0
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5ec738ccfc427dd1a33ec96338d16064e04788623a5b86cfa7305d3bcd1485d1
|
3 |
+
size 32205
|