added src
Browse files- src/readme.md +129 -0
- src/requirements.txt +9 -0
- src/run.sh +43 -0
- src/run_debug.sh +44 -0
- src/run_speech_recognition_seq2seq_streaming.py +730 -0
- src/setup_env.sh +25 -0
src/readme.md
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Description
|
2 |
+
|
3 |
+
Fine-tuning [OpenAI Whisper](https://github.com/openai/whisper) model for Belarusian language during
|
4 |
+
[Whisper fine-tuning Event](https://github.com/huggingface/community-events/tree/main/whisper-fine-tuning-event)
|
5 |
+
hosted by HuggingFace x Lambda.
|
6 |
+
|
7 |
+
The code in this repository is a modified version of code from
|
8 |
+
[Whisper fine-tuning Event](https://github.com/huggingface/community-events/tree/main/whisper-fine-tuning-event) repo.
|
9 |
+
|
10 |
+
## Tips:
|
11 |
+
* start with a port worwarding to monitor Tensorboard logs on local computer:
|
12 |
+
```
|
13 |
+
ssh <remote-address> -L <local_port>:localhost:<remote_tensorboard_port>
|
14 |
+
```
|
15 |
+
* Train with redirecting output to a file using `tee`:
|
16 |
+
```
|
17 |
+
source src/run.sh 2>&1 | tee train_run_<run_number>.log
|
18 |
+
```
|
19 |
+
|
20 |
+
## Fine-tuning todos:
|
21 |
+
* perform evaluation of fine-tuned model on CommonVoice test set
|
22 |
+
* Learning rate:
|
23 |
+
* max learning rate is not the same as LR passed as a parameter to training script. it is actually lower.
|
24 |
+
* when resuming training, LR scheduling behaves incorrectly
|
25 |
+
* check exact sizes of train, eval, test sets of CommonVoice 11
|
26 |
+
|
27 |
+
## Resuming training from exising checkpoint
|
28 |
+
When resuming training from existing checkpoint:
|
29 |
+
* it's better to save all `checkpoint-\d+` dirs. better not to rely on data saved to `output_dir` because:
|
30 |
+
* not all data is saved to `output_dir`. e.g. following files are not saved to `output_dir`:
|
31 |
+
`optimizer.pt`, `rng_state.pth`, `scaler.pt`, `scheduler.pt`. so can't resume training in a correct way from
|
32 |
+
data saved to `output_dir`
|
33 |
+
* when resuming training from `output_dir` as a checkpoint dir, model saved to `output_dir` can be worse than
|
34 |
+
previously save (need to investifate further. but such happened already)
|
35 |
+
* learning rate gets reset if passing same parameter value to training script as in previour run.<br>
|
36 |
+
need to provide learning rate from the last step of previous run to continue
|
37 |
+
training in a correct way
|
38 |
+
* however even if passing learning rate from the last step, in the new run it has different value than expected
|
39 |
+
* probably because last checkpont was chosen incorrectly
|
40 |
+
* or learning rate is treated as a starting learning rate at step 0 and not on step X (where we resume).<br>
|
41 |
+
need to try to pass same LR that was passes as a starting LR to the very first run
|
42 |
+
* it's unclear whether decision on saving current model
|
43 |
+
is made by comparing current metrics with metrics of the best checkpoint. I guess model with worse performance
|
44 |
+
will not overwrite best model checkpoint already exising in the output dir, but need to double check.
|
45 |
+
* we can set `ignore_data_skip=True` Training argument not to
|
46 |
+
skip data items already passed to a model - that will save time on data loads.
|
47 |
+
* it's unclear whether order of input items in the train set (that is shuffled) will be the same
|
48 |
+
across multiple reruns - i.e. it's unclear whether sampling is the same across reruns.
|
49 |
+
* if the sampling is the same across reruns, `ignore_data_skip=True` will lead to same items been passed to a model
|
50 |
+
in current run. it's OK if previous run ended with large step value on the last epoch.
|
51 |
+
if not, the same elements from the same epoch will be passed to a model again.
|
52 |
+
|
53 |
+
## Questions:
|
54 |
+
* What checkpoint (best, I guess) is saved in the `output_dir`?
|
55 |
+
How is it overwritten when resuming training from existing checkpoint?
|
56 |
+
* does `ShuffleCallback` work with StreamingDataset? it reshuffles data `on_epoch_begin()`,
|
57 |
+
but does StreamingDataset have any epochs?
|
58 |
+
|
59 |
+
### Prepended tokens
|
60 |
+
* Why are there following lines in Data Collator?
|
61 |
+
```python
|
62 |
+
# if bos token is appended in previous tokenization step,
|
63 |
+
# cut bos token here as it's append later anyways
|
64 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
65 |
+
labels = labels[:, 1:]
|
66 |
+
```
|
67 |
+
* `tokenizer.bos_token_id` vs `model.config.decoder_start_token_id`.<br>
|
68 |
+
which one to pass to Data Collator as `decoder_start_token_id` parameter?
|
69 |
+
* Answer:
|
70 |
+
* In this case, the two are equivalent. You can verify this:
|
71 |
+
```python
|
72 |
+
print(tokenizer.bos_token_id)
|
73 |
+
print(model.config.decoder_start_token_id)
|
74 |
+
```
|
75 |
+
|
76 |
+
* Print Output:
|
77 |
+
```
|
78 |
+
<|startoftranscript|>
|
79 |
+
<|startoftranscript|>
|
80 |
+
```
|
81 |
+
|
82 |
+
* Technically speaking, the decoder_start_token_id is the correct convention here. Before starting generating any tokens, we initialise the generate method with a starting token, which is the decoder_start_token_id.
|
83 |
+
See: https://huggingface.co/blog/how-to-generate. The decoder_start_token_id corresponds to the initial context word sequence, and is the zero'th token generated.
|
84 |
+
|
85 |
+
* We remove this token from the encoded labels in the data collator because we always set the zero'th generated token to the decoder_start_token_id. If we leave the decoder_start_token_id as part of the label sequence, then we'll predict the decoder_start_token_id as the zero'th token, and again as the first token! Because we're always forcing it as the zero'th token, we don't need to predict it as the first token, and so we remove it from the target lables
|
86 |
+
|
87 |
+
* These tokens are not forced in the generation process, and so we don't cut them in the data collator. We need to provide them to the model as target labels so that the model can learn the correct tasks from our data
|
88 |
+
|
89 |
+
* The tokens correspond to the audio language, task (translate or transcribe) and whether to predict timestamps
|
90 |
+
|
91 |
+
* We need to tell the model what language the audio corresponds to and what task it's performing during fine-tuning. This way, it learns what audio corresponds to what language, and the difference between transcribing audio vs translating it
|
92 |
+
|
93 |
+
## Notes:
|
94 |
+
* using CommonVoice 11 dataset in a streaming way.<br>
|
95 |
+
use `streaming=True` for train & validation & test.<br>
|
96 |
+
as an alternative, we can use `streaming=False` for validation & test sets to save time on data processing.
|
97 |
+
but the size of validation and test sets are unknown (need to check).
|
98 |
+
it's likely they are going to be large - thus pre-download of these sets might not reduce
|
99 |
+
overall fine-tuning time compared to streaming mode.
|
100 |
+
* size of train set is ~370'000 audiofiles. if using `batch_size=64`, then
|
101 |
+
1 epoch will have ~5782 steps. <br>
|
102 |
+
Because of `--eval_steps="1000"` will use `--max_steps="6000"` instead of `--max_steps="5800"`
|
103 |
+
to have evaluation metrics computed in the end of training.
|
104 |
+
* if using Google Colab, need to execute `sudo chmod -R 777 .git` inside hf repo to
|
105 |
+
to set right permissions to be able to push trained models to HuggingFace Hub
|
106 |
+
* Whispers BasicTextNormalizer splits words containing apostrophe:
|
107 |
+
```python
|
108 |
+
> from transformers.models.whisper.english_normalizer import BasicTextNormalizer
|
109 |
+
> normalizer = BasicTextNormalizer()
|
110 |
+
> normalizer("раз'яднаць")
|
111 |
+
'раз яднаць'
|
112 |
+
```
|
113 |
+
* That's why `BelarusianTextNormalizer` (edited version of `BasicTextNormalizer`) was added to training script:
|
114 |
+
```python
|
115 |
+
> from run_speech_recognition_seq2seq_streaming import BelarusianTextNormalizer
|
116 |
+
> normalizer_be = BelarusianTextNormalizer()
|
117 |
+
> normalizer_be("раз'яднаць")
|
118 |
+
"раз'яднаць"
|
119 |
+
```
|
120 |
+
* Need to set `use_cache` to False since we're using gradient checkpointing, and the two are incompatible
|
121 |
+
* Default Linear scheduler is used
|
122 |
+
* Default Adam optimizer is used
|
123 |
+
* To save memory (and increase either model or batch_size) can experiment with:
|
124 |
+
* using Adafactor instead of Adam.
|
125 |
+
Adam requires two optimiser params per one model param, but Adafactor uses only one.
|
126 |
+
> A word of caution: Adafactor is untested for fine-tuning Whisper,
|
127 |
+
so we are unsure sure how Adafactor performance compares to Adam!
|
128 |
+
* using Adam 8bit from `bitsandbytes` module.
|
129 |
+
need to provide `optim="adamw_bnb_8bit"` param to `Seq2SeqTrainingArguments`
|
src/requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch>=1.7
|
2 |
+
torchaudio
|
3 |
+
git+https://github.com/huggingface/transformers
|
4 |
+
git+https://github.com/huggingface/datasets
|
5 |
+
librosa
|
6 |
+
jiwer
|
7 |
+
evaluate>=0.3.0
|
8 |
+
more-itertools
|
9 |
+
tensorboard
|
src/run.sh
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python src/run_speech_recognition_seq2seq_streaming.py \
|
2 |
+
--model_name_or_path="openai/whisper-small" \
|
3 |
+
--dataset_name="mozilla-foundation/common_voice_11_0" \
|
4 |
+
--dataset_config_name="be" \
|
5 |
+
--language="be" \
|
6 |
+
--train_split_name="train" \
|
7 |
+
--eval_split_name="validation" \
|
8 |
+
--model_index_name="Whisper Small Belarusian" \
|
9 |
+
\
|
10 |
+
--max_steps="12000" \
|
11 |
+
--output_dir="./" \
|
12 |
+
--per_device_train_batch_size="64" \
|
13 |
+
--per_device_eval_batch_size="64" \
|
14 |
+
--logging_steps="50" \
|
15 |
+
--logging_first_step \
|
16 |
+
--learning_rate="1e-4" \
|
17 |
+
--warmup_steps="500" \
|
18 |
+
--evaluation_strategy="steps" \
|
19 |
+
--eval_steps="1000" \
|
20 |
+
--save_strategy="steps" \
|
21 |
+
--save_steps="1000" \
|
22 |
+
--gradient_checkpointing \
|
23 |
+
--fp16 \
|
24 |
+
\
|
25 |
+
--shuffle_buffer_size="500" \
|
26 |
+
--generation_max_length="225" \
|
27 |
+
--max_duration_in_seconds="30" \
|
28 |
+
--text_column_name="sentence" \
|
29 |
+
--freeze_feature_encoder="False" \
|
30 |
+
--report_to="tensorboard" \
|
31 |
+
--metric_for_best_model="wer" \
|
32 |
+
--greater_is_better="False" \
|
33 |
+
--load_best_model_at_end \
|
34 |
+
\
|
35 |
+
--do_train \
|
36 |
+
--do_eval \
|
37 |
+
--ignore_data_skip \
|
38 |
+
--predict_with_generate \
|
39 |
+
--do_normalize_eval \
|
40 |
+
--streaming \
|
41 |
+
--use_auth_token \
|
42 |
+
--push_to_hub \
|
43 |
+
--hub_model_id="ales/whisper-small-belarusian"
|
src/run_debug.sh
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python src/run_speech_recognition_seq2seq_streaming.py \
|
2 |
+
--model_name_or_path="openai/whisper-tiny" \
|
3 |
+
--dataset_name="mozilla-foundation/common_voice_11_0" \
|
4 |
+
--dataset_config_name="be" \
|
5 |
+
--language="be" \
|
6 |
+
--train_split_name="train" \
|
7 |
+
--eval_split_name="validation" \
|
8 |
+
--model_index_name="Whisper Tiny Belarusian" \
|
9 |
+
\
|
10 |
+
--max_steps="500" \
|
11 |
+
--max_eval_samples="64" \
|
12 |
+
--output_dir="./" \
|
13 |
+
--per_device_train_batch_size="32" \
|
14 |
+
--per_device_eval_batch_size="32" \
|
15 |
+
--logging_steps="10" \
|
16 |
+
--logging_first_step \
|
17 |
+
--learning_rate="1e-4" \
|
18 |
+
--warmup_steps="10" \
|
19 |
+
--evaluation_strategy="steps" \
|
20 |
+
--eval_steps="10" \
|
21 |
+
--save_strategy="steps" \
|
22 |
+
--save_steps="10" \
|
23 |
+
--gradient_checkpointing \
|
24 |
+
--fp16 \
|
25 |
+
\
|
26 |
+
--shuffle_buffer_size="20" \
|
27 |
+
--generation_max_length="225" \
|
28 |
+
--max_duration_in_seconds="30" \
|
29 |
+
--text_column_name="sentence" \
|
30 |
+
--freeze_feature_encoder="False" \
|
31 |
+
--report_to="tensorboard" \
|
32 |
+
--metric_for_best_model="wer" \
|
33 |
+
--greater_is_better="False" \
|
34 |
+
--load_best_model_at_end \
|
35 |
+
\
|
36 |
+
--do_train \
|
37 |
+
--do_eval \
|
38 |
+
--ignore_data_skip \
|
39 |
+
--predict_with_generate \
|
40 |
+
--do_normalize_eval \
|
41 |
+
--streaming \
|
42 |
+
--use_auth_token \
|
43 |
+
--push_to_hub \
|
44 |
+
--hub_model_id="ales/whisper-tiny-be-test"
|
src/run_speech_recognition_seq2seq_streaming.py
ADDED
@@ -0,0 +1,730 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import datetime
|
27 |
+
import re
|
28 |
+
import regex
|
29 |
+
import unicodedata
|
30 |
+
from dataclasses import dataclass, field
|
31 |
+
from typing import Any, Dict, List, Optional, Union, Iterable
|
32 |
+
|
33 |
+
import datasets
|
34 |
+
import torch
|
35 |
+
from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
|
36 |
+
from torch.utils.data import IterableDataset
|
37 |
+
|
38 |
+
import evaluate
|
39 |
+
import transformers
|
40 |
+
from transformers import (
|
41 |
+
AutoConfig,
|
42 |
+
AutoFeatureExtractor,
|
43 |
+
AutoModelForSpeechSeq2Seq,
|
44 |
+
AutoProcessor,
|
45 |
+
AutoTokenizer,
|
46 |
+
HfArgumentParser,
|
47 |
+
Seq2SeqTrainer,
|
48 |
+
Seq2SeqTrainingArguments,
|
49 |
+
TrainerCallback,
|
50 |
+
set_seed,
|
51 |
+
)
|
52 |
+
from transformers.trainer_pt_utils import IterableDatasetShard
|
53 |
+
from transformers.trainer_utils import get_last_checkpoint, is_main_process
|
54 |
+
from transformers.utils import check_min_version, send_example_telemetry
|
55 |
+
from transformers.utils.versions import require_version
|
56 |
+
|
57 |
+
|
58 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
59 |
+
check_min_version("4.25.0.dev0")
|
60 |
+
|
61 |
+
require_version("datasets>=1.18.2", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
|
62 |
+
|
63 |
+
logger = logging.getLogger(__name__)
|
64 |
+
|
65 |
+
|
66 |
+
@dataclass
|
67 |
+
class ModelArguments:
|
68 |
+
"""
|
69 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
70 |
+
"""
|
71 |
+
|
72 |
+
model_name_or_path: str = field(
|
73 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
74 |
+
)
|
75 |
+
config_name: Optional[str] = field(
|
76 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
77 |
+
)
|
78 |
+
tokenizer_name: Optional[str] = field(
|
79 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
80 |
+
)
|
81 |
+
feature_extractor_name: Optional[str] = field(
|
82 |
+
default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
|
83 |
+
)
|
84 |
+
cache_dir: Optional[str] = field(
|
85 |
+
default=None,
|
86 |
+
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
|
87 |
+
)
|
88 |
+
use_fast_tokenizer: bool = field(
|
89 |
+
default=True,
|
90 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
91 |
+
)
|
92 |
+
model_revision: str = field(
|
93 |
+
default="main",
|
94 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
95 |
+
)
|
96 |
+
use_auth_token: bool = field(
|
97 |
+
default=False,
|
98 |
+
metadata={
|
99 |
+
"help": (
|
100 |
+
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
|
101 |
+
"with private models)."
|
102 |
+
)
|
103 |
+
},
|
104 |
+
)
|
105 |
+
freeze_feature_encoder: bool = field(
|
106 |
+
default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
|
107 |
+
)
|
108 |
+
freeze_encoder: bool = field(
|
109 |
+
default=False, metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."}
|
110 |
+
)
|
111 |
+
forced_decoder_ids: List[List[int]] = field(
|
112 |
+
default=None,
|
113 |
+
metadata={
|
114 |
+
"help": (
|
115 |
+
"A list of pairs of integers which indicates a mapping from generation indices to token indices "
|
116 |
+
"that will be forced before sampling. For example, [[0, 123]] means the first generated token "
|
117 |
+
"will always be a token of index 123."
|
118 |
+
)
|
119 |
+
},
|
120 |
+
)
|
121 |
+
suppress_tokens: List[int] = field(
|
122 |
+
default=None, metadata={"help": "A list of tokens that will be suppressed at generation."}
|
123 |
+
)
|
124 |
+
model_index_name: str = field(default=None, metadata={"help": "Pretty name for the model card."})
|
125 |
+
|
126 |
+
|
127 |
+
@dataclass
|
128 |
+
class DataTrainingArguments:
|
129 |
+
"""
|
130 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
131 |
+
"""
|
132 |
+
|
133 |
+
dataset_name: str = field(
|
134 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
135 |
+
)
|
136 |
+
dataset_config_name: Optional[str] = field(
|
137 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
138 |
+
)
|
139 |
+
max_train_samples: Optional[int] = field(
|
140 |
+
default=None,
|
141 |
+
metadata={
|
142 |
+
"help": (
|
143 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
144 |
+
"value if set."
|
145 |
+
)
|
146 |
+
},
|
147 |
+
)
|
148 |
+
max_eval_samples: Optional[int] = field(
|
149 |
+
default=None,
|
150 |
+
metadata={
|
151 |
+
"help": (
|
152 |
+
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
153 |
+
"value if set."
|
154 |
+
)
|
155 |
+
},
|
156 |
+
)
|
157 |
+
audio_column_name: str = field(
|
158 |
+
default="audio",
|
159 |
+
metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
|
160 |
+
)
|
161 |
+
text_column_name: str = field(
|
162 |
+
default="text",
|
163 |
+
metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
|
164 |
+
)
|
165 |
+
max_duration_in_seconds: float = field(
|
166 |
+
default=20.0,
|
167 |
+
metadata={
|
168 |
+
"help": (
|
169 |
+
"Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
|
170 |
+
" 'max_duration_in_seconds`"
|
171 |
+
)
|
172 |
+
},
|
173 |
+
)
|
174 |
+
min_duration_in_seconds: float = field(
|
175 |
+
default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
|
176 |
+
)
|
177 |
+
train_split_name: str = field(
|
178 |
+
default="train",
|
179 |
+
metadata={
|
180 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
181 |
+
},
|
182 |
+
)
|
183 |
+
eval_split_name: str = field(
|
184 |
+
default="test",
|
185 |
+
metadata={
|
186 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
187 |
+
},
|
188 |
+
)
|
189 |
+
do_lower_case: bool = field(
|
190 |
+
default=False,
|
191 |
+
metadata={"help": "Whether the target text should be lower cased."},
|
192 |
+
)
|
193 |
+
do_remove_punctuation: bool = field(
|
194 |
+
default=False,
|
195 |
+
metadata={"help": "Whether the target text should be striped of punctuation."},
|
196 |
+
)
|
197 |
+
do_normalize_eval: bool = field(
|
198 |
+
default=True,
|
199 |
+
metadata={"help": "Whether to normalise the references and predictions in the eval WER calculation."},
|
200 |
+
)
|
201 |
+
language: str = field(
|
202 |
+
default=None,
|
203 |
+
metadata={
|
204 |
+
"help": (
|
205 |
+
"Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
|
206 |
+
"only. For English speech recognition, it should be set to `None`."
|
207 |
+
)
|
208 |
+
},
|
209 |
+
)
|
210 |
+
task: str = field(
|
211 |
+
default="transcribe",
|
212 |
+
metadata={"help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."},
|
213 |
+
)
|
214 |
+
shuffle_buffer_size: Optional[int] = field(
|
215 |
+
default=500,
|
216 |
+
metadata={
|
217 |
+
"help": (
|
218 |
+
"The number of streamed examples to download before shuffling them. The large the buffer, "
|
219 |
+
"the closer it is to real offline shuffling."
|
220 |
+
)
|
221 |
+
},
|
222 |
+
)
|
223 |
+
streaming: bool = field(
|
224 |
+
default=True,
|
225 |
+
metadata={"help": "Whether to use streaming mode to load and pre-process the data."},
|
226 |
+
)
|
227 |
+
|
228 |
+
|
229 |
+
class BelarusianTextNormalizer:
|
230 |
+
"""
|
231 |
+
Based on transformers.models.whisper.english_normalizer.BasicTextNormalizer
|
232 |
+
but with support not to remove certain characters.
|
233 |
+
e.g. apostrophe (') - a symbol from Belarusian alphabet - was removed using BasicTextNormalizer.
|
234 |
+
"""
|
235 |
+
|
236 |
+
def __init__(self, split_letters: bool = False):
|
237 |
+
self.split_letters = split_letters
|
238 |
+
self.allowed_symbols = ("'",)
|
239 |
+
|
240 |
+
@staticmethod
|
241 |
+
def clean(s: str, allowed_symbols: Iterable[str] = None):
|
242 |
+
"""
|
243 |
+
Replace any other markers, symbols, punctuations with a space, keeping diacritics
|
244 |
+
"""
|
245 |
+
if allowed_symbols is None:
|
246 |
+
allowed_symbols = []
|
247 |
+
res = "".join(" " if unicodedata.category(c)[0] in "MSP" and c not in allowed_symbols else c
|
248 |
+
for c in unicodedata.normalize("NFKC", s))
|
249 |
+
return res
|
250 |
+
|
251 |
+
def __call__(self, s: str):
|
252 |
+
s = s.lower()
|
253 |
+
s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets
|
254 |
+
s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis
|
255 |
+
s = self.clean(s, allowed_symbols=self.allowed_symbols).lower()
|
256 |
+
|
257 |
+
if self.split_letters:
|
258 |
+
s = " ".join(regex.findall(r"\X", s, regex.U))
|
259 |
+
|
260 |
+
s = re.sub(r"\s+", " ", s) # replace any successive whitespace characters with a space
|
261 |
+
|
262 |
+
return s
|
263 |
+
|
264 |
+
|
265 |
+
@dataclass
|
266 |
+
class DataCollatorSpeechSeq2SeqWithPadding:
|
267 |
+
"""
|
268 |
+
Data collator that will dynamically pad the inputs received.
|
269 |
+
Args:
|
270 |
+
processor ([`WhisperProcessor`])
|
271 |
+
The processor used for processing the data.
|
272 |
+
decoder_start_token_id (`int`)
|
273 |
+
The begin-of-sentence of the decoder.
|
274 |
+
"""
|
275 |
+
|
276 |
+
processor: Any
|
277 |
+
decoder_start_token_id: int
|
278 |
+
|
279 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
280 |
+
# split inputs and labels since they have to be of different lengths and need
|
281 |
+
# different padding methods
|
282 |
+
model_input_name = self.processor.model_input_names[0]
|
283 |
+
input_features = [{model_input_name: feature[model_input_name]} for feature in features]
|
284 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
285 |
+
|
286 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
287 |
+
|
288 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
289 |
+
|
290 |
+
# replace padding with -100 to ignore loss correctly
|
291 |
+
labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
292 |
+
|
293 |
+
# if bos token is appended in previous tokenization step,
|
294 |
+
# cut bos token here as it's append later anyways
|
295 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
296 |
+
labels = labels[:, 1:]
|
297 |
+
|
298 |
+
batch["labels"] = labels
|
299 |
+
|
300 |
+
return batch
|
301 |
+
|
302 |
+
|
303 |
+
def load_maybe_streaming_dataset(dataset_name, dataset_config_name, split="train", streaming=True, **kwargs):
|
304 |
+
"""
|
305 |
+
Utility function to load a dataset in streaming mode. For datasets with multiple splits,
|
306 |
+
each split is loaded individually and then splits combined by taking alternating examples from
|
307 |
+
each (interleaving).
|
308 |
+
"""
|
309 |
+
if "+" in split:
|
310 |
+
# load multiple splits separated by the `+` symbol with streaming mode
|
311 |
+
dataset_splits = [
|
312 |
+
load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=streaming, **kwargs)
|
313 |
+
for split_name in split.split("+")
|
314 |
+
]
|
315 |
+
# interleave multiple splits to form one dataset
|
316 |
+
interleaved_dataset = interleave_datasets(dataset_splits)
|
317 |
+
return interleaved_dataset
|
318 |
+
else:
|
319 |
+
# load a single split *with* streaming mode
|
320 |
+
dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=streaming, **kwargs)
|
321 |
+
return dataset
|
322 |
+
|
323 |
+
|
324 |
+
def main():
|
325 |
+
# 1. Parse input arguments
|
326 |
+
# See all possible arguments in src/transformers/training_args.py
|
327 |
+
# or by passing the --help flag to this script.
|
328 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
329 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
330 |
+
|
331 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
332 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
333 |
+
# let's parse it to get our arguments.
|
334 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
335 |
+
else:
|
336 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
337 |
+
|
338 |
+
|
339 |
+
# 2. Setup logging
|
340 |
+
now_str = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
|
341 |
+
logging.basicConfig(
|
342 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
343 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
344 |
+
handlers=[
|
345 |
+
logging.StreamHandler(sys.stdout),
|
346 |
+
logging.FileHandler(filename=f'train_{now_str}.log', mode='w')
|
347 |
+
],
|
348 |
+
)
|
349 |
+
log_level = training_args.get_process_log_level()
|
350 |
+
logger.setLevel(log_level)
|
351 |
+
datasets.utils.logging.set_verbosity(log_level)
|
352 |
+
transformers.utils.logging.set_verbosity(log_level)
|
353 |
+
transformers.utils.logging.enable_default_handler()
|
354 |
+
transformers.utils.logging.enable_explicit_format()
|
355 |
+
|
356 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
357 |
+
|
358 |
+
# Log on each process the small summary:
|
359 |
+
logger.warning(
|
360 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
361 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
362 |
+
)
|
363 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
364 |
+
|
365 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
366 |
+
if is_main_process(training_args.local_rank):
|
367 |
+
transformers.utils.logging.set_verbosity_info()
|
368 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
369 |
+
|
370 |
+
# 3. Detecting last checkpoint and eventually continue from last checkpoint
|
371 |
+
last_checkpoint = None
|
372 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
373 |
+
logger.info(f'output_dir already exists. will try to load last checkpoint.')
|
374 |
+
|
375 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
376 |
+
if last_checkpoint is not None:
|
377 |
+
if training_args.resume_from_checkpoint is None:
|
378 |
+
logger.info(
|
379 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
380 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
381 |
+
)
|
382 |
+
else:
|
383 |
+
logger.info(f'Last checkpoint found at: {last_checkpoint}. Will ignore it and resume training '
|
384 |
+
f'from passed resume_from_checkpoint param: {training_args.resume_from_checkpoint}')
|
385 |
+
assert os.path.isdir(training_args.resume_from_checkpoint)
|
386 |
+
else:
|
387 |
+
logger.info('last_checkpoint is None. will try to read from training_args.resume_from_checkpoint')
|
388 |
+
|
389 |
+
if training_args.resume_from_checkpoint is not None and os.path.isdir(training_args.resume_from_checkpoint):
|
390 |
+
logger.info(f'Will resume training from passed resume_from_checkpoint param: '
|
391 |
+
f'{training_args.resume_from_checkpoint}')
|
392 |
+
else:
|
393 |
+
logger.info('last_checkpoint is None. resume_from_checkpoint is either None or not existing dir. '
|
394 |
+
'will try to read from the model saved in the root of output_dir.')
|
395 |
+
|
396 |
+
dir_content = os.listdir(training_args.output_dir)
|
397 |
+
if len(dir_content) == 0:
|
398 |
+
logger.info('output_dir is empty. will start training from scratch.')
|
399 |
+
else:
|
400 |
+
model_fn = 'pytorch_model.bin'
|
401 |
+
if model_fn in dir_content:
|
402 |
+
logger.info(f'found {model_fn} inside output_dir. '
|
403 |
+
f'will continue training treating output_dir as a last checkpoint.')
|
404 |
+
last_checkpoint = training_args.output_dir
|
405 |
+
else:
|
406 |
+
allowed_dirs = ['.git', '.gitattributes', 'src']
|
407 |
+
unexpected_content = set(dir_content).difference(allowed_dirs)
|
408 |
+
if len(unexpected_content) > 0:
|
409 |
+
raise ValueError(
|
410 |
+
f'Could not find last_checkpoint, resume_from_checkpoint is either None '
|
411 |
+
'or not existing dir, output_dir is non-empty but does not contain a model.'
|
412 |
+
'Use --overwrite_output_dir to overcome. '
|
413 |
+
f'unexpected_content: {unexpected_content}'
|
414 |
+
)
|
415 |
+
else:
|
416 |
+
logger.info(f'dir is not empty, but contains only: {dir_content}. '
|
417 |
+
'it is OK - will start training')
|
418 |
+
|
419 |
+
|
420 |
+
# Set seed before initializing model.
|
421 |
+
set_seed(training_args.seed)
|
422 |
+
|
423 |
+
# 4. Load dataset
|
424 |
+
raw_datasets = IterableDatasetDict() if data_args.streaming else DatasetDict()
|
425 |
+
|
426 |
+
if training_args.do_train:
|
427 |
+
raw_datasets["train"] = load_maybe_streaming_dataset(
|
428 |
+
data_args.dataset_name,
|
429 |
+
data_args.dataset_config_name,
|
430 |
+
split=data_args.train_split_name,
|
431 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
432 |
+
streaming=data_args.streaming,
|
433 |
+
)
|
434 |
+
|
435 |
+
if training_args.do_eval:
|
436 |
+
raw_datasets["eval"] = load_maybe_streaming_dataset(
|
437 |
+
data_args.dataset_name,
|
438 |
+
data_args.dataset_config_name,
|
439 |
+
split=data_args.eval_split_name,
|
440 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
441 |
+
streaming=data_args.streaming,
|
442 |
+
)
|
443 |
+
|
444 |
+
raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
|
445 |
+
|
446 |
+
if data_args.audio_column_name not in raw_datasets_features:
|
447 |
+
raise ValueError(
|
448 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
|
449 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
450 |
+
f"{', '.join(raw_datasets_features)}."
|
451 |
+
)
|
452 |
+
|
453 |
+
if data_args.text_column_name not in raw_datasets_features:
|
454 |
+
raise ValueError(
|
455 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
|
456 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
457 |
+
f"{', '.join(raw_datasets_features)}."
|
458 |
+
)
|
459 |
+
|
460 |
+
# 5. Load pretrained model, tokenizer, and feature extractor
|
461 |
+
#
|
462 |
+
# Distributed training:
|
463 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
464 |
+
config = AutoConfig.from_pretrained(
|
465 |
+
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
|
466 |
+
cache_dir=model_args.cache_dir,
|
467 |
+
revision=model_args.model_revision,
|
468 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
469 |
+
)
|
470 |
+
|
471 |
+
config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
|
472 |
+
|
473 |
+
if training_args.gradient_checkpointing:
|
474 |
+
config.update({"use_cache": False})
|
475 |
+
|
476 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
477 |
+
model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
|
478 |
+
cache_dir=model_args.cache_dir,
|
479 |
+
revision=model_args.model_revision,
|
480 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
481 |
+
)
|
482 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
483 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
484 |
+
cache_dir=model_args.cache_dir,
|
485 |
+
use_fast=model_args.use_fast_tokenizer,
|
486 |
+
revision=model_args.model_revision,
|
487 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
488 |
+
)
|
489 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
490 |
+
model_args.model_name_or_path,
|
491 |
+
config=config,
|
492 |
+
cache_dir=model_args.cache_dir,
|
493 |
+
revision=model_args.model_revision,
|
494 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
495 |
+
)
|
496 |
+
|
497 |
+
if model.config.decoder_start_token_id is None:
|
498 |
+
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
|
499 |
+
|
500 |
+
if model_args.freeze_feature_encoder:
|
501 |
+
model.freeze_feature_encoder()
|
502 |
+
|
503 |
+
if model_args.freeze_encoder:
|
504 |
+
model.freeze_encoder()
|
505 |
+
|
506 |
+
if data_args.language is not None:
|
507 |
+
# We only need to set the task id when the language is specified (i.e. in a multilingual setting)
|
508 |
+
tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
|
509 |
+
|
510 |
+
# 6. Explicitly resample speech dataset
|
511 |
+
raw_datasets = raw_datasets.cast_column(
|
512 |
+
data_args.audio_column_name, datasets.features.Audio(
|
513 |
+
sampling_rate=feature_extractor.sampling_rate,
|
514 |
+
mono=True
|
515 |
+
)
|
516 |
+
)
|
517 |
+
|
518 |
+
# 7. Preprocessing the datasets.
|
519 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
520 |
+
max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
521 |
+
min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
522 |
+
max_labels_length = 448 # model.config.max_length
|
523 |
+
|
524 |
+
audio_column_name = data_args.audio_column_name
|
525 |
+
text_column_name = data_args.text_column_name
|
526 |
+
model_input_name = feature_extractor.model_input_names[0]
|
527 |
+
do_lower_case = data_args.do_lower_case
|
528 |
+
do_remove_punctuation = data_args.do_remove_punctuation
|
529 |
+
normalizer = BelarusianTextNormalizer() # custom normalizer based on 'official' text normalizer from OpenAI
|
530 |
+
|
531 |
+
if data_args.max_train_samples is not None:
|
532 |
+
raw_datasets["train"] = (
|
533 |
+
raw_datasets["train"].take(data_args.max_train_samples)
|
534 |
+
if data_args.streaming
|
535 |
+
else raw_datasets["train"].select(range(data_args.max_train_samples))
|
536 |
+
)
|
537 |
+
|
538 |
+
if data_args.max_eval_samples is not None:
|
539 |
+
raw_datasets["eval"] = (
|
540 |
+
raw_datasets["eval"].take(data_args.max_eval_samples)
|
541 |
+
if data_args.streaming
|
542 |
+
else raw_datasets["eval"].select(range(data_args.max_eval_samples))
|
543 |
+
)
|
544 |
+
|
545 |
+
def prepare_dataset(batch, labels_max_len: int = None):
|
546 |
+
# process audio
|
547 |
+
sample = batch[audio_column_name]
|
548 |
+
inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
|
549 |
+
# process audio length
|
550 |
+
batch[model_input_name] = inputs.get(model_input_name)[0]
|
551 |
+
batch["input_length"] = len(sample["array"])
|
552 |
+
|
553 |
+
# process targets
|
554 |
+
input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
|
555 |
+
if do_remove_punctuation:
|
556 |
+
input_str = normalizer(input_str).strip()
|
557 |
+
batch['labels'] = tokenizer(input_str).input_ids
|
558 |
+
batch['labels_length'] = len(batch['labels']) # include special characters
|
559 |
+
|
560 |
+
batch['labels_truncated'] = 0
|
561 |
+
# need to truncate validation and test labels that are longer that model.config.max_length.
|
562 |
+
# can't drop such examples because this will affect validation and test scores.
|
563 |
+
# thus need to truncate.
|
564 |
+
if labels_max_len is not None:
|
565 |
+
if len(batch['labels']) > labels_max_len:
|
566 |
+
batch['labels'] = batch['labels'][:labels_max_len]
|
567 |
+
batch['labels_truncated'] = 1
|
568 |
+
|
569 |
+
return batch
|
570 |
+
|
571 |
+
with training_args.main_process_first(desc="dataset map pre-processing"):
|
572 |
+
vectorized_datasets = IterableDatasetDict()
|
573 |
+
|
574 |
+
vectorized_datasets['train'] = raw_datasets['train'].map(
|
575 |
+
prepare_dataset, remove_columns=raw_datasets_features,
|
576 |
+
fn_kwargs=dict(labels_max_len=None),
|
577 |
+
).with_format("torch")
|
578 |
+
vectorized_datasets['eval'] = raw_datasets['eval'].map(
|
579 |
+
prepare_dataset, remove_columns=raw_datasets_features,
|
580 |
+
fn_kwargs=dict(labels_max_len=max_labels_length),
|
581 |
+
).with_format("torch")
|
582 |
+
|
583 |
+
if training_args.do_train and data_args.streaming:
|
584 |
+
# manually shuffle if streaming (done by the trainer for non-streaming)
|
585 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
|
586 |
+
buffer_size=data_args.shuffle_buffer_size,
|
587 |
+
seed=training_args.seed,
|
588 |
+
)
|
589 |
+
|
590 |
+
# Filter training data that is shorter than min_input_length or longer than max_input_length.
|
591 |
+
# Drop items with labels longer that max model length.
|
592 |
+
# Drop such items from the train set only. Should keep them in eval set not to affect eval metrics.
|
593 |
+
def is_audio_in_length_range(length):
|
594 |
+
return min_input_length < length < max_input_length
|
595 |
+
|
596 |
+
def are_labels_in_length_range(labels_length):
|
597 |
+
return labels_length <= max_labels_length
|
598 |
+
|
599 |
+
if training_args.do_train:
|
600 |
+
# Filter items from train set only.
|
601 |
+
# Should keep them in eval set not to affect eval metrics.
|
602 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].filter(
|
603 |
+
is_audio_in_length_range,
|
604 |
+
input_columns=["input_length"],
|
605 |
+
)
|
606 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].filter(
|
607 |
+
are_labels_in_length_range,
|
608 |
+
input_columns=["labels_length"],
|
609 |
+
)
|
610 |
+
|
611 |
+
# 8. Load Metric
|
612 |
+
metric = evaluate.load("wer")
|
613 |
+
do_normalize_eval = data_args.do_normalize_eval
|
614 |
+
|
615 |
+
def compute_metrics(pred):
|
616 |
+
pred_ids = pred.predictions
|
617 |
+
|
618 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
619 |
+
|
620 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
621 |
+
# we do not want to group tokens when computing the metrics
|
622 |
+
label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
|
623 |
+
|
624 |
+
if do_normalize_eval:
|
625 |
+
pred_str = [normalizer(pred) for pred in pred_str]
|
626 |
+
label_str = [normalizer(label) for label in label_str]
|
627 |
+
# filtering step to only evaluate the samples that correspond to non-zero references:
|
628 |
+
pred_str = [pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0]
|
629 |
+
label_str = [label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0]
|
630 |
+
|
631 |
+
wer = 100 * metric.compute(predictions=pred_str, references=label_str)
|
632 |
+
|
633 |
+
return {"wer": wer}
|
634 |
+
|
635 |
+
# 9. Create a single speech processor
|
636 |
+
if is_main_process(training_args.local_rank):
|
637 |
+
# save feature extractor, tokenizer and config
|
638 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
639 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
640 |
+
config.save_pretrained(training_args.output_dir)
|
641 |
+
|
642 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
643 |
+
|
644 |
+
# 10. Define data collator
|
645 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
|
646 |
+
processor=processor,
|
647 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
648 |
+
)
|
649 |
+
|
650 |
+
# 11. Configure Trainer
|
651 |
+
# Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
|
652 |
+
# Only required for streaming: Trainer automatically shuffles non-streaming datasets
|
653 |
+
class ShuffleCallback(TrainerCallback):
|
654 |
+
def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
|
655 |
+
if isinstance(train_dataloader.dataset, IterableDatasetShard):
|
656 |
+
pass # set_epoch() is handled by the Trainer
|
657 |
+
elif isinstance(train_dataloader.dataset, IterableDataset):
|
658 |
+
train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
|
659 |
+
|
660 |
+
# Initialize Trainer
|
661 |
+
trainer = Seq2SeqTrainer(
|
662 |
+
model=model,
|
663 |
+
args=training_args,
|
664 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
665 |
+
eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
|
666 |
+
tokenizer=processor,
|
667 |
+
data_collator=data_collator,
|
668 |
+
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
|
669 |
+
callbacks=[ShuffleCallback()] if data_args.streaming else None,
|
670 |
+
)
|
671 |
+
|
672 |
+
# 12. Training
|
673 |
+
if training_args.do_train:
|
674 |
+
checkpoint = None
|
675 |
+
if training_args.resume_from_checkpoint is not None:
|
676 |
+
checkpoint = training_args.resume_from_checkpoint
|
677 |
+
elif last_checkpoint is not None:
|
678 |
+
checkpoint = last_checkpoint
|
679 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
680 |
+
trainer.save_model() # Saves the feature extractor too for easy upload
|
681 |
+
|
682 |
+
metrics = train_result.metrics
|
683 |
+
if data_args.max_train_samples:
|
684 |
+
metrics["train_samples"] = data_args.max_train_samples
|
685 |
+
trainer.log_metrics("train", metrics)
|
686 |
+
trainer.save_metrics("train", metrics)
|
687 |
+
trainer.save_state()
|
688 |
+
|
689 |
+
# 13. Evaluation
|
690 |
+
results = {}
|
691 |
+
if training_args.do_eval:
|
692 |
+
logger.info("*** Evaluate ***")
|
693 |
+
metrics = trainer.evaluate(
|
694 |
+
metric_key_prefix="eval",
|
695 |
+
max_length=training_args.generation_max_length,
|
696 |
+
num_beams=training_args.generation_num_beams,
|
697 |
+
)
|
698 |
+
if data_args.max_eval_samples:
|
699 |
+
metrics["eval_samples"] = data_args.max_eval_samples
|
700 |
+
|
701 |
+
trainer.log_metrics("eval", metrics)
|
702 |
+
trainer.save_metrics("eval", metrics)
|
703 |
+
|
704 |
+
# 14. Write Training Stats
|
705 |
+
kwargs = {
|
706 |
+
"finetuned_from": model_args.model_name_or_path,
|
707 |
+
"tasks": "automatic-speech-recognition",
|
708 |
+
"tags": "whisper-event",
|
709 |
+
}
|
710 |
+
if data_args.dataset_name is not None:
|
711 |
+
kwargs["dataset_tags"] = data_args.dataset_name
|
712 |
+
if data_args.dataset_config_name is not None:
|
713 |
+
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
|
714 |
+
else:
|
715 |
+
kwargs["dataset"] = data_args.dataset_name
|
716 |
+
if "common_voice" in data_args.dataset_name:
|
717 |
+
kwargs["language"] = data_args.dataset_config_name[:2]
|
718 |
+
if model_args.model_index_name is not None:
|
719 |
+
kwargs["model_name"] = model_args.model_index_name
|
720 |
+
|
721 |
+
if training_args.push_to_hub:
|
722 |
+
trainer.push_to_hub(**kwargs)
|
723 |
+
else:
|
724 |
+
trainer.create_model_card(**kwargs)
|
725 |
+
|
726 |
+
return results
|
727 |
+
|
728 |
+
|
729 |
+
if __name__ == "__main__":
|
730 |
+
main()
|
src/setup_env.sh
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
sudo add-apt-repository -y ppa:jonathonf/ffmpeg-4
|
2 |
+
sudo apt update
|
3 |
+
sudo apt install -y ffmpeg
|
4 |
+
|
5 |
+
sudo apt-get install git-lfs
|
6 |
+
|
7 |
+
sudo apt-get install tmux
|
8 |
+
|
9 |
+
cd ~
|
10 |
+
echo "executing env setup from $(pwd)"
|
11 |
+
|
12 |
+
python3 -m venv ~/python_venvs/hf_env
|
13 |
+
source ~/python_venvs/hf_env/bin/activate
|
14 |
+
echo "source ~/python_venvs/hf_env/bin/activate" >> ~/.bashrc
|
15 |
+
|
16 |
+
git clone https://github.com/yks72p/whisper-finetuning-be
|
17 |
+
pip install -r ~/whisper-finetuning-be/requirements.txt
|
18 |
+
|
19 |
+
git config --global credential.helper store
|
20 |
+
huggingface-cli login
|
21 |
+
|
22 |
+
echo "env setup"
|
23 |
+
echo "! PLEASE LOGIN INTO GIT TO BE ABLE TO PUSH TO HF HUB !"
|
24 |
+
echo "> git config --globase user.name <user_name>"
|
25 |
+
echo "> git config --globase user.email <user_email>"
|