div
Browse files- run_speech_recognition_whisper.py +48 -112
- run_speech_recognition_whisper_pere.py +523 -0
run_speech_recognition_whisper.py
CHANGED
|
@@ -55,9 +55,9 @@ from transformers.utils import check_min_version
|
|
| 55 |
from transformers.utils.versions import require_version
|
| 56 |
|
| 57 |
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
| 58 |
-
check_min_version("4.24.0.dev0")
|
| 59 |
|
| 60 |
-
require_version("datasets>=2.6.1", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
|
| 61 |
|
| 62 |
logger = logging.getLogger(__name__)
|
| 63 |
|
|
@@ -281,129 +281,53 @@ class DataCollatorSpeechSeq2SeqWithPadding:
|
|
| 281 |
|
| 282 |
return batch
|
| 283 |
|
|
|
|
| 284 |
|
| 285 |
-
def create_vocabulary_from_data(
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
):
|
| 291 |
-
|
| 292 |
-
|
| 293 |
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
|
| 311 |
-
|
| 312 |
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
|
| 322 |
-
|
| 323 |
-
|
| 324 |
|
| 325 |
-
|
| 326 |
|
| 327 |
|
| 328 |
def make_dataset(training_args, data_args):
|
| 329 |
seed = training_args.seed or 42
|
| 330 |
-
# Pre-processing dataset
|
| 331 |
-
# import re
|
| 332 |
-
|
| 333 |
-
# def map_nst(entry):
|
| 334 |
-
# text = entry["text"].lower()
|
| 335 |
-
# text = text.replace("(...Vær stille under dette opptaket...)", "")
|
| 336 |
-
# text = re.sub('[áàâ]', 'a', text)
|
| 337 |
-
# text = re.sub('[ä]', 'æ', text)
|
| 338 |
-
# text = re.sub('[éèëê]', 'e', text)
|
| 339 |
-
# text = re.sub('[íìïî]', 'i', text)
|
| 340 |
-
# text = re.sub('[óòöô]', 'o', text)
|
| 341 |
-
# text = re.sub('[ö]', 'ø', text)
|
| 342 |
-
# text = re.sub('[ç]', 'c', text)
|
| 343 |
-
# text = re.sub('[úùüû]', 'u', text)
|
| 344 |
-
# # text = re.sub('\\(?=(Punktum|Komma|Utropstegn|Spørsmålstegn))', ' ', text)
|
| 345 |
-
# text = re.sub('\s+', ' ', text)
|
| 346 |
-
# return {"text": text}
|
| 347 |
-
|
| 348 |
-
# def filter_nst(entry):
|
| 349 |
-
# if not ((len(entry["text"]) <= len(entry["audio"]["array"]) // 320) and (len(entry["text"].strip()) >= 3)):
|
| 350 |
-
# return False # Too short
|
| 351 |
-
# if re.match(entry["type"], "pIW|CA"):
|
| 352 |
-
# return False # Spelling out words
|
| 353 |
-
# return True
|
| 354 |
-
|
| 355 |
-
# def filter_npsc(entry):
|
| 356 |
-
# # False if there are digits in the text
|
| 357 |
-
# if not ((len(entry["text"]) <= len(entry["audio"]["array"]) // 320) and (len(entry["text"].strip()) >= 3)):
|
| 358 |
-
# return False # Too short
|
| 359 |
-
# if re.search("\d", entry["text"]):
|
| 360 |
-
# return False
|
| 361 |
-
# return True
|
| 362 |
-
|
| 363 |
-
# def map_npsc(entry):
|
| 364 |
-
# batch = {"text": entry["text"].lower()}
|
| 365 |
-
# batch["text"] = re.sub('[áàâ]', 'a', batch["text"])
|
| 366 |
-
# batch["text"] = re.sub('[ä]', 'æ', batch["text"])
|
| 367 |
-
# batch["text"] = re.sub('[éèëê]', 'e', batch["text"])
|
| 368 |
-
# batch["text"] = re.sub('[íìïî]', 'i', batch["text"])
|
| 369 |
-
# batch["text"] = re.sub('[óòöô]', 'o', batch["text"])
|
| 370 |
-
# batch["text"] = re.sub('[ö]', 'ø', batch["text"])
|
| 371 |
-
# batch["text"] = re.sub('[ç]', 'c', batch["text"])
|
| 372 |
-
# batch["text"] = re.sub('[úùüû]', 'u', batch["text"])
|
| 373 |
-
# batch["text"] = re.sub('\s', ' ', batch["text"])
|
| 374 |
-
# batch["text"] = re.sub('<ee>', 'eee', batch["text"])
|
| 375 |
-
# batch["text"] = re.sub('<qq>', 'qqq', batch["text"])
|
| 376 |
-
# batch["text"] = re.sub('<mm>', 'mmm', batch["text"])
|
| 377 |
-
# batch["text"] = re.sub('<inaudible>', 'xxx', batch["text"])
|
| 378 |
-
# # batch["text"] = re.sub('<inaudible>', '?', batch["text"])
|
| 379 |
-
# if "<" in batch["text"]:
|
| 380 |
-
# raise ValueError(batch["text"])
|
| 381 |
-
# return batch
|
| 382 |
-
|
| 383 |
-
# nst = datasets.load_dataset("NbAiLab/NST", "no-close")
|
| 384 |
-
# npsc = datasets.load_dataset("NbAiLab/NPSC", "16K_mp3")
|
| 385 |
-
# # TODO NST_hesitate
|
| 386 |
-
|
| 387 |
-
# split = len(npsc["train"]) / (len(npsc["train"]) + len(npsc["validation"])) # Use same train/val ratio as NPSC
|
| 388 |
-
# nst_train = nst["train"].train_test_split(train_size=split, seed=seed)
|
| 389 |
-
# nst["train"] = nst_train["train"]
|
| 390 |
-
# nst["validation"] = nst_train["test"]
|
| 391 |
-
|
| 392 |
-
# nst = nst.filter(filter_nst).map(map_nst).shuffle(seed=seed)
|
| 393 |
-
# npsc = npsc.filter(filter_npsc).map(map_npsc).shuffle(seed=seed)
|
| 394 |
-
|
| 395 |
-
# npsc_base = npsc.remove_columns([col for col in npsc["train"].column_names if col not in ["text", "audio"]])
|
| 396 |
-
# nst_base = nst.remove_columns([col for col in nst["train"].column_names if col not in ["text", "audio"]])
|
| 397 |
-
|
| 398 |
-
# combined = {}
|
| 399 |
-
# for split in "train", "validation", "test":
|
| 400 |
-
# probs = np.array([len(nst_base[split]), len(npsc_base[split])]) # Weight by number of examples
|
| 401 |
-
# probs = (probs / probs.sum()).tolist()
|
| 402 |
-
# comb = datasets.interleave_datasets([nst_base[split], npsc_base[split]], probabilities=probs, seed=seed)
|
| 403 |
-
# combined[split] = comb
|
| 404 |
-
|
| 405 |
-
# return datasets.DatasetDict(**combined)
|
| 406 |
-
|
| 407 |
dataset = datasets.load_dataset(training_args.dataset_name, training_args.dataset_config_name, use_auth_token=data_args.use_auth_token)
|
| 408 |
return dataset
|
| 409 |
|
|
@@ -414,6 +338,7 @@ def main():
|
|
| 414 |
# or by passing the --help flag to this script.
|
| 415 |
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
| 416 |
|
|
|
|
| 417 |
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
| 418 |
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
| 419 |
# If we pass only one argument to the script and it's the path to a json file,
|
|
@@ -423,6 +348,7 @@ def main():
|
|
| 423 |
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
| 424 |
|
| 425 |
# Detecting last checkpoint.
|
|
|
|
| 426 |
last_checkpoint = None
|
| 427 |
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
| 428 |
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
|
@@ -490,6 +416,8 @@ def main():
|
|
| 490 |
# chars_to_ignore_regex = (
|
| 491 |
# f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
|
| 492 |
# )
|
|
|
|
|
|
|
| 493 |
chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]'
|
| 494 |
|
| 495 |
text_column_name = data_args.text_column_name
|
|
@@ -792,5 +720,13 @@ def main():
|
|
| 792 |
return results
|
| 793 |
|
| 794 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 795 |
if __name__ == "__main__":
|
| 796 |
main()
|
|
|
|
| 55 |
from transformers.utils.versions import require_version
|
| 56 |
|
| 57 |
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
| 58 |
+
# check_min_version("4.24.0.dev0")
|
| 59 |
|
| 60 |
+
# require_version("datasets>=2.6.1", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
|
| 61 |
|
| 62 |
logger = logging.getLogger(__name__)
|
| 63 |
|
|
|
|
| 281 |
|
| 282 |
return batch
|
| 283 |
|
| 284 |
+
# PERE - COMMENTING OUT - IS THIS NEEDED? We can load vocab from Whisper instead...
|
| 285 |
|
| 286 |
+
# def create_vocabulary_from_data(
|
| 287 |
+
# datasets: DatasetDict,
|
| 288 |
+
# word_delimiter_token: Optional[str] = None,
|
| 289 |
+
# unk_token: Optional[str] = None,
|
| 290 |
+
# pad_token: Optional[str] = None,
|
| 291 |
+
# ):
|
| 292 |
+
# # Given training and test labels create vocabulary
|
| 293 |
+
# alphabet = set()
|
| 294 |
|
| 295 |
+
# def extract_all_chars(batch):
|
| 296 |
+
# all_text = " ".join(batch["target_text"])
|
| 297 |
+
# alphabet.update(all_text)
|
| 298 |
|
| 299 |
+
# datasets.map(
|
| 300 |
+
# extract_all_chars,
|
| 301 |
+
# batched=True,
|
| 302 |
+
# batch_size=-1,
|
| 303 |
+
# keep_in_memory=True,
|
| 304 |
+
# remove_columns=datasets["train"].column_names,
|
| 305 |
+
# )
|
| 306 |
|
| 307 |
+
# # # take union of all unique characters in each dataset
|
| 308 |
+
# # vocab_set = functools.reduce(
|
| 309 |
+
# # lambda vocab_1, vocab_2: {"vocab": list(set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]))}, vocabs.values()
|
| 310 |
+
# # )["vocab"][0]
|
| 311 |
|
| 312 |
+
# vocab_dict = {v: k for k, v in enumerate(sorted(list(alphabet)))}
|
| 313 |
|
| 314 |
+
# # replace white space with delimiter token
|
| 315 |
+
# if word_delimiter_token is not None:
|
| 316 |
+
# vocab_dict[word_delimiter_token] = vocab_dict[" "]
|
| 317 |
+
# del vocab_dict[" "]
|
| 318 |
|
| 319 |
+
# # add unk and pad token
|
| 320 |
+
# if unk_token is not None:
|
| 321 |
+
# vocab_dict[unk_token] = len(vocab_dict)
|
| 322 |
|
| 323 |
+
# if pad_token is not None:
|
| 324 |
+
# vocab_dict[pad_token] = len(vocab_dict)
|
| 325 |
|
| 326 |
+
# return vocab_dict
|
| 327 |
|
| 328 |
|
| 329 |
def make_dataset(training_args, data_args):
|
| 330 |
seed = training_args.seed or 42
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
dataset = datasets.load_dataset(training_args.dataset_name, training_args.dataset_config_name, use_auth_token=data_args.use_auth_token)
|
| 332 |
return dataset
|
| 333 |
|
|
|
|
| 338 |
# or by passing the --help flag to this script.
|
| 339 |
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
| 340 |
|
| 341 |
+
|
| 342 |
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
| 343 |
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
| 344 |
# If we pass only one argument to the script and it's the path to a json file,
|
|
|
|
| 348 |
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
| 349 |
|
| 350 |
# Detecting last checkpoint.
|
| 351 |
+
# PERE - Great but does it set other parameters, like the current learning rate?
|
| 352 |
last_checkpoint = None
|
| 353 |
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
| 354 |
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
|
|
|
| 416 |
# chars_to_ignore_regex = (
|
| 417 |
# f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
|
| 418 |
# )
|
| 419 |
+
|
| 420 |
+
## PERE - JUST REMOVE THIS FOR WHISPER?
|
| 421 |
chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]'
|
| 422 |
|
| 423 |
text_column_name = data_args.text_column_name
|
|
|
|
| 720 |
return results
|
| 721 |
|
| 722 |
|
| 723 |
+
#XLA hook
|
| 724 |
+
def _mp_fn(index):
|
| 725 |
+
# For xla_spawn (TPUs)
|
| 726 |
+
print("The XLA is initiated")
|
| 727 |
+
main()
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
|
| 731 |
if __name__ == "__main__":
|
| 732 |
main()
|
run_speech_recognition_whisper_pere.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
|
| 15 |
+
""" Fine-tuning a 🤗 Transformers Whisper model for automatic speech recognition"""
|
| 16 |
+
|
| 17 |
+
import functools
|
| 18 |
+
import json
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
import sys
|
| 23 |
+
import warnings
|
| 24 |
+
from dataclasses import dataclass, field
|
| 25 |
+
from typing import Dict, List, Optional, Union
|
| 26 |
+
|
| 27 |
+
import datasets
|
| 28 |
+
import numpy as np
|
| 29 |
+
import torch
|
| 30 |
+
import evaluate
|
| 31 |
+
from datasets import DatasetDict, load_dataset
|
| 32 |
+
|
| 33 |
+
import transformers
|
| 34 |
+
from transformers import (
|
| 35 |
+
AutoConfig,
|
| 36 |
+
AutoFeatureExtractor,
|
| 37 |
+
AutoModelForCTC,
|
| 38 |
+
AutoProcessor,
|
| 39 |
+
AutoTokenizer,
|
| 40 |
+
HfArgumentParser,
|
| 41 |
+
Trainer,
|
| 42 |
+
TrainingArguments,
|
| 43 |
+
Wav2Vec2Processor,
|
| 44 |
+
set_seed,
|
| 45 |
+
|
| 46 |
+
WhisperFeatureExtractor,
|
| 47 |
+
WhisperTokenizer,
|
| 48 |
+
WhisperForConditionalGeneration,
|
| 49 |
+
WhisperProcessor,
|
| 50 |
+
Seq2SeqTrainer,
|
| 51 |
+
Seq2SeqTrainingArguments,
|
| 52 |
+
)
|
| 53 |
+
from transformers.trainer_utils import get_last_checkpoint, is_main_process
|
| 54 |
+
from transformers.utils import check_min_version
|
| 55 |
+
from transformers.utils.versions import require_version
|
| 56 |
+
|
| 57 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
| 58 |
+
# check_min_version("4.24.0.dev0")
|
| 59 |
+
|
| 60 |
+
# require_version("datasets>=2.6.1", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
|
| 61 |
+
|
| 62 |
+
logger = logging.getLogger(__name__)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def list_field(default=None, metadata=None):
|
| 66 |
+
return field(default_factory=lambda: default, metadata=metadata)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass
|
| 70 |
+
class ModelArguments:
|
| 71 |
+
"""
|
| 72 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
model_name_or_path: str = field(
|
| 76 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
| 77 |
+
)
|
| 78 |
+
language: str = field(
|
| 79 |
+
metadata={"help": "Whisper specific language"}
|
| 80 |
+
)
|
| 81 |
+
task: str = field(
|
| 82 |
+
metadata={"help": "Whisper specific task, i.e., 'transcribe' or 'translate'"}
|
| 83 |
+
)
|
| 84 |
+
tokenizer_name_or_path: Optional[str] = field(
|
| 85 |
+
default=None,
|
| 86 |
+
metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
|
| 87 |
+
)
|
| 88 |
+
cache_dir: Optional[str] = field(
|
| 89 |
+
default=None,
|
| 90 |
+
metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
|
| 91 |
+
)
|
| 92 |
+
freeze_feature_encoder: bool = field(
|
| 93 |
+
default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
|
| 94 |
+
)
|
| 95 |
+
attention_dropout: float = field(
|
| 96 |
+
default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."}
|
| 97 |
+
)
|
| 98 |
+
activation_dropout: float = field(
|
| 99 |
+
default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."}
|
| 100 |
+
)
|
| 101 |
+
feat_proj_dropout: float = field(default=0.0, metadata={"help": "The dropout ratio for the projected features."})
|
| 102 |
+
hidden_dropout: float = field(
|
| 103 |
+
default=0.0,
|
| 104 |
+
metadata={
|
| 105 |
+
"help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
|
| 106 |
+
},
|
| 107 |
+
)
|
| 108 |
+
final_dropout: float = field(
|
| 109 |
+
default=0.0,
|
| 110 |
+
metadata={"help": "The dropout probability for the final projection layer."},
|
| 111 |
+
)
|
| 112 |
+
mask_time_prob: float = field(
|
| 113 |
+
default=0.05,
|
| 114 |
+
metadata={
|
| 115 |
+
"help": "Probability of each feature vector along the time axis to be chosen as the start of the vector"
|
| 116 |
+
"span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
|
| 117 |
+
"vectors will be masked along the time axis."
|
| 118 |
+
},
|
| 119 |
+
)
|
| 120 |
+
mask_time_length: int = field(
|
| 121 |
+
default=10,
|
| 122 |
+
metadata={"help": "Length of vector span to mask along the time axis."},
|
| 123 |
+
)
|
| 124 |
+
mask_feature_prob: float = field(
|
| 125 |
+
default=0.0,
|
| 126 |
+
metadata={
|
| 127 |
+
"help": "Probability of each feature vector along the feature axis to be chosen as the start of the vector"
|
| 128 |
+
"span to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature bins will be masked along the time axis."
|
| 129 |
+
},
|
| 130 |
+
)
|
| 131 |
+
mask_feature_length: int = field(
|
| 132 |
+
default=10,
|
| 133 |
+
metadata={"help": "Length of vector span to mask along the feature axis."},
|
| 134 |
+
)
|
| 135 |
+
layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
|
| 136 |
+
ctc_loss_reduction: Optional[str] = field(
|
| 137 |
+
default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
|
| 138 |
+
)
|
| 139 |
+
ctc_zero_infinity: Optional[bool] = field(
|
| 140 |
+
default=False, metadata={"help": "If True, will try yo aboud the CTC loss goinf to infinity."}
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@dataclass
|
| 145 |
+
class DataTrainingArguments:
|
| 146 |
+
"""
|
| 147 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 148 |
+
|
| 149 |
+
Using `HfArgumentParser` we can turn this class
|
| 150 |
+
into argparse arguments to be able to specify them on
|
| 151 |
+
the command line.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
dataset_name: str = field(
|
| 155 |
+
metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
| 156 |
+
)
|
| 157 |
+
dataset_config_name: str = field(
|
| 158 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
| 159 |
+
)
|
| 160 |
+
train_split_name: str = field(
|
| 161 |
+
default="train",
|
| 162 |
+
metadata={
|
| 163 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
| 164 |
+
},
|
| 165 |
+
)
|
| 166 |
+
eval_split_name: str = field(
|
| 167 |
+
default="test",
|
| 168 |
+
metadata={
|
| 169 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
| 170 |
+
},
|
| 171 |
+
)
|
| 172 |
+
audio_column_name: str = field(
|
| 173 |
+
default="audio",
|
| 174 |
+
metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
|
| 175 |
+
)
|
| 176 |
+
text_column_name: str = field(
|
| 177 |
+
default="text",
|
| 178 |
+
metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
|
| 179 |
+
)
|
| 180 |
+
overwrite_cache: bool = field(
|
| 181 |
+
default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
|
| 182 |
+
)
|
| 183 |
+
preprocessing_num_workers: Optional[int] = field(
|
| 184 |
+
default=None,
|
| 185 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
| 186 |
+
)
|
| 187 |
+
max_train_samples: Optional[int] = field(
|
| 188 |
+
default=None,
|
| 189 |
+
metadata={
|
| 190 |
+
"help": "For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 191 |
+
"value if set."
|
| 192 |
+
},
|
| 193 |
+
)
|
| 194 |
+
max_eval_samples: Optional[int] = field(
|
| 195 |
+
default=None,
|
| 196 |
+
metadata={
|
| 197 |
+
"help": "For debugging purposes or quicker training, truncate the number of validation examples to this "
|
| 198 |
+
"value if set."
|
| 199 |
+
},
|
| 200 |
+
)
|
| 201 |
+
chars_to_ignore: Optional[List[str]] = list_field(
|
| 202 |
+
default=None,
|
| 203 |
+
metadata={"help": "A list of characters to remove from the transcripts."},
|
| 204 |
+
)
|
| 205 |
+
eval_metrics: List[str] = list_field(
|
| 206 |
+
default=["wer"],
|
| 207 |
+
metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
|
| 208 |
+
)
|
| 209 |
+
max_duration_in_seconds: float = field(
|
| 210 |
+
default=20.0,
|
| 211 |
+
metadata={
|
| 212 |
+
"help": "Filter audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
|
| 213 |
+
},
|
| 214 |
+
)
|
| 215 |
+
min_duration_in_seconds: float = field(
|
| 216 |
+
default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
|
| 217 |
+
)
|
| 218 |
+
preprocessing_only: bool = field(
|
| 219 |
+
default=False,
|
| 220 |
+
metadata={
|
| 221 |
+
"help": "Whether to only do data preprocessing and skip training. "
|
| 222 |
+
"This is especially useful when data preprocessing errors out in distributed training due to timeout. "
|
| 223 |
+
"In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
|
| 224 |
+
"so that the cached datasets can consequently be loaded in distributed training"
|
| 225 |
+
},
|
| 226 |
+
)
|
| 227 |
+
use_auth_token: bool = field(
|
| 228 |
+
default=False,
|
| 229 |
+
metadata={
|
| 230 |
+
"help": "If :obj:`True`, will use the token generated when running"
|
| 231 |
+
":obj:`transformers-cli login` as HTTP bearer authorization for remote files."
|
| 232 |
+
},
|
| 233 |
+
)
|
| 234 |
+
unk_token: str = field(
|
| 235 |
+
default="[UNK]",
|
| 236 |
+
metadata={"help": "The unk token for the tokenizer"},
|
| 237 |
+
)
|
| 238 |
+
pad_token: str = field(
|
| 239 |
+
default="[PAD]",
|
| 240 |
+
metadata={"help": "The padding token for the tokenizer"},
|
| 241 |
+
)
|
| 242 |
+
word_delimiter_token: str = field(
|
| 243 |
+
default="|",
|
| 244 |
+
metadata={"help": "The word delimiter token for the tokenizer"},
|
| 245 |
+
)
|
| 246 |
+
phoneme_language: Optional[str] = field(
|
| 247 |
+
default=None,
|
| 248 |
+
metadata={
|
| 249 |
+
"help": "The target language that should be used be"
|
| 250 |
+
" passed to the tokenizer for tokenization. Note that"
|
| 251 |
+
" this is only relevant if the model classifies the"
|
| 252 |
+
" input audio to a sequence of phoneme sequences."
|
| 253 |
+
},
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@dataclass
|
| 258 |
+
class DataCollatorSpeechSeq2SeqWithPadding:
|
| 259 |
+
processor: Any
|
| 260 |
+
|
| 261 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
| 262 |
+
# split inputs and labels since they have to be of different lengths and need different padding methods
|
| 263 |
+
# first treat the audio inputs by simply returning torch tensors
|
| 264 |
+
input_features = [{"input_features": feature["input_features"]} for feature in features]
|
| 265 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
| 266 |
+
|
| 267 |
+
# get the tokenized label sequences
|
| 268 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
| 269 |
+
# pad the labels to max length
|
| 270 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
| 271 |
+
|
| 272 |
+
# replace padding with -100 to ignore loss correctly
|
| 273 |
+
labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
| 274 |
+
|
| 275 |
+
# if bos token is appended in previous tokenization step,
|
| 276 |
+
# cut bos token here as it's append later anyways
|
| 277 |
+
if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():
|
| 278 |
+
labels = labels[:, 1:]
|
| 279 |
+
|
| 280 |
+
batch["labels"] = labels
|
| 281 |
+
|
| 282 |
+
return batch
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def main():
|
| 288 |
+
# See all possible arguments in src/transformers/training_args.py
|
| 289 |
+
# or by passing the --help flag to this script.
|
| 290 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
| 291 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
| 292 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# Metrics
|
| 296 |
+
def compute_metrics(pred):
|
| 297 |
+
pred_ids = pred.predictions
|
| 298 |
+
label_ids = pred.label_ids
|
| 299 |
+
|
| 300 |
+
# replace -100 with the pad_token_id
|
| 301 |
+
label_ids[label_ids == -100] = tokenizer.pad_token_id
|
| 302 |
+
|
| 303 |
+
# we do not want to group tokens when computing the metrics
|
| 304 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
| 305 |
+
label_str = tokenizer.batch_decode(label_ids, skip_special_tokens=True)
|
| 306 |
+
|
| 307 |
+
wer = 100 * metric.compute(predictions=pred_str, references=label_str)
|
| 308 |
+
|
| 309 |
+
return {"wer": wer}
|
| 310 |
+
|
| 311 |
+
# Prepare dataset
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def prepare_dataset(batch):
|
| 315 |
+
# load and resample audio data from 48 to 16kHz
|
| 316 |
+
audio = batch["audio"]
|
| 317 |
+
|
| 318 |
+
# compute log-Mel input features from input audio array
|
| 319 |
+
batch["input_features"] = feature_extractor(
|
| 320 |
+
audio["array"], sampling_rate=audio["sampling_rate"]).input_features[0]
|
| 321 |
+
|
| 322 |
+
# encode target text to label ids
|
| 323 |
+
batch["labels"] = tokenizer(batch["sentence"]).input_ids
|
| 324 |
+
return batch
|
| 325 |
+
|
| 326 |
+
def make_dataset(training_args, data_args):
|
| 327 |
+
seed = training_args.seed or 42
|
| 328 |
+
dataset = datasets.load_dataset(training_args.dataset_name, training_args.dataset_config_name, use_auth_token=data_args.use_auth_token)
|
| 329 |
+
return dataset
|
| 330 |
+
|
| 331 |
+
# PERE - SHOULD BE CHANGED TO STREAMING LATER
|
| 332 |
+
# Load dataset
|
| 333 |
+
speech_data = DatasetDict()
|
| 334 |
+
|
| 335 |
+
# The smallest dataset I found
|
| 336 |
+
speech_data["train"] = load_dataset(
|
| 337 |
+
"mozilla-foundation/common_voice_11_0", "nn-NO", split="train", use_auth_token=True)
|
| 338 |
+
speech_data["test"] = load_dataset(
|
| 339 |
+
"mozilla-foundation/common_voice_11_0", "nn-NO", split="test", use_auth_token=True)
|
| 340 |
+
|
| 341 |
+
# PERE - REPLACE WITH THIS
|
| 342 |
+
# speech_data = make_dataset(training_args, data_args)
|
| 343 |
+
|
| 344 |
+
# Rename columns
|
| 345 |
+
if "audio" not in speech_data.column_names["train"]:
|
| 346 |
+
speech_data = speech_data.rename_column(source, "audio")
|
| 347 |
+
|
| 348 |
+
if "sentence" not in speech_data.column_names["train"]:
|
| 349 |
+
speech_data = speech_data.rename_column(target, "sentence")
|
| 350 |
+
|
| 351 |
+
# Remove not needed columns - Not really sure if this is necessary
|
| 352 |
+
remove_list = [i for i in speech_data.column_names["train"]
|
| 353 |
+
if i not in ["audio", "sentence"]]
|
| 354 |
+
|
| 355 |
+
speech_data = speech_data.remove_columns(remove_list)
|
| 356 |
+
|
| 357 |
+
# PERE - NEEDS TO BE PARAMETERIZED
|
| 358 |
+
# Initialise
|
| 359 |
+
feature_extractor = WhisperFeatureExtractor.from_pretrained(
|
| 360 |
+
"openai/whisper-small")
|
| 361 |
+
tokenizer = WhisperTokenizer.from_pretrained(
|
| 362 |
+
"openai/whisper-small", language="Norwegian", task="transcribe")
|
| 363 |
+
processor = WhisperProcessor.from_pretrained(
|
| 364 |
+
"openai/whisper-small", language="Norwegian", task="transcribe")
|
| 365 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)
|
| 366 |
+
|
| 367 |
+
# Prepare data
|
| 368 |
+
speech_data = speech_data.cast_column("audio", Audio(sampling_rate=16000))
|
| 369 |
+
speech_data = speech_data.map(
|
| 370 |
+
prepare_dataset, remove_columns=speech_data.column_names["train"], num_proc=1)
|
| 371 |
+
|
| 372 |
+
# Metrics
|
| 373 |
+
metric = evaluate.load("wer")
|
| 374 |
+
|
| 375 |
+
#Detecting last checkpoint.
|
| 376 |
+
last_checkpoint = None
|
| 377 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
| 378 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
| 379 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
| 380 |
+
raise ValueError(
|
| 381 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
| 382 |
+
"Use --overwrite_output_dir to overcome."
|
| 383 |
+
)
|
| 384 |
+
elif last_checkpoint is not None:
|
| 385 |
+
logger.info(
|
| 386 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
| 387 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
| 388 |
+
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
# Training
|
| 392 |
+
if training_args.do_train:
|
| 393 |
+
|
| 394 |
+
# use last checkpoint if exist
|
| 395 |
+
if last_checkpoint is not None:
|
| 396 |
+
checkpoint = last_checkpoint
|
| 397 |
+
elif os.path.isdir(model_args.model_name_or_path):
|
| 398 |
+
checkpoint = model_args.model_name_or_path
|
| 399 |
+
# Initialise a Pretrained model
|
| 400 |
+
# We need to set use_cache=False here if we want to use gradient accumulation
|
| 401 |
+
# PERE - For the test this is set static
|
| 402 |
+
|
| 403 |
+
model = WhisperForConditionalGeneration.from_pretrained(
|
| 404 |
+
"openai/whisper-small", use_cache=False)
|
| 405 |
+
|
| 406 |
+
else:
|
| 407 |
+
checkpoint = None
|
| 408 |
+
|
| 409 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
| 410 |
+
trainer.save_model()
|
| 411 |
+
|
| 412 |
+
metrics = train_result.metrics
|
| 413 |
+
max_train_samples = (
|
| 414 |
+
data_args.max_train_samples
|
| 415 |
+
if data_args.max_train_samples is not None
|
| 416 |
+
else len(vectorized_datasets["train"])
|
| 417 |
+
)
|
| 418 |
+
metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
|
| 419 |
+
|
| 420 |
+
trainer.log_metrics("train", metrics)
|
| 421 |
+
trainer.save_metrics("train", metrics)
|
| 422 |
+
trainer.save_state()
|
| 423 |
+
|
| 424 |
+
# Overriding generation arguments - no tokens are forced as decoder outputs (see [`forced_decoder_ids`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.forced_decoder_ids)), no tokens are suppressed during generation (see [`suppress_tokens`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.suppress_tokens)):
|
| 425 |
+
model.config.forced_decoder_ids = None
|
| 426 |
+
model.config.suppress_tokens = []
|
| 427 |
+
|
| 428 |
+
# Set seed before initializing model.
|
| 429 |
+
set_seed(training_args.seed)
|
| 430 |
+
|
| 431 |
+
# Training arguments
|
| 432 |
+
training_args = Seq2SeqTrainingArguments(
|
| 433 |
+
output_dir="../whisper-testrun1", # change to a repo name of your choice
|
| 434 |
+
per_device_train_batch_size=16,
|
| 435 |
+
gradient_accumulation_steps=1, # increase by 2x for every 2x decrease in batch size
|
| 436 |
+
learning_rate=2e-5,
|
| 437 |
+
warmup_steps=500,
|
| 438 |
+
max_steps=5000, # Changed from 4000
|
| 439 |
+
gradient_checkpointing=True,
|
| 440 |
+
group_by_length=True,
|
| 441 |
+
evaluation_strategy="steps",
|
| 442 |
+
per_device_eval_batch_size=8,
|
| 443 |
+
predict_with_generate=True,
|
| 444 |
+
generation_max_length=225,
|
| 445 |
+
save_steps=500,
|
| 446 |
+
eval_steps=500,
|
| 447 |
+
logging_steps=25,
|
| 448 |
+
report_to=["tensorboard"],
|
| 449 |
+
load_best_model_at_end=True,
|
| 450 |
+
metric_for_best_model="wer",
|
| 451 |
+
greater_is_better=False,
|
| 452 |
+
push_to_hub=True,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
trainer = Seq2SeqTrainer(
|
| 456 |
+
args=training_args,
|
| 457 |
+
model=model,
|
| 458 |
+
train_dataset=speech_data["train"],
|
| 459 |
+
eval_dataset=speech_data["test"],
|
| 460 |
+
data_collator=data_collator,
|
| 461 |
+
compute_metrics=compute_metrics,
|
| 462 |
+
tokenizer=processor.feature_extractor,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# Initialize Trainer
|
| 467 |
+
trainer = Seq2SeqTrainer(
|
| 468 |
+
model=model,
|
| 469 |
+
data_collator=data_collator,
|
| 470 |
+
args=training_args,
|
| 471 |
+
compute_metrics=compute_metrics,
|
| 472 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
| 473 |
+
eval_dataset=vectorized_datasets["validation"] if training_args.do_eval else None,
|
| 474 |
+
tokenizer=feature_extractor,
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
# 8. Finally, we can start training
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# Evaluation
|
| 481 |
+
results = {}
|
| 482 |
+
if training_args.do_eval:
|
| 483 |
+
logger.info("*** Evaluate ***")
|
| 484 |
+
metrics = trainer.evaluate()
|
| 485 |
+
max_eval_samples = (
|
| 486 |
+
data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
|
| 487 |
+
)
|
| 488 |
+
metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
|
| 489 |
+
|
| 490 |
+
trainer.log_metrics("eval", metrics)
|
| 491 |
+
trainer.save_metrics("eval", metrics)
|
| 492 |
+
|
| 493 |
+
# Write model card and (optionally) push to hub
|
| 494 |
+
config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
|
| 495 |
+
kwargs = {
|
| 496 |
+
"finetuned_from": model_args.model_name_or_path,
|
| 497 |
+
"tasks": "automatic-speech-recognition",
|
| 498 |
+
"tags": ["hf-asr-leaderboard", "automatic-speech-recognition", data_args.dataset_name],
|
| 499 |
+
"dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}",
|
| 500 |
+
"dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
|
| 501 |
+
"language": model_args.language,
|
| 502 |
+
}
|
| 503 |
+
if "common_voice" in data_args.dataset_name:
|
| 504 |
+
kwargs["language"] = config_name
|
| 505 |
+
|
| 506 |
+
if training_args.push_to_hub:
|
| 507 |
+
trainer.push_to_hub(**kwargs)
|
| 508 |
+
else:
|
| 509 |
+
trainer.create_model_card(**kwargs)
|
| 510 |
+
|
| 511 |
+
return results
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
#XLA hook
|
| 515 |
+
def _mp_fn(index):
|
| 516 |
+
# For xla_spawn (TPUs)
|
| 517 |
+
print("The XLA is initiated")
|
| 518 |
+
main()
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
if __name__ == "__main__":
|
| 523 |
+
main()
|