File size: 21,660 Bytes
24303c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2024 Alibaba Inc
#
# 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.

import torch.nn as nn
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers import Qwen2ForCausalLM, Qwen2Config
from torch.nn.utils.rnn import pad_sequence, unpad_sequence
from tqdm import tqdm

def topk_sampling(weighted_scores, decoded_tokens, top_k=1024):
    zeros = weighted_scores.new_ones(weighted_scores.shape) * float('-inf')
    values,indices =  torch.topk(weighted_scores,top_k)
    zeros.scatter_(-1, indices, values)
    return random_sampling(zeros,decoded_tokens)

# Repetition Aware Sampling in VALL-E 2

def ras_sampling(weighted_scores, decoded_tokens, top_p=0.8, top_k=50, win_size=10, tau_r=0.1):
    top_ids = nucleus_sampling(weighted_scores, top_p=top_p, top_k=top_k)
    rep_num = (torch.tensor(decoded_tokens[-win_size:]).to(weighted_scores.device) == top_ids).sum().item()
    if rep_num >= win_size * tau_r:
        top_ids = random_sampling(weighted_scores, decoded_tokens)
    return top_ids

def caras_sampling(weighted_scores, decoded_tokens, top_p=0.8, top_k=25, win_size=10, tau_r=0.1):
    weighted_scores, cfg_weighted_scores = weighted_scores
    top_ids = nucleus_sampling(weighted_scores, top_p=top_p, top_k=top_k)
    rep_num = (torch.tensor(decoded_tokens[-win_size:]).to(weighted_scores.device) == top_ids).sum().item()
    if rep_num >= win_size * tau_r:
        top_ids = random_sampling(cfg_weighted_scores, decoded_tokens)
    return top_ids

def nucleus_sampling(weighted_scores, top_p=0.8, top_k=25):
    prob, indices = [], []
    cum_prob = 0.0
    sorted_value, sorted_idx = weighted_scores.softmax(dim=0).sort(descending=True, stable=True)
    for i in range(len(sorted_idx)):
        # sampling both top-p and numbers.
        if cum_prob < top_p and len(prob) < top_k:
            cum_prob += sorted_value[i]
            prob.append(sorted_value[i])
            indices.append(sorted_idx[i])
        else:
            break
    prob = torch.tensor(prob).to(weighted_scores)
    indices = torch.tensor(indices, dtype=torch.long).to(weighted_scores.device)
    top_ids = indices[prob.multinomial(1, replacement=True)]
    return top_ids


def random_sampling(weighted_scores, decoded_tokens):
    top_ids = weighted_scores.softmax(dim=0).multinomial(1, replacement=True)
    return top_ids

def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
                ignore_label: int) -> torch.Tensor:
    """Calculate accuracy.

    Args:
        pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
        pad_targets (LongTensor): Target label tensors (B, Lmax).
        ignore_label (int): Ignore label id.

    Returns:
        torch.Tensor: Accuracy value (0.0 - 1.0).

    """
    pad_pred = pad_outputs.view(pad_targets.size(0), pad_targets.size(1),
                                pad_outputs.size(1)).argmax(2)
    mask = pad_targets != ignore_label
    numerator = torch.sum(
        pad_pred.masked_select(mask) == pad_targets.masked_select(mask))
    denominator = torch.sum(mask)
    return (numerator / denominator).detach()


def subsequent_mask(
        size: int,
        device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
    """Create mask for subsequent steps (size, size).

    This mask is used only in decoder which works in an auto-regressive mode.
    This means the current step could only do attention with its left steps.

    In encoder, fully attention is used when streaming is not necessary and
    the sequence is not long. In this  case, no attention mask is needed.

    When streaming is need, chunk-based attention is used in encoder. See
    subsequent_chunk_mask for the chunk-based attention mask.

    Args:
        size (int): size of mask
        str device (str): "cpu" or "cuda" or torch.Tensor.device
        dtype (torch.device): result dtype

    Returns:
        torch.Tensor: mask

    Examples:
        >>> subsequent_mask(3)
        [[1, 0, 0],
         [1, 1, 0],
         [1, 1, 1]]
    """
    arange = torch.arange(size, device=device)
    mask = arange.expand(size, size)
    arange = arange.unsqueeze(-1)
    mask = mask <= arange
    return mask


def subsequent_chunk_mask(
        size: int,
        chunk_size: int,
        num_left_chunks: int = -1,
        device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
    """Create mask for subsequent steps (size, size) with chunk size,
       this is for streaming encoder

    Args:
        size (int): size of mask
        chunk_size (int): size of chunk
        num_left_chunks (int): number of left chunks
            <0: use full chunk
            >=0: use num_left_chunks
        device (torch.device): "cpu" or "cuda" or torch.Tensor.device

    Returns:
        torch.Tensor: mask

    Examples:
        >>> subsequent_chunk_mask(4, 2)
        [[1, 1, 0, 0],
         [1, 1, 0, 0],
         [1, 1, 1, 1],
         [1, 1, 1, 1]]
    """
    ret = torch.zeros(size, size, device=device, dtype=torch.bool)
    for i in range(size):
        if num_left_chunks < 0:
            start = 0
        else:
            start = max((i // chunk_size - num_left_chunks) * chunk_size, 0)
        ending = min((i // chunk_size + 1) * chunk_size, size)
        ret[i, start:ending] = True
    return ret


def add_optional_chunk_mask(xs: torch.Tensor,
                            masks: torch.Tensor,
                            use_dynamic_chunk: bool,
                            use_dynamic_left_chunk: bool,
                            decoding_chunk_size: int,
                            static_chunk_size: int,
                            num_decoding_left_chunks: int,
                            enable_full_context: bool = True):
    """ Apply optional mask for encoder.

    Args:
        xs (torch.Tensor): padded input, (B, L, D), L for max length
        mask (torch.Tensor): mask for xs, (B, 1, L)
        use_dynamic_chunk (bool): whether to use dynamic chunk or not
        use_dynamic_left_chunk (bool): whether to use dynamic left chunk for
            training.
        decoding_chunk_size (int): decoding chunk size for dynamic chunk, it's
            0: default for training, use random dynamic chunk.
            <0: for decoding, use full chunk.
            >0: for decoding, use fixed chunk size as set.
        static_chunk_size (int): chunk size for static chunk training/decoding
            if it's greater than 0, if use_dynamic_chunk is true,
            this parameter will be ignored
        num_decoding_left_chunks: number of left chunks, this is for decoding,
            the chunk size is decoding_chunk_size.
            >=0: use num_decoding_left_chunks
            <0: use all left chunks
        enable_full_context (bool):
            True: chunk size is either [1, 25] or full context(max_len)
            False: chunk size ~ U[1, 25]

    Returns:
        torch.Tensor: chunk mask of the input xs.
    """
    # Whether to use chunk mask or not
    if use_dynamic_chunk:
        max_len = xs.size(1)
        if decoding_chunk_size < 0:
            chunk_size = max_len
            num_left_chunks = -1
        elif decoding_chunk_size > 0:
            chunk_size = decoding_chunk_size
            num_left_chunks = num_decoding_left_chunks
        else:
            # chunk size is either [1, 25] or full context(max_len).
            # Since we use 4 times subsampling and allow up to 1s(100 frames)
            # delay, the maximum frame is 100 / 4 = 25.
            chunk_size = torch.randint(1, max_len, (1, )).item()
            num_left_chunks = -1
            if chunk_size > max_len // 2 and enable_full_context:
                chunk_size = max_len
            else:
                chunk_size = chunk_size % 25 + 1
                if use_dynamic_left_chunk:
                    max_left_chunks = (max_len - 1) // chunk_size
                    num_left_chunks = torch.randint(0, max_left_chunks,
                                                    (1, )).item()
        chunk_masks = subsequent_chunk_mask(xs.size(1), chunk_size,
                                            num_left_chunks,
                                            xs.device)  # (L, L)
        chunk_masks = chunk_masks.unsqueeze(0)  # (1, L, L)
        chunk_masks = masks & chunk_masks  # (B, L, L)
    elif static_chunk_size > 0:
        num_left_chunks = num_decoding_left_chunks
        chunk_masks = subsequent_chunk_mask(xs.size(1), static_chunk_size,
                                            num_left_chunks,
                                            xs.device)  # (L, L)
        chunk_masks = chunk_masks.unsqueeze(0)  # (1, L, L)
        chunk_masks = masks & chunk_masks  # (B, L, L)
    else:
        chunk_masks = masks
    return chunk_masks


def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
    """Make mask tensor containing indices of padded part.

    See description of make_non_pad_mask.

    Args:
        lengths (torch.Tensor): Batch of lengths (B,).
    Returns:
        torch.Tensor: Mask tensor containing indices of padded part.

    Examples:
        >>> lengths = [5, 3, 2]
        >>> make_pad_mask(lengths)
        masks = [[0, 0, 0, 0 ,0],
                 [0, 0, 0, 1, 1],
                 [0, 0, 1, 1, 1]]
    """
    batch_size = lengths.size(0)
    max_len = max_len if max_len > 0 else lengths.max().item()
    seq_range = torch.arange(0,
                             max_len,
                             dtype=torch.int64,
                             device=lengths.device)
    seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
    seq_length_expand = lengths.unsqueeze(-1)
    mask = seq_range_expand >= seq_length_expand
    return mask

qwen_conf = {
    "architectures": [
    "Qwen2ForCausalLM"
    ],
    "attention_dropout": 0.0,
    "bos_token_id": 151643,
    "eos_token_id": 151643,
    "hidden_act": "silu",
    "hidden_size": 896,
    "initializer_range": 0.02,
    "intermediate_size": 4864,
    "max_position_embeddings": 32768,
    "max_window_layers": 24,
    "model_type": "qwen2",
    "num_attention_heads": 14,
    "num_hidden_layers": 24,
    "num_key_value_heads": 2,
    "rms_norm_eps": 1e-06,
    "rope_theta": 1000000.0,
    "sliding_window": 32768,
    "tie_word_embeddings": True,
    "torch_dtype": "bfloat16",
    "transformers_version": "4.40.1",
    "use_cache": True,
    "use_mrope": False,
    "use_sliding_window": False,
    "vocab_size": 1024
}

# qwen_conf = {
#     "architectures": [
#     "Qwen2ForCausalLM"
#     ],
#     "attention_dropout": 0.0,
#     "bos_token_id": 151643,
#     "eos_token_id": 151643,
#     "hidden_act": "silu",
#     "hidden_size": 768,
#     "initializer_range": 0.02,
#     "intermediate_size": 3072,
#     "max_position_embeddings": 32768,
#     "max_window_layers": 24,
#     "model_type": "qwen2",
#     "num_attention_heads": 12,
#     "num_hidden_layers": 24,
#     "num_key_value_heads": 2,
#     "rms_norm_eps": 1e-06,
#     "rope_theta": 1000000.0,
#     "sliding_window": 32768,
#     "tie_word_embeddings": True,
#     "torch_dtype": "bfloat16",
#     "transformers_version": "4.40.1",
#     "use_cache": True,
#     "use_mrope": False,
#     "use_sliding_window": False,
#     "vocab_size": 1024
# }

DTYPES = {
    "bf16": torch.bfloat16,
    "fp16": torch.float16,
}

IGNORE_ID = -100
MAX_TEXT_TOKEN = 1024
BERT_DIM = 1024
SPK_EMB_DIM = 256

class QwenEmbeddingEncoder(nn.Module):
    def __init__(
            self,
            dtype: str = "bf16"
    ):
        super(QwenEmbeddingEncoder, self).__init__()
        self.dtype = DTYPES.get(dtype, torch.float32)
        config = Qwen2Config(**qwen_conf)
        self.model = AutoModelForCausalLM.from_config(config)
        self._output_size = self.model.config.hidden_size

    def output_size(self) -> int:
        return self._output_size

    def forward(
            self,
            input_embeds: torch.Tensor,
            ilens: torch.Tensor,
    ):
        input_masks = (~make_pad_mask(ilens)).to(input_embeds.device).long()

        outs = self.model(
            inputs_embeds=input_embeds,
            attention_mask=input_masks,
            output_hidden_states=True,
            return_dict=True,
        )

        return outs.hidden_states[-1], input_masks

    def forward_one_step(self, xs, masks, cache=None):
        outs = self.model(
            inputs_embeds=xs,
            attention_mask=masks,
            output_hidden_states=True,
            return_dict=True,
            use_cache=True,
            past_key_values=cache,
        )
        xs = outs.hidden_states[-1]
        new_cache = outs.past_key_values
        assert new_cache is not None
        return xs, masks, new_cache


class LLM(torch.nn.Module):
    def __init__(
            self,
            audio_token_size: int,
            dtype: str = "fp32",
    ):
        super().__init__()
        self.dtype = DTYPES.get(dtype, torch.float32)

        # 1. build text token inputs related modules

        self.llm = QwenEmbeddingEncoder(dtype=dtype)
        self.llm.model.model.embed_tokens = None
        self.llm_input_size = self.llm.model.config.hidden_size
        self.llm_output_size = self.llm.model.config.hidden_size
        self.audio_token_size = audio_token_size

        self.llm_decoder = nn.Linear(self.llm_output_size, audio_token_size + 1)
        self.criterion_ce = torch.nn.CrossEntropyLoss(ignore_index=IGNORE_ID)
        # 3. [Optional] build audio token related modules
        self.speech_embedding = torch.nn.Embedding(audio_token_size, self.llm_input_size)
        self.text_embedding = nn.Embedding(MAX_TEXT_TOKEN, self.llm_input_size)
        self.bert_embedding = nn.Linear(BERT_DIM, self.llm_input_size)
        self.spk_embedding =  nn.Linear(SPK_EMB_DIM, self.llm_input_size)

        self.audio_bos = nn.Parameter(torch.randn(1, self.llm_input_size))

    def forward(
            self,
            text_tokens,
            bert_features,
            spk_features,
            prosody_tokens,
            lengths,
    ):
        """
        Args:
            text_tokens: (B, L)
            bert_features: (B, T, 1024)
            spk_features: (B, 256)
            prosody_tokens: (B, L)
            lengths: (B,)
        """
        device = text_tokens.device
        bsz = text_tokens.size(0)

        # get input embeddings
        spk_embedding = self.spk_embedding(spk_features)  # [b, 256] -> [b, h]

        text_embedding = self.text_embedding(text_tokens)  # [b, t] -> [b, t, h]
        bert_embedding = self.bert_embedding(bert_features)  # [b, t, 1024] -> [b, t, h]
        text_embedding = text_embedding + bert_embedding

        audio_embedding = self.speech_embedding(prosody_tokens)  #[b, t] -> [b, t, h]

        # get lm input and target
        lm_input = []
        lm_target = []
        for b in range(bsz):
            # cond part
            spk_emb = spk_embedding[b].unsqueeze(0)  # [h] -> [1, h]
            text_emb = text_embedding[b][:lengths[b]]  # [t, h]

            # ar input
            audio_emb = audio_embedding[b][
                        :lengths[b]]  # [t, h]
            audio_emb = torch.cat([self.audio_bos, audio_emb], dim=0) # [t+1, h]

            cur_inp = torch.cat([spk_emb, text_emb, audio_emb], dim=0)  # [2t+2, h]
            lm_input.append(cur_inp)

            # ar target
            cur_target = prosody_tokens[b][:lengths[b]] # [t]
            eos = torch.tensor([self.audio_token_size], dtype=torch.int64).to(device)
            cur_target = torch.cat([cur_target, eos], dim=0) # [t+1]

            cur_target = torch.nn.functional.pad(cur_target, (cur_inp.shape[0] - cur_target.size(0), 0),
                                                 value=IGNORE_ID) # [2t+2]
            lm_target.append(cur_target)


        lm_input_len = torch.tensor([i.size(0) for i in lm_input], dtype=torch.int32).to(device)
        lm_input = pad_sequence(lm_input, batch_first=True, padding_value=IGNORE_ID)
        lm_target = pad_sequence(lm_target, batch_first=True, padding_value=IGNORE_ID)

        # 6. run lm forward
        lm_output, lm_output_mask = self.llm(lm_input.to(self.dtype), lm_input_len.to(device))
        logits = self.llm_decoder(lm_output)
        loss = self.criterion_ce(logits.view(-1, self.audio_token_size + 1), lm_target.view(-1))
        # print(loss,lm_input.shape)

        acc = th_accuracy(logits.view(-1, self.audio_token_size + 1), lm_target, ignore_label=IGNORE_ID)

        return {'loss': loss, 'acc': acc}

    @torch.inference_mode()
    @torch.no_grad()
    def inference(
            self,
            text_tokens,
            bert_features,
            spk_features,
            prompt_audio_token=None,
            sampling_method=None,
            sampling_kwargs=None,
    ):
        device = text_tokens.device
        if prompt_audio_token is not None:
            res_tokens = prompt_audio_token.clone()
            audio_embedding = self.speech_embedding(prompt_audio_token) # [b, t] -> [b, t, h]
            audio_embedding = torch.cat([self.audio_bos.unsqueeze(0), audio_embedding], dim=1) # [b, t+1, h]

        else:
            res_tokens = torch.zeros((text_tokens.size(0), 0), dtype=torch.int64).to(device)
            audio_embedding = self.audio_bos.unsqueeze(0) # [1, 1, h]


        # get input embeddings
        spk_embedding = self.spk_embedding(spk_features)  # [b, 256] -> [b, h]

        text_embedding = self.text_embedding(text_tokens)  # [b, t] -> [b, t, h]
        bert_embedding = self.bert_embedding(bert_features)  # [b, t, 1024] -> [b, t, h]
        text_embedding = text_embedding + bert_embedding


        # cond part
        spk_embedding = spk_embedding.unsqueeze(0)  # [b, h] -> [b, 1, h]


        lm_input = torch.cat([spk_embedding, text_embedding, audio_embedding], dim=1)
        # if cfg_scale != 1.0:
        #     print("infer with cfg_scale:", cfg_scale)
        #     lm_cf_input = torch.cat([0*clap_embedding, 0*text_embedding, audio_embedding], dim=1)
        #     lm_input = torch.cat([lm_input, lm_cf_input], dim=0)
        # 4. cal min/max_length

        max_len = text_tokens.shape[-1]

        # 5. step by step decode
        out_tokens = []
        offset = 0
        state = None

        for i in tqdm(range(int(max_len+1))):
            y_pred, _, state = self.llm.forward_one_step(lm_input.to(self.dtype),
                                                         torch.ones(lm_input.shape[0], lm_input.shape[1],
                                                                    device=lm_input.device).to(torch.bool), cache=state)
            logits = self.llm_decoder(y_pred[:, -1])
            # if cfg_scale != 1.0:
            #     # perform context free guidance
            #     logits_cf = logits[1]
            #     logits = logits[0]
            #     infer_cfg_ratio = cfg_scale
            #     logits = infer_cfg_ratio * logits + (1 - infer_cfg_ratio) * logits_cf

            logp = logits.log_softmax(dim=-1)
            logp = logp.squeeze(dim=0)

            # if i < int(min_len):
            #     logp[self.audio_token_size] = torch.tensor(float('-inf'), dtype=self.dtype)

            top_ids = sampling_method(logp, out_tokens, **sampling_kwargs).item()

            if top_ids == self.audio_token_size:
                print('end!')
                break

            # # in stream mode, yield token one by one

            current_token = torch.tensor([[top_ids]], dtype=torch.int64, device=device)
            res_tokens = torch.cat([res_tokens, current_token], dim=1)
            out_tokens.append(top_ids)
            offset += lm_input.size(1)
            lm_input = self.speech_embedding.weight[top_ids].reshape(1, 1, -1)
            # if cfg_scale != 1.0:
            #     lm_input = lm_input.repeat(2, 1, 1)
        
        if res_tokens.shape[-1]!=max_len:
            print('infer error', res_tokens.shape, max_len)
            res_tokens = res_tokens[:,:max_len]
            res_tokens = torch.nn.functional.pad(res_tokens, (0, max_len-res_tokens.size(1)), value=0)
        return res_tokens

if __name__ == '__main__':

    audio_token_size=1024
    device = 'cuda'
    llm = LLM(audio_token_size=audio_token_size).to(device)
    print('n_params:', sum(p.numel() for p in llm.parameters() if p.requires_grad)/1e6, 'M')
    text = torch.randint(0, 1024, (2, 11)).to(device)
    bert = torch.randn(2, 11, 1024).to(device)
    spk = torch.randn(2, 256).to(device)
    prosody = torch.randint(0, 1024, (2, 11)).to(device)
    lengths = torch.tensor([4, 11]).to(device)

    llm.train()
    res = llm(text, bert, spk, prosody, lengths)
    loss = res['loss']
    acc = res['acc']
    print('loss:', loss, 'acc:', acc)
    loss.backward()
    for name, param in llm.named_parameters():
        if param.grad is  None:
            print('name:', name, 'has no grad')

    llm.eval()
    text = text[:1]
    bert = bert[:1]
    spk = spk[:1]
    prosody = prosody[:1]

    res = llm.inference(text, bert, spk, None, topk_sampling, {'top_k': 1024})
    print('sampling res', res.shape)