-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathmegatron_t5_speechllm_model.py
More file actions
2677 lines (2402 loc) · 142 KB
/
megatron_t5_speechllm_model.py
File metadata and controls
2677 lines (2402 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# flake8: noqa
import itertools
import json
import os
import random
import string
from functools import partial
from typing import Any, List
import editdistance
import imageio
import numpy as np
import soundfile as sf
import torch
from lightning.pytorch.trainer.trainer import Trainer
from omegaconf import OmegaConf
from omegaconf.dictconfig import DictConfig
from omegaconf.omegaconf import open_dict
import nemo.collections.asr as nemo_asr
from nemo.collections.asr.metrics.wer import word_error_rate
from nemo.collections.common.tokenizers.sentencepiece_tokenizer import SentencePieceSpeechLLMTTSTokenizer
from nemo.collections.nlp.models.language_modeling.megatron_t5_model import MegatronT5Model
from nemo.collections.nlp.models.language_modeling.megatron_t5_sft_model import MegatronT5SFTModel
from nemo.collections.nlp.modules.common.megatron.token_level_encoder_decoder import (
MegatronTokenLevelEncoderDecoderSpeechLLMModule,
)
from nemo.collections.nlp.modules.common.megatron.utils import (
average_losses_across_data_parallel_group,
get_iterator_k_split,
init_method_normal,
)
from nemo.collections.nlp.parts.nlp_overrides import NLPSaveRestoreConnector
from nemo.collections.nlp.parts.utils_funcs import get_last_rank
from nemo.collections.tts.data.speechllm.t5_speechllm_dataset import Lang, T5SpeechLMDataset
from nemo.collections.tts.data.speechllm.t5_speechllm_tarred_dataset import T5SpeechLMTarredDataset
from nemo.collections.tts.losses.aligner_loss import ForwardSumLoss
from nemo.collections.tts.models import AudioCodecModel
from nemo.collections.tts.models.speechllm.megatron_base_speechllm_prompt_model import MegatronBaseSpeechLM
from nemo.collections.tts.parts.utils.helpers import plot_alignment_to_numpy_for_speechllm, plot_codec_to_numpy
from nemo.utils import AppState, logging
try:
from apex.transformer.pipeline_parallel.utils import get_micro_batch_size, get_num_microbatches
HAVE_APEX = True
except (ImportError, ModuleNotFoundError):
HAVE_APEX = False
try:
from megatron.core import parallel_state, tensor_parallel
from megatron.core.enums import ModelType
from megatron.core.pipeline_parallel.schedules import get_forward_backward_func
HAVE_MEGATRON_CORE = True
except (ImportError, ModuleNotFoundError):
HAVE_MEGATRON_CORE = False
import time
import librosa
from torchaudio.pipelines import SQUIM_SUBJECTIVE
from transformers import Wav2Vec2FeatureExtractor, WavLMForXVector
__all__ = ['MegatronT5SpeechLMModel']
class MegatronT5OverrideModel(MegatronT5Model):
def _build_tokenizer(self):
if self._cfg.tokenizer.library == "sentencepiece":
if hasattr(self._cfg.tokenizer, "sentencepiece_legacy"):
legacy = self._cfg.tokenizer.sentencepiece_legacy
else:
legacy = True if self._cfg.tokenizer.library == 'sentencepiece' else False
self.tokenizer = SentencePieceSpeechLLMTTSTokenizer(
model_path=self.register_artifact("tokenizer.model", self._cfg.tokenizer.get('model', None)),
legacy=legacy,
)
if self._cfg.tokenizer.get('additional_special_tokens', None) is not None:
tokens_list = OmegaConf.to_object(self._cfg.tokenizer.additional_special_tokens)
self.tokenizer.add_special_tokens(tokens_list)
else:
super()._build_tokenizer()
def model_provider_func(self, pre_process, post_process, add_encoder, add_decoder):
if not hasattr(self.cfg, 'encoder') or not hasattr(self.cfg, 'decoder'):
logging.warning(
'Could not find encoder or decoder in config. This is probably because of restoring an old checkpoint. Copying shared model configs to encoder and decoder configs.'
)
# After the call below, self.cfg.encoder and self.cfg.decoder will be populated with the cfg.model configs from old checkpoints.
self._populate_encoder_decoder_configs_for_backward_compatibility(self.cfg)
if parallel_state.get_pipeline_model_parallel_world_size() > 1 and self.cfg.encoder.arch == 'perceiver':
raise ValueError(f"Perceivers with pipeline parallel > 1 is not supported yet.")
if not hasattr(self.cfg, 'embedding_init_method_std'):
embedding_init_method_std = self.cfg.encoder.init_method_std
else:
embedding_init_method_std = self.cfg.embedding_init_method_std
if not hasattr(self.cfg, 'embedding_dropout'):
embedding_dropout = self.cfg.encoder.hidden_dropout
else:
embedding_dropout = self.cfg.embedding_dropout
model = MegatronTokenLevelEncoderDecoderSpeechLLMModule(
config=self.model_parallel_config,
encoder_cfg=self.cfg.encoder,
decoder_cfg=self.cfg.decoder,
vocab_size=self.padded_vocab_size,
max_position_embeddings=self.cfg.max_position_embeddings,
num_tokentypes=0,
parallel_output=True,
pre_process=pre_process,
post_process=post_process,
fp16_cross_entropy=self.cfg.get('fp16_lm_cross_entropy', False),
precision=self.cfg.get('precision', 16),
embedding_init_method_std=embedding_init_method_std,
embedding_dropout=embedding_dropout,
label_smoothing=self.cfg.get('label_smoothing', 0.0),
add_encoder=add_encoder,
add_decoder=add_decoder,
share_token_embeddings=self.cfg.get('share_token_embeddings', True),
share_decoder_tokens_head_embeddings=self.cfg.get('share_decoder_tokens_head_embeddings', True),
tokens_head_bias=self.cfg.get('tokens_head_bias', True),
hiddens_cfg=self.cfg.get('hiddens', None),
)
return model
class MegatronT5SpeechLMModel(MegatronBaseSpeechLM):
"""
Model class for prompt-tuning or p-tuning a pretrained Megatron T5 model.
Prompt Tuning initializes virtual prompt embeddings directly from a copy of
certain token embeddings from the pretrained T5 model's vocabulary
and directly tunes these embedding weights. The token embeddings used in
initialization are specified by the user in the config file. The model can
be prompt-tuned for multiple tasks at once. Virtual prompts are stored in a
prompt table and can be added or deleted without disrupting virtual prompts
for other tasks.
P-tuning initializes an LSTM encoder model that generates virtual prompt
embeddings for every task. Each task shares the same encoder. After p-tuning
is complete, the learned virtual prompts can be saved to the prompt table
using add_ptuned_prompts_to_prompt_table(). Thus, if a user wants to add a
new virtual prompt via p-tuning, they do not need to retrain on all previous
tasks. This gives p-tuning the same task flexibility as prompt-tuning.
"""
def __init__(self, cfg: DictConfig, trainer: Trainer):
super().__init__(cfg, trainer)
self.model_type = ModelType.encoder_or_decoder
speech_codebook_size = cfg.data.get('speech_codebook_size', 1024)
num_speech_codebooks = cfg.data.get('num_speech_codebooks', 8)
speech_offset = cfg.data.get('speech_offset', 30000)
codecmodel_type = cfg.get('codecmodel_type', 'nemo_codec')
attn_prior_scaledown_start_step = cfg.get('attn_prior_scaledown_start_step', 10000)
attn_prior_end_step = cfg.get('attn_prior_end_step', 11000)
num_cross_attention_heads = cfg.get('num_cross_attention_heads', 12)
self.lm_vocab_size = cfg.get('lm_vocab_size', 30000)
self.context_pattern = cfg.data.get('context_pattern', 'parallel')
self.context_conditioning = cfg.get('context_conditioning', "decoder")
self.context_duration_min = cfg.data.get('context_duration_min', 2.9)
self.context_duration_max = cfg.data.get('context_duration_max', 2.9)
self.codebook_fps = cfg.data.get('codebook_fps', 86)
self.decoder_context_len = 0
if self.context_conditioning == "decoder":
assert self.context_duration_min == self.context_duration_max, "Decoder context duration must be fixed"
self.decoder_context_len = int(self.codebook_fps * self.context_duration_min)
self.speech_offset = speech_offset
self.speech_codebook_size = speech_codebook_size
self.num_speech_codebooks = num_speech_codebooks
self.codecmodel_type = codecmodel_type
self.enc_output_to_layers = cfg.get('enc_output_to_layers', None)
if self.enc_output_to_layers is not None:
# Convert from listconfig to list
self.enc_output_to_layers = [[l for l in encoder_layer] for encoder_layer in self.enc_output_to_layers]
self.frozen_model.enc_dec_model.speech_offset = speech_offset
self.frozen_model.enc_dec_model.speech_codebook_size = speech_codebook_size
self.frozen_model.enc_dec_model.num_speech_codebooks = num_speech_codebooks
self.frozen_model.enc_dec_model.seq_pattern = cfg.get('seq_pattern', 'parallel')
self.frozen_model.enc_dec_model.attn_prior_scaledown_start_step = attn_prior_scaledown_start_step
self.frozen_model.enc_dec_model.attn_prior_end_step = attn_prior_end_step
self.frozen_model.enc_dec_model.alignment_decoder_layerids = cfg.get(
'alignment_decoder_layerids', list(range(0, 12))
)
self.frozen_model.enc_dec_model.return_all_crossattention_probs = cfg.get(
'return_all_crossattention_probs', False
)
self.frozen_model.enc_dec_model.num_cross_attention_heads = num_cross_attention_heads
self.frozen_model.enc_dec_model.context_conditioning = self.context_conditioning
self.frozen_model.enc_dec_model.decoder_context_len = self.decoder_context_len
self.frozen_model.enc_dec_model.enc_output_to_layers = self.enc_output_to_layers
self.alignment_loss_start_step = 0
self.alignment_loss_end_step = float('inf')
self.use_alignment_loss = cfg.get('use_alignment_loss', False)
if self.use_alignment_loss:
alignment_loss_scale = cfg.get('alignment_loss_scale', 1.0)
self.frozen_model.enc_dec_model.use_alignment_loss = True
self.frozen_model.enc_dec_model.forward_sum_loss = ForwardSumLoss(loss_scale=alignment_loss_scale)
self.frozen_model.enc_dec_model.alignment_text_end_offset = cfg.get('alignment_text_end_offset', 0)
self.frozen_model.enc_dec_model.align_every_n_head = cfg.get('align_every_n_head', 1)
self.alignment_loss_start_step = cfg.get('alignment_loss_start_step', 0)
self.alignment_loss_end_step = cfg.get('alignment_loss_end_step', float('inf'))
# Need to explicitly set this since it is already initialized
self.frozen_model.enc_dec_model.tokens_head.parallel_output = self.frozen_model.enc_dec_model.parallel_output
list_of_speech_heads = []
list_of_speech_tokens_embeddings = []
for _ in range(self.num_speech_codebooks - 1):
# init is NOT used since we overwrite the weight below anyways
_speech_head_embedding = tensor_parallel.VocabParallelEmbedding(
speech_codebook_size,
embedding_dim=self.word_embeddings.embedding_dim,
init_method=lambda x: x.data.fill_(0),
config=self.model_parallel_config,
)
_speech_head_embedding.weight.data.fill_(0)
_speech_head_embedding.shared = True
list_of_speech_tokens_embeddings.append(_speech_head_embedding)
# Linear layer that maps from hidden size to speech codebook size
hidden_size = self.frozen_model.enc_dec_model.decoder_cfg.hidden_size
init_method_std = self.frozen_model.enc_dec_model.decoder_cfg.init_method_std
# Changing to ColumnParallelLinear instead of Linear to support 3b Tensor Parallelism
_speech_head = tensor_parallel.ColumnParallelLinear(
input_size=hidden_size,
output_size=speech_codebook_size,
bias=True,
gather_output=not self.frozen_model.enc_dec_model.parallel_output,
init_method=init_method_normal(init_method_std),
config=self.model_parallel_config,
)
list_of_speech_heads.append(_speech_head)
self.frozen_model.enc_dec_model.speech_tokens_heads = torch.nn.ModuleList(list_of_speech_heads)
self.frozen_model.enc_dec_model.speech_tokens_embeddings = torch.nn.ModuleList(
list_of_speech_tokens_embeddings
)
self.sample_rate = 24000
if codecmodel_type == 'nemo_codec':
codec_model = AudioCodecModel.restore_from(cfg.get('codecmodel_path'))
codec_model.to('cuda')
codec_model.eval()
self.sample_rate = 22050
else:
raise NotImplementedError()
self.additional_models = {'codec': codec_model}
self.train_check_interval = self.cfg.get('train_check_interval', 500)
self.plot_alignments_sliced = self.cfg.get('plot_alignments_sliced', True)
app_state = AppState()
self.is_rank_zero = app_state.global_rank == 0
self.predict_step_outputs = []
self.phoneme_tokenizer = None
# classifier-free guidance (CFG) option during training. The probability (0.0 <= ε <= 1.0) is used to trigger the action that the
# text or audio tokens in a batch are replaced by [UNK], such that mimicking the text- or audio-free scenario.
# If a random number is greater than ε, then keep text or audio tokens as-is, otherwise, the text or audio tokens are
# replaced by [UNK]. Default to 0.0, meaning CFG is disabled.
self.train_text_cfg_prob = cfg.get('train_text_cfg_prob', 0.0)
self.train_audio_cfg_prob = cfg.get('train_audio_cfg_prob', 0.0)
self._rng = random.Random()
# control the strength of the classifier guidance during inference, Logits_cfg = w*Logits_cond + (1-w)*Logits_uncond,
# equivalent to Logits_cfg = Logits_cond + alpha*(Logits_cond - Logits_uncond) where alpha=w-1.
# Default w to 1.O, indicating no interpolation is applied.
self.inference_cfg_interpolation_scale = cfg.get('inference_cfg_interpolation_scale', 1.0)
self.inference_apply_text_cfg = cfg.get('inference_apply_text_cfg', False)
self.inference_apply_audio_cfg = cfg.get('inference_apply_audio_cfg', False)
if self.inference_cfg_interpolation_scale == 1.0:
self.inference_apply_text_cfg = False
self.inference_apply_audio_cfg = False
# whether to apply cfg filter to address faster speech rate.
self.inference_apply_cfg_filter = cfg.get("inference_apply_cfg_filter", False)
# this scale is suggested to be smaller than `self.question_guidance_scale` and it is used to balance the weights
# between the conditioned logits after applying cfg filter and the original unconditioned logits. Default to 1.0,
# indicating only conditioned logits are used.
if not self.inference_apply_cfg_filter:
self.inference_cfg_filter_interpolation_scale = None
else:
self.inference_cfg_filter_interpolation_scale = cfg.get('inference_cfg_filter_interpolation_scale', 1.0)
# whether to estimate MOS in predict_step.
self.estimate_mos = cfg.get('estimate_mos', True)
if self.estimate_mos:
# requires to specify a non-matching high-quality and clean reference audio file. It is used to estimate MOS.
self.non_matching_ref_audio_filepath = cfg.get('non_matching_ref_audio_filepath', None)
if self.non_matching_ref_audio_filepath is None:
raise ValueError(
f"Please provide a high-quality reference audio to estimate the MOS. Alternatively, "
f"set `model.estimate_mos=False` to disable MOS estimation."
)
if not os.path.exists(self.non_matching_ref_audio_filepath):
raise FileNotFoundError(
f"Please provide a valid file path for a high-quality reference audio to estimate"
f" the MOS. Alternatively, set `model.estimate_mos=False` to disable MOS estimation."
)
def decode_wav_from_codec_model(self, codes):
codec_model = self.additional_models['codec']
if self.codecmodel_type == 'nemo_codec':
codec_len = torch.Tensor([codes.shape[1]]).long().cuda()
if codec_len < 10:
# return a one-second silence
return torch.zeros(24000).cuda()
wav, _ = codec_model.decode(tokens=codes.unsqueeze(0), tokens_len=codec_len)
wav = wav[0]
else:
raise NotImplementedError()
return wav
def first_stage_of_pipeline(self):
if self.frozen_model.enc_dec_model.pre_process and parallel_state.get_pipeline_model_parallel_rank() == 0:
return True
return False
def forward(
self,
virtual_tokens,
context_and_question_tokens,
enc_mask,
dec_input,
dec_mask,
position_ids,
taskname_ids,
labels=None,
speech_mask=None,
inference=False,
inference_step=0,
cross_attention_prior=None,
text_limits=None,
decoder_max_sequence_len=None,
encoder_max_sequence_len=None,
):
"""
Special forward method for p-tuning/prompt-tuning pretrained
T5 style models.
"""
if isinstance(context_and_question_tokens, list):
multi_encoder = True
assert isinstance(enc_mask, list)
assert isinstance(position_ids, list)
if cross_attention_prior is None:
cross_attention_prior = [None for _ in range(len(context_and_question_tokens))]
assert isinstance(cross_attention_prior, list)
assert len(context_and_question_tokens) == len(enc_mask) == len(position_ids) == len(cross_attention_prior)
else:
multi_encoder = False
context_and_question_tokens = [context_and_question_tokens]
enc_mask = [enc_mask]
position_ids = [position_ids]
cross_attention_prior = [cross_attention_prior]
enc_output = None
logging.debug(
f"self.first_stage_of_pipeline()={self.first_stage_of_pipeline()}\tinference_step={inference_step}"
)
if self.first_stage_of_pipeline() and inference_step == 0:
# Get embeddings for text tokens and insert virtual token embeddings
encoder_input_list = []
for ei in range(len(context_and_question_tokens)):
input_embeds = self.get_embeddings_and_combine(
[virtual_tokens, context_and_question_tokens[ei]], taskname_ids, inference
)
# TODO: This check needs to be revisited with PP support.
if hasattr(self.frozen_model.enc_dec_model.encoder_embedding, 'position_embeddings'):
position_embeddings = self.frozen_model.enc_dec_model.encoder_embedding.position_embeddings(
position_ids[ei]
)
encoder_input = input_embeds + position_embeddings
else:
encoder_input = input_embeds
encoder_input_list.append(encoder_input)
else:
encoder_input_list = None
encoder_input = None
if inference_step != 0:
enc_output = context_and_question_tokens if multi_encoder else context_and_question_tokens[0]
# If the decoder input starts with <pad> instead of <bos>, which is the case for huggingface T5 models, we don't want to mask the first token.
# For NeMo-Megatron, the sequence starts with <bos>, which is never masked so we can always set index 0 to be unmasked.
dec_mask[:, 0] = 1
if not self.cfg.data.get('use_attention_prior', False):
cross_attention_prior = [None for _ in range(len(cross_attention_prior))]
_encoder_input = encoder_input_list
if not multi_encoder:
enc_mask = enc_mask[0]
cross_attention_prior = cross_attention_prior[0]
_encoder_input = encoder_input_list[0] if encoder_input_list is not None else None
# Call forward on T5 model with preprocessed embeddings
if inference and inference_step == 0:
set_inference_key_value_memory = True
else:
set_inference_key_value_memory = False
if self.autocast_dtype == torch.float32:
output, out_logits = self.frozen_model.enc_dec_model(
enc_input_ids=None,
enc_attn_mask=enc_mask,
dec_input_ids=dec_input,
dec_attn_mask=dec_mask,
token_type_ids=None,
labels=labels,
output_enc_hidden_only=False,
enc_input=_encoder_input,
enc_output=enc_output,
speech_mask=speech_mask,
cross_attention_prior=cross_attention_prior,
text_limits=text_limits,
global_step=self.global_step,
set_inference_key_value_memory=set_inference_key_value_memory,
decoder_max_sequence_len=decoder_max_sequence_len,
encoder_max_sequence_len=encoder_max_sequence_len,
)
else:
with torch.autocast(device_type="cuda", dtype=self.autocast_dtype):
output, out_logits = self.frozen_model.enc_dec_model(
enc_input_ids=None,
enc_attn_mask=enc_mask,
dec_input_ids=dec_input,
dec_attn_mask=dec_mask,
token_type_ids=None,
labels=labels,
output_enc_hidden_only=False,
enc_input=_encoder_input,
enc_output=enc_output,
speech_mask=speech_mask,
cross_attention_prior=cross_attention_prior,
text_limits=text_limits,
global_step=self.global_step,
set_inference_key_value_memory=set_inference_key_value_memory,
decoder_max_sequence_len=decoder_max_sequence_len,
encoder_max_sequence_len=encoder_max_sequence_len,
)
return output, encoder_input, out_logits
def load_frozen_model(self, cfg, trainer):
self.megatron_amp_O2 = cfg.get('megatron_amp_o2', False)
# TODO: Fix this once apex patches FusedScaledMaskedSoftmax.
# This is a workaround for the fact that `masked_softmax_fusion` has issues with certain input sizes that may be present while finetuning.
cfg_language_model_path = cfg.get('language_model_path', None)
cfg_frozen_model = cfg.get('frozen_model', None)
if not (bool(cfg_language_model_path) ^ bool(cfg_frozen_model)):
raise ValueError(
"T5-TTS requires either 'language_model_path' or 'frozen_model' in its config, but not both."
)
if cfg_language_model_path:
t5_cfg = MegatronT5Model.restore_from(cfg_language_model_path, trainer=trainer, return_config=True)
else:
t5_cfg = cfg_frozen_model
OmegaConf.set_struct(t5_cfg, True)
with open_dict(t5_cfg):
if hasattr(t5_cfg, 'encoder') and hasattr(t5_cfg, 'decoder'):
t5_cfg.encoder.masked_softmax_fusion = False
t5_cfg.decoder.masked_softmax_fusion = False
else:
t5_cfg.masked_softmax_fusion = False
t5_cfg.megatron_amp_O2 = self.megatron_amp_O2
# hack to make the _GLOBAL_NUM_MICROBATCHES_CALCULATOR initialize
t5_cfg.micro_batch_size = cfg.get('micro_batch_size', 4)
t5_cfg.global_batch_size = cfg.get('global_batch_size', 4)
t5_cfg.precision = trainer.precision
t5_cfg.tokenizer.num_sentinel_tokens = cfg.get('num_sentinel_tokens', 39184 - 29056)
t5_cfg.seq_length = cfg.data.max_seq_length
if cfg.get('max_position_embeddings', None) is None:
t5_cfg.max_position_embeddings = cfg.data.max_seq_length
else:
t5_cfg.max_position_embeddings = cfg.get('max_position_embeddings')
t5_cfg.use_flash_attention = cfg.get('use_flash_attention', False)
if cfg.get('override_token_model', None):
t5_cfg.tokenizer.model = cfg['override_token_model']
if cfg.get('override_tokenizer_vocab_file', None):
t5_cfg.tokenizer.vocab_file = cfg['override_tokenizer_vocab_file']
if cfg.get('train_from_scratch', False):
print("Training from scratch!")
# Defaults for 220m model
# To override any of these, add +model.override_<key>=<value> to the config file.
# Eg. +model.override_hidden_size=1024
overide_keys = [
'hidden_size', # 768
'num_layers', # 12
'num_attention_heads', # 12
'hidden_dropout', # 0.1
'attention_dropout', # 0.1
'kv_channels', # 64
'ffn_hidden_size', # 2048
]
# Defaults for 220m model
for k in overide_keys:
if cfg.get(f'override_{k}') is not None:
t5_cfg[k] = cfg.get(f'override_{k}')
self.frozen_model = MegatronT5OverrideModel(t5_cfg, trainer=trainer)
num_params = sum(p.numel() for p in self.frozen_model.parameters() if p.requires_grad)
print(f"Number of parameters: {num_params}")
else:
print(f"Loading from pretrained checkpoint: {cfg_language_model_path}")
if cfg_language_model_path is None:
raise ValueError(
"T5-TTS SFT on pretrained model checkpoint requires `langauge_model_path` in its config."
)
self.frozen_model = MegatronT5OverrideModel.restore_from(
cfg_language_model_path,
trainer=trainer,
override_config_path=t5_cfg,
save_restore_connector=NLPSaveRestoreConnector(),
)
if not cfg.get('english_only_model', False):
self.frozen_model.tokenizer.add_phone_tokens_to_special_tokens()
logging.info(f"self.frozen_model {self.frozen_model}")
def fwd_bwd_step(self, dataloader_iter, batch_idx, forward_only):
"""
Dataloader produces a global batch which is turned into a list of microbatches.
The list of microbatches is then piped through the pipeline using megatron-core fwd/bwd functions.
"""
# Get seq length of batch
batch = next(dataloader_iter)
_, seq_length = batch[0].shape
if batch[4].dim() > 2:
_, _, dec_seq_length = batch[4].shape
else:
_, dec_seq_length = batch[4].shape
data_iter = get_iterator_k_split(batch, get_num_microbatches())
fwd_bwd_function = get_forward_backward_func()
losses_reduced_per_micro_batch = fwd_bwd_function(
forward_step_func=self.get_forward_output_and_loss_func(forward_only),
data_iterator=data_iter,
model=[self],
num_microbatches=get_num_microbatches(),
forward_only=forward_only,
seq_length=seq_length,
micro_batch_size=get_micro_batch_size(),
decoder_seq_length=dec_seq_length,
)
# only the last stages of the pipeline return losses
if losses_reduced_per_micro_batch:
# average loss across micro batches
loss_tensors_list = [loss_reduced['avg'] for loss_reduced in losses_reduced_per_micro_batch]
loss_tensor = torch.concat(loss_tensors_list)
loss_mean = loss_tensor.mean()
else:
# we're not on the last pipeline stage so no losses
loss_mean = torch.tensor(0.0).cuda()
return loss_mean
def convert_tokens_to_range(self, tokens, apply_offset_correction=True, pattern=None):
# convert tokens to range [0, 1024]
output_tokens = tokens.clone()
if apply_offset_correction:
output_tokens[0] = output_tokens[0] - self.speech_offset
output_tokens = torch.clamp(output_tokens, min=0, max=self.speech_codebook_size - 1)
if pattern is None:
pattern = self.cfg.get('seq_pattern', 'delay_parallel')
if pattern == "delay_parallel":
output_tokens_new = []
for _c in range(output_tokens.shape[0]):
si = _c
ei = _c + output_tokens.shape[1] - self.num_speech_codebooks
output_tokens_new.append(output_tokens[_c, si:ei])
output_tokens_new = torch.stack(output_tokens_new)
output_tokens = output_tokens_new
return output_tokens
def get_forward_output_and_loss_func(self, validation_step=False):
def fwd_output_and_loss_func(dataloader_iter, model):
batch = next(dataloader_iter)
_batch = []
for x in batch:
if isinstance(x, torch.Tensor):
x = x.cuda(non_blocking=True)
elif isinstance(x, list):
if isinstance(x[0], torch.Tensor):
x = [y.cuda(non_blocking=True) for y in x]
_batch.append(x)
batch = _batch
# batch = [x.cuda(non_blocking=True) if isinstance(x, torch.Tensor) else x for x in batch]
(
virtual_tokens,
context_and_question_tokens,
enc_mask,
dec_input,
dec_input_mask,
labels,
loss_mask,
position_ids,
taskname_ids,
speech_mask,
context_and_question_tokens_lens,
cross_attention_prior,
text_limits,
_, # TODO: text limit and lang not in tarred dataset
_,
) = batch
if self.trainer.global_step % self.train_check_interval == 0 and not validation_step and self.is_rank_zero:
self.frozen_model.enc_dec_model.logging_step = True
_cross_attention_prior = cross_attention_prior
if isinstance(context_and_question_tokens, list):
# None for context and prior for question
_cross_attention_prior = [None, cross_attention_prior]
output_tensor, encoder_input, out_logits = model(
virtual_tokens,
context_and_question_tokens,
enc_mask,
dec_input,
dec_input_mask,
position_ids,
taskname_ids,
labels=labels,
speech_mask=speech_mask,
cross_attention_prior=_cross_attention_prior,
text_limits=text_limits,
inference=False,
)
output_tensor = output_tensor.contiguous()
alignment_loss = out_logits[3]
if alignment_loss is not None:
self.logger.experiment.add_scalar('train_alignment_loss', alignment_loss, self.global_step)
if self.trainer.global_step % self.train_check_interval == 0 and not validation_step and self.is_rank_zero:
self.frozen_model.enc_dec_model.logging_step = False
with torch.no_grad():
with torch.cuda.amp.autocast(enabled=False):
if torch.count_nonzero(speech_mask) == 0:
text_labels = labels[:, 0, :] # [B, 8, T] -> [B, T]
token_logits = out_logits[0] * 1 # [T, B, V]
if self.frozen_model.enc_dec_model.parallel_output:
# Gather from tensor parallel region
token_logits = tensor_parallel.gather_from_tensor_model_parallel_region(token_logits)
token_logits = token_logits.argmax(dim=2) # [T, B]
token_logits = token_logits.t() # [B, T]
score = 0
for i in range(text_labels.size()[0]):
r = text_labels[i].long()
nzm = r != 0
r = r.tolist()
h = token_logits[i].long() * nzm
h = h.tolist()
score += editdistance.eval(r, h)
score /= text_labels.size()[0]
logging.info(f"wer score : {score}")
self.logger.experiment.add_scalar('WER', score, self.global_step)
else:
audio_len = (
self.decoder_context_len + (labels[0][0][self.decoder_context_len :] != 0).sum().item()
)
labels_to_1024 = self.convert_tokens_to_range(labels[0, :, 0:audio_len])
label_wav = self.decode_wav_from_codec_model(labels_to_1024)
dec_input_to_1024 = self.convert_tokens_to_range(dec_input[0, :, 0:audio_len])
dec_input_wav = self.decode_wav_from_codec_model(dec_input_to_1024)
self.logger.experiment.add_audio(
"train_label_wav", label_wav, self.global_step, self.sample_rate
)
self.logger.experiment.add_audio(
"train_dec_input_wav", dec_input_wav, self.global_step, self.sample_rate
)
if isinstance(context_and_question_tokens, list):
context_tokens = context_and_question_tokens[0]
question_tokens = context_and_question_tokens[1]
input_token_list_all = [
question_tokens[0, 0, i].item() for i in range(question_tokens.shape[2])
]
input_token_list = [
(ti, t)
for ti, t in enumerate(input_token_list_all)
if t != 0 and t < self.speech_offset
]
context_end_step = context_and_question_tokens_lens[0][0].item()
_context_tokens = context_tokens[0, :, :context_end_step]
else:
input_token_list_all = [
context_and_question_tokens[0, 0, i].item()
for i in range(context_and_question_tokens.shape[2])
]
input_token_list = [
(ti, t)
for ti, t in enumerate(input_token_list_all)
if t != 0 and t < self.speech_offset
]
context_end_step = input_token_list[0][0]
_context_tokens = context_and_question_tokens[0, :, :context_end_step]
if context_end_step > 1:
is_speech_context = _context_tokens[1, :].sum().item() > 0
if is_speech_context:
_context_tokens = self.convert_tokens_to_range(
_context_tokens, pattern=self.context_pattern
)
_context_wav = self.decode_wav_from_codec_model(_context_tokens)
self.logger.experiment.add_audio(
"train_context_wav", _context_wav, self.global_step, self.sample_rate
)
else:
_context_token_list = [v.item() for v in _context_tokens[0, :]]
_context_text = self.frozen_model.tokenizer.ids_to_text(
[v for v in _context_token_list if v < self.lm_vocab_size]
)
self.logger.experiment.add_text(
"train_context_text", _context_text, self.global_step
)
question_si = text_limits[0, 0].item() - virtual_tokens.shape[1]
question_ei = text_limits[0, 1].item() - virtual_tokens.shape[1]
text_si = text_limits[0, 0].item()
text_ei = text_limits[0, 1].item()
input_text = self.frozen_model.tokenizer.ids_to_text(
[v for v in input_token_list_all[question_si:question_ei] if v < self.lm_vocab_size]
)
self.logger.experiment.add_text("Train Input Text", input_text, self.global_step)
input_phoneme_tokens = [
v - self.lm_vocab_size
for v in input_token_list_all[question_si:question_ei]
if v >= self.lm_vocab_size
]
if len(input_phoneme_tokens) > 0:
phoneme_text = self.phoneme_tokenizer.decode(input_phoneme_tokens)
self.logger.experiment.add_text(
"Train Input Phoneme Text", phoneme_text, self.global_step
)
token_logits = out_logits[0]
speech_logits_list = out_logits[1]
attention_probs_list = out_logits[2] # list of (BS, 12, out_length, in_length)
if attention_probs_list is not None:
attention_sliced_list = []
for lidx in range(len(attention_probs_list)):
attention_probs = attention_probs_list[lidx]
for _i in range(attention_probs.shape[1]):
name = f"Attention Probs Layer {lidx} Head {_i}"
attention_to_plot = attention_probs[0, _i, :audio_len, :text_ei]
if self.plot_alignments_sliced:
attention_to_plot = attention_probs[0, _i, 0:audio_len, text_si:text_ei]
# 4 to offset "Text to Speech this"
name += " Sliced"
alignment_image = plot_alignment_to_numpy_for_speechllm(
attention_to_plot.cpu().float().numpy().T,
phoneme_ver=0 if self.plot_alignments_sliced else 1,
phoneme_seq=None if self.plot_alignments_sliced else [text_si],
)
self.logger.experiment.add_image(
name,
alignment_image,
self.global_step,
dataformats="HWC",
)
attention_sliced_list.append(
attention_probs[
0, _i, self.decoder_context_len : audio_len, text_si:text_ei
]
)
attention_sliced = torch.stack(attention_sliced_list)
attention_sliced = torch.mean(attention_sliced, 0)
text = None
if len(input_text) > 0:
text = self.frozen_model.tokenizer.ids_to_tokens(
[
v
for v in input_token_list_all[question_si:question_ei]
if v < self.lm_vocab_size
]
)
if len(input_phoneme_tokens) > 0:
text = phoneme_text.split("|")
alignment_image_sliced = plot_alignment_to_numpy_for_speechllm(
attention_sliced.cpu().float().numpy().T,
phoneme_seq=text,
phoneme_ver=2,
vmin=0.0,
phone_offset=0,
h_offset=False,
)
self.logger.experiment.add_image(
f"Attention Probs Average Sliced",
alignment_image_sliced,
self.global_step,
dataformats="HWC",
)
if self.frozen_model.enc_dec_model.parallel_output:
# Gather from tensor parallel region
token_logits = tensor_parallel.gather_from_tensor_model_parallel_region(token_logits)
for _i in range(len(speech_logits_list)):
speech_logits_list[_i] = tensor_parallel.gather_from_tensor_model_parallel_region(
speech_logits_list[_i]
)
speech_logits = torch.stack(speech_logits_list, dim=-1) # (t, b, 1024, 7)
token_logits_example = token_logits[:, 0, :] * 1
speech_logits_example = speech_logits[:, 0, :, :] * 1
first_layer_tokens = token_logits_example.argmax(dim=1) - self.speech_offset
other_layer_tokens = []
for _i in range(speech_logits_example.shape[2]):
other_layer_tokens.append(speech_logits_example[:, :, _i].argmax(dim=1))
all_layer_tokens = torch.stack([first_layer_tokens] + other_layer_tokens) # (8, t)
all_layer_tokens = self.convert_tokens_to_range(
all_layer_tokens, apply_offset_correction=False
)
# all_layer_tokens = torch.clip(all_layer_tokens, 0, 1023)
predicted_wav = self.decode_wav_from_codec_model(all_layer_tokens)
self.logger.experiment.add_audio(
"train_tf_pred_wav", predicted_wav, self.global_step, self.sample_rate
)
def loss_func(loss_args):
output_tensor, out_logits, curr_step = loss_args
alignment_loss = out_logits[3]
loss = self.frozen_model.loss_func(loss_mask, output_tensor)
if (
(alignment_loss is not None)
and (curr_step > self.alignment_loss_start_step)
and (curr_step < self.alignment_loss_end_step)
):
logging.debug(f"Adding alignment loss. cur:{curr_step} start:{self.alignment_loss_start_step}")
loss = loss + alignment_loss
reduced_loss = average_losses_across_data_parallel_group([loss])
return loss, {'avg': reduced_loss}
return [output_tensor, out_logits, self.global_step], loss_func
return fwd_output_and_loss_func
def get_forward_output_only_func(self):
"""Used in inference / predict"""
def fwd_output_only_func(dataloader_iter, model):
batch = next(dataloader_iter)
_batch = []
for x in batch:
if isinstance(x, torch.Tensor):
x = x.cuda(non_blocking=True)
elif isinstance(x, list):
if isinstance(x[0], torch.Tensor):
x = [y.cuda(non_blocking=True) for y in x]
_batch.append(x)
batch = _batch
# batch = [x.cuda(non_blocking=True) if isinstance(x, torch.Tensor) else x for x in batch]
(
decoder_max_sequence_len,
encoder_max_sequence_len,
context_and_question_tokens,
enc_mask,
dec_input,
dec_input_mask,
position_ids,
taskname_ids,
speech_mask,
) = batch
output_logits, _, token_and_speech_logits = model(
context_and_question_tokens,
context_and_question_tokens,
enc_mask,
dec_input,
dec_input_mask,
position_ids,
taskname_ids,
labels=None,
speech_mask=speech_mask,
inference=True,
inference_step=1,
decoder_max_sequence_len=decoder_max_sequence_len,
encoder_max_sequence_len=encoder_max_sequence_len,
)
output_tensor = [output_logits, token_and_speech_logits]
def id_func(output_tensor):
return 0, {'output_logits': output_tensor[0], 'token_and_speech_logits': output_tensor[1]}
return output_tensor, id_func
return fwd_output_only_func
def backward(self, *args, **kwargs):
"""LightningModule hook to do backward.
We want this to do nothing since we run backward in the fwd/bwd functions from megatron-core.
No need to call it here.
"""
return
def optimizer_zero_grad(self, *args, **kwargs):
"""LightningModule hook to zero grad.
We want this to do nothing as we are zeroing grads during the training_step.
"""
return
def set_input_tensor(self, input_tensor):
"""Set input tensor to be used instead of forward()'s input.
When using pipeline parallelism the input from the previous
stage comes from communication, not from the input, so the
model's forward_step_func won't have it. This function is thus
used by internal code to bypass the input provided by the
forward_step_func"""
self.frozen_model.enc_dec_model.set_input_tensor(input_tensor)
def on_train_epoch_start(self) -> None:
gbs = self.cfg.global_batch_size
mbs = self.cfg.micro_batch_size
self._reconfigure_batch_sizes(gbs, mbs)
return super().on_train_epoch_start()
def on_validation_epoch_start(self) -> None:
gbs = self.cfg.get('validation_global_batch_size', self.cfg.global_batch_size)
mbs = self.cfg.get('validation_micro_batch_size', self.cfg.micro_batch_size)
self._reconfigure_batch_sizes(gbs, mbs)
return super().on_validation_epoch_start()
def training_step(self, dataloader_iter, batch_idx):
self._optimizer.zero_grad()
batch = next(dataloader_iter)
# apply text classifier-free guidance by replacing input question tokens with [UNK].
if self.train_text_cfg_prob > 0.0:
if self._rng.random() < self.train_text_cfg_prob:
logging.info(f"Text Classifier-Free Guidance is triggered for the {batch_idx}-th batch.")
# temporally disable computing CTC alignment loss.
if self.use_alignment_loss:
self.frozen_model.enc_dec_model.use_alignment_loss = False
# make cross-attention prior to None to remove the prior.
batch[11] = None
# replace question token IDs with [UNK]'s id. No speech offset for Phoneme's [UNK]. Same op as train.
# instruction token IDs are bpe token IDs directly obtained from self.tokenizer without any offset.
# question token IDs are phoneme and grapheme token IDs and are offset by self.lm_vocab_size
# if under "Phoneme TTS" instruction, so existing no overlaps between instruction and question token IDs.
# question token IDs are bpe token IDs without any offset
# if under "Text to speech this" instruction, so existing overlaps between instruction and question token IDs.
context_and_question_tokens = batch[
1
] # (batch_size, self.num_speech_codebooks, max_context_question_tokens_len)
text_limits = batch[12]
virtual_tokens = batch[0]
question_limits = text_limits - virtual_tokens.size(
1
) # (b, 2), reset question range to start from [pad] context, same start position as context_and_question_tokens.
question_start = question_limits[:, 0].unsqueeze(1) # (b, 1)
question_end = question_limits[:, 1].unsqueeze(1) # (b, 1)
if isinstance(context_and_question_tokens, list): # indicate self.encoder_type=multi_transformers.
context_tokens, question_tokens = context_and_question_tokens
question_tokens_unconditioned = question_tokens.clone()
time_range = torch.arange(
question_tokens_unconditioned.size(2), device=question_tokens_unconditioned.device
).unsqueeze(0)
question_mask = (time_range >= question_start) & (
time_range < question_end
) # create a mask for question only tokens.
question_tokens_unconditioned[:, 0][