forked from huggingface/distil-whisper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_distillation_nodes.py
2144 lines (1887 loc) · 90.8 KB
/
run_distillation_nodes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding=utf-8
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Training the Whisper model for sequence to sequence speech recognition via teacher-student distillation.
"""
# You can also adapt this script for your own distillation tasks. Pointers for this are left as comments.
import logging
import os
import re
import shutil
import string
import sys
import time
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Union
import datasets
import evaluate
import flax
import jax
import jax.numpy as jnp
import numpy as np
import optax
import torch
import transformers
from datasets import (
DatasetDict,
IterableDataset,
IterableDatasetDict,
concatenate_datasets,
interleave_datasets,
load_dataset,
)
from datasets.distributed import split_dataset_by_node
from flax import jax_utils, traverse_util
from flax.jax_utils import pad_shard_unpad, unreplicate
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key
from huggingface_hub import Repository, create_repo
from jax.experimental.compilation_cache import compilation_cache as cc
from optax._src import linear_algebra
from torch.utils.data import DataLoader
from torchdata.datapipes.iter import IterableWrapper
from tqdm import tqdm
from transformers import (
AddedToken,
HfArgumentParser,
Seq2SeqTrainingArguments,
WhisperConfig,
WhisperFeatureExtractor,
WhisperProcessor,
WhisperTokenizerFast,
is_tensorboard_available,
is_wandb_available,
set_seed,
)
from transformers.file_utils import get_full_repo_name
from transformers.modeling_flax_outputs import FlaxBaseModelOutput
from transformers.models.whisper.english_normalizer import EnglishTextNormalizer
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
from distil_whisper import FlaxWhisperForConditionalGeneration
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.27.0.dev0")
require_version(
"datasets>=1.18.0",
"To fix: pip install -r examples/flax/speech-recogintion/requirements.txt",
)
logger = logging.getLogger(__name__)
@flax.struct.dataclass
class ModelArguments:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={"help": ("Path to pretrained student model or model identifier from huggingface.co/models")}
)
teacher_model_name_or_path: str = field(
metadata={"help": ("Path to pretrained teacher model or model identifier from huggingface.co/models")}
)
config_name: Optional[str] = field(
default=None,
metadata={"help": "Pretrained config name or path if not the same as model_name"},
)
tokenizer_name: Optional[str] = field(
default=None,
metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"},
)
feature_extractor_name: Optional[str] = field(
default=None,
metadata={"help": "feature extractor name or path if not the same as model_name"},
)
cache_dir: Optional[str] = field(
default=None,
metadata={"help": ("Where to store the pretrained models downloaded from huggingface.co")},
)
use_fast_tokenizer: bool = field(
default=True,
metadata={"help": ("Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.")},
)
model_revision: str = field(
default="main",
metadata={"help": ("The specific model version to use (can be a branch name, tag name or commit id).")},
)
subfolder: str = field(
default="",
metadata={
"help": "In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can"
"specify the folder name here."
},
)
use_auth_token: bool = field(
default=False,
metadata={
"help": (
"Will use the token generated when running `transformers-cli login`"
" (necessary to use this script with private models)."
)
},
)
dtype: Optional[str] = field(
default="float32",
metadata={
"help": (
"Floating-point format in which the model weights should be initialized"
" and trained. Choose one of `[float32, float16, bfloat16]`."
)
},
)
load_with_scan_weights: bool = field(
default=False,
metadata={
"help": "Whether the pre-trained checkpoint has its weights stored in scan format. Set to True for scanned "
"weights, defaults to False for non-scan (unrolled) weights."
},
)
activation_dropout: float = field(
default=0.0,
metadata={"help": "The dropout ratio for activations inside the fully connected layer."},
)
attention_dropout: float = field(
default=0.0,
metadata={"help": "The dropout ratio for the attention probabilities."},
)
dropout: float = field(
default=0.0,
metadata={
"help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
},
)
@flax.struct.dataclass
class DataTrainingArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
train_dataset_name: str = field(
default=None,
metadata={
"help": "The name of the training dataset to use (via the datasets library). Load and combine "
"multiple datasets by separating dataset ids by a '+' symbol. For example, to load and combine "
" librispeech and common voice, set `train_dataset_name='librispeech_asr+common_voice'`."
},
)
train_dataset_config_name: Optional[str] = field(
default=None,
metadata={
"help": "The configuration name of the training dataset to use (via the datasets library). Load and combine "
"multiple datasets by separating dataset configs by a '+' symbol."
},
)
train_dataset_samples: str = field(
default=None,
metadata={
"help": "Number of samples in the training data. Load and combine "
"multiple datasets by separating dataset samples by a '+' symbol."
},
)
eval_dataset_name: str = field(
default=None,
metadata={
"help": "The name of the evaluation dataset to use (via the datasets library). Defaults to the training dataset name if unspecified."
},
)
eval_dataset_config_name: Optional[str] = field(
default=None,
metadata={
"help": "The configuration name of the evaluation dataset to use (via the datasets library). Defaults to the training dataset config name if unspecified"
},
)
dataset_cache_dir: Optional[str] = field(
default=None,
metadata={"help": "Path to cache directory for saving and loading datasets"},
)
overwrite_cache: bool = field(
default=False,
metadata={"help": "Overwrite the cached training and evaluation sets"},
)
preprocessing_num_workers: Optional[int] = field(
default=None,
metadata={"help": "The number of processes to use for the preprocessing."},
)
max_train_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of"
" training examples to this value if set."
)
},
)
max_eval_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of"
" evaluation examples to this value if set."
)
},
)
audio_column_name: str = field(
default="audio",
metadata={"help": ("The name of the dataset column containing the audio data. Defaults to 'audio'")},
)
train_text_column_name: str = field(
default="whisper_transcript",
metadata={
"help": (
"The name of the dataset column containing the text data. Defaults to"
" 'whisper_transcript'which is the pseudo-labelled Whisper"
" transcription data."
)
},
)
eval_text_column_name: str = field(
default="text",
metadata={
"help": (
"The name of the dataset column containing the text data. Defaults to"
" 'text', which is the original text data"
)
},
)
max_duration_in_seconds: float = field(
default=30.0,
metadata={"help": ("Filter audio files that are longer than `max_duration_in_seconds` seconds")},
)
min_duration_in_seconds: float = field(
default=0.0,
metadata={"help": ("Filter audio files that are shorter than `min_duration_in_seconds` seconds")},
)
max_label_length: int = field(
default=128,
metadata={"help": "Truncate transcriptions that are longer `max_label_length` tokens."},
)
pad_target_to_multiple_of: Optional[int] = field(
default=None,
metadata={
"help": (
"If set will pad the target sequence to a multiple of the provided"
" value. This is important to avoid triggering recompilations on TPU."
" If unspecified, will default to padding the targets to max length."
)
},
)
preprocessing_only: bool = field(
default=False,
metadata={
"help": (
"Whether to only do data preprocessing and skip training. This is"
" especially useful when data preprocessing errors out in distributed"
" training due to timeout. In this case, one should run the"
" preprocessing in a non-distributed setup with"
" `preprocessing_only=True` so that the cached datasets can"
" consequently be loaded in distributed training"
)
},
)
train_split_name: str = field(
default="train",
metadata={
"help": ("The name of the training data set split to use (via the datasets library). Defaults to 'train'")
},
)
eval_split_name: str = field(
default="validation",
metadata={
"help": (
"The name of the evaluation data set split to use (via the datasets"
" library). Defaults to 'validation'"
)
},
)
wandb_project: str = field(
default="distil-whisper",
metadata={"help": "The name of the wandb project."},
)
wandb_name: str = field(
default=None,
metadata={"help": "The name of the wandb run."},
)
wandb_job_type: str = field(
default="distil-whisper",
metadata={"help": "The name of the wandb job type."},
)
wandb_dir: str = field(
default=None,
metadata={"help": "The absolute path to save the wandb logs."},
)
save_code_to_wandb: bool = field(
default=False,
metadata={
"help": (
"Whether to save main script to wandb. This is valuable for improving"
" experiment reproducibility and to diff code across experiments in"
" the UI."
)
},
)
streaming: bool = field(
default=True,
metadata={"help": "Whether to use Datasets' streaming mode to load and the data."},
)
wer_threshold: float = field(
default=None,
metadata={
"help": "Filter training data with Whisper transcriptions that have greater than `wer_threshold` "
"WER with the normalised transcriptions."
},
)
prefetch_size: int = field(
default=0,
metadata={"help": "Number of samples to pre-fetch if using an iterable dataset."},
)
timestamp_probability: float = field(
default=0.5, metadata={"help": "Probability for training on timestamped tokens if the data contains it."}
)
return_timestamps: bool = field(
default=False, metadata={"help": "Whether or not to predict timestamps in the generation step."}
)
round_timestamps: bool = field(
default=False,
metadata={
"help": "Whether or not to round the timestamp tokens to the nearest tenth of a second."
"By default, Whisper predicts timestamps to the nearest hundredth of a second."
"Reducing the timestamp precision to one tenth of a second simplifies the timestamp"
"prediction task, at the expense of timestamp granularity."
},
)
@dataclass
class FlaxSeq2SeqTrainingArguments(Seq2SeqTrainingArguments):
use_scan: Optional[bool] = field(
default=True,
metadata={
"help": (
"Whether or not to use `scan_with_axes` over the encoder and decoder blocks. Using scan results "
"in faster compile times and more efficient memory use during training, since all of the layers "
"in the encoder/decoder are stacked, and we perform a lax.scan over the stacked block to index "
"each layer. However, it results in slower inference time due to the overhead of stacking the "
"layers this way. Thus, we **always** default to disabling scan for the inference step."
)
},
)
freeze_encoder: Optional[bool] = field(
default=False,
metadata={
"help": (
"Whether to freeze the entire encoder model. Only recommended when the entire encoder has been "
"copied from the teacher model."
)
},
)
temperature: Optional[float] = field(
default=2.0, metadata={"help": "Temperature to anneal the logits when computing the softmax."}
)
kl_weight: Optional[float] = field(
default=1.0,
metadata={
"help": (
"Weighting assigned to the MSE loss in the KD formulation. MSE loss is "
"computed between the teacher-student hidden states and attentions."
)
},
)
mse_weight: Optional[float] = field(
default=0.0,
metadata={
"help": (
"Weighting assigned to the MSE loss in the KD formulation. MSE loss is "
"computed between the teacher-student hidden states and attentions."
)
},
)
precision: Optional[str] = field(
default="half_mixed",
metadata={
"help": (
"Precision with which run training, Can be one of `full`, `half_mixed` or `full_mixed`, the latter two"
"of which enable *mixed-precision* training. **Note that this only specifies the dtype of the computation "
"and optimizer state. It does not influence the dtype of model parameters.** An explanation of the three "
"settings is provided below:"
" 1. Full precision: forward pass, backward pass and optimiser states all in float32."
" 2. Half mixed precision: forward pass in bfloat16, backward pass and optimiser states in float32. This "
" corresponds to setting the dtype argument to bfloat16 when instantiating the model."
" 3. Full mixed precision: forward pass, backward pass and optimiser states all in bfloat16. The dtype "
" argument is set to bfloat16 for the forward pass, and the gradients computed with respect to the bfloat16 "
" parameters in the backward pass (giving bfloat16 gradients). The new optimiser states and parameter "
" updates are computed in float32 by upcasting the bfloat16 gradients and optimiser states to float32 "
" prior to the optimiser update step. The optimiser states are returned in float32 (but not saved to "
" memory) and then downcasted to bfloat16 (saved to memory) for the subsequent train step."
"For further details, refer to https://github.com/deepmind/optax/discussions/336"
)
},
)
compilation_cache: Optional[bool] = field(
default=False,
metadata={
"help": (
"Whether to enable the JAX (experimental) compilation cache. The compilation step is *cached* the "
"first time it is run. Successive compilation steps for the same function utilise the cache to reduce"
"the compilation time."
)
},
)
save_train_state: Optional[bool] = field(
default=False,
metadata={
"help": "Whether or not to save the Flax Train State on each `save_steps` steps. Required if you intend"
"to resume training from partial training runs. If False, only the model weights will be saved."
"If True, both the model weights and Flax Train state will be saved."
},
)
def shift_tokens_right(label_ids: np.array, decoder_start_token_id: int) -> np.ndarray:
"""
Shift label ids one token to the right.
"""
shifted_label_ids = np.zeros_like(label_ids)
shifted_label_ids[:, 1:] = label_ids[:, :-1]
shifted_label_ids[:, 0] = decoder_start_token_id
return shifted_label_ids
@flax.struct.dataclass
class FlaxDataCollatorSpeechSeq2SeqWithPadding:
"""
Data collator that will dynamically pad the inputs received.
Args:
processor ([`Wav2Vec2Processor`])
The processor used for proccessing the data.
decoder_start_token_id (:obj: `int`)
The start-of-sequence token id of the decoder.
decoder_prev_token_id (:obj: `int`)
The start-of-prompt token id of the decoder
input_padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
Select a strategy to pad the returned input sequences (according to the model's padding side and padding index)
among:
* :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
sequence if provided).
* :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
maximum acceptable input length for the model if that argument is not provided.
* :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
different lengths).
target_padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
Select a strategy to pad the returned target sequences (according to the model's padding side and padding index).
See above for details.
max_target_length (:obj:`int`, `optional`):
Maximum length of the ``labels`` of the returned list and optionally padding length (see above).
"""
processor: Any
decoder_start_token_id: int
decoder_prev_token_id: int
input_padding: Union[bool, str] = "max_length"
target_padding: Union[bool, str] = "max_length"
max_target_length: Optional[int] = None
def __call__(self, features: List[Dict[str, Union[List[int], np.ndarray]]]) -> Dict[str, np.ndarray]:
# split inputs and labels since they have to be of different lengths and need
# different padding methods
model_input_name = self.processor.model_input_names[0]
# dataloader returns a list of features which we convert to a dict
input_features = {model_input_name: [feature[model_input_name] for feature in features]}
label_features = {"input_ids": [feature["labels"] for feature in features]}
# reformat list to dict and set to pytorch format
batch = self.processor.feature_extractor.pad(
input_features,
padding=self.input_padding,
return_tensors="np",
)
labels_batch = self.processor.tokenizer.pad(
label_features,
max_length=self.max_target_length,
padding=self.target_padding,
return_tensors="np",
)
# if bos token is appended in previous tokenization step,
# cut bos token here as it's append later anyways
labels = labels_batch["input_ids"]
if set(np.unique(labels[:, 0])).issubset({self.decoder_start_token_id, self.decoder_prev_token_id}):
decoder_input_ids = labels[:, :-1]
labels = labels[:, 1:]
labels_batch.attention_mask = labels_batch.attention_mask[:, 1:]
else:
decoder_input_ids = shift_tokens_right(labels, self.decoder_start_token_id)
# replace padding with -100 to ignore correctly when computing the loss
labels = np.ma.array(labels, mask=np.not_equal(labels_batch.attention_mask, 1))
labels = labels.filled(fill_value=-100)
# replace initial prompt tokens with -100 to ignore correctly when computing the loss
bos_index = np.argmax(labels == self.decoder_start_token_id, axis=1)
prompt_mask = np.arange(labels.shape[1]) < bos_index[:, None]
labels = np.where(prompt_mask, -100, labels)
batch["labels"] = labels
batch["decoder_input_ids"] = decoder_input_ids
return batch
def get_data_loader(
seed: int,
dataset: IterableDataset,
batch_size: int,
data_collator: FlaxDataCollatorSpeechSeq2SeqWithPadding,
shuffle: bool = True,
drop_last: bool = True,
dataloader_num_workers: int = 0,
skip_batches: int = 0,
pin_memory: bool = True,
prefetch_size: int = 0,
) -> DataLoader:
"""
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final batch may be incomplete,
and range in size from 1 to `batch_size`. Shuffle batches if `shuffle` is `True`.
Args:
seed (int): Numpy seed for generating pseudo random numbers. Used if shuffling the dataset.
dataset (IterableDataset): streaming dataset from which to load the data.
batch_size (int): how many samples per batch to load.
data_collator (FlaxDataCollatorSpeechSeq2SeqWithPadding, optional): merges a list of samples to form a
mini-batch of Tensor(s). Used when using batched loading from a map-style dataset.
shuffle (bool, optional): set to `True` to have the batches reshuffled.
drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
if the dataset size is not divisible by the batch size. If ``False`` and
the size of dataset is not divisible by the batch size, then the last batch
will be smaller. (default: ``False``)
dataloader_num_workers (int, optional): how many subprocesses to use for data
loading. ``0`` means that the data will be loaded in the main process.
(default: ``0``)
skip_batches (int, optional): Efficiently skip the first `skip_batches`.
pin_memory (bool, optional): If ``True``, the data loader will copy Tensors
into device/CUDA pinned memory before returning them. If your data elements
are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type,
see the example below.
"""
if shuffle:
dataset = dataset.shuffle(seed)
if skip_batches > 0:
dataset = dataset.skip(skip_batches * batch_size)
if prefetch_size > 0:
dataset = IterableWrapper(dataset)
dataset = dataset.prefetch(prefetch_size)
num_of_hosts = jax.process_count()
dataset = split_dataset_by_node(dataset, rank=jax.process_index(), world_size=num_of_hosts)
assert batch_size % num_of_hosts == 0, "Batch size must be divisible by the number of hosts."
if dataset.n_shards < dataloader_num_workers:
dataloader_num_workers = dataset.n_shards
data_loader = DataLoader(
dataset,
batch_size=batch_size // num_of_hosts,
drop_last=drop_last,
pin_memory=pin_memory,
collate_fn=data_collator,
num_workers=dataloader_num_workers,
)
return data_loader
def sorted_checkpoints(output_dir=None, checkpoint_prefix="checkpoint", use_mtime=False) -> List[str]:
ordering_and_checkpoint_path = []
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*") if os.path.isdir(x)]
for path in glob_checkpoints:
if use_mtime:
ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
else:
regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path)
if regex_match is not None and regex_match.groups() is not None:
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
return checkpoints_sorted
def rotate_checkpoints(
save_total_limit=None, use_mtime=False, output_dir=None, checkpoint_prefix="checkpoint"
) -> None:
if save_total_limit is None or save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
checkpoints_sorted = sorted_checkpoints(
use_mtime=use_mtime, output_dir=output_dir, checkpoint_prefix=checkpoint_prefix
)
if len(checkpoints_sorted) <= save_total_limit:
return
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit)
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
for checkpoint in checkpoints_to_be_deleted:
logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit")
shutil.rmtree(checkpoint, ignore_errors=True)
def to_fp32(t):
return jax.tree_map(lambda x: x.astype(jnp.float32) if x.dtype == jnp.bfloat16 else x, t)
def to_bf16(t):
return jax.tree_map(lambda x: x.astype(jnp.bfloat16) if x.dtype == jnp.float32 else x, t)
class TrainState(train_state.TrainState):
dropout_rng: jnp.ndarray
max_grad_norm: float
def apply_gradients(self, *, grads, to_dtype: to_fp32, **kwargs):
"""Updates `step`, `params`, `opt_state` and `**kwargs` in return value, clipping the
gradients by the maximum grad norm.
Note that internally this function calls `.tx.update()` followed by a call
to `optax.apply_updates()` to update `params` and `opt_state`.
Args:
grads: Gradients that have the same pytree structure as `.params`.
**kwargs: Additional dataclass attributes that should be `.replace()`-ed.
Returns:
An updated instance of `self` with `step` incremented by one, `params`
and `opt_state` updated by applying `grads`, and additional attributes
replaced as specified by `kwargs`.
"""
# clip gradients by global l2 norm
casted_max_grad_norm = to_dtype(self.max_grad_norm)
g_norm = linear_algebra.global_norm(grads)
g_norm = jnp.maximum(casted_max_grad_norm, g_norm)
grads = jax.tree_map(lambda t: (t / g_norm) * casted_max_grad_norm, grads)
# perform update step in fp32 and subsequently downcast optimizer states if mixed precision training
# grads and opt_state in bf16 (need to upcast), params in fp32 (leave as is)
updates, new_opt_state = self.tx.update(to_fp32(grads), to_fp32(self.opt_state), self.params)
new_params = optax.apply_updates(self.params, updates)
return self.replace(
step=self.step + 1,
params=new_params,
opt_state=to_dtype(new_opt_state),
**kwargs,
)
@classmethod
def create(cls, *, apply_fn, params, tx, to_dtype: to_fp32, **kwargs):
"""Creates a new instance with `step=0` and initialized `opt_state`."""
# downcast optimizer state to bf16 if mixed-precision training
opt_state = tx.init(to_dtype(params))
return cls(
step=0,
apply_fn=apply_fn,
params=params,
tx=tx,
opt_state=opt_state,
**kwargs,
)
def replicate(self):
return jax_utils.replicate(self).replace(dropout_rng=shard_prng_key(self.dropout_rng))
def unreplicate(self):
return jax_utils.unreplicate(self)
def save_state(self, output_dir, save_total_limit=None, checkpoint_prefix="checkpoint"):
step = int(jax.device_get(unreplicate(self.step)))
serialized_state = to_bytes(self.unreplicate())
output_file = Path(os.path.join(output_dir, f"{checkpoint_prefix}-{step}", "train_state.msgpack"))
output_file.parent.mkdir(exist_ok=True, parents=True)
with output_file.open("wb") as f:
f.write(serialized_state)
logger.info(f"Flax train state saved in {output_file}")
rotate_checkpoints(
save_total_limit=save_total_limit, output_dir=output_dir, checkpoint_prefix=checkpoint_prefix
)
def save_hf_weights(
student_state: TrainState,
student_model: FlaxWhisperForConditionalGeneration,
processor: WhisperProcessor,
output_dir: str,
cur_step: int,
total_train_steps: int,
use_scan: bool = True,
checkpoint_prefix: str = "checkpoint",
) -> None:
# always disable scan in the params / model so that we can load from PyTorch directly - this is a no-op if we're not using scan for training
student_state_params = unreplicate(student_state.params)
student_state_params = student_model.convert_scan_to_unroll(student_state_params)
student_params = jax.device_get(student_state_params)
student_model.disable_scan()
if cur_step != total_train_steps:
output_dir = os.path.join(output_dir, f"{checkpoint_prefix}-{cur_step}")
os.makedirs(output_dir, exist_ok=True)
student_model.save_pretrained(output_dir, params=student_params)
processor.save_pretrained(output_dir)
# re-enable scan only if required for training
if use_scan:
student_model.enable_scan()
def write_train_metric(summary_writer, train_metrics, train_time, step, logging_steps):
summary_writer.scalar("train/time", train_time, step)
train_metrics = get_metrics(train_metrics)
for key, vals in train_metrics.items():
steps_arr = np.arange(0, step, logging_steps)[-len(vals):]
tag = f"train/{key}"
for i, val in enumerate(vals):
summary_writer.scalar(tag, val, steps_arr[i])
def write_eval_metric(summary_writer, eval_metrics, step, prefix="eval"):
for metric_name, value in eval_metrics.items():
summary_writer.scalar(f"{prefix}/{metric_name}", value, step)
def write_wandb_metric(wandb_logger, metrics, train_time, step, epoch, prefix="train"):
log_metrics = {}
for k, v in metrics.items():
log_metrics[f"{prefix}/{k}"] = v
log_metrics[f"{prefix}/time"] = train_time
log_metrics[f"{prefix}/epoch"] = epoch
wandb_logger.log(log_metrics, step)
def write_wandb_pred(
wandb_logger, pred_str, label_str, norm_pred_str, norm_label_str, cur_step, prefix="eval", num_lines=200000
):
# pretty name for current step: step 50000 -> step 50k
cur_step_pretty = f"{int(cur_step // 1000)}k" if cur_step > 1000 else cur_step
# convert str data to a wandb compatible format
str_data = [[label_str[i], pred_str[i], norm_label_str[i], norm_pred_str[i]] for i in range(len(pred_str))]
# log as a table with the appropriate headers
wandb_logger.log(
{
f"predictions/{prefix.replace('/', '-')}-step-{cur_step_pretty}": wandb_logger.Table(
columns=["Target", "Pred", "Norm Target", "Norm Pred"], data=str_data[:num_lines]
)
},
cur_step,
)
# log incorrect normalised predictions
str_data = np.asarray(str_data)
str_data_incorrect = str_data[str_data[:, -2] != str_data[:, -1]]
# log as a table with the appropriate headers
wandb_logger.log(
{
f"incorrect_predictions/{prefix.replace('/', '-')}-step-{cur_step_pretty}": wandb_logger.Table(
columns=["Target", "Pred", "Norm Target", "Norm Pred"], data=str_data_incorrect[:num_lines]
)
},
cur_step,
)
def create_learning_rate_fn(
num_train_steps: int, lr_scheduler_type: str, num_warmup_steps: int, learning_rate: float
) -> Callable[[int], jnp.array]:
"""Returns a linear warmup, linear_decay learning rate function."""
lr_scheduler_types = ("linear", "constant_with_warmup")
if lr_scheduler_type not in lr_scheduler_types:
raise ValueError(
f"lr_scheduler_type of type {lr_scheduler_type} not supported, choose from {lr_scheduler_types}."
)
warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps)
decay_fn = optax.linear_schedule(
init_value=learning_rate,
end_value=0 if lr_scheduler_type == "linear" else learning_rate,
transition_steps=num_train_steps - num_warmup_steps,
)
schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps])
return schedule_fn
def convert_dataset_str_to_list(
dataset_names,
dataset_config_names,
splits=None,
text_column_names=None,
dataset_samples=None,
default_split="train",
):
if isinstance(dataset_names, str):
dataset_names = dataset_names.split("+")
# we assume that all the datasets we're using derive from the distil-whisper org on the Hub - prepend the org name if necessary
for i in range(len(dataset_names)):
ds_name = dataset_names[i]
dataset_names[i] = f"distil-whisper/{ds_name}" if "/" not in ds_name else ds_name
dataset_config_names = dataset_config_names.split("+")
splits = splits.split("+") if splits is not None else None
text_column_names = text_column_names.split("+") if text_column_names is not None else None
dataset_samples = dataset_samples.split("+") if dataset_samples is not None else None
# basic checks to ensure we've got the right number of datasets/configs/splits/columns/probs
if len(dataset_names) != len(dataset_config_names):
raise ValueError(
f"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and"
f" {len(dataset_config_names)} configs."
)
if splits is not None and len(splits) != len(dataset_names):
raise ValueError(
f"Ensure one split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits."
)
if text_column_names is not None and len(text_column_names) != len(dataset_names):
raise ValueError(
f"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and"
f" {len(text_column_names)} text column names."
)
if dataset_samples is not None:
if len(dataset_samples) != len(dataset_names):
raise ValueError(
f"Ensure one sample is passed for each dataset, got {len(dataset_names)} datasets and "
f"{len(dataset_samples)} samples."
)
dataset_samples = [float(ds_sample) for ds_sample in dataset_samples]
else:
dataset_samples = [None] * len(dataset_names)
text_column_names = (
text_column_names if text_column_names is not None else ["text" for _ in range(len(dataset_names))]
)
splits = splits if splits is not None else [default_split for _ in range(len(dataset_names))]
dataset_names_dict = []
for i, ds_name in enumerate(dataset_names):
dataset_names_dict.append(
{
"name": ds_name,
"config": dataset_config_names[i],
"split": splits[i],
"text_column_name": text_column_names[i],
"samples": dataset_samples[i],
}
)
return dataset_names_dict
def load_multiple_datasets(
dataset_names: Union[List, str],
dataset_config_names: Union[List, str],
splits: Optional[Union[List, str]] = None,
text_column_names: Optional[List] = None,
sampling_rate: Optional[int] = 16000,
stopping_strategy: Optional[str] = "first_exhausted",
dataset_samples: Optional[Union[List, np.array]] = None,
streaming: bool = True,
seed: int = None,
**kwargs,
) -> IterableDataset:
dataset_names_dict = convert_dataset_str_to_list(
dataset_names, dataset_config_names, splits, text_column_names, dataset_samples
)
if dataset_samples is not None:
dataset_samples = [ds_dict["samples"] for ds_dict in dataset_names_dict]
probabilities = np.array(dataset_samples) / np.sum(dataset_samples)
else:
probabilities = None
if len(dataset_names_dict) == 1:
dataset_dict = dataset_names_dict[0]
# we have a single dataset so just return it as is
return load_dataset(
dataset_dict["name"],
dataset_dict["config"],
split=dataset_dict["split"],
streaming=streaming,
**kwargs,
)
all_datasets = []
# iterate over the datasets we want to interleave
for dataset_dict in tqdm(dataset_names_dict, desc="Combining datasets..."):
dataset = load_dataset(
dataset_dict["name"],
dataset_dict["config"],
split=dataset_dict["split"],
streaming=streaming,
**kwargs,
)
# resample to specified sampling rate
dataset = dataset.cast_column("audio", datasets.features.Audio(sampling_rate))
dataset = dataset.remove_columns(
set(dataset.features.keys()) - {"audio", dataset_dict["text_column_name"], "whisper_transcript"}
)
all_datasets.append(dataset)
if streaming:
interleaved_dataset = interleave_datasets(
all_datasets,
stopping_strategy=stopping_strategy,
probabilities=probabilities,
seed=seed,
)
else:
interleaved_dataset = concatenate_datasets(all_datasets)
return interleaved_dataset
def get_layers_to_supervise(student_layers: int, teacher_layers: int) -> dict:
"""Helper function to map the student layer i to the teacher layer j whose output we'd like them to emulate. Used
for MSE loss terms in distillation (hidden-states and activations). Student layers are paired with teacher layers
in equal increments, e.g. for a 12-layer model distilled to a 3-layer model, student layer 0 emulates teacher layer
3 (such that it behaves like the first 4 teacher layers), student layer 1 emulates teacher layer 7, and student layer
2 emulates teacher layer 11. This mapping is summarised by the dictionary: {0: 3, 1: 7, 2: 11}, which is precisely
the output of this function for the arguments (student_layers=3, teacher_layers=12)."""
layer_intervals = np.linspace(teacher_layers // student_layers - 1, teacher_layers - 1, student_layers, dtype=int)
layer_intervals[-1] = teacher_layers - 1
layer_map = {}
for student_layer, teacher_layer in enumerate(layer_intervals):
layer_map[student_layer] = teacher_layer
return layer_map
class FlaxWhisperFeatureExtractor(WhisperFeatureExtractor):
def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray:
"""
Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation
computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation
in transformers, and matches to within 1e-5 abs tolerance.