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