added logs from run 2 of fine-tuning
Browse files- run_2/readme.md +31 -0
- run_2/src/readme.md +238 -0
- run_2/src/requirements.txt +9 -0
- run_2/src/run_base.sh +44 -0
- run_2/src/run_small.sh +43 -0
- run_2/src/run_speech_recognition_seq2seq_streaming.py +775 -0
- run_2/src/run_tiny_debug.sh +44 -0
- run_2/src/setup_env.sh +25 -0
- run_2/tensorboard_logs/Dec17_22-46-51_129-213-88-66/1671320122.0745487/events.out.tfevents.1671320122.129-213-88-66.1004273.1 +3 -0
- run_2/tensorboard_logs/Dec17_22-46-51_129-213-88-66/events.out.tfevents.1671320122.129-213-88-66.1004273.0 +3 -0
- run_2/train_20221217-224651.log +130 -0
- run_2/train_run_2.log +0 -0
run_2/readme.md
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Fine-tuning run 2
|
2 |
+
|
3 |
+
Tried to improve model fine-tuned during run 1.
|
4 |
+
|
5 |
+
Checkpoint used: checkpoint-12000
|
6 |
+
|
7 |
+
* Learning rate picked for fine-tuning in run 2 turned out to be too small.
|
8 |
+
WER did not improve compared to run 1.
|
9 |
+
* Fine-tuning during run 2 followed WER trajectory of the end of run 1:
|
10 |
+
from checkpoint-8000 - checkpoint-10000
|
11 |
+
* Have stopped run 2 after 3000 steps
|
12 |
+
* do not upload checkpoints from that run
|
13 |
+
* uploading training stdout logs and tensorboard logs
|
14 |
+
|
15 |
+
## Advices
|
16 |
+
|
17 |
+
* For the next fine-tuning it's better to use higher Learning Rates.
|
18 |
+
As for LR Scheduler it's better to:
|
19 |
+
* either use a constant Learning Rate Scheduler
|
20 |
+
* or manually instantiate a LinearSchedulerWithWarmups and set `num_training_steps` to be larger
|
21 |
+
than the actual number of optimization in the run, so that LR in the end would be >> 0 (much larger than 0)
|
22 |
+
* need to use `seed` other than the one used during run 1. e.g. `seed=43`<br>
|
23 |
+
actual seed used during train dataset reshuffling is computed as:
|
24 |
+
`train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)`
|
25 |
+
however, when resuming training `train_dataloader.dataset._epoch` is reset to 0.<br>
|
26 |
+
thus need to provide different seed
|
27 |
+
* can use original Mozilla Common Voice dataset instead of a HuggingFace's one.<br>
|
28 |
+
the reason is that original contains multiple voicings of same sentence -
|
29 |
+
so there is at least twice as more data.<br>
|
30 |
+
to use this "additional" data, train, validation, test sets need to be enlarged using `validated` set -
|
31 |
+
the one that is absent in HuggingFace's CV11 dataset
|
run_2/src/readme.md
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
* logs are printed only right before the evalutaion:<br>
|
22 |
+
```
|
23 |
+
--logging_steps="50"
|
24 |
+
--eval_steps="1000"
|
25 |
+
```
|
26 |
+
* on the next run:
|
27 |
+
* download the whole dataset before the launch.
|
28 |
+
this will probably save some time for data processing,
|
29 |
+
and allow to load and prepare data in a parallel fashion
|
30 |
+
* can also decrease eval batch size. currently it's probably causing GPU to wait for CPU to prepare a next batch
|
31 |
+
* perform evaluation of fine-tuned model on CommonVoice test set
|
32 |
+
* add [Whisper fine-tuning Event repo](https://github.com/huggingface/community-events/tree/main/whisper-fine-tuning-event)
|
33 |
+
to remotes and merge updates from this original event repo
|
34 |
+
* Learning rate:
|
35 |
+
* max learning rate is not the same as LR passed as a parameter to training script. it is actually lower.
|
36 |
+
* when resuming training, LR scheduling behaves incorrectly
|
37 |
+
* check exact sizes of train, eval, test sets of CommonVoice 11
|
38 |
+
* fill TODOs in Notes section with answers and discussions from a Discord
|
39 |
+
|
40 |
+
## Resuming training from exising checkpoint
|
41 |
+
When resuming training from existing checkpoint:
|
42 |
+
* it's better to save all `checkpoint-\d+` dirs. better not to rely on data saved to `output_dir` because:
|
43 |
+
* not all data is saved to `output_dir`. e.g. following files are not saved to `output_dir`:
|
44 |
+
`optimizer.pt`, `rng_state.pth`, `scaler.pt`, `scheduler.pt`. so can't resume training in a correct way from
|
45 |
+
data saved to `output_dir`
|
46 |
+
* when resuming training from `output_dir` as a checkpoint dir, model saved to `output_dir` can be worse than
|
47 |
+
previously save (need to investifate further. but such happened already)
|
48 |
+
* learning rate gets reset if passing same parameter value to training script as in previour run.<br>
|
49 |
+
need to provide learning rate from the last step of previous run to continue
|
50 |
+
training in a correct way
|
51 |
+
* however even if passing learning rate from the last step, in the new run it has different value than expected
|
52 |
+
* probably because last checkpont was chosen incorrectly
|
53 |
+
* or learning rate is treated as a starting learning rate at step 0 and not on step X (where we resume).<br>
|
54 |
+
need to try to pass same LR that was passes as a starting LR to the very first run
|
55 |
+
* it's unclear whether decision on saving current model
|
56 |
+
is made by comparing current metrics with metrics of the best checkpoint. I guess model with worse performance
|
57 |
+
will not overwrite best model checkpoint already exising in the output dir, but need to double check.
|
58 |
+
* we can set `ignore_data_skip=True` Training argument not to
|
59 |
+
skip data items already passed to a model - that will save time on data loads.
|
60 |
+
* it's unclear whether order of input items in the train set (that is shuffled) will be the same
|
61 |
+
across multiple reruns - i.e. it's unclear whether sampling is the same across reruns.
|
62 |
+
* if the sampling is the same across reruns, `ignore_data_skip=True` will lead to same items been passed to a model
|
63 |
+
in current run. it's OK if previous run ended with large step value on the last epoch.
|
64 |
+
if not, the same elements from the same epoch will be passed to a model again.
|
65 |
+
|
66 |
+
## Questions:
|
67 |
+
* What checkpoint (best, I guess) is saved in the `output_dir`?
|
68 |
+
How is it overwritten when resuming training from existing checkpoint?
|
69 |
+
* does `ShuffleCallback` work with StreamingDataset? it reshuffles data `on_epoch_begin()`,
|
70 |
+
but does StreamingDataset have any epochs?
|
71 |
+
* does streaming mode support parallel data load and processing?<br>
|
72 |
+
when using non-streaming mode we can use `dataset.map(..., num_proc=<num_proc>)`
|
73 |
+
|
74 |
+
|
75 |
+
## Notes:
|
76 |
+
* using CommonVoice 11 dataset in a streaming way.<br>
|
77 |
+
use `streaming=True` for train & validation & test.<br>
|
78 |
+
as an alternative, we can use `streaming=False` for validation & test sets to save time on data processing.
|
79 |
+
but the size of validation and test sets are unknown (need to check).
|
80 |
+
it's likely they are going to be large - thus pre-download of these sets might not reduce
|
81 |
+
overall fine-tuning time compared to streaming mode.
|
82 |
+
* size of train set is ~370'000 audiofiles. if using `batch_size=64`, then
|
83 |
+
1 epoch will have ~5782 steps. <br>
|
84 |
+
Because of `--eval_steps="1000"` will use `--max_steps="6000"` instead of `--max_steps="5800"`
|
85 |
+
to have evaluation metrics computed in the end of training.
|
86 |
+
* if using Google Colab, need to execute `sudo chmod -R 777 .git` inside hf repo to
|
87 |
+
to set right permissions to be able to push trained models to HuggingFace Hub
|
88 |
+
* Log tracking in Jupyter (not working) and in bash (works as expected with `tee`)
|
89 |
+
* Loggers in `run_speech.....py` do not control `transformers` and `datasets` loggers.
|
90 |
+
can't redirect their outputs using handlers. it's better and easier to redirect output in a bash
|
91 |
+
* Need to set `use_cache` to False since we're using gradient checkpointing, and the two are incompatible
|
92 |
+
* Default Linear scheduler is used
|
93 |
+
* Default Adam optimizer is used
|
94 |
+
|
95 |
+
### Logs not printed when expected
|
96 |
+
* Train logs are printed only before start of a validation.
|
97 |
+
During training they are not printed to a stdout.
|
98 |
+
All worked fine in a Colab.
|
99 |
+
* No progressbar for validation (at least when using streaming and iterable dataset).
|
100 |
+
possible reason is that when using streaming, the dataset len in unknown.
|
101 |
+
* Evaluation metrics get printed to stdout only before the next validation call.
|
102 |
+
All worked fine in a Colab.
|
103 |
+
* Possible reason: usage of `... | tee file.log`. But it's unlikely
|
104 |
+
|
105 |
+
### Text normalization
|
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 |
+
|
121 |
+
### Different batch sizes for train and evaluation:
|
122 |
+
* Theoretically you can use a larger batch size for evaluation vs training!
|
123 |
+
* Training: we do a forward pass, storing all the activations, and then a backwards pass, storing all the gradients
|
124 |
+
* Inference (evaluation): we only do a forward pass, and don't store any activations
|
125 |
+
* So the memory required for evaluation is much lower than it is for training
|
126 |
+
(we're only doing the forward pass and not storing any values)
|
127 |
+
* In my experience, altering the eval batch size has little effect on eval speed ->
|
128 |
+
I set it to a lower value as this tends to give a more responsive progress bar
|
129 |
+
when evaluating in non-streaming mode (the bar updates faster and more frequently)
|
130 |
+
|
131 |
+
### Slow inference. Long evalutaion compared to training:
|
132 |
+
* Slower inference is an inherent limitation of the sequence-to-sequence architecture.
|
133 |
+
The auto-regressive decoding means that you have to do as many decoder forward passes as tokens generated.
|
134 |
+
* This is much slower than CTC, where you do a single encoder forward pass
|
135 |
+
* Note that 1 evaluation step **will take much longer** than 1 training step, even with the same batch sizes.
|
136 |
+
* With training, we do one forward pass of the encoder, one forward pass of the decoder,
|
137 |
+
one backward pass of the decoder and one backward pass of the encoder (=4 passes total):<br>
|
138 |
+
```
|
139 |
+
audio -> encoder -> decoder -> labels
|
140 |
+
encoder <- decoder <- loss
|
141 |
+
```
|
142 |
+
* During evaluation we do one forward pass of the encoder, and then auto-regressively generate tokens in the decoder.
|
143 |
+
Here, we do as many forward passes of the decoder as tokens generated.
|
144 |
+
So in total, we do one forward pass of the encoder, and N forward passes of the decoder,
|
145 |
+
where N is the number of tokens generated (can be up to the max length, which is 448...).
|
146 |
+
You can see that for 4 or more generated tokens, evaluation is going to be slower than training:<br>
|
147 |
+
```
|
148 |
+
audio -> encoder -> decoder -> decoder -> decoder -> ... -> decoder -> end of sentence token
|
149 |
+
```
|
150 |
+
* I've made a bit of a simplification here in saying that one forward pass
|
151 |
+
takes the same amount of time as one backward pass, but for the purpose of illustrating,
|
152 |
+
this demonstrates the point why evaluation is much slower than training
|
153 |
+
* Essentially it doesn't really matter what you set your eval batch size as we're not aggregating any statistics
|
154 |
+
over the eval batch (in contrast during training we evaluate a true gradient value based on a given batch).
|
155 |
+
* Since we just do a forward pass, we could even run eval with a batch size of 1 and get exactly the same results!
|
156 |
+
* Because we don't get much of an improvement with batch sizes beyond around 8, it's set somewhat arbitrarily
|
157 |
+
|
158 |
+
### Ways to decrease evaluation time during fine-tuning:
|
159 |
+
* reduce `generation_max_length` param:
|
160 |
+
* During training, we can limit the generation max length to a lower number to cut-off the generation
|
161 |
+
after fewer tokens (e.g. 40). This will give worse results during training,
|
162 |
+
but we can still infer the evolution of WER performance over training.
|
163 |
+
* For the final eval step, we can bump up the generation max length back up to 448.
|
164 |
+
* WER performance varies monotonically with generation max length
|
165 |
+
(WER can only stay equal or improve by increasing generation max length),
|
166 |
+
so we know that our final eval WER will be less than (improved) or equal to the WER during training
|
167 |
+
* We can evaluate at less frequent eval_steps: this reduces the number of times we have to perform evaluation
|
168 |
+
|
169 |
+
### Decrease inference time more generally
|
170 |
+
* PyTorch 2.0 and compiling the model could get you a decent speed-up
|
171 |
+
(https://pytorch.org/blog/Accelerating-Hugging-Face-and-TIMM-models/#hugging-face-models)
|
172 |
+
* Downcasting to fp16
|
173 |
+
|
174 |
+
### Memory saving and training larger models:
|
175 |
+
To save memory (and increase either model or batch_size) can experiment with:
|
176 |
+
* using Adafactor instead of Adam.
|
177 |
+
Adam requires two optimiser params per one model param, but Adafactor uses only one.
|
178 |
+
> A word of caution: Adafactor is untested for fine-tuning Whisper,
|
179 |
+
so we are unsure sure how Adafactor performance compares to Adam!
|
180 |
+
* using Adam 8bit from `bitsandbytes` module.
|
181 |
+
need to provide `optim="adamw_bnb_8bit"` param to `Seq2SeqTrainingArguments`
|
182 |
+
* use `deepspeed`. scripts are there in
|
183 |
+
[Whisper fine-tuning Event repo](https://github.com/huggingface/community-events/tree/main/whisper-fine-tuning-event)
|
184 |
+
* load the model and processor in 8bit mode:
|
185 |
+
```python
|
186 |
+
from transformers import WhisperForConditionalGeneration, WhisperProcessor
|
187 |
+
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large", device_map="auto", load_in_8bit=True)
|
188 |
+
processor = WhisperProcessor.from_pretrained("openai/whisper-large", load_in_8bit=True)
|
189 |
+
```
|
190 |
+
inference loop:
|
191 |
+
```python
|
192 |
+
for data in dataset:
|
193 |
+
inputs = processor.feature_extractor(data["audio"]["array"], return_tensors="pt", sampling_rate=16_000).input_features.half().to(device)
|
194 |
+
forced_decoder_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe")
|
195 |
+
predicted_ids = model.generate(inputs, forced_decoder_ids=forced_decoder_ids)
|
196 |
+
text = processor.tokenizer.batch_decode(predicted_ids, skip_special_tokens=True, normalize=False)[0]
|
197 |
+
print(text)
|
198 |
+
```
|
199 |
+
* 8bit will slower iference compared to full/half-precision
|
200 |
+
* But the memory saving you get is immense (up to 4x vs full-precision).<br>
|
201 |
+
This is the recommended approach when you're limited on VRAM.<br>
|
202 |
+
If you care about inference speed, still to full precision
|
203 |
+
|
204 |
+
### Prepended tokens
|
205 |
+
* Why are there following lines in Data Collator?
|
206 |
+
```python
|
207 |
+
# if bos token is appended in previous tokenization step,
|
208 |
+
# cut bos token here as it's append later anyways
|
209 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
210 |
+
labels = labels[:, 1:]
|
211 |
+
```
|
212 |
+
* `tokenizer.bos_token_id` vs `model.config.decoder_start_token_id`.<br>
|
213 |
+
which one to pass to Data Collator as `decoder_start_token_id` parameter?
|
214 |
+
* Answer:
|
215 |
+
* In this case, the two are equivalent. You can verify this:
|
216 |
+
```python
|
217 |
+
print(tokenizer.bos_token_id)
|
218 |
+
print(model.config.decoder_start_token_id)
|
219 |
+
```
|
220 |
+
|
221 |
+
* Print Output:
|
222 |
+
```
|
223 |
+
<|startoftranscript|>
|
224 |
+
<|startoftranscript|>
|
225 |
+
```
|
226 |
+
|
227 |
+
* 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.
|
228 |
+
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.
|
229 |
+
|
230 |
+
* 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
|
231 |
+
|
232 |
+
* 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
|
233 |
+
|
234 |
+
* The tokens correspond to the audio language, task (translate or transcribe) and whether to predict timestamps
|
235 |
+
|
236 |
+
* 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
|
237 |
+
|
238 |
+
|
run_2/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
|
run_2/src/run_base.sh
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python src/run_speech_recognition_seq2seq_streaming.py \
|
2 |
+
--model_name_or_path="openai/whisper-base" \
|
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 Base Belarusian" \
|
9 |
+
\
|
10 |
+
--max_steps="6000" \
|
11 |
+
--output_dir="./" \
|
12 |
+
--per_device_train_batch_size="64" \
|
13 |
+
--per_device_eval_batch_size="32" \
|
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_train="True" \
|
41 |
+
--streaming_eval="False" \
|
42 |
+
--use_auth_token \
|
43 |
+
--push_to_hub \
|
44 |
+
--hub_model_id="ales/whisper-base-belarusian"
|
run_2/src/run_small.sh
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python src/run_speech_recognition_seq2seq_streaming.py \
|
2 |
+
--model_name_or_path="ales/whisper-small-belarusian" \
|
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="6000" \
|
11 |
+
--output_dir="./" \
|
12 |
+
--per_device_train_batch_size="64" \
|
13 |
+
--per_device_eval_batch_size="32" \
|
14 |
+
--logging_steps="50" \
|
15 |
+
--logging_first_step \
|
16 |
+
--learning_rate="3.5e-5" \
|
17 |
+
--warmup_steps="0" \
|
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_train="True" \
|
41 |
+
--streaming_eval="False" \
|
42 |
+
--seed="43" \
|
43 |
+
--use_auth_token
|
run_2/src/run_speech_recognition_seq2seq_streaming.py
ADDED
@@ -0,0 +1,775 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_train: bool = field(
|
224 |
+
default=True,
|
225 |
+
metadata={"help": "Whether to use streaming mode to load and pre-process the train split."},
|
226 |
+
)
|
227 |
+
streaming_eval: bool = field(
|
228 |
+
default=True,
|
229 |
+
metadata={"help": "Whether to use streaming mode to load and pre-process the evaluation split."},
|
230 |
+
)
|
231 |
+
|
232 |
+
|
233 |
+
class BelarusianTextNormalizer:
|
234 |
+
"""
|
235 |
+
Based on transformers.models.whisper.english_normalizer.BasicTextNormalizer
|
236 |
+
but with support not to remove certain characters.
|
237 |
+
e.g. apostrophe (') - a symbol from Belarusian alphabet - was removed using BasicTextNormalizer.
|
238 |
+
"""
|
239 |
+
|
240 |
+
def __init__(self, split_letters: bool = False):
|
241 |
+
self.split_letters = split_letters
|
242 |
+
self.allowed_symbols = ("'",)
|
243 |
+
|
244 |
+
@staticmethod
|
245 |
+
def clean(s: str, allowed_symbols: Iterable[str] = None):
|
246 |
+
"""
|
247 |
+
Replace any other markers, symbols, punctuations with a space, keeping diacritics
|
248 |
+
"""
|
249 |
+
if allowed_symbols is None:
|
250 |
+
allowed_symbols = []
|
251 |
+
res = "".join(" " if unicodedata.category(c)[0] in "MSP" and c not in allowed_symbols else c
|
252 |
+
for c in unicodedata.normalize("NFKC", s))
|
253 |
+
return res
|
254 |
+
|
255 |
+
def __call__(self, s: str):
|
256 |
+
s = s.lower()
|
257 |
+
s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets
|
258 |
+
s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis
|
259 |
+
s = self.clean(s, allowed_symbols=self.allowed_symbols).lower()
|
260 |
+
|
261 |
+
if self.split_letters:
|
262 |
+
s = " ".join(regex.findall(r"\X", s, regex.U))
|
263 |
+
|
264 |
+
s = re.sub(r"\s+", " ", s) # replace any successive whitespace characters with a space
|
265 |
+
|
266 |
+
return s
|
267 |
+
|
268 |
+
|
269 |
+
@dataclass
|
270 |
+
class DataCollatorSpeechSeq2SeqWithPadding:
|
271 |
+
"""
|
272 |
+
Data collator that will dynamically pad the inputs received.
|
273 |
+
Args:
|
274 |
+
processor ([`WhisperProcessor`])
|
275 |
+
The processor used for processing the data.
|
276 |
+
decoder_start_token_id (`int`)
|
277 |
+
The begin-of-sentence of the decoder.
|
278 |
+
"""
|
279 |
+
|
280 |
+
processor: Any
|
281 |
+
decoder_start_token_id: int
|
282 |
+
|
283 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
284 |
+
# split inputs and labels since they have to be of different lengths and need
|
285 |
+
# different padding methods
|
286 |
+
model_input_name = self.processor.model_input_names[0]
|
287 |
+
input_features = [{model_input_name: feature[model_input_name]} for feature in features]
|
288 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
289 |
+
|
290 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
291 |
+
|
292 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
293 |
+
|
294 |
+
# replace padding with -100 to ignore loss correctly
|
295 |
+
labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
296 |
+
|
297 |
+
# if bos token is appended in previous tokenization step,
|
298 |
+
# cut bos token here as it's append later anyways
|
299 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
300 |
+
labels = labels[:, 1:]
|
301 |
+
|
302 |
+
batch["labels"] = labels
|
303 |
+
|
304 |
+
return batch
|
305 |
+
|
306 |
+
|
307 |
+
def load_maybe_streaming_dataset(dataset_name, dataset_config_name, split="train", streaming=True, **kwargs):
|
308 |
+
"""
|
309 |
+
Utility function to load a dataset in streaming mode. For datasets with multiple splits,
|
310 |
+
each split is loaded individually and then splits combined by taking alternating examples from
|
311 |
+
each (interleaving).
|
312 |
+
"""
|
313 |
+
if "+" in split:
|
314 |
+
# load multiple splits separated by the `+` symbol with streaming mode
|
315 |
+
dataset_splits = [
|
316 |
+
load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=streaming, **kwargs)
|
317 |
+
for split_name in split.split("+")
|
318 |
+
]
|
319 |
+
# interleave multiple splits to form one dataset
|
320 |
+
interleaved_dataset = interleave_datasets(dataset_splits)
|
321 |
+
return interleaved_dataset
|
322 |
+
else:
|
323 |
+
# load a single split *with* streaming mode
|
324 |
+
dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=streaming, **kwargs)
|
325 |
+
return dataset
|
326 |
+
|
327 |
+
|
328 |
+
def main():
|
329 |
+
# 1. Parse input arguments
|
330 |
+
# See all possible arguments in src/transformers/training_args.py
|
331 |
+
# or by passing the --help flag to this script.
|
332 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
333 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
334 |
+
|
335 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
336 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
337 |
+
# let's parse it to get our arguments.
|
338 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
339 |
+
else:
|
340 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
341 |
+
|
342 |
+
|
343 |
+
# 2. Setup logging
|
344 |
+
now_str = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
|
345 |
+
logging.basicConfig(
|
346 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
347 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
348 |
+
handlers=[
|
349 |
+
logging.StreamHandler(sys.stdout),
|
350 |
+
logging.FileHandler(filename=f'train_{now_str}.log', mode='w')
|
351 |
+
],
|
352 |
+
)
|
353 |
+
log_level = training_args.get_process_log_level()
|
354 |
+
logger.setLevel(log_level)
|
355 |
+
datasets.utils.logging.set_verbosity(log_level)
|
356 |
+
transformers.utils.logging.set_verbosity(log_level)
|
357 |
+
transformers.utils.logging.enable_default_handler()
|
358 |
+
transformers.utils.logging.enable_explicit_format()
|
359 |
+
|
360 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
361 |
+
|
362 |
+
# Log on each process the small summary:
|
363 |
+
logger.warning(
|
364 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
365 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
366 |
+
)
|
367 |
+
|
368 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
369 |
+
logger.info(f"Data parameters: {data_args}")
|
370 |
+
logger.info(f"Model parameters: {model_args}")
|
371 |
+
|
372 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
373 |
+
if is_main_process(training_args.local_rank):
|
374 |
+
transformers.utils.logging.set_verbosity_info()
|
375 |
+
|
376 |
+
# 3. Detecting last checkpoint and eventually continue from last checkpoint
|
377 |
+
last_checkpoint = None
|
378 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
379 |
+
logger.info(f'output_dir already exists. will try to load last checkpoint.')
|
380 |
+
|
381 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
382 |
+
if last_checkpoint is not None:
|
383 |
+
if training_args.resume_from_checkpoint is None:
|
384 |
+
logger.info(
|
385 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
386 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
387 |
+
)
|
388 |
+
else:
|
389 |
+
logger.info(f'Last checkpoint found at: {last_checkpoint}. Will ignore it and resume training '
|
390 |
+
f'from passed resume_from_checkpoint param: {training_args.resume_from_checkpoint}')
|
391 |
+
assert os.path.isdir(training_args.resume_from_checkpoint)
|
392 |
+
else:
|
393 |
+
logger.info('last_checkpoint is None. will try to read from training_args.resume_from_checkpoint')
|
394 |
+
|
395 |
+
if training_args.resume_from_checkpoint is not None and os.path.isdir(training_args.resume_from_checkpoint):
|
396 |
+
logger.info(f'Will resume training from passed resume_from_checkpoint param: '
|
397 |
+
f'{training_args.resume_from_checkpoint}')
|
398 |
+
else:
|
399 |
+
logger.info('last_checkpoint is None. resume_from_checkpoint is either None or not existing dir. '
|
400 |
+
'will try to read from the model saved in the root of output_dir.')
|
401 |
+
|
402 |
+
dir_content = os.listdir(training_args.output_dir)
|
403 |
+
if len(dir_content) == 0:
|
404 |
+
logger.info('output_dir is empty. will start training from scratch.')
|
405 |
+
else:
|
406 |
+
model_fn = 'pytorch_model.bin'
|
407 |
+
if model_fn in dir_content:
|
408 |
+
logger.info(f'found {model_fn} inside output_dir. '
|
409 |
+
f'will continue training treating output_dir as a last checkpoint.')
|
410 |
+
last_checkpoint = training_args.output_dir
|
411 |
+
else:
|
412 |
+
allowed_dirs = ['.git', '.gitattributes', 'src']
|
413 |
+
unexpected_content = set(dir_content).difference(allowed_dirs)
|
414 |
+
unexpected_content = [x for x in unexpected_content
|
415 |
+
if not x.endswith('.log') and os.path.isfile(x)]
|
416 |
+
if len(unexpected_content) > 0:
|
417 |
+
raise ValueError(
|
418 |
+
f'Could not find last_checkpoint, resume_from_checkpoint is either None '
|
419 |
+
'or not existing dir, output_dir is non-empty but does not contain a model.'
|
420 |
+
'Use --overwrite_output_dir to overcome. '
|
421 |
+
f'unexpected_content: {unexpected_content}'
|
422 |
+
)
|
423 |
+
else:
|
424 |
+
logger.info(f'dir is not empty, but contains only: {dir_content}. '
|
425 |
+
'it is OK - will start training')
|
426 |
+
|
427 |
+
|
428 |
+
# Set seed before initializing model.
|
429 |
+
set_seed(training_args.seed)
|
430 |
+
|
431 |
+
# 4. Load dataset
|
432 |
+
|
433 |
+
# TODO: replace dataset dicts with single key to IterableDataset and to Dataset.
|
434 |
+
# don't know how to do it know - using dict simply because they work.
|
435 |
+
raw_train = IterableDatasetDict() if data_args.streaming_train else DatasetDict()
|
436 |
+
raw_eval = IterableDatasetDict() if data_args.streaming_eval else DatasetDict()
|
437 |
+
|
438 |
+
if training_args.do_train:
|
439 |
+
raw_train['train'] = load_maybe_streaming_dataset(
|
440 |
+
data_args.dataset_name,
|
441 |
+
data_args.dataset_config_name,
|
442 |
+
split=data_args.train_split_name,
|
443 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
444 |
+
streaming=data_args.streaming_train,
|
445 |
+
)
|
446 |
+
|
447 |
+
if training_args.do_eval:
|
448 |
+
raw_eval['eval'] = load_maybe_streaming_dataset(
|
449 |
+
data_args.dataset_name,
|
450 |
+
data_args.dataset_config_name,
|
451 |
+
split=data_args.eval_split_name,
|
452 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
453 |
+
streaming=data_args.streaming_eval,
|
454 |
+
)
|
455 |
+
|
456 |
+
raw_datasets_features = list(next(iter(raw_train.values())).features.keys())
|
457 |
+
|
458 |
+
if data_args.audio_column_name not in raw_datasets_features:
|
459 |
+
raise ValueError(
|
460 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
|
461 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
462 |
+
f"{', '.join(raw_datasets_features)}."
|
463 |
+
)
|
464 |
+
|
465 |
+
if data_args.text_column_name not in raw_datasets_features:
|
466 |
+
raise ValueError(
|
467 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
|
468 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
469 |
+
f"{', '.join(raw_datasets_features)}."
|
470 |
+
)
|
471 |
+
|
472 |
+
# 5. Load pretrained model, tokenizer, and feature extractor
|
473 |
+
#
|
474 |
+
# Distributed training:
|
475 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
476 |
+
config = AutoConfig.from_pretrained(
|
477 |
+
model_args.config_name if model_args.config_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 |
+
|
483 |
+
config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
|
484 |
+
|
485 |
+
if training_args.gradient_checkpointing:
|
486 |
+
config.update({"use_cache": False})
|
487 |
+
|
488 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
489 |
+
model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
|
490 |
+
cache_dir=model_args.cache_dir,
|
491 |
+
revision=model_args.model_revision,
|
492 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
493 |
+
)
|
494 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
495 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
496 |
+
cache_dir=model_args.cache_dir,
|
497 |
+
use_fast=model_args.use_fast_tokenizer,
|
498 |
+
revision=model_args.model_revision,
|
499 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
500 |
+
)
|
501 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
502 |
+
model_args.model_name_or_path,
|
503 |
+
config=config,
|
504 |
+
cache_dir=model_args.cache_dir,
|
505 |
+
revision=model_args.model_revision,
|
506 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
507 |
+
)
|
508 |
+
|
509 |
+
if model.config.decoder_start_token_id is None:
|
510 |
+
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
|
511 |
+
|
512 |
+
if model_args.freeze_feature_encoder:
|
513 |
+
model.freeze_feature_encoder()
|
514 |
+
|
515 |
+
if model_args.freeze_encoder:
|
516 |
+
model.freeze_encoder()
|
517 |
+
|
518 |
+
if data_args.language is not None:
|
519 |
+
# We only need to set the task id when the language is specified (i.e. in a multilingual setting)
|
520 |
+
tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
|
521 |
+
|
522 |
+
# 6. Explicitly resample speech dataset
|
523 |
+
raw_train = raw_train.cast_column(
|
524 |
+
data_args.audio_column_name, datasets.features.Audio(
|
525 |
+
sampling_rate=feature_extractor.sampling_rate,
|
526 |
+
mono=True
|
527 |
+
)
|
528 |
+
)
|
529 |
+
raw_eval = raw_eval.cast_column(
|
530 |
+
data_args.audio_column_name, datasets.features.Audio(
|
531 |
+
sampling_rate=feature_extractor.sampling_rate,
|
532 |
+
mono=True
|
533 |
+
)
|
534 |
+
)
|
535 |
+
|
536 |
+
# 7. Preprocessing the datasets.
|
537 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
538 |
+
max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
539 |
+
min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
540 |
+
max_labels_length = 448 # model.config.max_length
|
541 |
+
|
542 |
+
audio_column_name = data_args.audio_column_name
|
543 |
+
text_column_name = data_args.text_column_name
|
544 |
+
model_input_name = feature_extractor.model_input_names[0]
|
545 |
+
do_lower_case = data_args.do_lower_case
|
546 |
+
do_remove_punctuation = data_args.do_remove_punctuation
|
547 |
+
normalizer = BelarusianTextNormalizer() # custom normalizer based on 'official' text normalizer from OpenAI
|
548 |
+
|
549 |
+
if data_args.max_train_samples is not None:
|
550 |
+
raw_train['train'] = (
|
551 |
+
raw_train['train'].take(data_args.max_train_samples)
|
552 |
+
if data_args.streaming_train
|
553 |
+
else raw_train['train'].select(range(data_args.max_train_samples))
|
554 |
+
)
|
555 |
+
|
556 |
+
if data_args.max_eval_samples is not None:
|
557 |
+
raw_eval['eval'] = (
|
558 |
+
raw_eval['eval'].take(data_args.max_eval_samples)
|
559 |
+
if data_args.streaming_eval
|
560 |
+
else raw_eval['eval'].select(range(data_args.max_eval_samples))
|
561 |
+
)
|
562 |
+
|
563 |
+
def prepare_dataset(sample, labels_max_len: int = None):
|
564 |
+
# process audio
|
565 |
+
audio = sample[audio_column_name]
|
566 |
+
inputs = feature_extractor(audio["array"], sampling_rate=audio["sampling_rate"])
|
567 |
+
# process audio length
|
568 |
+
sample[model_input_name] = inputs.get(model_input_name)[0]
|
569 |
+
sample["input_length"] = len(audio["array"])
|
570 |
+
|
571 |
+
# process targets
|
572 |
+
input_str = sample[text_column_name].lower() if do_lower_case else sample[text_column_name]
|
573 |
+
if do_remove_punctuation:
|
574 |
+
input_str = normalizer(input_str).strip()
|
575 |
+
sample['labels'] = tokenizer(input_str).input_ids
|
576 |
+
sample['labels_length'] = len(sample['labels']) # include special characters
|
577 |
+
|
578 |
+
sample['labels_truncated'] = 0
|
579 |
+
# need to truncate validation and test labels that are longer that model.config.max_length.
|
580 |
+
# can't drop such examples because this will affect validation and test scores.
|
581 |
+
# thus need to truncate.
|
582 |
+
if labels_max_len is not None:
|
583 |
+
if len(sample['labels']) > labels_max_len:
|
584 |
+
sample['labels'] = sample['labels'][:labels_max_len]
|
585 |
+
sample['labels_truncated'] = 1
|
586 |
+
|
587 |
+
return sample
|
588 |
+
|
589 |
+
with training_args.main_process_first(desc="dataset map pre-processing"):
|
590 |
+
logger.info(f'vectorizing dataset')
|
591 |
+
|
592 |
+
# TODO: replace dataset dicts with single key to IterableDataset and to Dataset.
|
593 |
+
# don't know how to do it know - using dict simply because they work.
|
594 |
+
vectorized_train = IterableDatasetDict() if data_args.streaming_train else DatasetDict()
|
595 |
+
vectorized_eval = IterableDatasetDict() if data_args.streaming_eval else DatasetDict()
|
596 |
+
|
597 |
+
num_proc = None
|
598 |
+
if data_args.streaming_train or data_args.streaming_eval:
|
599 |
+
logger.info(f'will preprocess data using {num_proc} processes.')
|
600 |
+
|
601 |
+
if data_args.streaming_train:
|
602 |
+
vectorized_train['train'] = raw_train['train'].map(
|
603 |
+
prepare_dataset, remove_columns=raw_datasets_features,
|
604 |
+
fn_kwargs=dict(labels_max_len=None),
|
605 |
+
).with_format("torch")
|
606 |
+
else:
|
607 |
+
vectorized_train['train'] = raw_train['train'].map(
|
608 |
+
prepare_dataset, remove_columns=raw_datasets_features,
|
609 |
+
num_proc=num_proc,
|
610 |
+
fn_kwargs=dict(labels_max_len=None),
|
611 |
+
).with_format("torch")
|
612 |
+
|
613 |
+
if data_args.streaming_eval:
|
614 |
+
vectorized_eval['eval'] = raw_eval['eval'].map(
|
615 |
+
prepare_dataset, remove_columns=raw_datasets_features,
|
616 |
+
fn_kwargs=dict(labels_max_len=max_labels_length),
|
617 |
+
).with_format("torch")
|
618 |
+
else:
|
619 |
+
vectorized_eval['eval'] = raw_eval['eval'].map(
|
620 |
+
prepare_dataset, remove_columns=raw_datasets_features,
|
621 |
+
num_proc=num_proc,
|
622 |
+
fn_kwargs=dict(labels_max_len=max_labels_length),
|
623 |
+
).with_format("torch")
|
624 |
+
|
625 |
+
if training_args.do_train and data_args.streaming_train:
|
626 |
+
# manually shuffle if streaming (done by the trainer for non-streaming)
|
627 |
+
vectorized_train['train'] = vectorized_train['train'].shuffle(
|
628 |
+
buffer_size=data_args.shuffle_buffer_size,
|
629 |
+
seed=training_args.seed,
|
630 |
+
)
|
631 |
+
|
632 |
+
# Filter training data that is shorter than min_input_length or longer than max_input_length.
|
633 |
+
# Drop items with labels longer that max model length.
|
634 |
+
# Drop such items from the train set only. Should keep them in eval set not to affect eval metrics.
|
635 |
+
def is_audio_in_length_range(length):
|
636 |
+
return min_input_length < length < max_input_length
|
637 |
+
|
638 |
+
def are_labels_in_length_range(labels_length):
|
639 |
+
return labels_length <= max_labels_length
|
640 |
+
|
641 |
+
if training_args.do_train:
|
642 |
+
# Filter items from train set only.
|
643 |
+
# Should keep them in eval set not to affect eval metrics.
|
644 |
+
vectorized_train['train'] = vectorized_train['train'].filter(
|
645 |
+
is_audio_in_length_range,
|
646 |
+
input_columns=["input_length"],
|
647 |
+
)
|
648 |
+
vectorized_train['train'] = vectorized_train['train'].filter(
|
649 |
+
are_labels_in_length_range,
|
650 |
+
input_columns=["labels_length"],
|
651 |
+
)
|
652 |
+
|
653 |
+
# 8. Load Metric
|
654 |
+
metric = evaluate.load("wer")
|
655 |
+
do_normalize_eval = data_args.do_normalize_eval
|
656 |
+
|
657 |
+
def compute_metrics(pred):
|
658 |
+
pred_ids = pred.predictions
|
659 |
+
|
660 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
661 |
+
|
662 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
663 |
+
# we do not want to group tokens when computing the metrics
|
664 |
+
label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
|
665 |
+
|
666 |
+
if do_normalize_eval:
|
667 |
+
pred_str = [normalizer(pred) for pred in pred_str]
|
668 |
+
label_str = [normalizer(label) for label in label_str]
|
669 |
+
# filtering step to only evaluate the samples that correspond to non-zero references:
|
670 |
+
pred_str = [pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0]
|
671 |
+
label_str = [label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0]
|
672 |
+
|
673 |
+
wer = 100 * metric.compute(predictions=pred_str, references=label_str)
|
674 |
+
|
675 |
+
return {"wer": wer}
|
676 |
+
|
677 |
+
# 9. Create a single speech processor
|
678 |
+
if is_main_process(training_args.local_rank):
|
679 |
+
# save feature extractor, tokenizer and config
|
680 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
681 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
682 |
+
config.save_pretrained(training_args.output_dir)
|
683 |
+
|
684 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
685 |
+
|
686 |
+
# 10. Define data collator
|
687 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
|
688 |
+
processor=processor,
|
689 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
690 |
+
)
|
691 |
+
|
692 |
+
# 11. Configure Trainer
|
693 |
+
# Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
|
694 |
+
# Only required for streaming: Trainer automatically shuffles non-streaming datasets
|
695 |
+
class ShuffleCallback(TrainerCallback):
|
696 |
+
def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
|
697 |
+
if isinstance(train_dataloader.dataset, IterableDatasetShard):
|
698 |
+
pass # set_epoch() is handled by the Trainer
|
699 |
+
elif isinstance(train_dataloader.dataset, IterableDataset):
|
700 |
+
logger.info(f'ShuffleCallback. shuffling train dataset. '
|
701 |
+
f'seed: {training_args.seed}. dataset epoch: {train_dataloader.dataset._epoch}')
|
702 |
+
train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
|
703 |
+
|
704 |
+
# Initialize Trainer
|
705 |
+
trainer = Seq2SeqTrainer(
|
706 |
+
model=model,
|
707 |
+
args=training_args,
|
708 |
+
train_dataset=vectorized_train['train'] if training_args.do_train else None,
|
709 |
+
eval_dataset=vectorized_eval['eval'] if training_args.do_eval else None,
|
710 |
+
tokenizer=processor,
|
711 |
+
data_collator=data_collator,
|
712 |
+
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
|
713 |
+
callbacks=[ShuffleCallback()] if data_args.streaming_train else None,
|
714 |
+
)
|
715 |
+
|
716 |
+
# 12. Training
|
717 |
+
if training_args.do_train:
|
718 |
+
checkpoint = None
|
719 |
+
if training_args.resume_from_checkpoint is not None:
|
720 |
+
checkpoint = training_args.resume_from_checkpoint
|
721 |
+
elif last_checkpoint is not None:
|
722 |
+
checkpoint = last_checkpoint
|
723 |
+
logger.info(f'will launch training and pass resume_from_checkpoint={checkpoint}')
|
724 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
725 |
+
trainer.save_model() # Saves the feature extractor too for easy upload
|
726 |
+
|
727 |
+
metrics = train_result.metrics
|
728 |
+
if data_args.max_train_samples:
|
729 |
+
metrics["train_samples"] = data_args.max_train_samples
|
730 |
+
trainer.log_metrics("train", metrics)
|
731 |
+
trainer.save_metrics("train", metrics)
|
732 |
+
trainer.save_state()
|
733 |
+
|
734 |
+
# 13. Evaluation
|
735 |
+
results = {}
|
736 |
+
if training_args.do_eval:
|
737 |
+
logger.info("*** Evaluate ***")
|
738 |
+
metrics = trainer.evaluate(
|
739 |
+
metric_key_prefix="eval",
|
740 |
+
max_length=training_args.generation_max_length,
|
741 |
+
num_beams=training_args.generation_num_beams,
|
742 |
+
)
|
743 |
+
if data_args.max_eval_samples:
|
744 |
+
metrics["eval_samples"] = data_args.max_eval_samples
|
745 |
+
|
746 |
+
trainer.log_metrics("eval", metrics)
|
747 |
+
trainer.save_metrics("eval", metrics)
|
748 |
+
|
749 |
+
# 14. Write Training Stats
|
750 |
+
kwargs = {
|
751 |
+
"finetuned_from": model_args.model_name_or_path,
|
752 |
+
"tasks": "automatic-speech-recognition",
|
753 |
+
"tags": "whisper-event",
|
754 |
+
}
|
755 |
+
if data_args.dataset_name is not None:
|
756 |
+
kwargs["dataset_tags"] = data_args.dataset_name
|
757 |
+
if data_args.dataset_config_name is not None:
|
758 |
+
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
|
759 |
+
else:
|
760 |
+
kwargs["dataset"] = data_args.dataset_name
|
761 |
+
if "common_voice" in data_args.dataset_name:
|
762 |
+
kwargs["language"] = data_args.dataset_config_name[:2]
|
763 |
+
if model_args.model_index_name is not None:
|
764 |
+
kwargs["model_name"] = model_args.model_index_name
|
765 |
+
|
766 |
+
if training_args.push_to_hub:
|
767 |
+
trainer.push_to_hub(**kwargs)
|
768 |
+
else:
|
769 |
+
trainer.create_model_card(**kwargs)
|
770 |
+
|
771 |
+
return results
|
772 |
+
|
773 |
+
|
774 |
+
if __name__ == "__main__":
|
775 |
+
main()
|
run_2/src/run_tiny_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"
|
run_2/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>"
|
run_2/tensorboard_logs/Dec17_22-46-51_129-213-88-66/1671320122.0745487/events.out.tfevents.1671320122.129-213-88-66.1004273.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4377571bbe4887a09d3a9565e3c561ab7c4f1cf581824b96a749e1ebd79dfdbc
|
3 |
+
size 5863
|
run_2/tensorboard_logs/Dec17_22-46-51_129-213-88-66/events.out.tfevents.1671320122.129-213-88-66.1004273.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3a5879ae4dfa16bf058980f59de635a4f35af313ba2ed1e7b54b8fc8e2f412e8
|
3 |
+
size 15105
|
run_2/train_20221217-224651.log
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
12/17/2022 22:46:51 - WARNING - __main__ - Process rank: -1, device: cuda:0, n_gpu: 1distributed training: False, 16-bits training: True
|
2 |
+
12/17/2022 22:46:51 - INFO - __main__ - Training/evaluation parameters Seq2SeqTrainingArguments(
|
3 |
+
_n_gpu=1,
|
4 |
+
adafactor=False,
|
5 |
+
adam_beta1=0.9,
|
6 |
+
adam_beta2=0.999,
|
7 |
+
adam_epsilon=1e-08,
|
8 |
+
auto_find_batch_size=False,
|
9 |
+
bf16=False,
|
10 |
+
bf16_full_eval=False,
|
11 |
+
data_seed=None,
|
12 |
+
dataloader_drop_last=False,
|
13 |
+
dataloader_num_workers=0,
|
14 |
+
dataloader_pin_memory=True,
|
15 |
+
ddp_bucket_cap_mb=None,
|
16 |
+
ddp_find_unused_parameters=None,
|
17 |
+
ddp_timeout=1800,
|
18 |
+
debug=[],
|
19 |
+
deepspeed=None,
|
20 |
+
disable_tqdm=False,
|
21 |
+
do_eval=True,
|
22 |
+
do_predict=False,
|
23 |
+
do_train=True,
|
24 |
+
eval_accumulation_steps=None,
|
25 |
+
eval_delay=0,
|
26 |
+
eval_steps=1000,
|
27 |
+
evaluation_strategy=steps,
|
28 |
+
fp16=True,
|
29 |
+
fp16_backend=auto,
|
30 |
+
fp16_full_eval=False,
|
31 |
+
fp16_opt_level=O1,
|
32 |
+
fsdp=[],
|
33 |
+
fsdp_min_num_params=0,
|
34 |
+
fsdp_transformer_layer_cls_to_wrap=None,
|
35 |
+
full_determinism=False,
|
36 |
+
generation_max_length=225,
|
37 |
+
generation_num_beams=None,
|
38 |
+
gradient_accumulation_steps=1,
|
39 |
+
gradient_checkpointing=True,
|
40 |
+
greater_is_better=False,
|
41 |
+
group_by_length=False,
|
42 |
+
half_precision_backend=auto,
|
43 |
+
hub_model_id=None,
|
44 |
+
hub_private_repo=False,
|
45 |
+
hub_strategy=every_save,
|
46 |
+
hub_token=<HUB_TOKEN>,
|
47 |
+
ignore_data_skip=True,
|
48 |
+
include_inputs_for_metrics=False,
|
49 |
+
jit_mode_eval=False,
|
50 |
+
label_names=None,
|
51 |
+
label_smoothing_factor=0.0,
|
52 |
+
learning_rate=3.5e-05,
|
53 |
+
length_column_name=length,
|
54 |
+
load_best_model_at_end=True,
|
55 |
+
local_rank=-1,
|
56 |
+
log_level=passive,
|
57 |
+
log_level_replica=passive,
|
58 |
+
log_on_each_node=True,
|
59 |
+
logging_dir=./runs/Dec17_22-46-51_129-213-88-66,
|
60 |
+
logging_first_step=True,
|
61 |
+
logging_nan_inf_filter=True,
|
62 |
+
logging_steps=50,
|
63 |
+
logging_strategy=steps,
|
64 |
+
lr_scheduler_type=linear,
|
65 |
+
max_grad_norm=1.0,
|
66 |
+
max_steps=6000,
|
67 |
+
metric_for_best_model=wer,
|
68 |
+
mp_parameters=,
|
69 |
+
no_cuda=False,
|
70 |
+
num_train_epochs=3.0,
|
71 |
+
optim=adamw_hf,
|
72 |
+
optim_args=None,
|
73 |
+
output_dir=./,
|
74 |
+
overwrite_output_dir=False,
|
75 |
+
past_index=-1,
|
76 |
+
per_device_eval_batch_size=32,
|
77 |
+
per_device_train_batch_size=64,
|
78 |
+
predict_with_generate=True,
|
79 |
+
prediction_loss_only=False,
|
80 |
+
push_to_hub=False,
|
81 |
+
push_to_hub_model_id=None,
|
82 |
+
push_to_hub_organization=None,
|
83 |
+
push_to_hub_token=<PUSH_TO_HUB_TOKEN>,
|
84 |
+
ray_scope=last,
|
85 |
+
remove_unused_columns=True,
|
86 |
+
report_to=['tensorboard'],
|
87 |
+
resume_from_checkpoint=None,
|
88 |
+
run_name=./,
|
89 |
+
save_on_each_node=False,
|
90 |
+
save_steps=1000,
|
91 |
+
save_strategy=steps,
|
92 |
+
save_total_limit=None,
|
93 |
+
seed=43,
|
94 |
+
sharded_ddp=[],
|
95 |
+
skip_memory_metrics=True,
|
96 |
+
sortish_sampler=False,
|
97 |
+
tf32=None,
|
98 |
+
torch_compile=False,
|
99 |
+
torch_compile_backend=None,
|
100 |
+
torch_compile_mode=None,
|
101 |
+
torchdynamo=None,
|
102 |
+
tpu_metrics_debug=False,
|
103 |
+
tpu_num_cores=None,
|
104 |
+
use_ipex=False,
|
105 |
+
use_legacy_prediction_loop=False,
|
106 |
+
use_mps_device=False,
|
107 |
+
warmup_ratio=0.0,
|
108 |
+
warmup_steps=0,
|
109 |
+
weight_decay=0.0,
|
110 |
+
xpu_backend=None,
|
111 |
+
)
|
112 |
+
12/17/2022 22:46:51 - INFO - __main__ - Data parameters: DataTrainingArguments(dataset_name='mozilla-foundation/common_voice_11_0', dataset_config_name='be', max_train_samples=None, max_eval_samples=None, audio_column_name='audio', text_column_name='sentence', max_duration_in_seconds=30.0, min_duration_in_seconds=0.0, train_split_name='train', eval_split_name='validation', do_lower_case=False, do_remove_punctuation=False, do_normalize_eval=True, language='be', task='transcribe', shuffle_buffer_size=500, streaming_train=True, streaming_eval=False)
|
113 |
+
12/17/2022 22:46:51 - INFO - __main__ - Model parameters: ModelArguments(model_name_or_path='ales/whisper-small-belarusian', config_name=None, tokenizer_name=None, feature_extractor_name=None, cache_dir=None, use_fast_tokenizer=True, model_revision='main', use_auth_token=True, freeze_feature_encoder=False, freeze_encoder=False, forced_decoder_ids=None, suppress_tokens=None, model_index_name='Whisper Small Belarusian')
|
114 |
+
12/17/2022 22:46:51 - INFO - __main__ - output_dir already exists. will try to load last checkpoint.
|
115 |
+
12/17/2022 22:46:51 - INFO - __main__ - last_checkpoint is None. will try to read from training_args.resume_from_checkpoint
|
116 |
+
12/17/2022 22:46:51 - INFO - __main__ - last_checkpoint is None. resume_from_checkpoint is either None or not existing dir. will try to read from the model saved in the root of output_dir.
|
117 |
+
12/17/2022 22:46:51 - INFO - __main__ - dir is not empty, but contains only: ['src', 'train_20221217-224651.log', 'train_run_2.log']. it is OK - will start training
|
118 |
+
12/17/2022 22:46:51 - INFO - datasets.info - Loading Dataset Infos from /home/ubuntu/.cache/huggingface/modules/datasets_modules/datasets/mozilla-foundation--common_voice_11_0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f
|
119 |
+
12/17/2022 22:46:51 - INFO - datasets.builder - Overwrite dataset info from restored data version.
|
120 |
+
12/17/2022 22:46:51 - INFO - datasets.info - Loading Dataset info from /home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/be/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f
|
121 |
+
12/17/2022 22:46:51 - INFO - datasets.info - Loading Dataset Infos from /home/ubuntu/.cache/huggingface/modules/datasets_modules/datasets/mozilla-foundation--common_voice_11_0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f
|
122 |
+
12/17/2022 22:46:51 - INFO - datasets.builder - Overwrite dataset info from restored data version.
|
123 |
+
12/17/2022 22:46:51 - INFO - datasets.info - Loading Dataset info from /home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/be/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f
|
124 |
+
12/17/2022 22:46:51 - WARNING - datasets.builder - Found cached dataset common_voice_11_0 (/home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/be/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f)
|
125 |
+
12/17/2022 22:46:51 - INFO - datasets.info - Loading Dataset info from /home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/be/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f
|
126 |
+
12/17/2022 22:47:06 - INFO - __main__ - vectorizing dataset
|
127 |
+
12/17/2022 22:47:06 - INFO - __main__ - will preprocess data using None processes.
|
128 |
+
12/17/2022 22:47:08 - INFO - datasets.arrow_dataset - Caching processed dataset at /home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/be/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f/cache-796bd4b577aed289.arrow
|
129 |
+
12/17/2022 23:35:22 - INFO - __main__ - will launch training and pass resume_from_checkpoint=None
|
130 |
+
12/17/2022 23:35:22 - INFO - __main__ - ShuffleCallback. shuffling train dataset. seed: 43. dataset epoch: 0
|
run_2/train_run_2.log
ADDED
The diff for this file is too large to render.
See raw diff
|
|