xezpeleta commited on
Commit
7f3ea39
·
verified ·
1 Parent(s): 6d14859

Training in progress, step 1000

Browse files
config.json CHANGED
@@ -31,7 +31,7 @@
31
  "mask_time_length": 10,
32
  "mask_time_min_masks": 2,
33
  "mask_time_prob": 0.05,
34
- "max_length": 448,
35
  "max_source_positions": 1500,
36
  "max_target_positions": 448,
37
  "median_filter_width": 7,
@@ -41,7 +41,7 @@
41
  "pad_token_id": 50256,
42
  "scale_embedding": false,
43
  "torch_dtype": "float32",
44
- "transformers_version": "4.46.0.dev0",
45
  "use_cache": false,
46
  "use_weighted_layer_sum": false,
47
  "vocab_size": 51866
 
31
  "mask_time_length": 10,
32
  "mask_time_min_masks": 2,
33
  "mask_time_prob": 0.05,
34
+ "max_length": null,
35
  "max_source_positions": 1500,
36
  "max_target_positions": 448,
37
  "median_filter_width": 7,
 
41
  "pad_token_id": 50256,
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": 51866
model-00001-of-00002.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:70e95881b347aab16bfadb8b06b24d389bceb51ce8b9894db264ed67fc19f29e
3
  size 4993448880
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f19f041acff32cec525af7f2685700fdfef887382388ed14ec888a4fbf1eafe
3
  size 4993448880
model-00002-of-00002.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:52bad486fd09fef8dae53b1e1e2b13ea27a7a645786a7a9920fe7344b96bf162
3
  size 1180663192
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e392c9b8208f172dbb0775e074de0beba10a38023b69cfe310e8637407f430c
3
  size 1180663192
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-large-v3" \
4
- --dataset_name="mozilla-foundation/common_voice_17_0" \
5
- --dataset_config_name="eu" \
6
  --language="basque" \
7
- --train_split_name="train+validation" \
8
- --eval_split_name="test" \
9
  --model_index_name="Whisper Large Basque" \
10
  --max_steps="10000" \
11
  --output_dir="./" \
@@ -14,7 +13,7 @@ WANDB_PROJECT=whisper-medium-eu \
14
  --gradient_accumulation_steps="1" \
15
  --logging_steps="25" \
16
  --learning_rate="4.375e-6" \
17
- --warmup_steps="500" \
18
  --evaluation_strategy="steps" \
19
  --eval_steps="500" \
20
  --save_strategy="steps" \
@@ -31,7 +30,6 @@ WANDB_PROJECT=whisper-medium-eu \
31
  --gradient_checkpointing \
32
  --fp16 \
33
  --overwrite_output_dir \
34
- --resume_from_checkpoint="checkpoint-9000" \
35
  --do_train \
36
  --do_eval \
37
  --predict_with_generate \
@@ -39,4 +37,4 @@ WANDB_PROJECT=whisper-medium-eu \
39
  --streaming \
40
  --push_to_hub \
41
  --report_to "wandb" \
42
- --run_name "whisper-large-eu"
 
1
  WANDB_PROJECT=whisper-medium-eu \
2
  python run_speech_recognition_seq2seq_streaming.py \
3
  --model_name_or_path="openai/whisper-large-v3" \
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 Large Basque" \
9
  --max_steps="10000" \
10
  --output_dir="./" \
 
13
  --gradient_accumulation_steps="1" \
14
  --logging_steps="25" \
15
  --learning_rate="4.375e-6" \
16
+ --warmup_steps="1000" \
17
  --evaluation_strategy="steps" \
18
  --eval_steps="500" \
19
  --save_strategy="steps" \
 
30
  --gradient_checkpointing \
31
  --fp16 \
32
  --overwrite_output_dir \
 
33
  --do_train \
34
  --do_eval \
35
  --predict_with_generate \
 
37
  --streaming \
38
  --push_to_hub \
39
  --report_to "wandb" \
40
+ --run_name "whisper-large-eu-v3"
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. 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():
@@ -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
- 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
@@ -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
- # 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(
@@ -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 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):
 
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):
run_speech_recognition_seq2seq_streaming_cv.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import numpy
29
+
30
+ import datasets
31
+ import torch
32
+ from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
33
+ from torch.utils.data import IterableDataset
34
+
35
+ import evaluate
36
+ import transformers
37
+ from transformers import (
38
+ AutoConfig,
39
+ AutoFeatureExtractor,
40
+ AutoModelForSpeechSeq2Seq,
41
+ AutoProcessor,
42
+ AutoTokenizer,
43
+ HfArgumentParser,
44
+ Seq2SeqTrainer,
45
+ Seq2SeqTrainingArguments,
46
+ TrainerCallback,
47
+ set_seed,
48
+ )
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, trust_remote_code=True, **kwargs)
279
+ for split_name in split.split("+")
280
+ ]
281
+ # interleave multiple splits to form one dataset
282
+ interleaved_dataset = interleave_datasets(dataset_splits)
283
+ return interleaved_dataset
284
+ else:
285
+ # load a single split *with* streaming mode
286
+ dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=streaming, trust_remote_code=True, **kwargs)
287
+ return dataset
288
+
289
+
290
+ def main():
291
+ # 1. Parse input arguments
292
+ # See all possible arguments in src/transformers/training_args.py
293
+ # or by passing the --help flag to this script.
294
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
295
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
296
+
297
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
298
+ # If we pass only one argument to the script and it's the path to a json file,
299
+ # let's parse it to get our arguments.
300
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
301
+ else:
302
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
303
+
304
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
305
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
306
+ send_example_telemetry("run_speech_recognition_seq2seq_streaming", model_args, data_args)
307
+
308
+ # 2. Setup logging
309
+ logging.basicConfig(
310
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
311
+ datefmt="%m/%d/%Y %H:%M:%S",
312
+ handlers=[logging.StreamHandler(sys.stdout)],
313
+ )
314
+ log_level = training_args.get_process_log_level()
315
+ logger.setLevel(log_level)
316
+ datasets.utils.logging.set_verbosity(log_level)
317
+ transformers.utils.logging.set_verbosity(log_level)
318
+ transformers.utils.logging.enable_default_handler()
319
+ transformers.utils.logging.enable_explicit_format()
320
+
321
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
322
+
323
+ # Log on each process the small summary:
324
+ logger.warning(
325
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
326
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
327
+ )
328
+ logger.info(f"Training/evaluation parameters {training_args}")
329
+
330
+ # Set the verbosity to info of the Transformers logger (on main process only):
331
+ if is_main_process(training_args.local_rank):
332
+ transformers.utils.logging.set_verbosity_info()
333
+ logger.info("Training/evaluation parameters %s", training_args)
334
+
335
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
336
+ last_checkpoint = None
337
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
338
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
339
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
340
+ raise ValueError(
341
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
342
+ "Use --overwrite_output_dir to overcome."
343
+ )
344
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
345
+ logger.info(
346
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
347
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
348
+ )
349
+
350
+ # Set seed before initializing model.
351
+ set_seed(training_args.seed)
352
+
353
+ # 4. Load dataset
354
+ raw_datasets = IterableDatasetDict() if data_args.streaming else DatasetDict()
355
+
356
+ if training_args.do_train:
357
+ raw_datasets["train"] = load_maybe_streaming_dataset(
358
+ data_args.dataset_name,
359
+ data_args.dataset_config_name,
360
+ split=data_args.train_split_name,
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
+
476
+ # Handle different audio formats - some datasets provide raw arrays, others provide paths
477
+ if isinstance(sample, dict):
478
+ if "array" in sample:
479
+ audio_array = sample["array"]
480
+ sampling_rate = sample["sampling_rate"]
481
+ elif "path" in sample:
482
+ # Load from path if array is not available
483
+ audio_array = sample["path"] # datasets will load the file for us
484
+ sampling_rate = sample.get("sampling_rate", feature_extractor.sampling_rate)
485
+ else:
486
+ raise ValueError(f"Unsupported audio format. Sample must contain either 'array' or 'path'. Got {sample.keys()}")
487
+ else:
488
+ # Assume it's a direct path or array
489
+ audio_array = sample
490
+ sampling_rate = feature_extractor.sampling_rate
491
+
492
+ inputs = feature_extractor(audio_array, sampling_rate=sampling_rate)
493
+
494
+ # process audio length
495
+ if isinstance(audio_array, numpy.ndarray):
496
+ batch["input_length"] = len(audio_array)
497
+ else:
498
+ # If we couldn't get the direct array length, estimate it from the processed features
499
+ batch["input_length"] = inputs.get(model_input_name)[0].shape[0] * feature_extractor.hop_length
500
+
501
+ # process targets
502
+ input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
503
+ if do_remove_punctuation:
504
+ input_str = normalizer(input_str).strip()
505
+ batch["labels"] = tokenizer(input_str).input_ids
506
+ return batch
507
+
508
+ with training_args.main_process_first(desc="dataset map pre-processing"):
509
+ vectorized_datasets = raw_datasets.map(
510
+ prepare_dataset,
511
+ remove_columns=raw_datasets_features,
512
+ ).with_format("torch")
513
+
514
+ if training_args.do_train and data_args.streaming:
515
+ # manually shuffle if streaming (done by the trainer for non-streaming)
516
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
517
+ buffer_size=data_args.shuffle_buffer_size,
518
+ seed=training_args.seed,
519
+ )
520
+
521
+ # filter training data that is shorter than min_input_length or longer than
522
+ # max_input_length
523
+ def is_audio_in_length_range(length):
524
+ return min_input_length < length < max_input_length
525
+
526
+ if training_args.do_train:
527
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
528
+ is_audio_in_length_range,
529
+ input_columns=["input_length"],
530
+ )
531
+
532
+ # 8. Load Metric
533
+ metric = evaluate.load("wer")
534
+ do_normalize_eval = data_args.do_normalize_eval
535
+
536
+ def compute_metrics(pred):
537
+ pred_ids = pred.predictions
538
+
539
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
540
+
541
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
542
+ # we do not want to group tokens when computing the metrics
543
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
544
+
545
+ if do_normalize_eval:
546
+ pred_str = [normalizer(pred) for pred in pred_str]
547
+ label_str = [normalizer(label) for label in label_str]
548
+ # filtering step to only evaluate the samples that correspond to non-zero references:
549
+ pred_str = [pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0]
550
+ label_str = [label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0]
551
+
552
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
553
+
554
+ return {"wer": wer}
555
+
556
+ # 9. Create a single speech processor
557
+ if is_main_process(training_args.local_rank):
558
+ # save feature extractor, tokenizer and config
559
+ feature_extractor.save_pretrained(training_args.output_dir)
560
+ tokenizer.save_pretrained(training_args.output_dir)
561
+ config.save_pretrained(training_args.output_dir)
562
+
563
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
564
+
565
+ # 10. Define data collator
566
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
567
+ processor=processor,
568
+ decoder_start_token_id=model.config.decoder_start_token_id,
569
+ )
570
+
571
+ # 11. Configure Trainer
572
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
573
+ # Only required for streaming: Trainer automatically shuffles non-streaming datasets
574
+ class ShuffleCallback(TrainerCallback):
575
+ def on_train_begin(self, args, state, control, **kwargs):
576
+ self.trainer = kwargs.get('trainer')
577
+
578
+ def on_epoch_begin(self, args, state, control, **kwargs):
579
+ if not hasattr(self, "trainer") or not hasattr(self.trainer, "train_dataloader") or self.trainer.train_dataloader is None:
580
+ return
581
+ train_dataloader = self.trainer.train_dataloader
582
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
583
+ pass # set_epoch() is handled by the Trainer
584
+ elif isinstance(train_dataloader.dataset, IterableDataset):
585
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
586
+
587
+ # Initialize Trainer
588
+ trainer = Seq2SeqTrainer(
589
+ model=model,
590
+ args=training_args,
591
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
592
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
593
+ processing_class=feature_extractor,
594
+ data_collator=data_collator,
595
+ compute_metrics=compute_metrics if training_args.predict_with_generate else None,
596
+ callbacks=[ShuffleCallback()] if data_args.streaming else None,
597
+ )
598
+
599
+ # 12. Training
600
+ if training_args.do_train:
601
+ checkpoint = None
602
+ if training_args.resume_from_checkpoint is not None:
603
+ checkpoint = training_args.resume_from_checkpoint
604
+ elif last_checkpoint is not None:
605
+ checkpoint = last_checkpoint
606
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
607
+ trainer.save_model() # Saves the feature extractor too for easy upload
608
+
609
+ metrics = train_result.metrics
610
+ if data_args.max_train_samples:
611
+ metrics["train_samples"] = data_args.max_train_samples
612
+ trainer.log_metrics("train", metrics)
613
+ trainer.save_metrics("train", metrics)
614
+ trainer.save_state()
615
+
616
+ # 13. Evaluation
617
+ results = {}
618
+ if training_args.do_eval:
619
+ logger.info("*** Evaluate ***")
620
+ metrics = trainer.evaluate(
621
+ metric_key_prefix="eval",
622
+ max_length=training_args.generation_max_length,
623
+ num_beams=training_args.generation_num_beams,
624
+ )
625
+ if data_args.max_eval_samples:
626
+ metrics["eval_samples"] = data_args.max_eval_samples
627
+
628
+ trainer.log_metrics("eval", metrics)
629
+ trainer.save_metrics("eval", metrics)
630
+
631
+ # 14. Write Training Stats
632
+ kwargs = {
633
+ "finetuned_from": model_args.model_name_or_path,
634
+ "tasks": "automatic-speech-recognition",
635
+ "tags": "whisper-event",
636
+ }
637
+ if data_args.dataset_name is not None:
638
+ kwargs["dataset_tags"] = data_args.dataset_name
639
+ if data_args.dataset_config_name is not None:
640
+ kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
641
+ else:
642
+ kwargs["dataset"] = data_args.dataset_name
643
+ if "common_voice" in data_args.dataset_name:
644
+ kwargs["language"] = data_args.dataset_config_name.split('-')[0]
645
+ if model_args.model_index_name is not None:
646
+ kwargs["model_name"] = model_args.model_index_name
647
+
648
+ if training_args.push_to_hub:
649
+ trainer.push_to_hub(**kwargs)
650
+ else:
651
+ trainer.create_model_card(**kwargs)
652
+
653
+ return results
654
+
655
+
656
+ if __name__ == "__main__":
657
+ main()
tokenizer_config.json CHANGED
@@ -12987,6 +12987,7 @@
12987
  "clean_up_tokenization_spaces": true,
12988
  "eos_token": "<|endoftext|>",
12989
  "errors": "replace",
 
12990
  "model_max_length": 1000000000000000019884624838656,
12991
  "pad_token": "<|endoftext|>",
12992
  "processor_class": "WhisperProcessor",
 
12987
  "clean_up_tokenization_spaces": true,
12988
  "eos_token": "<|endoftext|>",
12989
  "errors": "replace",
12990
+ "extra_special_tokens": {},
12991
  "model_max_length": 1000000000000000019884624838656,
12992
  "pad_token": "<|endoftext|>",
12993
  "processor_class": "WhisperProcessor",
training_args.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bf7a986abd3107068a3a0d5d4f994d9792d101aaf76cd5472057cde7be944e18
3
- size 5368
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1fbb1e83bfa724f802875b50dc42275d9c7a8a5ff867993f1edbeedd5b91d4e
3
+ size 5432