Commit
•
320c039
1
Parent(s):
9c2e43c
Add training scripts and weights
Browse files- .gitattributes +1 -1
- README.md +45 -0
- conf/conformer_transducer_bpe_xlarge.yaml +0 -0
- models/__init__.py +1 -0
- models/modeling_rnnt.py +126 -0
- run_speech_recognition_rnnt.py +789 -0
- run_spgispeech.sh +32 -0
- stt_en_conformer_transducer_xlarge.nemo +3 -0
.gitattributes
CHANGED
@@ -21,7 +21,6 @@
|
|
21 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
22 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
23 |
*.rar filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
25 |
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
26 |
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
27 |
*.tflite filter=lfs diff=lfs merge=lfs -text
|
@@ -31,3 +30,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
31 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
32 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
33 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
21 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
22 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
23 |
*.rar filter=lfs diff=lfs merge=lfs -text
|
|
|
24 |
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
25 |
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
26 |
*.tflite filter=lfs diff=lfs merge=lfs -text
|
|
|
30 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
31 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
32 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.nemo filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language:
|
3 |
+
- en
|
4 |
+
tags:
|
5 |
+
- esb
|
6 |
+
datasets:
|
7 |
+
- esb/datasets
|
8 |
+
- kensho/spgispeech
|
9 |
+
---
|
10 |
+
To reproduce this run, first install NVIDIA NeMo according to the [official instructions](https://github.com/NVIDIA/NeMo#installation), then execute:
|
11 |
+
```python
|
12 |
+
#!/usr/bin/env bash
|
13 |
+
CUDA_VISIBLE_DEVICES=0 python run_speech_recognition_rnnt.py \
|
14 |
+
--config_path="conf/conformer_transducer_bpe_xlarge.yaml" \
|
15 |
+
--model_name_or_path="stt_en_conformer_transducer_xlarge" \
|
16 |
+
--dataset_name="esb/datasets" \
|
17 |
+
--tokenizer_path="tokenizer" \
|
18 |
+
--vocab_size="1024" \
|
19 |
+
--max_steps="100000" \
|
20 |
+
--dataset_config_name="spgispeech" \
|
21 |
+
--output_dir="./" \
|
22 |
+
--run_name="conformer-rnnt-spgispeech" \
|
23 |
+
--wandb_project="rnnt" \
|
24 |
+
--per_device_train_batch_size="8" \
|
25 |
+
--per_device_eval_batch_size="4" \
|
26 |
+
--logging_steps="50" \
|
27 |
+
--learning_rate="1e-4" \
|
28 |
+
--warmup_steps="500" \
|
29 |
+
--save_strategy="steps" \
|
30 |
+
--save_steps="20000" \
|
31 |
+
--evaluation_strategy="steps" \
|
32 |
+
--eval_steps="20000" \
|
33 |
+
--report_to="wandb" \
|
34 |
+
--preprocessing_num_workers="4" \
|
35 |
+
--fused_batch_size="4" \
|
36 |
+
--length_column_name="input_lengths" \
|
37 |
+
--fuse_loss_wer \
|
38 |
+
--group_by_length \
|
39 |
+
--overwrite_output_dir \
|
40 |
+
--do_train \
|
41 |
+
--do_eval \
|
42 |
+
--do_predict \
|
43 |
+
--use_auth_token
|
44 |
+
|
45 |
+
```
|
conf/conformer_transducer_bpe_xlarge.yaml
ADDED
File without changes
|
models/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .modeling_rnnt import RNNTBPEModel
|
models/modeling_rnnt.py
ADDED
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass
|
2 |
+
from typing import Optional
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from nemo.collections.asr.models import EncDecRNNTBPEModel
|
6 |
+
from omegaconf import DictConfig
|
7 |
+
from transformers.utils import ModelOutput
|
8 |
+
|
9 |
+
|
10 |
+
@dataclass
|
11 |
+
class RNNTOutput(ModelOutput):
|
12 |
+
"""
|
13 |
+
Base class for RNNT outputs.
|
14 |
+
"""
|
15 |
+
|
16 |
+
loss: Optional[torch.FloatTensor] = None
|
17 |
+
wer: Optional[float] = None
|
18 |
+
wer_num: Optional[float] = None
|
19 |
+
wer_denom: Optional[float] = None
|
20 |
+
|
21 |
+
|
22 |
+
# Adapted from https://github.com/NVIDIA/NeMo/blob/66c7677cd4a68d78965d4905dd1febbf5385dff3/nemo/collections/asr/models/rnnt_bpe_models.py#L33
|
23 |
+
class RNNTBPEModel(EncDecRNNTBPEModel):
|
24 |
+
def __init__(self, cfg: DictConfig):
|
25 |
+
super().__init__(cfg=cfg, trainer=None)
|
26 |
+
|
27 |
+
def encoding(
|
28 |
+
self, input_signal=None, input_signal_length=None, processed_signal=None, processed_signal_length=None
|
29 |
+
):
|
30 |
+
"""
|
31 |
+
Forward pass of the acoustic model. Note that for RNNT Models, the forward pass of the model is a 3 step process,
|
32 |
+
and this method only performs the first step - forward of the acoustic model.
|
33 |
+
|
34 |
+
Please refer to the `forward` in order to see the full `forward` step for training - which
|
35 |
+
performs the forward of the acoustic model, the prediction network and then the joint network.
|
36 |
+
Finally, it computes the loss and possibly compute the detokenized text via the `decoding` step.
|
37 |
+
|
38 |
+
Please refer to the `validation_step` in order to see the full `forward` step for inference - which
|
39 |
+
performs the forward of the acoustic model, the prediction network and then the joint network.
|
40 |
+
Finally, it computes the decoded tokens via the `decoding` step and possibly compute the batch metrics.
|
41 |
+
|
42 |
+
Args:
|
43 |
+
input_signal: Tensor that represents a batch of raw audio signals,
|
44 |
+
of shape [B, T]. T here represents timesteps, with 1 second of audio represented as
|
45 |
+
`self.sample_rate` number of floating point values.
|
46 |
+
input_signal_length: Vector of length B, that contains the individual lengths of the audio
|
47 |
+
sequences.
|
48 |
+
processed_signal: Tensor that represents a batch of processed audio signals,
|
49 |
+
of shape (B, D, T) that has undergone processing via some DALI preprocessor.
|
50 |
+
processed_signal_length: Vector of length B, that contains the individual lengths of the
|
51 |
+
processed audio sequences.
|
52 |
+
|
53 |
+
Returns:
|
54 |
+
A tuple of 2 elements -
|
55 |
+
1) The log probabilities tensor of shape [B, T, D].
|
56 |
+
2) The lengths of the acoustic sequence after propagation through the encoder, of shape [B].
|
57 |
+
"""
|
58 |
+
has_input_signal = input_signal is not None and input_signal_length is not None
|
59 |
+
has_processed_signal = processed_signal is not None and processed_signal_length is not None
|
60 |
+
if (has_input_signal ^ has_processed_signal) is False:
|
61 |
+
raise ValueError(
|
62 |
+
f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive "
|
63 |
+
" with ``processed_signal`` and ``processed_signal_len`` arguments."
|
64 |
+
)
|
65 |
+
|
66 |
+
if not has_processed_signal:
|
67 |
+
processed_signal, processed_signal_length = self.preprocessor(
|
68 |
+
input_signal=input_signal, length=input_signal_length,
|
69 |
+
)
|
70 |
+
|
71 |
+
# Spec augment is not applied during evaluation/testing
|
72 |
+
if self.spec_augmentation is not None and self.training:
|
73 |
+
processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length)
|
74 |
+
|
75 |
+
encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length)
|
76 |
+
return encoded, encoded_len
|
77 |
+
|
78 |
+
def forward(self, input_ids, input_lengths=None, labels=None, label_lengths=None):
|
79 |
+
# encoding() only performs encoder forward
|
80 |
+
encoded, encoded_len = self.encoding(input_signal=input_ids, input_signal_length=input_lengths)
|
81 |
+
del input_ids
|
82 |
+
|
83 |
+
# During training, loss must be computed, so decoder forward is necessary
|
84 |
+
decoder, target_length, states = self.decoder(targets=labels, target_length=label_lengths)
|
85 |
+
|
86 |
+
# If experimental fused Joint-Loss-WER is not used
|
87 |
+
if not self.joint.fuse_loss_wer:
|
88 |
+
# Compute full joint and loss
|
89 |
+
joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder)
|
90 |
+
loss_value = self.loss(
|
91 |
+
log_probs=joint, targets=labels, input_lengths=encoded_len, target_lengths=target_length
|
92 |
+
)
|
93 |
+
# Add auxiliary losses, if registered
|
94 |
+
loss_value = self.add_auxiliary_losses(loss_value)
|
95 |
+
wer = wer_num = wer_denom = None
|
96 |
+
if not self.training:
|
97 |
+
self.wer.update(encoded, encoded_len, labels, target_length)
|
98 |
+
wer, wer_num, wer_denom = self.wer.compute()
|
99 |
+
self.wer.reset()
|
100 |
+
|
101 |
+
else:
|
102 |
+
# If experimental fused Joint-Loss-WER is used
|
103 |
+
# Fused joint step
|
104 |
+
loss_value, wer, wer_num, wer_denom = self.joint(
|
105 |
+
encoder_outputs=encoded,
|
106 |
+
decoder_outputs=decoder,
|
107 |
+
encoder_lengths=encoded_len,
|
108 |
+
transcripts=labels,
|
109 |
+
transcript_lengths=label_lengths,
|
110 |
+
compute_wer=not self.training,
|
111 |
+
)
|
112 |
+
# Add auxiliary losses, if registered
|
113 |
+
loss_value = self.add_auxiliary_losses(loss_value)
|
114 |
+
|
115 |
+
return RNNTOutput(loss=loss_value, wer=wer, wer_num=wer_num, wer_denom=wer_denom)
|
116 |
+
|
117 |
+
def transcribe(self, input_ids, input_lengths=None, labels=None, label_lengths=None, return_hypotheses: bool = False, partial_hypothesis: Optional = None):
|
118 |
+
encoded, encoded_len = self.encoding(input_signal=input_ids, input_signal_length=input_lengths)
|
119 |
+
del input_ids
|
120 |
+
best_hyp, all_hyp = self.decoding.rnnt_decoder_predictions_tensor(
|
121 |
+
encoded,
|
122 |
+
encoded_len,
|
123 |
+
return_hypotheses=return_hypotheses,
|
124 |
+
partial_hypotheses=partial_hypothesis,
|
125 |
+
)
|
126 |
+
return best_hyp, all_hyp
|
run_speech_recognition_rnnt.py
ADDED
@@ -0,0 +1,789 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""
|
16 |
+
Fine-tuning NVIDIA RNN-T models for speech recognition.
|
17 |
+
"""
|
18 |
+
# You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
|
19 |
+
import copy
|
20 |
+
import logging
|
21 |
+
import os
|
22 |
+
import sys
|
23 |
+
from dataclasses import dataclass, field
|
24 |
+
|
25 |
+
import wandb
|
26 |
+
from torch.utils.data import Dataset
|
27 |
+
from tqdm import tqdm
|
28 |
+
import json
|
29 |
+
from typing import Optional, Dict, Union, List, Any
|
30 |
+
|
31 |
+
import numpy as np
|
32 |
+
import torch
|
33 |
+
|
34 |
+
from omegaconf import OmegaConf
|
35 |
+
from models import RNNTBPEModel
|
36 |
+
|
37 |
+
import datasets
|
38 |
+
from datasets import DatasetDict, load_dataset, load_metric
|
39 |
+
import transformers
|
40 |
+
from transformers import (
|
41 |
+
HfArgumentParser,
|
42 |
+
Seq2SeqTrainingArguments,
|
43 |
+
set_seed,
|
44 |
+
Trainer,
|
45 |
+
)
|
46 |
+
from transformers.trainer_utils import get_last_checkpoint, is_main_process
|
47 |
+
from transformers.utils import check_min_version
|
48 |
+
from transformers.utils.versions import require_version
|
49 |
+
|
50 |
+
from process_asr_text_tokenizer import __process_data as nemo_process_data, \
|
51 |
+
__build_document_from_manifests as nemo_build_document_from_manifests
|
52 |
+
|
53 |
+
|
54 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
55 |
+
check_min_version("4.17.0.dev0")
|
56 |
+
|
57 |
+
require_version("datasets>=1.18.0", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
|
58 |
+
|
59 |
+
logger = logging.getLogger(__name__)
|
60 |
+
|
61 |
+
|
62 |
+
@dataclass
|
63 |
+
class ModelArguments:
|
64 |
+
"""
|
65 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
66 |
+
"""
|
67 |
+
|
68 |
+
config_path: str = field(
|
69 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."},
|
70 |
+
)
|
71 |
+
model_name_or_path: Optional[str] = field(
|
72 |
+
default=None,
|
73 |
+
metadata={"help": "Path to pretrained model or model identifier from NVIDIA NeMo NGC."}
|
74 |
+
)
|
75 |
+
pretrained_model_name_or_path: Optional[str] = field(
|
76 |
+
default=None,
|
77 |
+
metadata={"help": "Path to local pretrained model or model identifier."}
|
78 |
+
)
|
79 |
+
cache_dir: Optional[str] = field(
|
80 |
+
default=None,
|
81 |
+
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co or NVIDIA NeMo NGC."},
|
82 |
+
)
|
83 |
+
use_auth_token: bool = field(
|
84 |
+
default=False,
|
85 |
+
metadata={
|
86 |
+
"help": "Will use the token generated when running `transformers-cli login` (necessary to use this script "
|
87 |
+
"with private models)."
|
88 |
+
},
|
89 |
+
)
|
90 |
+
manifest_path: str = field(
|
91 |
+
default="data",
|
92 |
+
metadata={
|
93 |
+
"help": "Manifest path."
|
94 |
+
},
|
95 |
+
)
|
96 |
+
tokenizer_path: str = field(
|
97 |
+
default="tokenizers",
|
98 |
+
metadata={
|
99 |
+
"help": "Tokenizer path."
|
100 |
+
},
|
101 |
+
)
|
102 |
+
vocab_size: int = field(
|
103 |
+
default=1024,
|
104 |
+
metadata={"help": "Tokenizer vocab size."}
|
105 |
+
)
|
106 |
+
tokenizer_type: str = field(
|
107 |
+
default="spe",
|
108 |
+
metadata={
|
109 |
+
"help": "Can be either spe or wpe. spe refers to the Google sentencepiece library tokenizer."
|
110 |
+
"wpe refers to the HuggingFace BERT Word Piece tokenizer."
|
111 |
+
},
|
112 |
+
)
|
113 |
+
spe_type: str = field(
|
114 |
+
default="bpe",
|
115 |
+
metadata={
|
116 |
+
"help": "Type of the SentencePiece model. Can be `bpe`, `unigram`, `char` or `word`."
|
117 |
+
"Used only if `tokenizer_type` == `spe`"
|
118 |
+
},
|
119 |
+
)
|
120 |
+
cutoff_freq: str = field(
|
121 |
+
default=0.001,
|
122 |
+
metadata={"help": "Drop the least frequent chars from the train set when building the tokenizer."}
|
123 |
+
)
|
124 |
+
fuse_loss_wer: bool = field(
|
125 |
+
default=True,
|
126 |
+
metadata={
|
127 |
+
"help": "Whether to fuse the computation of prediction net + joint net + loss + WER calculation to be run "
|
128 |
+
"on sub-batches of size `fused_batch_size`"
|
129 |
+
}
|
130 |
+
)
|
131 |
+
fused_batch_size: int = field(
|
132 |
+
default=8,
|
133 |
+
metadata={
|
134 |
+
"help": "`fused_batch_size` is the actual batch size of the prediction net, joint net and transducer loss."
|
135 |
+
"Using small values here will preserve a lot of memory during training, but will make training slower as well."
|
136 |
+
"An optimal ratio of fused_batch_size : per_device_train_batch_size is 1:1."
|
137 |
+
"However, to preserve memory, this ratio can be 1:8 or even 1:16."
|
138 |
+
}
|
139 |
+
)
|
140 |
+
final_decoding_strategy: str = field(
|
141 |
+
default="greedy_batch",
|
142 |
+
metadata={
|
143 |
+
"help": "Decoding strategy for final eval/prediction steps. One of: [`greedy`, `greedy_batch`, `beam`, "
|
144 |
+
"`tsd`, `alsd`]."
|
145 |
+
}
|
146 |
+
)
|
147 |
+
final_num_beams: int = field(
|
148 |
+
default=1,
|
149 |
+
metadata={
|
150 |
+
"help": "Number of beams for final eval/prediction steps. Increase beam size for better scores, "
|
151 |
+
"but it will take much longer for transcription!"
|
152 |
+
}
|
153 |
+
)
|
154 |
+
|
155 |
+
|
156 |
+
@dataclass
|
157 |
+
class DataTrainingArguments:
|
158 |
+
"""
|
159 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
160 |
+
"""
|
161 |
+
|
162 |
+
dataset_name: str = field(
|
163 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
164 |
+
)
|
165 |
+
dataset_config_name: Optional[str] = field(
|
166 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
167 |
+
)
|
168 |
+
text_column: Optional[str] = field(
|
169 |
+
default=None,
|
170 |
+
metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
|
171 |
+
)
|
172 |
+
dataset_cache_dir: Optional[str] = field(
|
173 |
+
default=None, metadata={"help": "Path to cache directory for saving and loading datasets"}
|
174 |
+
)
|
175 |
+
overwrite_cache: bool = field(
|
176 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
177 |
+
)
|
178 |
+
preprocessing_num_workers: Optional[int] = field(
|
179 |
+
default=None,
|
180 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
181 |
+
)
|
182 |
+
max_train_samples: Optional[int] = field(
|
183 |
+
default=None,
|
184 |
+
metadata={
|
185 |
+
"help": "For debugging purposes or quicker training, truncate the number of training examples to this "
|
186 |
+
"value if set."
|
187 |
+
},
|
188 |
+
)
|
189 |
+
max_eval_samples: Optional[int] = field(
|
190 |
+
default=None,
|
191 |
+
metadata={
|
192 |
+
"help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
193 |
+
"value if set."
|
194 |
+
},
|
195 |
+
)
|
196 |
+
max_predict_samples: Optional[int] = field(
|
197 |
+
default=None,
|
198 |
+
metadata={
|
199 |
+
"help": "For debugging purposes or quicker training, truncate the number of test examples to this "
|
200 |
+
"value if set."
|
201 |
+
},
|
202 |
+
)
|
203 |
+
audio_column_name: str = field(
|
204 |
+
default="audio",
|
205 |
+
metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
|
206 |
+
)
|
207 |
+
text_column_name: str = field(
|
208 |
+
default="text",
|
209 |
+
metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
|
210 |
+
)
|
211 |
+
max_duration_in_seconds: float = field(
|
212 |
+
default=20.0,
|
213 |
+
metadata={
|
214 |
+
"help": "Truncate training audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
|
215 |
+
},
|
216 |
+
)
|
217 |
+
min_duration_in_seconds: float = field(
|
218 |
+
default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
|
219 |
+
)
|
220 |
+
max_eval_duration_in_seconds: float = field(
|
221 |
+
default=None,
|
222 |
+
metadata={
|
223 |
+
"help": "Truncate eval/test audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
|
224 |
+
},
|
225 |
+
)
|
226 |
+
max_target_length: Optional[int] = field(
|
227 |
+
default=128,
|
228 |
+
metadata={
|
229 |
+
"help": "The maximum total sequence length for target text after tokenization. Sequences longer "
|
230 |
+
"than this will be truncated, sequences shorter will be padded."
|
231 |
+
},
|
232 |
+
)
|
233 |
+
min_target_length: Optional[int] = field(
|
234 |
+
default=2,
|
235 |
+
metadata={
|
236 |
+
"help": "The minimum total sequence length for target text after tokenization. Sequences shorter "
|
237 |
+
"than this will be filtered."
|
238 |
+
},
|
239 |
+
)
|
240 |
+
preprocessing_only: bool = field(
|
241 |
+
default=False,
|
242 |
+
metadata={
|
243 |
+
"help": "Whether to only do data preprocessing and skip training. "
|
244 |
+
"This is especially useful when data preprocessing errors out in distributed training due to timeout. "
|
245 |
+
"In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
|
246 |
+
"so that the cached datasets can consequently be loaded in distributed training"
|
247 |
+
},
|
248 |
+
)
|
249 |
+
train_split_name: str = field(
|
250 |
+
default="train",
|
251 |
+
metadata={
|
252 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
253 |
+
},
|
254 |
+
)
|
255 |
+
eval_split_name: str = field(
|
256 |
+
default="validation",
|
257 |
+
metadata={
|
258 |
+
"help": "The name of the evaluation data set split to use (via the datasets library). Defaults to 'validation'"
|
259 |
+
},
|
260 |
+
)
|
261 |
+
test_split_name: str = field(
|
262 |
+
default="test",
|
263 |
+
metadata={"help": "The name of the test data set split to use (via the datasets library). Defaults to 'test'"},
|
264 |
+
)
|
265 |
+
do_lower_case: bool = field(
|
266 |
+
default=True,
|
267 |
+
metadata={"help": "Whether the target text should be lower cased."},
|
268 |
+
)
|
269 |
+
wandb_project: str = field(
|
270 |
+
default="speech-recognition-rnnt",
|
271 |
+
metadata={"help": "The name of the wandb project."},
|
272 |
+
)
|
273 |
+
|
274 |
+
|
275 |
+
def write_wandb_pred(pred_str, label_str, prefix="eval"):
|
276 |
+
# convert str data to a wandb compatible format
|
277 |
+
str_data = [[label_str[i], pred_str[i]] for i in range(len(pred_str))]
|
278 |
+
# we'll log all predictions for the last epoch
|
279 |
+
wandb.log(
|
280 |
+
{
|
281 |
+
f"{prefix}/predictions": wandb.Table(
|
282 |
+
columns=["label_str", "pred_str"], data=str_data
|
283 |
+
)
|
284 |
+
},
|
285 |
+
)
|
286 |
+
|
287 |
+
|
288 |
+
def build_tokenizer(model_args, data_args, manifests):
|
289 |
+
"""
|
290 |
+
Function to build a NeMo tokenizer from manifest file(s).
|
291 |
+
Copied from https://github.com/NVIDIA/NeMo/blob/66c7677cd4a68d78965d4905dd1febbf5385dff3/scripts/tokenizers/process_asr_text_tokenizer.py#L268
|
292 |
+
"""
|
293 |
+
data_root = model_args.tokenizer_path
|
294 |
+
if isinstance(manifests, list):
|
295 |
+
joint_manifests = ",".join(manifests)
|
296 |
+
else:
|
297 |
+
joint_manifests = manifests
|
298 |
+
vocab_size = model_args.vocab_size
|
299 |
+
tokenizer = model_args.tokenizer_type
|
300 |
+
spe_type = model_args.spe_type
|
301 |
+
if not 0 <= model_args.cutoff_freq < 1:
|
302 |
+
raise ValueError(f"`cutoff_freq` must be between zero and one, got {model_args.cutoff_freq}")
|
303 |
+
spe_character_coverage = 1 - model_args.cutoff_freq
|
304 |
+
|
305 |
+
logger.info("Building tokenizer...")
|
306 |
+
if not os.path.exists(data_root):
|
307 |
+
os.makedirs(data_root)
|
308 |
+
|
309 |
+
text_corpus_path = nemo_build_document_from_manifests(data_root, joint_manifests)
|
310 |
+
|
311 |
+
tokenizer_path = nemo_process_data(
|
312 |
+
text_corpus_path,
|
313 |
+
data_root,
|
314 |
+
vocab_size,
|
315 |
+
tokenizer,
|
316 |
+
spe_type,
|
317 |
+
lower_case=data_args.do_lower_case,
|
318 |
+
spe_character_coverage=spe_character_coverage,
|
319 |
+
spe_sample_size=-1,
|
320 |
+
spe_train_extremely_large_corpus=False,
|
321 |
+
spe_max_sentencepiece_length=-1,
|
322 |
+
spe_bos=False,
|
323 |
+
spe_eos=False,
|
324 |
+
spe_pad=False,
|
325 |
+
)
|
326 |
+
|
327 |
+
print("Serialized tokenizer at location :", tokenizer_path)
|
328 |
+
logger.info('Done!')
|
329 |
+
|
330 |
+
# Tokenizer path
|
331 |
+
if tokenizer == 'spe':
|
332 |
+
tokenizer_dir = os.path.join(data_root, f"tokenizer_spe_{spe_type}_v{vocab_size}")
|
333 |
+
tokenizer_type_cfg = "bpe"
|
334 |
+
else:
|
335 |
+
tokenizer_dir = os.path.join(data_root, f"tokenizer_wpe_v{vocab_size}")
|
336 |
+
tokenizer_type_cfg = "wpe"
|
337 |
+
|
338 |
+
return tokenizer_dir, tokenizer_type_cfg
|
339 |
+
|
340 |
+
|
341 |
+
def NeMoDataCollator(features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
342 |
+
"""
|
343 |
+
Data collator that will dynamically pad the inputs received.
|
344 |
+
Since NeMo models don't have a HF processor defined (feature extractor + tokenizer), we'll pad by hand...
|
345 |
+
The padding idx is arbitrary: we provide the model with the input lengths and label lengths, from which
|
346 |
+
all the relevant padding information is inferred. Thus, we'll use the default np.pad padding idx (0).
|
347 |
+
"""
|
348 |
+
# split inputs and labels since they have to be of different lengths
|
349 |
+
# and need different padding methods
|
350 |
+
input_ids = [feature["input_ids"] for feature in features]
|
351 |
+
labels = [feature["labels"] for feature in features]
|
352 |
+
|
353 |
+
# first, pad the audio inputs to max_len
|
354 |
+
input_lengths = [feature["input_lengths"] for feature in features]
|
355 |
+
max_input_len = max(input_lengths)
|
356 |
+
input_ids = [np.pad(input_val, (0, max_input_len - input_len), 'constant') for input_val, input_len in
|
357 |
+
zip(input_ids, input_lengths)]
|
358 |
+
|
359 |
+
# next, pad the target labels to max_len
|
360 |
+
label_lengths = [len(lab) for lab in labels]
|
361 |
+
max_label_len = max(label_lengths)
|
362 |
+
labels = [np.pad(lab, (0, max_label_len - lab_len), 'constant') for lab, lab_len in zip(labels, label_lengths)]
|
363 |
+
|
364 |
+
batch = {"input_lengths": input_lengths, "labels": labels, "label_lengths": label_lengths}
|
365 |
+
|
366 |
+
# return batch as a pt tensor (list -> np.array -> torch.tensor)
|
367 |
+
batch = {k: torch.tensor(np.array(v), requires_grad=False) for k, v in batch.items()}
|
368 |
+
|
369 |
+
# leave all ints as are, convert float64 to pt float
|
370 |
+
batch["input_ids"] = torch.tensor(np.array(input_ids, dtype=np.float32), requires_grad=False)
|
371 |
+
|
372 |
+
return batch
|
373 |
+
|
374 |
+
|
375 |
+
def main():
|
376 |
+
# See all possible arguments in src/transformers/training_args.py
|
377 |
+
# or by passing the --help flag to this script.
|
378 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
379 |
+
|
380 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
381 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
382 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
383 |
+
# let's parse it to get our arguments.
|
384 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
385 |
+
else:
|
386 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
387 |
+
|
388 |
+
# Set wandb project ID before instantiating the Trainer
|
389 |
+
os.environ["WANDB_PROJECT"] = data_args.wandb_project
|
390 |
+
|
391 |
+
# Detecting last checkpoint.
|
392 |
+
last_checkpoint = None
|
393 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
394 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
395 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
396 |
+
raise ValueError(
|
397 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
398 |
+
"Use --overwrite_output_dir to overcome."
|
399 |
+
)
|
400 |
+
elif last_checkpoint is not None:
|
401 |
+
logger.info(
|
402 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
403 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
404 |
+
)
|
405 |
+
|
406 |
+
# Setup logging
|
407 |
+
logging.basicConfig(
|
408 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
409 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
410 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
411 |
+
)
|
412 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
413 |
+
|
414 |
+
# Log on each process the small summary:
|
415 |
+
logger.warning(
|
416 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
417 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
418 |
+
)
|
419 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
420 |
+
if is_main_process(training_args.local_rank):
|
421 |
+
transformers.utils.logging.set_verbosity_info()
|
422 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
423 |
+
|
424 |
+
# Set seed before initializing model.
|
425 |
+
set_seed(training_args.seed)
|
426 |
+
|
427 |
+
# load the model config (discarding optimiser and trainer attributes)
|
428 |
+
config = OmegaConf.load(model_args.config_path).model
|
429 |
+
|
430 |
+
# 4. Load dataset
|
431 |
+
raw_datasets = DatasetDict()
|
432 |
+
|
433 |
+
if training_args.do_train:
|
434 |
+
raw_datasets["train"] = load_dataset(
|
435 |
+
data_args.dataset_name,
|
436 |
+
data_args.dataset_config_name,
|
437 |
+
split=data_args.train_split_name,
|
438 |
+
cache_dir=data_args.dataset_cache_dir,
|
439 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
440 |
+
)
|
441 |
+
|
442 |
+
if training_args.do_eval:
|
443 |
+
raw_datasets["eval"] = load_dataset(
|
444 |
+
data_args.dataset_name,
|
445 |
+
data_args.dataset_config_name,
|
446 |
+
split=data_args.eval_split_name,
|
447 |
+
cache_dir=data_args.dataset_cache_dir,
|
448 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
449 |
+
)
|
450 |
+
|
451 |
+
if training_args.do_predict:
|
452 |
+
test_split = data_args.test_split_name.split("+")
|
453 |
+
for split in test_split:
|
454 |
+
raw_datasets[split] = load_dataset(
|
455 |
+
data_args.dataset_name,
|
456 |
+
data_args.dataset_config_name,
|
457 |
+
split=split,
|
458 |
+
cache_dir=data_args.dataset_cache_dir,
|
459 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
460 |
+
)
|
461 |
+
|
462 |
+
if not training_args.do_train and not training_args.do_eval and not training_args.do_predict:
|
463 |
+
raise ValueError(
|
464 |
+
"Cannot not train, not do evaluation and not do prediction. At least one of "
|
465 |
+
"training, evaluation or prediction has to be done."
|
466 |
+
)
|
467 |
+
|
468 |
+
# if not training, there is no need to run multiple epochs
|
469 |
+
if not training_args.do_train:
|
470 |
+
training_args.num_train_epochs = 1
|
471 |
+
|
472 |
+
if data_args.audio_column_name not in next(iter(raw_datasets.values())).column_names:
|
473 |
+
raise ValueError(
|
474 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
|
475 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
476 |
+
f"{', '.join(next(iter(raw_datasets.values())).column_names)}."
|
477 |
+
)
|
478 |
+
|
479 |
+
if data_args.text_column_name not in next(iter(raw_datasets.values())).column_names:
|
480 |
+
raise ValueError(
|
481 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
|
482 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
483 |
+
f"{', '.join(next(iter(raw_datasets.values())).column_names)}."
|
484 |
+
)
|
485 |
+
|
486 |
+
# 6. Resample speech dataset ALWAYS
|
487 |
+
raw_datasets = raw_datasets.cast_column(
|
488 |
+
data_args.audio_column_name, datasets.features.Audio(sampling_rate=config.sample_rate)
|
489 |
+
)
|
490 |
+
|
491 |
+
# 7. Preprocessing the datasets.
|
492 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
493 |
+
max_input_length = int(data_args.max_duration_in_seconds * config.sample_rate)
|
494 |
+
min_input_length = max(int(data_args.min_duration_in_seconds * config.sample_rate), 1)
|
495 |
+
max_eval_input_length = int(data_args.max_eval_duration_in_seconds * config.sample_rate) if data_args.max_eval_duration_in_seconds else None
|
496 |
+
audio_column_name = data_args.audio_column_name
|
497 |
+
num_workers = data_args.preprocessing_num_workers
|
498 |
+
text_column_name = data_args.text_column_name
|
499 |
+
|
500 |
+
if training_args.do_train and data_args.max_train_samples is not None:
|
501 |
+
raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
|
502 |
+
|
503 |
+
if training_args.do_eval and data_args.max_eval_samples is not None:
|
504 |
+
raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
|
505 |
+
|
506 |
+
if training_args.do_predict and data_args.max_predict_samples is not None:
|
507 |
+
for split in test_split:
|
508 |
+
raw_datasets[split] = raw_datasets[split].select(range(data_args.max_predict_samples))
|
509 |
+
|
510 |
+
# Function to build a NeMo tokenizer manifest from a HF dataset
|
511 |
+
# TODO: with a bit of hacking around we can probably bypass this step entirely
|
512 |
+
def build_manifest(ds, manifest_path):
|
513 |
+
with open(manifest_path, 'w') as fout:
|
514 |
+
for sample in tqdm(ds[text_column_name]):
|
515 |
+
# Write the metadata to the manifest
|
516 |
+
metadata = {
|
517 |
+
"text": sample
|
518 |
+
}
|
519 |
+
json.dump(metadata, fout)
|
520 |
+
fout.write('\n')
|
521 |
+
|
522 |
+
config.train_ds = config.validation_ds = config.test_ds = None
|
523 |
+
|
524 |
+
if not os.path.exists(model_args.manifest_path) and training_args.do_train:
|
525 |
+
os.makedirs(model_args.manifest_path)
|
526 |
+
manifest = os.path.join(model_args.manifest_path, "train.json")
|
527 |
+
logger.info(f"Building training manifest at {manifest}")
|
528 |
+
build_manifest(raw_datasets["train"], manifest)
|
529 |
+
else:
|
530 |
+
manifest = os.path.join(model_args.manifest_path, "train.json")
|
531 |
+
logger.info(f"Re-using training manifest at {manifest}")
|
532 |
+
|
533 |
+
tokenizer_dir, tokenizer_type_cfg = build_tokenizer(model_args, data_args, manifest)
|
534 |
+
|
535 |
+
# generalise the script later to load a pre-built tokenizer for eval only
|
536 |
+
config.tokenizer.dir = tokenizer_dir
|
537 |
+
config.tokenizer.type = tokenizer_type_cfg
|
538 |
+
|
539 |
+
# possibly fused-computation of prediction net + joint net + loss + WER calculation
|
540 |
+
config.joint.fuse_loss_wer = model_args.fuse_loss_wer
|
541 |
+
if model_args.fuse_loss_wer:
|
542 |
+
config.joint.fused_batch_size = model_args.fused_batch_size
|
543 |
+
|
544 |
+
if model_args.model_name_or_path is not None:
|
545 |
+
# load pre-trained model weights
|
546 |
+
model = RNNTBPEModel.from_pretrained(model_args.model_name_or_path, override_config_path=config,
|
547 |
+
map_location="cpu")
|
548 |
+
model.save_name = model_args.model_name_or_path
|
549 |
+
|
550 |
+
pretrained_decoder = model.decoder.state_dict()
|
551 |
+
pretrained_joint = model.joint.state_dict()
|
552 |
+
model.change_vocabulary(new_tokenizer_dir=tokenizer_dir, new_tokenizer_type=tokenizer_type_cfg)
|
553 |
+
|
554 |
+
# TODO: add checks for loading decoder/joint state dict
|
555 |
+
model.decoder.load_state_dict(pretrained_decoder)
|
556 |
+
model.joint.load_state_dict(pretrained_joint)
|
557 |
+
|
558 |
+
elif model_args.pretrained_model_name_or_path is not None:
|
559 |
+
model = RNNTBPEModel.restore_from(model_args.pretrained_model_name_or_path, override_config_path=config,
|
560 |
+
map_location="cpu")
|
561 |
+
model.save_name = model_args.config_path.split("/")[-1].split(".")[0]
|
562 |
+
|
563 |
+
else:
|
564 |
+
model = RNNTBPEModel(cfg=config)
|
565 |
+
model.save_name = model_args.config_path.split("/")[-1].split(".")[0]
|
566 |
+
model.change_vocabulary(new_tokenizer_dir=tokenizer_dir, new_tokenizer_type=tokenizer_type_cfg)
|
567 |
+
|
568 |
+
# now that we have our model and tokenizer defined, we can tokenize the text data
|
569 |
+
tokenizer = model.tokenizer.tokenizer.encode_as_ids
|
570 |
+
|
571 |
+
def prepare_dataset(batch):
|
572 |
+
# pre-process audio
|
573 |
+
sample = batch[audio_column_name]
|
574 |
+
|
575 |
+
# NeMo RNNT model performs the audio preprocessing in the `.forward()` call
|
576 |
+
# => we only need to supply it with the raw audio values
|
577 |
+
batch["input_ids"] = sample["array"]
|
578 |
+
batch["input_lengths"] = len(sample["array"])
|
579 |
+
|
580 |
+
batch["labels"] = tokenizer(batch[text_column_name])
|
581 |
+
return batch
|
582 |
+
|
583 |
+
vectorized_datasets = raw_datasets.map(
|
584 |
+
prepare_dataset,
|
585 |
+
remove_columns=next(iter(raw_datasets.values())).column_names,
|
586 |
+
num_proc=num_workers,
|
587 |
+
desc="preprocess train dataset",
|
588 |
+
)
|
589 |
+
|
590 |
+
# filter training data with inputs shorter than min_input_length or longer than max_input_length
|
591 |
+
def is_audio_in_length_range(length):
|
592 |
+
return min_input_length < length < max_input_length
|
593 |
+
|
594 |
+
vectorized_datasets = vectorized_datasets.filter(
|
595 |
+
is_audio_in_length_range,
|
596 |
+
num_proc=num_workers,
|
597 |
+
input_columns=["input_lengths"],
|
598 |
+
)
|
599 |
+
|
600 |
+
if max_eval_input_length is not None:
|
601 |
+
# filter training data with inputs longer than max_input_length
|
602 |
+
def is_eval_audio_in_length_range(length):
|
603 |
+
return min_input_length < length < max_eval_input_length
|
604 |
+
|
605 |
+
vectorized_datasets = vectorized_datasets.filter(
|
606 |
+
is_eval_audio_in_length_range,
|
607 |
+
num_proc=num_workers,
|
608 |
+
input_columns=["input_lengths"],
|
609 |
+
)
|
610 |
+
|
611 |
+
# for large datasets it is advised to run the preprocessing on a
|
612 |
+
# single machine first with `args.preprocessing_only` since there will mostly likely
|
613 |
+
# be a timeout when running the script in distributed mode.
|
614 |
+
# In a second step `args.preprocessing_only` can then be set to `False` to load the
|
615 |
+
# cached dataset
|
616 |
+
if data_args.preprocessing_only:
|
617 |
+
cache = {k: v.cache_files for k, v in vectorized_datasets.items()}
|
618 |
+
logger.info(f"Data preprocessing finished. Files cached at {cache}.")
|
619 |
+
return
|
620 |
+
|
621 |
+
|
622 |
+
def compute_metrics(pred):
|
623 |
+
# Tuple of WERs returned by the model during eval: (wer, wer_num, wer_denom)
|
624 |
+
wer_num = pred.predictions[1]
|
625 |
+
wer_denom = pred.predictions[2]
|
626 |
+
# compute WERs over concat batches
|
627 |
+
wer = sum(wer_num) / sum(wer_denom)
|
628 |
+
return {"wer": wer}
|
629 |
+
|
630 |
+
|
631 |
+
class NeMoTrainer(Trainer):
|
632 |
+
def _save(self, output_dir: Optional[str] = None, state_dict=None):
|
633 |
+
# If we are executing this function, we are the process zero, so we don't check for that.
|
634 |
+
output_dir = output_dir if output_dir is not None else self.args.output_dir
|
635 |
+
os.makedirs(output_dir, exist_ok=True)
|
636 |
+
logger.info(f"Saving model checkpoint to {output_dir}")
|
637 |
+
# Save a trained model and configuration using `save_pretrained()`.
|
638 |
+
# They can then be reloaded using `from_pretrained()`
|
639 |
+
self.model.save_to(save_path=os.path.join(output_dir, model.save_name + ".nemo"))
|
640 |
+
# Good practice: save your training arguments together with the trained model
|
641 |
+
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
|
642 |
+
|
643 |
+
def transcribe(self, test_dataset: Dataset) -> List[Any]:
|
644 |
+
self.model.eval()
|
645 |
+
test_dataloader = self.get_test_dataloader(test_dataset)
|
646 |
+
hypotheses = []
|
647 |
+
for test_batch in tqdm(test_dataloader, desc="Transcribing"):
|
648 |
+
inputs = self._prepare_inputs(test_batch)
|
649 |
+
best_hyp, all_hyp = self.model.transcribe(**inputs)
|
650 |
+
hypotheses += best_hyp
|
651 |
+
del test_batch
|
652 |
+
return hypotheses
|
653 |
+
|
654 |
+
|
655 |
+
# Initialize Trainer
|
656 |
+
trainer = NeMoTrainer(
|
657 |
+
model=model,
|
658 |
+
args=training_args,
|
659 |
+
compute_metrics=compute_metrics,
|
660 |
+
train_dataset=vectorized_datasets['train'] if training_args.do_train else None,
|
661 |
+
eval_dataset=vectorized_datasets['eval'] if training_args.do_eval else None,
|
662 |
+
data_collator=NeMoDataCollator,
|
663 |
+
)
|
664 |
+
|
665 |
+
# 8. Finally, we can start training
|
666 |
+
|
667 |
+
# Training
|
668 |
+
if training_args.do_train:
|
669 |
+
|
670 |
+
# use last checkpoint if exist
|
671 |
+
if last_checkpoint is not None:
|
672 |
+
checkpoint = last_checkpoint
|
673 |
+
elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path):
|
674 |
+
checkpoint = model_args.model_name_or_path
|
675 |
+
else:
|
676 |
+
checkpoint = None
|
677 |
+
|
678 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
679 |
+
trainer.save_model()
|
680 |
+
|
681 |
+
metrics = train_result.metrics
|
682 |
+
max_train_samples = (
|
683 |
+
data_args.max_train_samples
|
684 |
+
if data_args.max_train_samples is not None
|
685 |
+
else len(vectorized_datasets["train"])
|
686 |
+
)
|
687 |
+
metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
|
688 |
+
|
689 |
+
trainer.log_metrics("train", metrics)
|
690 |
+
trainer.save_metrics("train", metrics)
|
691 |
+
trainer.save_state()
|
692 |
+
|
693 |
+
# Change decoding strategy for final eval/predict
|
694 |
+
if training_args.do_eval or training_args.do_predict:
|
695 |
+
# set beam search decoding config
|
696 |
+
beam_decoding_config = copy.deepcopy(trainer.model.cfg.decoding)
|
697 |
+
beam_decoding_config.strategy = model_args.final_decoding_strategy
|
698 |
+
beam_decoding_config.beam.beam_size = model_args.final_num_beams
|
699 |
+
|
700 |
+
trainer.model.change_decoding_strategy(beam_decoding_config)
|
701 |
+
|
702 |
+
results = {}
|
703 |
+
if training_args.do_eval:
|
704 |
+
logger.info(f"*** Running Final Evaluation ({model_args.final_decoding_strategy}) ***")
|
705 |
+
|
706 |
+
predictions = trainer.transcribe(vectorized_datasets["eval"])
|
707 |
+
targets = model.tokenizer.ids_to_text(vectorized_datasets["eval"]["labels"])
|
708 |
+
|
709 |
+
cer_metric = load_metric("cer")
|
710 |
+
wer_metric = load_metric("wer")
|
711 |
+
|
712 |
+
cer = cer_metric.compute(predictions=predictions, references=targets)
|
713 |
+
wer = wer_metric.compute(predictions=predictions, references=targets)
|
714 |
+
|
715 |
+
metrics = {f"eval_cer": cer, f"eval_wer": wer}
|
716 |
+
|
717 |
+
max_eval_samples = (
|
718 |
+
data_args.max_eval_samples if data_args.max_eval_samples is not None else len(
|
719 |
+
vectorized_datasets["eval"])
|
720 |
+
)
|
721 |
+
metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
|
722 |
+
|
723 |
+
trainer.log_metrics("eval", metrics)
|
724 |
+
trainer.save_metrics("eval", metrics)
|
725 |
+
|
726 |
+
if "wandb" in training_args.report_to:
|
727 |
+
if not training_args.do_train:
|
728 |
+
wandb.init(name=training_args.run_name, project=data_args.wandb_project)
|
729 |
+
metrics = {os.path.join("eval", k[len("eval") + 1:]): v for k, v in metrics.items()}
|
730 |
+
# wandb.init(project=data_args.wandb_project, name=training_args.run_name)
|
731 |
+
wandb.log(metrics)
|
732 |
+
write_wandb_pred(predictions, targets, prefix="eval")
|
733 |
+
|
734 |
+
if training_args.do_predict:
|
735 |
+
logger.info(f"*** Running Final Prediction ({model_args.final_decoding_strategy}) ***")
|
736 |
+
|
737 |
+
for split in test_split:
|
738 |
+
predictions = trainer.transcribe(vectorized_datasets[split])
|
739 |
+
targets = model.tokenizer.ids_to_text(vectorized_datasets[split]["labels"])
|
740 |
+
|
741 |
+
cer_metric = load_metric("cer")
|
742 |
+
wer_metric = load_metric("wer")
|
743 |
+
|
744 |
+
cer = cer_metric.compute(predictions=predictions, references=targets)
|
745 |
+
wer = wer_metric.compute(predictions=predictions, references=targets)
|
746 |
+
|
747 |
+
metrics = {f"{split}_cer": cer, f"{split}_wer": wer}
|
748 |
+
|
749 |
+
max_predict_samples = (
|
750 |
+
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(
|
751 |
+
vectorized_datasets[split])
|
752 |
+
)
|
753 |
+
metrics[f"{split}_samples"] = min(max_predict_samples, len(vectorized_datasets[split]))
|
754 |
+
|
755 |
+
trainer.log_metrics(split, metrics)
|
756 |
+
trainer.save_metrics(split, metrics)
|
757 |
+
|
758 |
+
if "wandb" in training_args.report_to:
|
759 |
+
if not training_args.do_train or training_args.do_eval:
|
760 |
+
wandb.init(name=training_args.run_name, project=data_args.wandb_project)
|
761 |
+
metrics = {os.path.join(split, k[len(split) + 1:]): v for k, v in metrics.items()}
|
762 |
+
wandb.log(metrics)
|
763 |
+
write_wandb_pred(predictions, targets, prefix=split)
|
764 |
+
|
765 |
+
# Write model card and (optionally) push to hub
|
766 |
+
config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
|
767 |
+
kwargs = {
|
768 |
+
"finetuned_from": model_args.model_name_or_path,
|
769 |
+
"tasks": "speech-recognition",
|
770 |
+
"tags": ["automatic-speech-recognition", data_args.dataset_name],
|
771 |
+
"dataset_args": (
|
772 |
+
f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split:"
|
773 |
+
f" {data_args.eval_split_name}"
|
774 |
+
),
|
775 |
+
"dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
|
776 |
+
}
|
777 |
+
if "common_voice" in data_args.dataset_name:
|
778 |
+
kwargs["language"] = config_name
|
779 |
+
|
780 |
+
if training_args.push_to_hub:
|
781 |
+
trainer.push_to_hub(**kwargs)
|
782 |
+
#else:
|
783 |
+
#trainer.create_model_card(**kwargs)
|
784 |
+
|
785 |
+
return results
|
786 |
+
|
787 |
+
|
788 |
+
if __name__ == "__main__":
|
789 |
+
main()
|
run_spgispeech.sh
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env bash
|
2 |
+
CUDA_VISIBLE_DEVICES=0 python run_speech_recognition_rnnt.py \
|
3 |
+
--config_path="conf/conformer_transducer_bpe_xlarge.yaml" \
|
4 |
+
--model_name_or_path="stt_en_conformer_transducer_xlarge" \
|
5 |
+
--dataset_name="esb/datasets" \
|
6 |
+
--tokenizer_path="tokenizer" \
|
7 |
+
--vocab_size="1024" \
|
8 |
+
--max_steps="100000" \
|
9 |
+
--dataset_config_name="spgispeech" \
|
10 |
+
--output_dir="./" \
|
11 |
+
--run_name="conformer-rnnt-spgispeech" \
|
12 |
+
--wandb_project="rnnt" \
|
13 |
+
--per_device_train_batch_size="8" \
|
14 |
+
--per_device_eval_batch_size="4" \
|
15 |
+
--logging_steps="50" \
|
16 |
+
--learning_rate="1e-4" \
|
17 |
+
--warmup_steps="500" \
|
18 |
+
--save_strategy="steps" \
|
19 |
+
--save_steps="20000" \
|
20 |
+
--evaluation_strategy="steps" \
|
21 |
+
--eval_steps="20000" \
|
22 |
+
--report_to="wandb" \
|
23 |
+
--preprocessing_num_workers="4" \
|
24 |
+
--fused_batch_size="4" \
|
25 |
+
--length_column_name="input_lengths" \
|
26 |
+
--fuse_loss_wer \
|
27 |
+
--group_by_length \
|
28 |
+
--overwrite_output_dir \
|
29 |
+
--do_train \
|
30 |
+
--do_eval \
|
31 |
+
--do_predict \
|
32 |
+
--use_auth_token
|
stt_en_conformer_transducer_xlarge.nemo
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6619304cc9b9924096b38299fc8ad959ff9ba079ac9cc980429a49d1cfc57d1b
|
3 |
+
size 2577971200
|