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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env/python3
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import DataLoader
|
| 8 |
+
import torchaudio
|
| 9 |
+
from hyperpyyaml import load_hyperpyyaml
|
| 10 |
+
|
| 11 |
+
import speechbrain as sb
|
| 12 |
+
from speechbrain.utils.data_utils import undo_padding
|
| 13 |
+
from speechbrain.utils.distributed import if_main_process, run_on_main
|
| 14 |
+
import logging
|
| 15 |
+
from transformers import AutoTokenizer
|
| 16 |
+
|
| 17 |
+
from jiwer import wer, cer
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Define training procedure
|
| 23 |
+
class ASR(sb.Brain):
|
| 24 |
+
def compute_forward(self, batch, stage):
|
| 25 |
+
"""Forward computations from the waveform batches to the output probabilities."""
|
| 26 |
+
batch = batch.to(self.device)
|
| 27 |
+
wavs, wav_lens = batch.sig
|
| 28 |
+
bos_tokens, bos_tokens_lens = batch.tokens_bos
|
| 29 |
+
|
| 30 |
+
if stage == sb.Stage.TRAIN:
|
| 31 |
+
wavs, self.wav_lens = self.hparams.wav_augment(wavs, wav_lens)
|
| 32 |
+
|
| 33 |
+
# We compute the padding mask and replace the values with the pad_token_id
|
| 34 |
+
# that the Whisper decoder expect to see.
|
| 35 |
+
abs_tokens_lens = (bos_tokens_lens * bos_tokens.shape[1]).long()
|
| 36 |
+
pad_mask = (torch.arange(abs_tokens_lens.max(), device=self.device)[None, :] < abs_tokens_lens[:, None])
|
| 37 |
+
bos_tokens[~pad_mask] = self.tokenizer.pad_token_id
|
| 38 |
+
|
| 39 |
+
# Forward encoder + decoder
|
| 40 |
+
enc_out, logits, _ = self.modules.whisper(wavs, bos_tokens)
|
| 41 |
+
log_probs = self.hparams.log_softmax(logits)
|
| 42 |
+
|
| 43 |
+
hyps = None
|
| 44 |
+
if stage == sb.Stage.VALID:
|
| 45 |
+
hyps, _, _, _ = self.hparams.valid_search(enc_out.detach(), wav_lens)
|
| 46 |
+
elif stage == sb.Stage.TEST:
|
| 47 |
+
hyps, _, _, _ = self.hparams.test_search(enc_out.detach(), wav_lens)
|
| 48 |
+
|
| 49 |
+
return log_probs, hyps, wav_lens
|
| 50 |
+
|
| 51 |
+
def compute_objectives(self, predictions, batch, stage):
|
| 52 |
+
"""Computes the loss NLL given predictions and targets."""
|
| 53 |
+
|
| 54 |
+
(log_probs, hyps, wav_lens) = predictions
|
| 55 |
+
batch = batch.to(self.device)
|
| 56 |
+
ids = batch.id
|
| 57 |
+
tokens_eos, tokens_eos_lens = batch.tokens_eos
|
| 58 |
+
|
| 59 |
+
# Augment Labels
|
| 60 |
+
# if stage == sb.Stage.TRAIN and hasattr(self.hparams, "wav_augment"):
|
| 61 |
+
# tokens_eos = self.hparams.wav_augment.replicate_labels(tokens_eos)
|
| 62 |
+
# tokens_eos_lens = self.hparams.wav_augment.replicate_labels(
|
| 63 |
+
# tokens_eos_lens
|
| 64 |
+
# )
|
| 65 |
+
|
| 66 |
+
loss = self.hparams.nll_loss(log_probs, tokens_eos, length=tokens_eos_lens)
|
| 67 |
+
|
| 68 |
+
if stage != sb.Stage.TRAIN:
|
| 69 |
+
tokens, tokens_lens = batch.tokens
|
| 70 |
+
|
| 71 |
+
# Decode token terms to words
|
| 72 |
+
predicted_words = [self.tokenizer.decode(t, skip_special_tokens=True).strip() for t in hyps]
|
| 73 |
+
|
| 74 |
+
# Convert indices to words
|
| 75 |
+
target_words = undo_padding(tokens, tokens_lens)
|
| 76 |
+
target_words = self.tokenizer.batch_decode(target_words, skip_special_tokens=True)
|
| 77 |
+
|
| 78 |
+
if hasattr(self.hparams, "normalized_transcripts"):
|
| 79 |
+
predicted_words = [self.tokenizer.normalize(text).split(" ") for text in predicted_words]
|
| 80 |
+
target_words = [self.tokenizer.normalize(text).split(" ") for text in target_words]
|
| 81 |
+
else:
|
| 82 |
+
predicted_words = [text.split(" ") for text in predicted_words]
|
| 83 |
+
target_words = [text.split(" ") for text in target_words]
|
| 84 |
+
|
| 85 |
+
self.wer_metric.append(ids, predicted_words, target_words)
|
| 86 |
+
self.cer_metric.append(ids, predicted_words, target_words)
|
| 87 |
+
|
| 88 |
+
return loss
|
| 89 |
+
|
| 90 |
+
def on_stage_start(self, stage, epoch):
|
| 91 |
+
"""Gets called at the beginning of each epoch"""
|
| 92 |
+
if stage != sb.Stage.TRAIN:
|
| 93 |
+
self.cer_metric = self.hparams.cer_computer()
|
| 94 |
+
self.wer_metric = self.hparams.error_rate_computer()
|
| 95 |
+
|
| 96 |
+
def on_stage_end(self, stage, stage_loss, epoch):
|
| 97 |
+
"""Gets called at the end of an epoch."""
|
| 98 |
+
# Compute/store important stats
|
| 99 |
+
stage_stats = {"loss": stage_loss}
|
| 100 |
+
if stage == sb.Stage.TRAIN:
|
| 101 |
+
self.train_stats = stage_stats
|
| 102 |
+
else:
|
| 103 |
+
stage_stats["CER"] = self.cer_metric.summarize("error_rate")
|
| 104 |
+
stage_stats["WER"] = self.wer_metric.summarize("error_rate")
|
| 105 |
+
|
| 106 |
+
# Perform end-of-iteration things, like annealing, logging, etc.
|
| 107 |
+
if stage == sb.Stage.VALID:
|
| 108 |
+
lr = self.hparams.lr_annealing_whisper.current_lr
|
| 109 |
+
self.hparams.train_logger.log_stats(
|
| 110 |
+
stats_meta={"epoch": epoch, "lr": lr},
|
| 111 |
+
train_stats=self.train_stats,
|
| 112 |
+
valid_stats=stage_stats,
|
| 113 |
+
)
|
| 114 |
+
self.checkpointer.save_and_keep_only(
|
| 115 |
+
meta={"WER": stage_stats["WER"]},
|
| 116 |
+
min_keys=["WER"],
|
| 117 |
+
)
|
| 118 |
+
elif stage == sb.Stage.TEST:
|
| 119 |
+
self.hparams.train_logger.log_stats(
|
| 120 |
+
stats_meta={"Epoch loaded": self.hparams.epoch_counter.current},
|
| 121 |
+
test_stats=stage_stats,
|
| 122 |
+
)
|
| 123 |
+
if if_main_process():
|
| 124 |
+
with open(self.hparams.test_wer_file, "w") as w:
|
| 125 |
+
self.wer_metric.write_stats(w)
|
| 126 |
+
|
| 127 |
+
def run_inference(
|
| 128 |
+
self,
|
| 129 |
+
dataset, # Must be obtained from the dataio_function
|
| 130 |
+
min_key, # We load the model with the lowest error rate
|
| 131 |
+
loader_kwargs, # opts for the dataloading
|
| 132 |
+
):
|
| 133 |
+
|
| 134 |
+
# If dataset isn't a Dataloader, we create it.
|
| 135 |
+
if not isinstance(dataset, DataLoader):
|
| 136 |
+
loader_kwargs["ckpt_prefix"] = None
|
| 137 |
+
dataset = self.make_dataloader(
|
| 138 |
+
dataset, sb.Stage.TEST, **loader_kwargs
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
self.checkpointer.recover_if_possible(min_key=min_key)
|
| 142 |
+
self.modules.eval() # We set the model to eval mode (remove dropout etc)
|
| 143 |
+
|
| 144 |
+
with torch.no_grad():
|
| 145 |
+
true_labels = []
|
| 146 |
+
pred_labels = []
|
| 147 |
+
#for batch in tqdm(dataset, dynamic_ncols=True):
|
| 148 |
+
|
| 149 |
+
for batch in dataset:
|
| 150 |
+
# Make sure that your compute_forward returns the predictions !!!
|
| 151 |
+
# In the case of the template, when stage = TEST, a beam search is applied
|
| 152 |
+
# in compute_forward().
|
| 153 |
+
|
| 154 |
+
tokens, tokens_lens = batch.tokens
|
| 155 |
+
log_probs, predictions, wav_lens = self.compute_forward(batch, stage=sb.Stage.TEST)
|
| 156 |
+
pred_batch = []
|
| 157 |
+
predicted_words = []
|
| 158 |
+
|
| 159 |
+
# Decode token terms to words
|
| 160 |
+
predicted_words = [tokenizer.decode(token, skip_special_tokens=True).strip() for token in predictions]
|
| 161 |
+
# predicted_words = [tokenizer.decode(pred) for pred in predictions]
|
| 162 |
+
# labels = [tokenizer.decode(trn) for trn in batch.tokens_list]
|
| 163 |
+
|
| 164 |
+
# Convert indices to words
|
| 165 |
+
target_words = undo_padding(tokens, tokens_lens)
|
| 166 |
+
target_words = tokenizer.batch_decode(target_words, skip_special_tokens=True)
|
| 167 |
+
|
| 168 |
+
for sent in predicted_words:
|
| 169 |
+
sent = filter_repetitions([sent], 3)
|
| 170 |
+
sent = " ".join(sent)
|
| 171 |
+
pred_batch.append(sent)
|
| 172 |
+
|
| 173 |
+
# if len(pred_batch[0].split()) > 50:
|
| 174 |
+
# continue
|
| 175 |
+
pred_labels.append(pred_batch[0])
|
| 176 |
+
true_labels.append(target_words[0])
|
| 177 |
+
|
| 178 |
+
print('WER: ', wer(true_labels, pred_labels) * 100)
|
| 179 |
+
print('CER: ', cer(true_labels, pred_labels) * 100)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def filter_repetitions(seq, max_repetition_length):
|
| 183 |
+
seq = list(seq)
|
| 184 |
+
output = []
|
| 185 |
+
max_n = len(seq) // 2
|
| 186 |
+
for n in range(max_n, 0, -1):
|
| 187 |
+
max_repetitions = max(max_repetition_length // n, 1)
|
| 188 |
+
# Don't need to iterate over impossible n values:
|
| 189 |
+
# len(seq) can change a lot during iteration
|
| 190 |
+
if (len(seq) <= n*2) or (len(seq) <= max_repetition_length):
|
| 191 |
+
continue
|
| 192 |
+
iterator = enumerate(seq)
|
| 193 |
+
# Fill first buffers:
|
| 194 |
+
buffers = [[next(iterator)[1]] for _ in range(n)]
|
| 195 |
+
for seq_index, token in iterator:
|
| 196 |
+
current_buffer = seq_index % n
|
| 197 |
+
if token != buffers[current_buffer][-1]:
|
| 198 |
+
# No repeat, we can flush some tokens
|
| 199 |
+
buf_len = sum(map(len, buffers))
|
| 200 |
+
flush_start = (current_buffer-buf_len) % n
|
| 201 |
+
# Keep n-1 tokens, but possibly mark some for removal
|
| 202 |
+
for flush_index in range(buf_len - buf_len%n):
|
| 203 |
+
if (buf_len - flush_index) > n-1:
|
| 204 |
+
to_flush = buffers[(flush_index + flush_start) % n].pop(0)
|
| 205 |
+
else:
|
| 206 |
+
to_flush = None
|
| 207 |
+
# Here, repetitions get removed:
|
| 208 |
+
if (flush_index // n < max_repetitions) and to_flush is not None:
|
| 209 |
+
output.append(to_flush)
|
| 210 |
+
elif (flush_index // n >= max_repetitions) and to_flush is None:
|
| 211 |
+
output.append(to_flush)
|
| 212 |
+
buffers[current_buffer].append(token)
|
| 213 |
+
# At the end, final flush
|
| 214 |
+
current_buffer += 1
|
| 215 |
+
buf_len = sum(map(len, buffers))
|
| 216 |
+
flush_start = (current_buffer-buf_len) % n
|
| 217 |
+
for flush_index in range(buf_len):
|
| 218 |
+
to_flush = buffers[(flush_index + flush_start) % n].pop(0)
|
| 219 |
+
# Here, repetitions just get removed:
|
| 220 |
+
if flush_index // n < max_repetitions:
|
| 221 |
+
output.append(to_flush)
|
| 222 |
+
seq = []
|
| 223 |
+
to_delete = 0
|
| 224 |
+
for token in output:
|
| 225 |
+
if token is None:
|
| 226 |
+
to_delete += 1
|
| 227 |
+
elif to_delete > 0:
|
| 228 |
+
to_delete -= 1
|
| 229 |
+
else:
|
| 230 |
+
seq.append(token)
|
| 231 |
+
output = []
|
| 232 |
+
return seq
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def dataio_prepare(hparams, tokenizer):
|
| 236 |
+
"""This function prepares the datasets to be used in the brain class.
|
| 237 |
+
It also defines the data processing pipeline through user-defined functions.
|
| 238 |
+
"""
|
| 239 |
+
data_folder = hparams["data_folder"]
|
| 240 |
+
|
| 241 |
+
train_data = sb.dataio.dataset.DynamicItemDataset.from_json(json_path=os.path.join(hparams["data_folder"], "train_dev.json"), replacements={"data_root": data_folder})
|
| 242 |
+
train_data = train_data.filtered_sorted(sort_key="duration")
|
| 243 |
+
hparams["train_dataloader_opts"]["shuffle"] = False
|
| 244 |
+
|
| 245 |
+
valid_data = sb.dataio.dataset.DynamicItemDataset.from_json(json_path=os.path.join(hparams["data_folder"], "test_all.json"), replacements={"data_root": data_folder})
|
| 246 |
+
valid_data = valid_data.filtered_sorted(sort_key="duration")
|
| 247 |
+
|
| 248 |
+
test_data = sb.dataio.dataset.DynamicItemDataset.from_json(json_path=os.path.join(hparams["data_folder"], "test_eaz.json"), replacements={"data_root": data_folder})
|
| 249 |
+
|
| 250 |
+
datasets = [train_data, valid_data, test_data]
|
| 251 |
+
|
| 252 |
+
# 2. Define audio pipeline:
|
| 253 |
+
@sb.utils.data_pipeline.takes("data_path")
|
| 254 |
+
@sb.utils.data_pipeline.provides("sig")
|
| 255 |
+
def audio_pipeline(data_path):
|
| 256 |
+
info = torchaudio.info(data_path)
|
| 257 |
+
sig = sb.dataio.dataio.read_audio(data_path)
|
| 258 |
+
if info.sample_rate != hparams["sample_rate"]:
|
| 259 |
+
sig = torchaudio.transforms.Resample(info.sample_rate, hparams["sample_rate"])(sig)
|
| 260 |
+
return sig
|
| 261 |
+
|
| 262 |
+
sb.dataio.dataset.add_dynamic_item(datasets, audio_pipeline)
|
| 263 |
+
|
| 264 |
+
# 3. Define text pipeline:
|
| 265 |
+
@sb.utils.data_pipeline.takes("transcript")
|
| 266 |
+
@sb.utils.data_pipeline.provides("transcript", "tokens_list", "tokens_bos", "tokens_eos", "tokens")
|
| 267 |
+
def text_pipeline(transcript):
|
| 268 |
+
# if hasattr(hparams, "normalized_transcripts"):
|
| 269 |
+
# transcript = tokenizer.normalize(transcript)
|
| 270 |
+
yield transcript
|
| 271 |
+
tokens_list = tokenizer.encode(transcript, add_special_tokens=False)
|
| 272 |
+
yield tokens_list
|
| 273 |
+
tokens_list = tokenizer.build_inputs_with_special_tokens(tokens_list)
|
| 274 |
+
tokens_bos = torch.LongTensor(tokens_list[:-1])
|
| 275 |
+
yield tokens_bos
|
| 276 |
+
tokens_eos = torch.LongTensor(tokens_list[1:])
|
| 277 |
+
yield tokens_eos
|
| 278 |
+
tokens = torch.LongTensor(tokens_list)
|
| 279 |
+
yield tokens
|
| 280 |
+
|
| 281 |
+
sb.dataio.dataset.add_dynamic_item(datasets, text_pipeline)
|
| 282 |
+
|
| 283 |
+
# 4. Set output:
|
| 284 |
+
sb.dataio.dataset.set_output_keys(
|
| 285 |
+
datasets,
|
| 286 |
+
["id", "sig", "tokens_list", "tokens_bos", "tokens_eos", "tokens"],
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
return train_data, valid_data, test_data
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
if __name__ == "__main__":
|
| 293 |
+
# CLI:
|
| 294 |
+
hparams_file, run_opts, overrides = sb.parse_arguments(sys.argv[1:])
|
| 295 |
+
|
| 296 |
+
# create ddp_group with the right communication protocol
|
| 297 |
+
sb.utils.distributed.ddp_init_group(run_opts)
|
| 298 |
+
|
| 299 |
+
with open(hparams_file) as fin:
|
| 300 |
+
hparams = load_hyperpyyaml(fin, overrides)
|
| 301 |
+
|
| 302 |
+
# Create experiment directory
|
| 303 |
+
sb.create_experiment_directory(
|
| 304 |
+
experiment_directory=hparams["output_folder"],
|
| 305 |
+
hyperparams_to_save=hparams_file,
|
| 306 |
+
overrides=overrides,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
# Defining tokenizer and loading it
|
| 310 |
+
tokenizer = hparams["whisper"].tokenizer
|
| 311 |
+
|
| 312 |
+
# here we create the datasets objects as well as tokenization and encoding
|
| 313 |
+
train_data, valid_data, test_data = dataio_prepare(hparams, tokenizer)
|
| 314 |
+
|
| 315 |
+
run_on_main(hparams["pretrainer"].collect_files)
|
| 316 |
+
hparams["pretrainer"].load_collected()
|
| 317 |
+
|
| 318 |
+
# Trainer initialization
|
| 319 |
+
asr_brain = ASR(
|
| 320 |
+
modules=hparams["modules"],
|
| 321 |
+
hparams=hparams,
|
| 322 |
+
run_opts=run_opts,
|
| 323 |
+
checkpointer=hparams["checkpointer"],
|
| 324 |
+
opt_class=hparams["whisper_opt_class"],
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# We load the pretrained whisper model
|
| 328 |
+
if "pretrainer" in hparams.keys():
|
| 329 |
+
hparams["pretrainer"].collect_files()
|
| 330 |
+
hparams["pretrainer"].load_collected(asr_brain.device)
|
| 331 |
+
|
| 332 |
+
# We dynamically add the tokenizer to our brain class.
|
| 333 |
+
# NB: This tokenizer corresponds to the one used for Whisper.
|
| 334 |
+
asr_brain.tokenizer = tokenizer
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# Training/validation loop
|
| 338 |
+
if hparams["skip_training"] == False:
|
| 339 |
+
print("Training...")
|
| 340 |
+
# Training
|
| 341 |
+
asr_brain.fit(
|
| 342 |
+
asr_brain.hparams.epoch_counter,
|
| 343 |
+
train_data,
|
| 344 |
+
valid_data,
|
| 345 |
+
train_loader_kwargs=hparams["train_dataloader_opts"],
|
| 346 |
+
valid_loader_kwargs=hparams["valid_dataloader_opts"],
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
else:
|
| 350 |
+
# evaluate
|
| 351 |
+
print("Evaluating")
|
| 352 |
+
asr_brain.run_inference(test_data, "WER", hparams["test_dataloader_opts"])
|