File size: 14,600 Bytes
c968fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2023 Amphion.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import json
import os
import shutil
import torch
import time
from pathlib import Path
import torch
from tqdm import tqdm
import torch.nn as nn
from .base_trainer import BaseTrainer


def make_pad_mask(
    lengths: torch.Tensor, max_len: int = 0, left_pad=False
) -> torch.Tensor:
    """
    Args:
      lengths:
        A 1-D tensor containing sentence lengths.
      max_len:
        The length of masks.
    left_pad:
        A boolean indicating whether to left pad the mask.
    Returns:
      Return a 2-D bool tensor, where masked positions
      are filled with `True` and non-masked positions are
      filled with `False`.

    >>> lengths = torch.tensor([1, 3, 2, 5])
    >>> make_pad_mask(lengths)
    tensor([[False,  True,  True,  True,  True],
            [False, False, False,  True,  True],
            [False, False,  True,  True,  True],
            [False, False, False, False, False]])
    """
    assert lengths.ndim == 1, lengths.ndim
    max_len = max(max_len, lengths.max())
    n = lengths.size(0)
    seq_range = torch.arange(0, max_len, device=lengths.device)
    expaned_lengths = seq_range.unsqueeze(0).expand(n, max_len)
    mask = expaned_lengths >= lengths.unsqueeze(-1)

    if left_pad:
        mask = mask.flip(dims=[1])

    return mask


class ValleARTrainer(BaseTrainer):
    def __init__(self, args=None, cfg=None):
        super().__init__(args, cfg)
        if self.cfg.use_speechtokenizer:
            from models.codec.speechtokenizer.model import SpeechTokenizer

            config_path = "./ckpts/speechtokenizer_hubert_avg/config.json"
            ckpt_path = "./ckpts/speechtokenizer_hubert_avg/SpeechTokenizer.pt"
            assert os.path.isfile(
                config_path
            ), f"codec model {config_path} not found! Download with huggingface-cli download fnlp/SpeechTokenizer speechtokenizer_hubert_avg/SpeechTokenizer.pt speechtokenizer_hubert_avg/config.json --local-dir ckpts"
            assert os.path.isfile(
                ckpt_path
            ), f"codec model {ckpt_path} not found! Download with huggingface-cli download fnlp/SpeechTokenizer speechtokenizer_hubert_avg/SpeechTokenizer.pt speechtokenizer_hubert_avg/config.json --local-dir ckpts"
            self.codec_encoder = SpeechTokenizer.load_from_checkpoint(
                config_path, ckpt_path
            )
            self.codec_encoder.eval()
            self.codec_encoder.to(self.accelerator.device)
            print(f"Loaded SpeechTokenizer from {config_path} and {ckpt_path}")
        else:
            from encodec import EncodecModel

            with self.accelerator.main_process_first():
                self.codec_encoder = EncodecModel.encodec_model_24khz()
                self.codec_encoder.set_target_bandwidth(6.0)
                self.codec_encoder.to(self.accelerator.device)
                self.codec_decoder = None
                print("Loaded EncodecModel")
        self.top1_accuracies = []
        self.top5_accuracies = []
        self.top10_accuracies = []

        if hasattr(self.cfg, "flatten_first_2_layers"):
            self.flatten_first_2_layers = self.cfg.flatten_first_2_layers
            print("flattened:", self.flatten_first_2_layers)
        else:
            self.flatten_first_2_layers = False

        if hasattr(self.cfg, "num_prediction_heads"):
            self.num_prediction_heads = self.cfg.num_prediction_heads
            print("num_prediction_heads:", self.num_prediction_heads)

    def _accelerator_prepare(self):
        # if self.accelerator.is_main_process:
        #     breakpoint()
        # self.accelerator.wait_for_everyone()

        (
            self.model,
            self.optimizer,
        ) = self.accelerator.prepare(
            self.model,
            self.optimizer,
        )

    def _build_criterion(self):
        pass  # loss is directly returned from model

    def _build_scheduler(self):
        from transformers import (
            get_cosine_schedule_with_warmup,
            get_constant_schedule_with_warmup,
        )

        return get_cosine_schedule_with_warmup(
            self.optimizer,
            num_warmup_steps=self.cfg.train.scheduler.warmup_steps,
            num_training_steps=self.cfg.train.scheduler.total_steps,
        )

    def _build_model(self):
        if hasattr(self.cfg.model, "num_prediction_heads"):
            from .valle_ar_multihead import ValleAR
        else:
            from .valle_ar import ValleAR
        return ValleAR(**self.cfg.model)

    def _train_step(self, batch):
        # inference codec
        """Returns: dict('speech', 'speech_len', 'phone_ids', 'phone_lens')
        speech: [B, T]
        speech_len: [B]
        phone_ids: [B, T]
        phone_lens: [B]
        """
        device = self.accelerator.device
        for k, v in batch.items():
            if isinstance(v, torch.Tensor):
                batch[k] = v.to(device)
        with torch.no_grad():
            if self.cfg.use_speechtokenizer:
                # Extract discrete codes from SpeechTokenizer
                vq_id = self.codec_encoder.encode(
                    batch["speech"].unsqueeze(1)
                )  # [B,1,T] -> (n_q, B, T)
            else:
                vq_id = self.codec_encoder.encode(batch["speech"].unsqueeze(1))
                vq_id = torch.cat([encoded[0] for encoded in vq_id], dim=-1).transpose(
                    0, 1
                )

            # recovered_audio = self.codec_decoder(vq_emb, vq=False)
            # torchaudio.save('a.wav', recovered_audio[0], 16000)
            # vq_id: [8, B, T//320]
            if self.flatten_first_2_layers:
                first_layer = vq_id[0]
                second_layer = vq_id[1]
                # flatten the first two layers
                batch["speech"] = torch.stack(
                    [first_layer, second_layer], dim=-1
                ).flatten(-2, -1)
                batch["speech_len"] = batch["speech_len"] // 160
            elif hasattr(self.cfg.model, "num_prediction_heads"):
                batch["speech"] = vq_id[:2]  # first two layers
                batch["speech_len"] = (
                    batch["speech_len"] // 320
                )  # our codec downsamples 320x
            else:
                batch["speech"] = vq_id[0]  # use first layer
                batch["speech_len"] = (
                    batch["speech_len"] // 320
                )  # our codec downsamples 320x
        assert batch["speech_len"].max() <= batch["speech"].shape[-1]

        phone_mask = 1 - make_pad_mask(
            batch["phone_lens"], max_len=batch["phone_ids"].size(1), left_pad=False
        ).to(torch.long)
        speech_mask = 1 - make_pad_mask(
            batch["speech_len"], max_len=batch["speech"].size(1)
        ).to(torch.long)

        out = self.model(
            phone_ids=batch["phone_ids"],
            phone_mask=phone_mask,
            target_ids=batch["speech"],
            target_mask=speech_mask,
        )
        loss = out.loss
        # if self.accelerator.is_main_process:
        #     print(loss)
        # if hasattr(out, 'top1_acc'):
        #     self.top1_accuracies.append(out.top1_acc)
        #     self.top5_accuracies.append(out.top5_acc)
        #     self.top10_accuracies.append(out.top10_acc)
        #     print(f'avgs: top1: {sum(self.top1_accuracies)/len(self.top1_accuracies)}, top5: {sum(self.top5_accuracies)/len(self.top5_accuracies)}, top10: {sum(self.top10_accuracies)/len(self.top10_accuracies)}')
        #     breakpoint()
        return loss

    ##########add your own dataloader to the trainer#############
    def _build_dataloader(self):
        from torch.utils.data import ConcatDataset, DataLoader

        if self.cfg.train.dataset.name == "emilia":
            from .emilia_dataset import EmiliaDataset as VALLEDataset

            train_dataset = VALLEDataset()
        elif self.cfg.train.dataset.name == "mls":
            from .mls_dataset import VALLEDataset as VALLEDataset

            train_dataset = VALLEDataset(self.cfg.dataset, resample_to_24k=False)
        elif self.cfg.train.dataset.name == "libritts":
            from .libritts_dataset import VALLEDataset as VALLEDataset

            train_dataset = VALLEDataset(self.cfg.dataset)

        from .valle_collator import VALLECollator
        import numpy as np

        print("length of train_dataset:", len(train_dataset))

        collator = VALLECollator()

        if self.cfg.train.dataset.use_dynamic_batchsize:
            if self.accelerator.is_main_process:
                self.logger.info("Use Dynamic Batchsize......")
            from .mls_dataset import batch_by_size

            batch_sampler = batch_by_size(
                train_dataset.num_frame_indices,
                train_dataset.get_num_frames,
                max_tokens=self.cfg.train.max_tokens * self.accelerator.num_processes,
                max_sentences=self.cfg.train.max_sentences
                * self.accelerator.num_processes,
                required_batch_size_multiple=self.accelerator.num_processes,
            )
            np.random.shuffle(batch_sampler)
            print(batch_sampler[0])
            batches = [
                x[
                    self.accelerator.local_process_index :: self.accelerator.num_processes
                ]
                for x in batch_sampler
                if len(x) % self.accelerator.num_processes == 0
            ]
            from models.base.base_sampler import VariableSampler

            train_loader = DataLoader(
                train_dataset,
                collate_fn=collator,
                num_workers=self.cfg.train.dataloader.num_worker,
                batch_sampler=VariableSampler(
                    batches, drop_last=True, use_random_sampler=True
                ),
                pin_memory=self.cfg.train.dataloader.pin_memory,
                persistent_workers=self.cfg.train.dataloader.persistent_workers,
                prefetch_factor=4,
            )
            print(
                f"process {self.accelerator.local_process_index} has {len(batches)} batches"
            )
            self.accelerator.wait_for_everyone()

        else:
            sampler = torch.utils.data.distributed.DistributedSampler(
                train_dataset,
                num_replicas=self.accelerator.num_processes,
                rank=self.accelerator.local_process_index,
                shuffle=True,
            )
            train_loader = DataLoader(
                train_dataset,
                batch_size=self.cfg.train.batch_size,
                num_workers=self.cfg.train.dataloader.num_worker,
                pin_memory=self.cfg.train.dataloader.pin_memory,
                collate_fn=collator,
                sampler=sampler,
            )
            print(
                f"process {self.accelerator.local_process_index} has {len(train_loader)} batches"
            )

        return train_loader, None

    def _test_step(self, batch):
        # inference codec
        """Returns: dict('speech', 'speech_len', 'phone_ids', 'phone_lens')
        speech: [B, T]
        speech_len: [B]
        phone_ids: [B, T]
        phone_lens: [B]
        """
        import torchaudio

        device = self.accelerator.device
        for k, v in batch.items():
            if isinstance(v, torch.Tensor):
                batch[k] = v.to(device)
        with torch.no_grad():
            if self.cfg.use_speechtokenizer:
                # Extract discrete codes from SpeechTokenizer
                vq_id = self.codec_encoder.encode(
                    batch["speech"].unsqueeze(1)
                )  # [B,1,T] -> (n_q, B, T)
            else:
                vq_id = self.codec_encoder.encode(batch["speech"].unsqueeze(1))
                vq_id = torch.cat([encoded[0] for encoded in vq_id], dim=-1).transpose(
                    0, 1
                )
            # recovered_audio = self.codec_decoder(vq_emb, vq=False)
            # torchaudio.save('a.wav', recovered_audio[0], 16000)
            # vq_id: [8, B, T//200]

            # vq_emb = self.codec_decoder.quantizer.vq2emb(vq=vq_id[:1], n_quantizers=1)
            # recovered_audio = self.codec_decoder(vq_emb, vq=False)
            # recovered_audio.shape: torch.Size([1, 1, 50200])

            if self.flatten_first_2_layers:
                first_layer = vq_id[0]
                second_layer = vq_id[1]
                # flatten the first two layers
                batch["speech"] = torch.stack(
                    [first_layer, second_layer], dim=-1
                ).flatten(-2, -1)
                batch["speech_len"] = batch["speech_len"] // 160
            elif hasattr(self.cfg.model, "num_prediction_heads"):
                batch["speech"] = vq_id[:2]  # first two layers
                batch["speech_len"] = (
                    batch["speech_len"] // 320
                )  # our codec downsamples 320x
            else:
                batch["speech"] = vq_id[0]  # use first layer
                batch["speech_len"] = (
                    batch["speech_len"] // 320
                )  # our codec downsamples 320x

            # save gt
            breakpoint()
            recovered_audio = self.codec_encoder.decode(vq_id[:1, :1])
            # recovered_audio = self.codec_encoder.decode([(vq_id[:1].transpose(0,1), None)])
            torchaudio.save("gt.wav", recovered_audio[0].cpu(), 16000)
            out_vq_ids = self.model.sample_hf(
                batch["phone_ids"][:1, ...], batch["speech"][:1, :225], temperature=0.9
            )
            # out_vq_ids = torch.cat([batch['speech'][:1, :225], out_vq_ids[:1, ...]], dim=1)

            # reconstruct form tokens
            recovered_audio = self.codec_encoder.decode(out_vq_ids.unsqueeze(0))
            # recovered_audio = self.codec_encoder.decode([(out_vq_ids, None)])
            torchaudio.save("a.wav", recovered_audio[0].cpu(), 16000)
            breakpoint()
            print()

    @torch.inference_mode()
    def _valid_epoch(self):
        r"""Testing epoch. Should return average loss of a batch (sample) over
        one epoch. See ``train_loop`` for usage.
        """
        epoch_sum_loss = 0.0
        return epoch_sum_loss

    def _inference(self):
        pass

    def test_loop(self):
        self.model.eval()
        for batch in self.train_dataloader:
            self._test_step(batch)