File size: 30,190 Bytes
d8bfe4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
#               2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou)
#
# 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 os
from typing import Generator
import torch
import numpy as np
import threading
import time
from torch.nn import functional as F
from contextlib import nullcontext
import uuid
from models.cosyvoice.utils.common import fade_in_out
from models.cosyvoice.utils.file_utils import (
    convert_onnx_to_trt,
    export_cosyvoice2_vllm,
)
from models.cosyvoice.utils.common import TrtContextWrapper


class CosyVoiceModel:

    def __init__(
        self,
        llm: torch.nn.Module,
        flow: torch.nn.Module,
        hift: torch.nn.Module,
        fp16: bool = False,
    ):
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.llm = llm
        self.flow = flow
        self.hift = hift
        self.fp16 = fp16
        self.token_min_hop_len = 2 * self.flow.input_frame_rate
        self.token_max_hop_len = 4 * self.flow.input_frame_rate
        self.token_overlap_len = 20
        # mel fade in out
        self.mel_overlap_len = int(
            self.token_overlap_len / self.flow.input_frame_rate * 22050 / 256
        )
        self.mel_window = np.hamming(2 * self.mel_overlap_len)
        # hift cache
        self.mel_cache_len = 20
        self.source_cache_len = int(self.mel_cache_len * 256)
        # speech fade in out
        self.speech_window = np.hamming(2 * self.source_cache_len)
        # rtf and decoding related
        self.stream_scale_factor = 1
        assert (
            self.stream_scale_factor >= 1
        ), "stream_scale_factor should be greater than 1, change it according to your actual rtf"
        self.llm_context = (
            torch.cuda.stream(torch.cuda.Stream(self.device))
            if torch.cuda.is_available()
            else nullcontext()
        )
        self.lock = threading.Lock()
        # dict used to store session related variable
        self.tts_speech_token_dict = {}
        self.llm_end_dict = {}
        self.mel_overlap_dict = {}
        self.flow_cache_dict = {}
        self.hift_cache_dict = {}
        self.silent_tokens = []

    def load(self, llm_model, flow_model, hift_model):
        self.llm.load_state_dict(
            torch.load(llm_model, map_location=self.device, weights_only=True),
            strict=True,
        )
        self.llm.to(self.device).eval()
        self.flow.load_state_dict(
            torch.load(flow_model, map_location=self.device, weights_only=True),
            strict=True,
        )
        self.flow.to(self.device).eval()
        # in case hift_model is a hifigan model
        hift_state_dict = {
            k.replace("generator.", ""): v
            for k, v in torch.load(
                hift_model, map_location=self.device, weights_only=True
            ).items()
        }
        self.hift.load_state_dict(hift_state_dict, strict=True)
        self.hift.to(self.device).eval()

    def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
        llm_text_encoder = torch.jit.load(
            llm_text_encoder_model, map_location=self.device
        )
        self.llm.text_encoder = llm_text_encoder
        llm_llm = torch.jit.load(llm_llm_model, map_location=self.device)
        self.llm.llm = llm_llm
        flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
        self.flow.encoder = flow_encoder

    def load_trt(
        self,
        flow_decoder_estimator_model,
        flow_decoder_onnx_model,
        trt_concurrent,
        fp16,
    ):
        assert torch.cuda.is_available(), "tensorrt only supports gpu!"
        if (
            not os.path.exists(flow_decoder_estimator_model)
            or os.path.getsize(flow_decoder_estimator_model) == 0
        ):
            convert_onnx_to_trt(
                flow_decoder_estimator_model,
                self.get_trt_kwargs(),
                flow_decoder_onnx_model,
                fp16,
            )
        del self.flow.decoder.estimator
        import tensorrt as trt

        with open(flow_decoder_estimator_model, "rb") as f:
            estimator_engine = trt.Runtime(
                trt.Logger(trt.Logger.INFO)
            ).deserialize_cuda_engine(f.read())
        assert estimator_engine is not None, "failed to load trt {}".format(
            flow_decoder_estimator_model
        )
        self.flow.decoder.estimator = TrtContextWrapper(
            estimator_engine, trt_concurrent=trt_concurrent, device=self.device
        )

    def get_trt_kwargs(self):
        min_shape = [(2, 80, 4), (2, 1, 4), (2, 80, 4), (2, 80, 4)]
        opt_shape = [(2, 80, 500), (2, 1, 500), (2, 80, 500), (2, 80, 500)]
        max_shape = [(2, 80, 3000), (2, 1, 3000), (2, 80, 3000), (2, 80, 3000)]
        input_names = ["x", "mask", "mu", "cond"]
        return {
            "min_shape": min_shape,
            "opt_shape": opt_shape,
            "max_shape": max_shape,
            "input_names": input_names,
        }

    def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
        cur_silent_token_num, max_silent_token_num = 0, 5
        with self.llm_context, torch.cuda.amp.autocast(
            self.fp16 is True and hasattr(self.llm, "vllm") is False
        ):
            if isinstance(text, Generator):
                assert (self.__class__.__name__ != "CosyVoiceModel") and not hasattr(
                    self.llm, "vllm"
                ), "streaming input text is only implemented for CosyVoice2/3 and do not support vllm!"
                token_generator = self.llm.inference_bistream(
                    text=text,
                    prompt_text=prompt_text.to(self.device),
                    prompt_text_len=torch.tensor(
                        [prompt_text.shape[1]], dtype=torch.int32
                    ).to(self.device),
                    prompt_speech_token=llm_prompt_speech_token.to(self.device),
                    prompt_speech_token_len=torch.tensor(
                        [llm_prompt_speech_token.shape[1]], dtype=torch.int32
                    ).to(self.device),
                    embedding=llm_embedding.to(self.device),
                )
            else:
                token_generator = self.llm.inference(
                    text=text.to(self.device),
                    text_len=torch.tensor([text.shape[1]], dtype=torch.int32).to(
                        self.device
                    ),
                    prompt_text=prompt_text.to(self.device),
                    prompt_text_len=torch.tensor(
                        [prompt_text.shape[1]], dtype=torch.int32
                    ).to(self.device),
                    prompt_speech_token=llm_prompt_speech_token.to(self.device),
                    prompt_speech_token_len=torch.tensor(
                        [llm_prompt_speech_token.shape[1]], dtype=torch.int32
                    ).to(self.device),
                    embedding=llm_embedding.to(self.device),
                    uuid=uuid,
                )
            for i in token_generator:
                if i in self.silent_tokens:
                    cur_silent_token_num += 1
                    if cur_silent_token_num > max_silent_token_num:
                        continue
                else:
                    cur_silent_token_num = 0
                self.tts_speech_token_dict[uuid].append(i)
        self.llm_end_dict[uuid] = True

    def vc_job(self, source_speech_token, uuid):
        self.tts_speech_token_dict[uuid] = source_speech_token.flatten().tolist()
        self.llm_end_dict[uuid] = True

    def token2wav(
        self,
        token,
        prompt_token,
        prompt_feat,
        embedding,
        uuid,
        finalize=False,
        speed=1.0,
    ):
        with torch.cuda.amp.autocast(self.fp16):
            tts_mel, self.flow_cache_dict[uuid] = self.flow.inference(
                token=token.to(self.device, dtype=torch.int32),
                token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(
                    self.device
                ),
                prompt_token=prompt_token.to(self.device),
                prompt_token_len=torch.tensor(
                    [prompt_token.shape[1]], dtype=torch.int32
                ).to(self.device),
                prompt_feat=prompt_feat.to(self.device),
                prompt_feat_len=torch.tensor(
                    [prompt_feat.shape[1]], dtype=torch.int32
                ).to(self.device),
                embedding=embedding.to(self.device),
                flow_cache=self.flow_cache_dict[uuid],
            )

        # mel overlap fade in out
        if self.mel_overlap_dict[uuid].shape[2] != 0:
            tts_mel = fade_in_out(tts_mel, self.mel_overlap_dict[uuid], self.mel_window)
        # append hift cache
        if self.hift_cache_dict[uuid] is not None:
            hift_cache_mel, hift_cache_source = (
                self.hift_cache_dict[uuid]["mel"],
                self.hift_cache_dict[uuid]["source"],
            )
            tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
        else:
            hift_cache_source = torch.zeros(1, 1, 0)
        # keep overlap mel and hift cache
        if finalize is False:
            self.mel_overlap_dict[uuid] = tts_mel[:, :, -self.mel_overlap_len :]
            tts_mel = tts_mel[:, :, : -self.mel_overlap_len]
            tts_speech, tts_source = self.hift.inference(
                speech_feat=tts_mel, cache_source=hift_cache_source
            )
            if self.hift_cache_dict[uuid] is not None:
                tts_speech = fade_in_out(
                    tts_speech, self.hift_cache_dict[uuid]["speech"], self.speech_window
                )
            self.hift_cache_dict[uuid] = {
                "mel": tts_mel[:, :, -self.mel_cache_len :],
                "source": tts_source[:, :, -self.source_cache_len :],
                "speech": tts_speech[:, -self.source_cache_len :],
            }
            tts_speech = tts_speech[:, : -self.source_cache_len]
        else:
            if speed != 1.0:
                assert (
                    self.hift_cache_dict[uuid] is None
                ), "speed change only support non-stream inference mode"
                tts_mel = F.interpolate(
                    tts_mel, size=int(tts_mel.shape[2] / speed), mode="linear"
                )
            tts_speech, tts_source = self.hift.inference(
                speech_feat=tts_mel, cache_source=hift_cache_source
            )
            if self.hift_cache_dict[uuid] is not None:
                tts_speech = fade_in_out(
                    tts_speech, self.hift_cache_dict[uuid]["speech"], self.speech_window
                )
        return tts_speech

    def tts(
        self,
        text=torch.zeros(1, 0, dtype=torch.int32),
        flow_embedding=torch.zeros(0, 192),
        llm_embedding=torch.zeros(0, 192),
        prompt_text=torch.zeros(1, 0, dtype=torch.int32),
        llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        prompt_speech_feat=torch.zeros(1, 0, 80),
        source_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        stream=False,
        speed=1.0,
        **kwargs
    ):
        # this_uuid is used to track variables related to this inference thread
        this_uuid = str(uuid.uuid1())
        with self.lock:
            self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = (
                [],
                False,
            )
            self.hift_cache_dict[this_uuid] = None
            self.mel_overlap_dict[this_uuid] = torch.zeros(1, 80, 0)
            self.flow_cache_dict[this_uuid] = torch.zeros(1, 80, 0, 2)
        if source_speech_token.shape[1] == 0:
            p = threading.Thread(
                target=self.llm_job,
                args=(
                    text,
                    prompt_text,
                    llm_prompt_speech_token,
                    llm_embedding,
                    this_uuid,
                ),
            )
        else:
            p = threading.Thread(
                target=self.vc_job, args=(source_speech_token, this_uuid)
            )
        p.start()
        if stream is True:
            token_hop_len = self.token_min_hop_len
            while True:
                time.sleep(0.1)
                if (
                    len(self.tts_speech_token_dict[this_uuid])
                    >= token_hop_len + self.token_overlap_len
                ):
                    this_tts_speech_token = torch.tensor(
                        self.tts_speech_token_dict[this_uuid][
                            : token_hop_len + self.token_overlap_len
                        ]
                    ).unsqueeze(dim=0)
                    this_tts_speech = self.token2wav(
                        token=this_tts_speech_token,
                        prompt_token=flow_prompt_speech_token,
                        prompt_feat=prompt_speech_feat,
                        embedding=flow_embedding,
                        uuid=this_uuid,
                        finalize=False,
                    )
                    yield {"tts_speech": this_tts_speech.cpu()}
                    with self.lock:
                        self.tts_speech_token_dict[this_uuid] = (
                            self.tts_speech_token_dict[this_uuid][token_hop_len:]
                        )
                    # increase token_hop_len for better speech quality
                    token_hop_len = min(
                        self.token_max_hop_len,
                        int(token_hop_len * self.stream_scale_factor),
                    )
                if (
                    self.llm_end_dict[this_uuid] is True
                    and len(self.tts_speech_token_dict[this_uuid])
                    < token_hop_len + self.token_overlap_len
                ):
                    break
            p.join()
            # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
            this_tts_speech_token = torch.tensor(
                self.tts_speech_token_dict[this_uuid]
            ).unsqueeze(dim=0)
            this_tts_speech = self.token2wav(
                token=this_tts_speech_token,
                prompt_token=flow_prompt_speech_token,
                prompt_feat=prompt_speech_feat,
                embedding=flow_embedding,
                uuid=this_uuid,
                finalize=True,
            )
            yield {"tts_speech": this_tts_speech.cpu()}
        else:
            # deal with all tokens
            p.join()
            this_tts_speech_token = torch.tensor(
                self.tts_speech_token_dict[this_uuid]
            ).unsqueeze(dim=0)
            this_tts_speech = self.token2wav(
                token=this_tts_speech_token,
                prompt_token=flow_prompt_speech_token,
                prompt_feat=prompt_speech_feat,
                embedding=flow_embedding,
                uuid=this_uuid,
                finalize=True,
                speed=speed,
            )
            yield {"tts_speech": this_tts_speech.cpu()}
        with self.lock:
            self.tts_speech_token_dict.pop(this_uuid)
            self.llm_end_dict.pop(this_uuid)
            self.mel_overlap_dict.pop(this_uuid)
            self.hift_cache_dict.pop(this_uuid)
            self.flow_cache_dict.pop(this_uuid)
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            torch.cuda.current_stream().synchronize()


class CosyVoice2Model(CosyVoiceModel):

    def __init__(
        self,
        llm: torch.nn.Module,
        flow: torch.nn.Module,
        hift: torch.nn.Module,
        fp16: bool = False,
    ):
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.llm = llm
        self.flow = flow
        self.hift = hift
        self.fp16 = fp16
        # NOTE must matching training static_chunk_size
        self.token_hop_len = 25
        # hift cache
        self.mel_cache_len = 8
        self.source_cache_len = int(self.mel_cache_len * 480)
        # speech fade in out
        self.speech_window = np.hamming(2 * self.source_cache_len)
        # rtf and decoding related
        self.llm_context = (
            torch.cuda.stream(torch.cuda.Stream(self.device))
            if torch.cuda.is_available()
            else nullcontext()
        )
        self.lock = threading.Lock()
        # dict used to store session related variable
        self.tts_speech_token_dict = {}
        self.llm_end_dict = {}
        self.hift_cache_dict = {}
        self.silent_tokens = []

    def load_jit(self, flow_encoder_model):
        flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
        self.flow.encoder = flow_encoder

    def load_vllm(self, model_dir):
        export_cosyvoice2_vllm(self.llm, model_dir, self.device)
        from vllm import EngineArgs, LLMEngine

        engine_args = EngineArgs(
            model=model_dir,
            skip_tokenizer_init=True,
            enable_prompt_embeds=True,
            gpu_memory_utilization=0.2,
        )
        self.llm.vllm = LLMEngine.from_engine_args(engine_args)
        self.llm.lock = threading.Lock()
        del self.llm.llm.model.model.layers

    def token2wav(
        self,
        token,
        prompt_token,
        prompt_feat,
        embedding,
        token_offset,
        uuid,
        stream=False,
        finalize=False,
        speed=1.0,
    ):
        with torch.cuda.amp.autocast(self.fp16):
            tts_mel, _ = self.flow.inference(
                token=token.to(self.device, dtype=torch.int32),
                token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(
                    self.device
                ),
                prompt_token=prompt_token.to(self.device),
                prompt_token_len=torch.tensor(
                    [prompt_token.shape[1]], dtype=torch.int32
                ).to(self.device),
                prompt_feat=prompt_feat.to(self.device),
                prompt_feat_len=torch.tensor(
                    [prompt_feat.shape[1]], dtype=torch.int32
                ).to(self.device),
                embedding=embedding.to(self.device),
                streaming=stream,
                finalize=finalize,
            )
        tts_mel = tts_mel[:, :, token_offset * self.flow.token_mel_ratio :]
        # append hift cache
        if self.hift_cache_dict[uuid] is not None:
            hift_cache_mel, hift_cache_source = (
                self.hift_cache_dict[uuid]["mel"],
                self.hift_cache_dict[uuid]["source"],
            )
            tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
        else:
            hift_cache_source = torch.zeros(1, 1, 0)
        # keep overlap mel and hift cache
        if finalize is False:
            tts_speech, tts_source = self.hift.inference(
                speech_feat=tts_mel, cache_source=hift_cache_source
            )
            if self.hift_cache_dict[uuid] is not None:
                tts_speech = fade_in_out(
                    tts_speech, self.hift_cache_dict[uuid]["speech"], self.speech_window
                )
            self.hift_cache_dict[uuid] = {
                "mel": tts_mel[:, :, -self.mel_cache_len :],
                "source": tts_source[:, :, -self.source_cache_len :],
                "speech": tts_speech[:, -self.source_cache_len :],
            }
            tts_speech = tts_speech[:, : -self.source_cache_len]
        else:
            if speed != 1.0:
                assert (
                    self.hift_cache_dict[uuid] is None
                ), "speed change only support non-stream inference mode"
                tts_mel = F.interpolate(
                    tts_mel, size=int(tts_mel.shape[2] / speed), mode="linear"
                )
            tts_speech, tts_source = self.hift.inference(
                speech_feat=tts_mel, cache_source=hift_cache_source
            )
            if self.hift_cache_dict[uuid] is not None:
                tts_speech = fade_in_out(
                    tts_speech, self.hift_cache_dict[uuid]["speech"], self.speech_window
                )
        return tts_speech

    def tts(
        self,
        text=torch.zeros(1, 0, dtype=torch.int32),
        flow_embedding=torch.zeros(0, 192),
        llm_embedding=torch.zeros(0, 192),
        prompt_text=torch.zeros(1, 0, dtype=torch.int32),
        llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        prompt_speech_feat=torch.zeros(1, 0, 80),
        source_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        stream=False,
        speed=1.0,
        **kwargs
    ):
        # this_uuid is used to track variables related to this inference thread
        this_uuid = str(uuid.uuid1())
        with self.lock:
            self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = (
                [],
                False,
            )
            self.hift_cache_dict[this_uuid] = None
        if source_speech_token.shape[1] == 0:
            p = threading.Thread(
                target=self.llm_job,
                args=(
                    text,
                    prompt_text,
                    llm_prompt_speech_token,
                    llm_embedding,
                    this_uuid,
                ),
            )
        else:
            p = threading.Thread(
                target=self.vc_job, args=(source_speech_token, this_uuid)
            )
        p.start()
        if stream is True:
            token_offset = 0
            prompt_token_pad = int(
                np.ceil(flow_prompt_speech_token.shape[1] / self.token_hop_len)
                * self.token_hop_len
                - flow_prompt_speech_token.shape[1]
            )
            while True:
                time.sleep(0.1)
                this_token_hop_len = (
                    self.token_hop_len + prompt_token_pad
                    if token_offset == 0
                    else self.token_hop_len
                )
                if (
                    len(self.tts_speech_token_dict[this_uuid]) - token_offset
                    >= this_token_hop_len + self.flow.pre_lookahead_len
                ):
                    this_tts_speech_token = torch.tensor(
                        self.tts_speech_token_dict[this_uuid][
                            : token_offset
                            + this_token_hop_len
                            + self.flow.pre_lookahead_len
                        ]
                    ).unsqueeze(dim=0)
                    this_tts_speech = self.token2wav(
                        token=this_tts_speech_token,
                        prompt_token=flow_prompt_speech_token,
                        prompt_feat=prompt_speech_feat,
                        embedding=flow_embedding,
                        token_offset=token_offset,
                        uuid=this_uuid,
                        stream=stream,
                        finalize=False,
                    )
                    token_offset += this_token_hop_len
                    yield {"tts_speech": this_tts_speech.cpu()}
                if (
                    self.llm_end_dict[this_uuid] is True
                    and len(self.tts_speech_token_dict[this_uuid]) - token_offset
                    < this_token_hop_len + self.flow.pre_lookahead_len
                ):
                    break
            p.join()
            # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
            this_tts_speech_token = torch.tensor(
                self.tts_speech_token_dict[this_uuid]
            ).unsqueeze(dim=0)
            this_tts_speech = self.token2wav(
                token=this_tts_speech_token,
                prompt_token=flow_prompt_speech_token,
                prompt_feat=prompt_speech_feat,
                embedding=flow_embedding,
                token_offset=token_offset,
                uuid=this_uuid,
                finalize=True,
            )
            yield {"tts_speech": this_tts_speech.cpu()}
        else:
            # deal with all tokens
            p.join()
            this_tts_speech_token = torch.tensor(
                self.tts_speech_token_dict[this_uuid]
            ).unsqueeze(dim=0)
            this_tts_speech = self.token2wav(
                token=this_tts_speech_token,
                prompt_token=flow_prompt_speech_token,
                prompt_feat=prompt_speech_feat,
                embedding=flow_embedding,
                token_offset=0,
                uuid=this_uuid,
                finalize=True,
                speed=speed,
            )
            yield {"tts_speech": this_tts_speech.cpu()}
        with self.lock:
            self.tts_speech_token_dict.pop(this_uuid)
            self.llm_end_dict.pop(this_uuid)
            self.hift_cache_dict.pop(this_uuid)
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            torch.cuda.current_stream().synchronize()

    def reconstruct(
        self,
        text=torch.zeros(1, 0, dtype=torch.int32),
        flow_embedding=torch.zeros(0, 192),
        llm_embedding=torch.zeros(0, 192),
        prompt_text=torch.zeros(1, 0, dtype=torch.int32),
        llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        prompt_speech_feat=torch.zeros(1, 0, 80),
        source_speech_token=torch.zeros(1, 0, dtype=torch.int32),
        stream=False,
        speed=1.0,
        **kwargs
    ):
        this_uuid = str(uuid.uuid1())
        with self.lock:
            self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = (
                [],
                False,
            )
            self.hift_cache_dict[this_uuid] = None
        this_tts_speech = self.token2wav(
            token=llm_prompt_speech_token,
            prompt_token=flow_prompt_speech_token,
            prompt_feat=prompt_speech_feat,
            embedding=flow_embedding,
            token_offset=0,
            uuid=this_uuid,
            finalize=True,
            speed=speed,
        )
        yield {"tts_speech": this_tts_speech.cpu()}


class CosyVoice3Model(CosyVoice2Model):

    def __init__(
        self,
        llm: torch.nn.Module,
        flow: torch.nn.Module,
        hift: torch.nn.Module,
        fp16: bool = False,
    ):
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.llm = llm
        self.flow = flow
        self.hift = hift
        self.fp16 = fp16
        # NOTE must matching training static_chunk_size
        self.token_hop_len = 25
        # rtf and decoding related
        self.llm_context = (
            torch.cuda.stream(torch.cuda.Stream(self.device))
            if torch.cuda.is_available()
            else nullcontext()
        )
        self.lock = threading.Lock()
        # dict used to store session related variable
        self.tts_speech_token_dict = {}
        self.llm_end_dict = {}
        self.hift_cache_dict = {}
        # FSQ silent and breath token
        self.silent_tokens = [1, 2, 28, 29, 55, 248, 494, 2241, 2242, 2322, 2323]

    def token2wav(
        self,
        token,
        prompt_token,
        prompt_feat,
        embedding,
        token_offset,
        uuid,
        stream=False,
        finalize=False,
        speed=1.0,
    ):
        with torch.cuda.amp.autocast(self.fp16):
            tts_mel, _ = self.flow.inference(
                token=token.to(self.device, dtype=torch.int32),
                token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(
                    self.device
                ),
                prompt_token=prompt_token.to(self.device),
                prompt_token_len=torch.tensor(
                    [prompt_token.shape[1]], dtype=torch.int32
                ).to(self.device),
                prompt_feat=prompt_feat.to(self.device),
                prompt_feat_len=torch.tensor(
                    [prompt_feat.shape[1]], dtype=torch.int32
                ).to(self.device),
                embedding=embedding.to(self.device),
                streaming=stream,
                finalize=finalize,
            )
            tts_mel = tts_mel[:, :, token_offset * self.flow.token_mel_ratio :]
            # append mel cache
            if self.hift_cache_dict[uuid] is not None:
                hift_cache_mel = self.hift_cache_dict[uuid]["mel"]
                tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
                self.hift_cache_dict[uuid]["mel"] = tts_mel
            else:
                self.hift_cache_dict[uuid] = {"mel": tts_mel, "speech_offset": 0}
            if speed != 1.0:
                assert (
                    token_offset == 0 and finalize is True
                ), "speed change only support non-stream inference mode"
                tts_mel = F.interpolate(
                    tts_mel, size=int(tts_mel.shape[2] / speed), mode="linear"
                )
            tts_speech, _ = self.hift.inference(speech_feat=tts_mel, finalize=finalize)
            tts_speech = tts_speech[:, self.hift_cache_dict[uuid]["speech_offset"] :]
            self.hift_cache_dict[uuid]["speech_offset"] += tts_speech.shape[1]
        return tts_speech