walston commited on
Commit
e97e3a2
·
verified ·
1 Parent(s): bda964e

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .msc +0 -0
  2. CosyVoice-BlankEN/config.json +27 -0
  3. CosyVoice-BlankEN/generation_config.json +14 -0
  4. CosyVoice-BlankEN/merges.txt +0 -0
  5. CosyVoice-BlankEN/tokenizer_config.json +40 -0
  6. CosyVoice-BlankEN/vocab.json +0 -0
  7. cosyvoice/__pycache__/__init__.cpython-310.pyc +0 -0
  8. cosyvoice/bin/average_model.py +93 -0
  9. cosyvoice/bin/export_jit.py +99 -0
  10. cosyvoice/bin/export_onnx.py +114 -0
  11. cosyvoice/bin/train.py +195 -0
  12. cosyvoice/cli/__pycache__/cosyvoice.cpython-310.pyc +0 -0
  13. cosyvoice/cli/__pycache__/frontend.cpython-310.pyc +0 -0
  14. cosyvoice/cli/__pycache__/model.cpython-310.pyc +0 -0
  15. cosyvoice/cli/model.py +450 -0
  16. cosyvoice/dataset/__pycache__/dataset.cpython-310.pyc +0 -0
  17. cosyvoice/flow/DiT/__pycache__/dit.cpython-310.pyc +0 -0
  18. cosyvoice/flow/DiT/__pycache__/modules.cpython-310.pyc +0 -0
  19. cosyvoice/flow/DiT/dit.py +176 -0
  20. cosyvoice/flow/DiT/modules.py +616 -0
  21. cosyvoice/flow/__pycache__/flow_matching.cpython-310.pyc +0 -0
  22. cosyvoice/flow/decoder.py +494 -0
  23. cosyvoice/flow/flow_matching.py +227 -0
  24. cosyvoice/flow/length_regulator.py +70 -0
  25. cosyvoice/hifigan/__pycache__/discriminator.cpython-310.pyc +0 -0
  26. cosyvoice/hifigan/__pycache__/f0_predictor.cpython-310.pyc +0 -0
  27. cosyvoice/hifigan/__pycache__/generator.cpython-310.pyc +0 -0
  28. cosyvoice/hifigan/__pycache__/hifigan.cpython-310.pyc +0 -0
  29. cosyvoice/hifigan/generator.py +746 -0
  30. cosyvoice/hifigan/hifigan.py +67 -0
  31. cosyvoice/llm/__pycache__/llm.cpython-310.pyc +0 -0
  32. cosyvoice/tokenizer/__pycache__/tokenizer.cpython-310.pyc +0 -0
  33. cosyvoice/transformer/__pycache__/__init__.cpython-310.pyc +0 -0
  34. cosyvoice/transformer/__pycache__/activation.cpython-310.pyc +0 -0
  35. cosyvoice/transformer/__pycache__/convolution.cpython-310.pyc +0 -0
  36. cosyvoice/transformer/__pycache__/positionwise_feed_forward.cpython-310.pyc +0 -0
  37. cosyvoice/transformer/__pycache__/upsample_encoder.cpython-310.pyc +0 -0
  38. cosyvoice/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  39. cosyvoice/utils/__pycache__/class_utils.cpython-310.pyc +0 -0
  40. cosyvoice/utils/__pycache__/file_utils.cpython-310.pyc +0 -0
  41. cosyvoice/utils/__pycache__/frontend_utils.cpython-310.pyc +0 -0
  42. cosyvoice/utils/__pycache__/onnx.cpython-310.pyc +0 -0
  43. cosyvoice/utils/common.py +214 -0
  44. cosyvoice/utils/executor.py +176 -0
  45. cosyvoice/utils/file_utils.py +118 -0
  46. cosyvoice/utils/frontend_utils.py +136 -0
  47. cosyvoice/utils/mask.py +265 -0
  48. cosyvoice/utils/onnx.py +54 -0
  49. cosyvoice/utils/scheduler.py +738 -0
  50. cosyvoice/utils/train_utils.py +367 -0
.msc ADDED
Binary file (1.31 kB). View file
 
CosyVoice-BlankEN/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2ForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 151643,
7
+ "eos_token_id": 151645,
8
+ "hidden_act": "silu",
9
+ "hidden_size": 896,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 4864,
12
+ "max_position_embeddings": 32768,
13
+ "max_window_layers": 24,
14
+ "model_type": "qwen2",
15
+ "num_attention_heads": 14,
16
+ "num_hidden_layers": 24,
17
+ "num_key_value_heads": 2,
18
+ "rms_norm_eps": 1e-06,
19
+ "rope_theta": 1000000.0,
20
+ "sliding_window": 32768,
21
+ "tie_word_embeddings": true,
22
+ "torch_dtype": "bfloat16",
23
+ "transformers_version": "4.40.1",
24
+ "use_cache": true,
25
+ "use_sliding_window": false,
26
+ "vocab_size": 151936
27
+ }
CosyVoice-BlankEN/generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "pad_token_id": 151643,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 151645,
7
+ 151643
8
+ ],
9
+ "repetition_penalty": 1.1,
10
+ "temperature": 0.7,
11
+ "top_p": 0.8,
12
+ "top_k": 20,
13
+ "transformers_version": "4.37.0"
14
+ }
CosyVoice-BlankEN/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
CosyVoice-BlankEN/tokenizer_config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ }
28
+ },
29
+ "additional_special_tokens": ["<|im_start|>", "<|im_end|>"],
30
+ "bos_token": null,
31
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "<|im_end|>",
34
+ "errors": "replace",
35
+ "model_max_length": 32768,
36
+ "pad_token": "<|endoftext|>",
37
+ "split_special_tokens": false,
38
+ "tokenizer_class": "Qwen2Tokenizer",
39
+ "unk_token": null
40
+ }
CosyVoice-BlankEN/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
cosyvoice/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (149 Bytes). View file
 
cosyvoice/bin/average_model.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020 Mobvoi Inc (Di Wu)
2
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ import argparse
18
+ import glob
19
+
20
+ import yaml
21
+ import torch
22
+
23
+
24
+ def get_args():
25
+ parser = argparse.ArgumentParser(description='average model')
26
+ parser.add_argument('--dst_model', required=True, help='averaged model')
27
+ parser.add_argument('--src_path',
28
+ required=True,
29
+ help='src model path for average')
30
+ parser.add_argument('--val_best',
31
+ action="store_true",
32
+ help='averaged model')
33
+ parser.add_argument('--num',
34
+ default=5,
35
+ type=int,
36
+ help='nums for averaged model')
37
+
38
+ args = parser.parse_args()
39
+ print(args)
40
+ return args
41
+
42
+
43
+ def main():
44
+ args = get_args()
45
+ val_scores = []
46
+ if args.val_best:
47
+ yamls = glob.glob('{}/*.yaml'.format(args.src_path))
48
+ yamls = [
49
+ f for f in yamls
50
+ if not (os.path.basename(f).startswith('train')
51
+ or os.path.basename(f).startswith('init'))
52
+ ]
53
+ for y in yamls:
54
+ with open(y, 'r') as f:
55
+ dic_yaml = yaml.load(f, Loader=yaml.BaseLoader)
56
+ loss = float(dic_yaml['loss_dict']['loss'])
57
+ epoch = int(dic_yaml['epoch'])
58
+ step = int(dic_yaml['step'])
59
+ tag = dic_yaml['tag']
60
+ val_scores += [[epoch, step, loss, tag]]
61
+ sorted_val_scores = sorted(val_scores,
62
+ key=lambda x: x[2],
63
+ reverse=False)
64
+ print("best val (epoch, step, loss, tag) = " +
65
+ str(sorted_val_scores[:args.num]))
66
+ path_list = [
67
+ args.src_path + '/epoch_{}_whole.pt'.format(score[0])
68
+ for score in sorted_val_scores[:args.num]
69
+ ]
70
+ print(path_list)
71
+ avg = {}
72
+ num = args.num
73
+ assert num == len(path_list)
74
+ for path in path_list:
75
+ print('Processing {}'.format(path))
76
+ states = torch.load(path, map_location=torch.device('cpu'))
77
+ for k in states.keys():
78
+ if k not in ['step', 'epoch']:
79
+ if k not in avg.keys():
80
+ avg[k] = states[k].clone()
81
+ else:
82
+ avg[k] += states[k]
83
+ # average
84
+ for k in avg.keys():
85
+ if avg[k] is not None:
86
+ # pytorch 1.6 use true_divide instead of /=
87
+ avg[k] = torch.true_divide(avg[k], num)
88
+ print('Saving to {}'.format(args.dst_model))
89
+ torch.save(avg, args.dst_model)
90
+
91
+
92
+ if __name__ == '__main__':
93
+ main()
cosyvoice/bin/export_jit.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import print_function
16
+
17
+ import argparse
18
+ import logging
19
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
20
+ import os
21
+ import sys
22
+ import torch
23
+ ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
24
+ sys.path.append('{}/../..'.format(ROOT_DIR))
25
+ sys.path.append('{}/../../third_party/Matcha-TTS'.format(ROOT_DIR))
26
+ from cosyvoice.cli.cosyvoice import AutoModel
27
+ from cosyvoice.utils.file_utils import logging
28
+
29
+
30
+ def get_args():
31
+ parser = argparse.ArgumentParser(description='export your model for deployment')
32
+ parser.add_argument('--model_dir',
33
+ type=str,
34
+ default='pretrained_models/CosyVoice-300M',
35
+ help='local path')
36
+ args = parser.parse_args()
37
+ print(args)
38
+ return args
39
+
40
+
41
+ def get_optimized_script(model, preserved_attrs=[]):
42
+ script = torch.jit.script(model)
43
+ if preserved_attrs != []:
44
+ script = torch.jit.freeze(script, preserved_attrs=preserved_attrs)
45
+ else:
46
+ script = torch.jit.freeze(script)
47
+ script = torch.jit.optimize_for_inference(script)
48
+ return script
49
+
50
+
51
+ def main():
52
+ args = get_args()
53
+ logging.basicConfig(level=logging.DEBUG,
54
+ format='%(asctime)s %(levelname)s %(message)s')
55
+
56
+ torch._C._jit_set_fusion_strategy([('STATIC', 1)])
57
+ torch._C._jit_set_profiling_mode(False)
58
+ torch._C._jit_set_profiling_executor(False)
59
+
60
+ model = AutoModel(model_dir=args.model_dir)
61
+
62
+ if model.__class__.__name__ == 'CosyVoice':
63
+ # 1. export llm text_encoder
64
+ llm_text_encoder = model.model.llm.text_encoder
65
+ script = get_optimized_script(llm_text_encoder)
66
+ script.save('{}/llm.text_encoder.fp32.zip'.format(args.model_dir))
67
+ script = get_optimized_script(llm_text_encoder.half())
68
+ script.save('{}/llm.text_encoder.fp16.zip'.format(args.model_dir))
69
+ logging.info('successfully export llm_text_encoder')
70
+
71
+ # 2. export llm llm
72
+ llm_llm = model.model.llm.llm
73
+ script = get_optimized_script(llm_llm, ['forward_chunk'])
74
+ script.save('{}/llm.llm.fp32.zip'.format(args.model_dir))
75
+ script = get_optimized_script(llm_llm.half(), ['forward_chunk'])
76
+ script.save('{}/llm.llm.fp16.zip'.format(args.model_dir))
77
+ logging.info('successfully export llm_llm')
78
+
79
+ # 3. export flow encoder
80
+ flow_encoder = model.model.flow.encoder
81
+ script = get_optimized_script(flow_encoder)
82
+ script.save('{}/flow.encoder.fp32.zip'.format(args.model_dir))
83
+ script = get_optimized_script(flow_encoder.half())
84
+ script.save('{}/flow.encoder.fp16.zip'.format(args.model_dir))
85
+ logging.info('successfully export flow_encoder')
86
+ elif model.__class__.__name__ == 'CosyVoice2':
87
+ # 1. export flow encoder
88
+ flow_encoder = model.model.flow.encoder
89
+ script = get_optimized_script(flow_encoder)
90
+ script.save('{}/flow.encoder.fp32.zip'.format(args.model_dir))
91
+ script = get_optimized_script(flow_encoder.half())
92
+ script.save('{}/flow.encoder.fp16.zip'.format(args.model_dir))
93
+ logging.info('successfully export flow_encoder')
94
+ else:
95
+ raise ValueError('unsupported model type')
96
+
97
+
98
+ if __name__ == '__main__':
99
+ main()
cosyvoice/bin/export_onnx.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Antgroup Inc (authors: Zhoubofan, hexisyztem@icloud.com)
2
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import print_function
17
+
18
+ import argparse
19
+ import logging
20
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
21
+ import os
22
+ import sys
23
+ import onnxruntime
24
+ import random
25
+ import torch
26
+ from tqdm import tqdm
27
+ ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
28
+ sys.path.append('{}/../..'.format(ROOT_DIR))
29
+ sys.path.append('{}/../../third_party/Matcha-TTS'.format(ROOT_DIR))
30
+ from cosyvoice.cli.cosyvoice import AutoModel
31
+ from cosyvoice.utils.file_utils import logging
32
+
33
+
34
+ def get_dummy_input(batch_size, seq_len, out_channels, device):
35
+ x = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
36
+ mask = torch.ones((batch_size, 1, seq_len), dtype=torch.float32, device=device)
37
+ mu = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
38
+ t = torch.rand((batch_size), dtype=torch.float32, device=device)
39
+ spks = torch.rand((batch_size, out_channels), dtype=torch.float32, device=device)
40
+ cond = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
41
+ return x, mask, mu, t, spks, cond
42
+
43
+
44
+ def get_args():
45
+ parser = argparse.ArgumentParser(description='export your model for deployment')
46
+ parser.add_argument('--model_dir',
47
+ type=str,
48
+ default='pretrained_models/CosyVoice-300M',
49
+ help='local path')
50
+ args = parser.parse_args()
51
+ print(args)
52
+ return args
53
+
54
+
55
+ @torch.no_grad()
56
+ def main():
57
+ args = get_args()
58
+ logging.basicConfig(level=logging.DEBUG,
59
+ format='%(asctime)s %(levelname)s %(message)s')
60
+
61
+ model = AutoModel(model_dir=args.model_dir)
62
+
63
+ # 1. export flow decoder estimator
64
+ estimator = model.model.flow.decoder.estimator
65
+ estimator.eval()
66
+
67
+ device = model.model.device
68
+ batch_size, seq_len = 2, 256
69
+ out_channels = model.model.flow.decoder.estimator.out_channels
70
+ x, mask, mu, t, spks, cond = get_dummy_input(batch_size, seq_len, out_channels, device)
71
+ torch.onnx.export(
72
+ estimator,
73
+ (x, mask, mu, t, spks, cond),
74
+ '{}/flow.decoder.estimator.fp32.onnx'.format(args.model_dir),
75
+ export_params=True,
76
+ opset_version=18,
77
+ do_constant_folding=True,
78
+ input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
79
+ output_names=['estimator_out'],
80
+ dynamic_axes={
81
+ 'x': {2: 'seq_len'},
82
+ 'mask': {2: 'seq_len'},
83
+ 'mu': {2: 'seq_len'},
84
+ 'cond': {2: 'seq_len'},
85
+ 'estimator_out': {2: 'seq_len'},
86
+ }
87
+ )
88
+
89
+ # 2. test computation consistency
90
+ option = onnxruntime.SessionOptions()
91
+ option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
92
+ option.intra_op_num_threads = 1
93
+ providers = ['CUDAExecutionProvider' if torch.cuda.is_available() else 'CPUExecutionProvider']
94
+ estimator_onnx = onnxruntime.InferenceSession('{}/flow.decoder.estimator.fp32.onnx'.format(args.model_dir),
95
+ sess_options=option, providers=providers)
96
+
97
+ for _ in tqdm(range(10)):
98
+ x, mask, mu, t, spks, cond = get_dummy_input(batch_size, random.randint(16, 512), out_channels, device)
99
+ output_pytorch = estimator(x, mask, mu, t, spks, cond)
100
+ ort_inputs = {
101
+ 'x': x.cpu().numpy(),
102
+ 'mask': mask.cpu().numpy(),
103
+ 'mu': mu.cpu().numpy(),
104
+ 't': t.cpu().numpy(),
105
+ 'spks': spks.cpu().numpy(),
106
+ 'cond': cond.cpu().numpy()
107
+ }
108
+ output_onnx = estimator_onnx.run(None, ort_inputs)[0]
109
+ torch.testing.assert_allclose(output_pytorch, torch.from_numpy(output_onnx).to(device), rtol=1e-2, atol=1e-4)
110
+ logging.info('successfully export estimator')
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
cosyvoice/bin/train.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import print_function
16
+ import argparse
17
+ import datetime
18
+ import logging
19
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
20
+ from copy import deepcopy
21
+ import os
22
+ import torch
23
+ import torch.distributed as dist
24
+ import deepspeed
25
+
26
+ from hyperpyyaml import load_hyperpyyaml
27
+
28
+ from torch.distributed.elastic.multiprocessing.errors import record
29
+
30
+ from cosyvoice.utils.losses import DPOLoss
31
+ from cosyvoice.utils.executor import Executor
32
+ from cosyvoice.utils.train_utils import (
33
+ init_distributed,
34
+ init_dataset_and_dataloader,
35
+ init_optimizer_and_scheduler,
36
+ init_summarywriter, save_model,
37
+ wrap_cuda_model, check_modify_and_save_config)
38
+
39
+
40
+ def get_args():
41
+ parser = argparse.ArgumentParser(description='training your network')
42
+ parser.add_argument('--train_engine',
43
+ default='torch_ddp',
44
+ choices=['torch_ddp', 'deepspeed'],
45
+ help='Engine for paralleled training')
46
+ parser.add_argument('--model', required=True, help='model which will be trained')
47
+ parser.add_argument('--ref_model', required=False, help='ref model used in dpo')
48
+ parser.add_argument('--config', required=True, help='config file')
49
+ parser.add_argument('--train_data', required=True, help='train data file')
50
+ parser.add_argument('--cv_data', required=True, help='cv data file')
51
+ parser.add_argument('--qwen_pretrain_path', required=False, help='qwen pretrain path')
52
+ parser.add_argument('--onnx_path', required=False, help='onnx path, which is required for online feature extraction')
53
+ parser.add_argument('--checkpoint', help='checkpoint model')
54
+ parser.add_argument('--model_dir', required=True, help='save model dir')
55
+ parser.add_argument('--tensorboard_dir',
56
+ default='tensorboard',
57
+ help='tensorboard log dir')
58
+ parser.add_argument('--ddp.dist_backend',
59
+ dest='dist_backend',
60
+ default='nccl',
61
+ choices=['nccl', 'gloo'],
62
+ help='distributed backend')
63
+ parser.add_argument('--num_workers',
64
+ default=0,
65
+ type=int,
66
+ help='num of subprocess workers for reading')
67
+ parser.add_argument('--prefetch',
68
+ default=100,
69
+ type=int,
70
+ help='prefetch number')
71
+ parser.add_argument('--pin_memory',
72
+ action='store_true',
73
+ default=False,
74
+ help='Use pinned memory buffers used for reading')
75
+ parser.add_argument('--use_amp',
76
+ action='store_true',
77
+ default=False,
78
+ help='Use automatic mixed precision training')
79
+ parser.add_argument('--dpo',
80
+ action='store_true',
81
+ default=False,
82
+ help='Use Direct Preference Optimization')
83
+ parser.add_argument('--deepspeed.save_states',
84
+ dest='save_states',
85
+ default='model_only',
86
+ choices=['model_only', 'model+optimizer'],
87
+ help='save model/optimizer states')
88
+ parser.add_argument('--timeout',
89
+ default=60,
90
+ type=int,
91
+ help='timeout (in seconds) of cosyvoice_join.')
92
+ parser = deepspeed.add_config_arguments(parser)
93
+ args = parser.parse_args()
94
+ return args
95
+
96
+
97
+ @record
98
+ def main():
99
+ args = get_args()
100
+ os.environ['onnx_path'] = args.onnx_path
101
+ logging.basicConfig(level=logging.DEBUG,
102
+ format='%(asctime)s %(levelname)s %(message)s')
103
+ # gan train has some special initialization logic
104
+ gan = True if args.model == 'hifigan' else False
105
+
106
+ override_dict = {k: None for k in ['llm', 'flow', 'hift', 'hifigan'] if k != args.model}
107
+ if gan is True:
108
+ override_dict.pop('hift')
109
+ if args.qwen_pretrain_path is not None:
110
+ override_dict['qwen_pretrain_path'] = args.qwen_pretrain_path
111
+ with open(args.config, 'r') as f:
112
+ configs = load_hyperpyyaml(f, overrides=override_dict)
113
+ if gan is True:
114
+ configs['train_conf'] = configs['train_conf_gan']
115
+ configs['train_conf'].update(vars(args))
116
+
117
+ # Init env for ddp
118
+ init_distributed(args)
119
+
120
+ # Get dataset & dataloader
121
+ train_dataset, cv_dataset, train_data_loader, cv_data_loader = \
122
+ init_dataset_and_dataloader(args, configs, gan, args.dpo)
123
+
124
+ # Do some sanity checks and save config to arsg.model_dir
125
+ configs = check_modify_and_save_config(args, configs)
126
+
127
+ # Tensorboard summary
128
+ writer = init_summarywriter(args)
129
+
130
+ # load checkpoint
131
+ if args.dpo is True:
132
+ configs[args.model].forward = configs[args.model].forward_dpo
133
+ model = configs[args.model]
134
+ start_step, start_epoch = 0, -1
135
+ if args.checkpoint is not None:
136
+ if os.path.exists(args.checkpoint):
137
+ state_dict = torch.load(args.checkpoint, map_location='cpu')
138
+ model.load_state_dict(state_dict, strict=False)
139
+ if 'step' in state_dict:
140
+ start_step = state_dict['step']
141
+ if 'epoch' in state_dict:
142
+ start_epoch = state_dict['epoch']
143
+ else:
144
+ logging.warning('checkpoint {} do not exsist!'.format(args.checkpoint))
145
+
146
+ # Dispatch model from cpu to gpu
147
+ model = wrap_cuda_model(args, model)
148
+
149
+ # Get optimizer & scheduler
150
+ model, optimizer, scheduler, optimizer_d, scheduler_d = init_optimizer_and_scheduler(args, configs, model, gan)
151
+ scheduler.set_step(start_step)
152
+ if scheduler_d is not None:
153
+ scheduler_d.set_step(start_step)
154
+
155
+ # Save init checkpoints
156
+ info_dict = deepcopy(configs['train_conf'])
157
+ info_dict['step'] = start_step
158
+ info_dict['epoch'] = start_epoch
159
+ save_model(model, 'init', info_dict)
160
+
161
+ # DPO related
162
+ if args.dpo is True:
163
+ ref_model = deepcopy(configs[args.model])
164
+ state_dict = torch.load(args.ref_model, map_location='cpu')
165
+ ref_model.load_state_dict(state_dict, strict=False)
166
+ dpo_loss = DPOLoss(beta=0.01, label_smoothing=0.0, ipo=False)
167
+ # NOTE maybe it is not needed to wrap ref_model as ddp because its parameter is not updated
168
+ ref_model = wrap_cuda_model(args, ref_model)
169
+ else:
170
+ ref_model, dpo_loss = None, None
171
+
172
+ # Get executor
173
+ executor = Executor(gan=gan, ref_model=ref_model, dpo_loss=dpo_loss)
174
+ executor.step = start_step
175
+
176
+ # Init scaler, used for pytorch amp mixed precision training
177
+ scaler = torch.cuda.amp.GradScaler() if args.use_amp else None
178
+ print('start step {} start epoch {}'.format(start_step, start_epoch))
179
+
180
+ # Start training loop
181
+ for epoch in range(start_epoch + 1, info_dict['max_epoch']):
182
+ executor.epoch = epoch
183
+ train_dataset.set_epoch(epoch)
184
+ dist.barrier()
185
+ group_join = dist.new_group(backend="gloo", timeout=datetime.timedelta(seconds=args.timeout))
186
+ if gan is True:
187
+ executor.train_one_epoc_gan(model, optimizer, scheduler, optimizer_d, scheduler_d, train_data_loader, cv_data_loader,
188
+ writer, info_dict, scaler, group_join)
189
+ else:
190
+ executor.train_one_epoc(model, optimizer, scheduler, train_data_loader, cv_data_loader, writer, info_dict, scaler, group_join, ref_model=ref_model)
191
+ dist.destroy_process_group(group_join)
192
+
193
+
194
+ if __name__ == '__main__':
195
+ main()
cosyvoice/cli/__pycache__/cosyvoice.cpython-310.pyc ADDED
Binary file (9.2 kB). View file
 
cosyvoice/cli/__pycache__/frontend.cpython-310.pyc ADDED
Binary file (8.59 kB). View file
 
cosyvoice/cli/__pycache__/model.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
cosyvoice/cli/model.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
2
+ # 2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou)
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import os
16
+ from typing import Generator
17
+ import torch
18
+ import numpy as np
19
+ import threading
20
+ import time
21
+ from torch.nn import functional as F
22
+ from contextlib import nullcontext
23
+ import uuid
24
+ from cosyvoice.utils.common import fade_in_out
25
+ from cosyvoice.utils.file_utils import convert_onnx_to_trt, export_cosyvoice2_vllm
26
+ from cosyvoice.utils.common import TrtContextWrapper
27
+
28
+
29
+ class CosyVoiceModel:
30
+
31
+ def __init__(self,
32
+ llm: torch.nn.Module,
33
+ flow: torch.nn.Module,
34
+ hift: torch.nn.Module,
35
+ fp16: bool = False):
36
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
37
+ self.llm = llm
38
+ self.flow = flow
39
+ self.hift = hift
40
+ self.fp16 = fp16
41
+ self.token_min_hop_len = 2 * self.flow.input_frame_rate
42
+ self.token_max_hop_len = 4 * self.flow.input_frame_rate
43
+ self.token_overlap_len = 20
44
+ # mel fade in out
45
+ self.mel_overlap_len = int(self.token_overlap_len / self.flow.input_frame_rate * 22050 / 256)
46
+ self.mel_window = np.hamming(2 * self.mel_overlap_len)
47
+ # hift cache
48
+ self.mel_cache_len = 20
49
+ self.source_cache_len = int(self.mel_cache_len * 256)
50
+ # speech fade in out
51
+ self.speech_window = np.hamming(2 * self.source_cache_len)
52
+ # rtf and decoding related
53
+ self.stream_scale_factor = 1
54
+ assert self.stream_scale_factor >= 1, 'stream_scale_factor should be greater than 1, change it according to your actual rtf'
55
+ self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
56
+ self.lock = threading.Lock()
57
+ # dict used to store session related variable
58
+ self.tts_speech_token_dict = {}
59
+ self.llm_end_dict = {}
60
+ self.mel_overlap_dict = {}
61
+ self.flow_cache_dict = {}
62
+ self.hift_cache_dict = {}
63
+ self.silent_tokens = []
64
+
65
+ def load(self, llm_model, flow_model, hift_model):
66
+ self.llm.load_state_dict(torch.load(llm_model, map_location=self.device, weights_only=True), strict=True)
67
+ self.llm.to(self.device).eval()
68
+ self.flow.load_state_dict(torch.load(flow_model, map_location=self.device, weights_only=True), strict=True)
69
+ self.flow.to(self.device).eval()
70
+ # in case hift_model is a hifigan model
71
+ hift_state_dict = {k.replace('generator.', ''): v for k, v in torch.load(hift_model, map_location=self.device, weights_only=True).items()}
72
+ self.hift.load_state_dict(hift_state_dict, strict=True)
73
+ self.hift.to(self.device).eval()
74
+
75
+ def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
76
+ llm_text_encoder = torch.jit.load(llm_text_encoder_model, map_location=self.device)
77
+ self.llm.text_encoder = llm_text_encoder
78
+ llm_llm = torch.jit.load(llm_llm_model, map_location=self.device)
79
+ self.llm.llm = llm_llm
80
+ flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
81
+ self.flow.encoder = flow_encoder
82
+
83
+ def load_trt(self, flow_decoder_estimator_model, flow_decoder_onnx_model, trt_concurrent, fp16):
84
+ assert torch.cuda.is_available(), 'tensorrt only supports gpu!'
85
+ if not os.path.exists(flow_decoder_estimator_model) or os.path.getsize(flow_decoder_estimator_model) == 0:
86
+ convert_onnx_to_trt(flow_decoder_estimator_model, self.get_trt_kwargs(), flow_decoder_onnx_model, fp16)
87
+ del self.flow.decoder.estimator
88
+ import tensorrt as trt
89
+ with open(flow_decoder_estimator_model, 'rb') as f:
90
+ estimator_engine = trt.Runtime(trt.Logger(trt.Logger.INFO)).deserialize_cuda_engine(f.read())
91
+ assert estimator_engine is not None, 'failed to load trt {}'.format(flow_decoder_estimator_model)
92
+ self.flow.decoder.estimator = TrtContextWrapper(estimator_engine, trt_concurrent=trt_concurrent, device=self.device)
93
+
94
+ def get_trt_kwargs(self):
95
+ min_shape = [(2, 80, 4), (2, 1, 4), (2, 80, 4), (2, 80, 4)]
96
+ opt_shape = [(2, 80, 500), (2, 1, 500), (2, 80, 500), (2, 80, 500)]
97
+ max_shape = [(2, 80, 3000), (2, 1, 3000), (2, 80, 3000), (2, 80, 3000)]
98
+ input_names = ["x", "mask", "mu", "cond"]
99
+ return {'min_shape': min_shape, 'opt_shape': opt_shape, 'max_shape': max_shape, 'input_names': input_names}
100
+
101
+ def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
102
+ cur_silent_token_num, max_silent_token_num = 0, 5
103
+ with self.llm_context, torch.cuda.amp.autocast(self.fp16 is True and hasattr(self.llm, 'vllm') is False):
104
+ if isinstance(text, Generator):
105
+ 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!'
106
+ token_generator = self.llm.inference_bistream(text=text,
107
+ prompt_text=prompt_text.to(self.device),
108
+ prompt_text_len=torch.tensor([prompt_text.shape[1]], dtype=torch.int32).to(self.device),
109
+ prompt_speech_token=llm_prompt_speech_token.to(self.device),
110
+ prompt_speech_token_len=torch.tensor([llm_prompt_speech_token.shape[1]], dtype=torch.int32).to(self.device),
111
+ embedding=llm_embedding.to(self.device))
112
+ else:
113
+ token_generator = self.llm.inference(text=text.to(self.device),
114
+ text_len=torch.tensor([text.shape[1]], dtype=torch.int32).to(self.device),
115
+ prompt_text=prompt_text.to(self.device),
116
+ prompt_text_len=torch.tensor([prompt_text.shape[1]], dtype=torch.int32).to(self.device),
117
+ prompt_speech_token=llm_prompt_speech_token.to(self.device),
118
+ prompt_speech_token_len=torch.tensor([llm_prompt_speech_token.shape[1]], dtype=torch.int32).to(self.device),
119
+ embedding=llm_embedding.to(self.device),
120
+ uuid=uuid)
121
+ for i in token_generator:
122
+ if i in self.silent_tokens:
123
+ cur_silent_token_num += 1
124
+ if cur_silent_token_num > max_silent_token_num:
125
+ continue
126
+ else:
127
+ cur_silent_token_num = 0
128
+ self.tts_speech_token_dict[uuid].append(i)
129
+ self.llm_end_dict[uuid] = True
130
+
131
+ def vc_job(self, source_speech_token, uuid):
132
+ self.tts_speech_token_dict[uuid] = source_speech_token.flatten().tolist()
133
+ self.llm_end_dict[uuid] = True
134
+
135
+ def token2wav(self, token, prompt_token, prompt_feat, embedding, uuid, finalize=False, speed=1.0):
136
+ with torch.cuda.amp.autocast(self.fp16):
137
+ tts_mel, self.flow_cache_dict[uuid] = self.flow.inference(token=token.to(self.device, dtype=torch.int32),
138
+ token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
139
+ prompt_token=prompt_token.to(self.device),
140
+ prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
141
+ prompt_feat=prompt_feat.to(self.device),
142
+ prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
143
+ embedding=embedding.to(self.device),
144
+ flow_cache=self.flow_cache_dict[uuid])
145
+
146
+ # mel overlap fade in out
147
+ if self.mel_overlap_dict[uuid].shape[2] != 0:
148
+ tts_mel = fade_in_out(tts_mel, self.mel_overlap_dict[uuid], self.mel_window)
149
+ # append hift cache
150
+ if self.hift_cache_dict[uuid] is not None:
151
+ hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
152
+ tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
153
+ else:
154
+ hift_cache_source = torch.zeros(1, 1, 0)
155
+ # keep overlap mel and hift cache
156
+ if finalize is False:
157
+ self.mel_overlap_dict[uuid] = tts_mel[:, :, -self.mel_overlap_len:]
158
+ tts_mel = tts_mel[:, :, :-self.mel_overlap_len]
159
+ tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
160
+ if self.hift_cache_dict[uuid] is not None:
161
+ tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
162
+ self.hift_cache_dict[uuid] = {'mel': tts_mel[:, :, -self.mel_cache_len:],
163
+ 'source': tts_source[:, :, -self.source_cache_len:],
164
+ 'speech': tts_speech[:, -self.source_cache_len:]}
165
+ tts_speech = tts_speech[:, :-self.source_cache_len]
166
+ else:
167
+ if speed != 1.0:
168
+ assert self.hift_cache_dict[uuid] is None, 'speed change only support non-stream inference mode'
169
+ tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
170
+ tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
171
+ if self.hift_cache_dict[uuid] is not None:
172
+ tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
173
+ return tts_speech
174
+
175
+ def tts(self, text=torch.zeros(1, 0, dtype=torch.int32), flow_embedding=torch.zeros(0, 192), llm_embedding=torch.zeros(0, 192),
176
+ prompt_text=torch.zeros(1, 0, dtype=torch.int32),
177
+ llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
178
+ flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
179
+ prompt_speech_feat=torch.zeros(1, 0, 80), source_speech_token=torch.zeros(1, 0, dtype=torch.int32), stream=False, speed=1.0, **kwargs):
180
+ # this_uuid is used to track variables related to this inference thread
181
+ this_uuid = str(uuid.uuid1())
182
+ with self.lock:
183
+ self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = [], False
184
+ self.hift_cache_dict[this_uuid] = None
185
+ self.mel_overlap_dict[this_uuid] = torch.zeros(1, 80, 0)
186
+ self.flow_cache_dict[this_uuid] = torch.zeros(1, 80, 0, 2)
187
+ if source_speech_token.shape[1] == 0:
188
+ p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
189
+ else:
190
+ p = threading.Thread(target=self.vc_job, args=(source_speech_token, this_uuid))
191
+ p.start()
192
+ if stream is True:
193
+ token_hop_len = self.token_min_hop_len
194
+ while True:
195
+ time.sleep(0.1)
196
+ if len(self.tts_speech_token_dict[this_uuid]) >= token_hop_len + self.token_overlap_len:
197
+ this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_hop_len + self.token_overlap_len]) \
198
+ .unsqueeze(dim=0)
199
+ this_tts_speech = self.token2wav(token=this_tts_speech_token,
200
+ prompt_token=flow_prompt_speech_token,
201
+ prompt_feat=prompt_speech_feat,
202
+ embedding=flow_embedding,
203
+ uuid=this_uuid,
204
+ finalize=False)
205
+ yield {'tts_speech': this_tts_speech.cpu()}
206
+ with self.lock:
207
+ self.tts_speech_token_dict[this_uuid] = self.tts_speech_token_dict[this_uuid][token_hop_len:]
208
+ # increase token_hop_len for better speech quality
209
+ token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
210
+ 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:
211
+ break
212
+ p.join()
213
+ # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
214
+ this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
215
+ this_tts_speech = self.token2wav(token=this_tts_speech_token,
216
+ prompt_token=flow_prompt_speech_token,
217
+ prompt_feat=prompt_speech_feat,
218
+ embedding=flow_embedding,
219
+ uuid=this_uuid,
220
+ finalize=True)
221
+ yield {'tts_speech': this_tts_speech.cpu()}
222
+ else:
223
+ # deal with all tokens
224
+ p.join()
225
+ this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
226
+ this_tts_speech = self.token2wav(token=this_tts_speech_token,
227
+ prompt_token=flow_prompt_speech_token,
228
+ prompt_feat=prompt_speech_feat,
229
+ embedding=flow_embedding,
230
+ uuid=this_uuid,
231
+ finalize=True,
232
+ speed=speed)
233
+ yield {'tts_speech': this_tts_speech.cpu()}
234
+ with self.lock:
235
+ self.tts_speech_token_dict.pop(this_uuid)
236
+ self.llm_end_dict.pop(this_uuid)
237
+ self.mel_overlap_dict.pop(this_uuid)
238
+ self.hift_cache_dict.pop(this_uuid)
239
+ self.flow_cache_dict.pop(this_uuid)
240
+ if torch.cuda.is_available():
241
+ torch.cuda.empty_cache()
242
+ torch.cuda.current_stream().synchronize()
243
+
244
+
245
+ class CosyVoice2Model(CosyVoiceModel):
246
+
247
+ def __init__(self,
248
+ llm: torch.nn.Module,
249
+ flow: torch.nn.Module,
250
+ hift: torch.nn.Module,
251
+ fp16: bool = False):
252
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
253
+ self.llm = llm
254
+ self.flow = flow
255
+ self.hift = hift
256
+ self.fp16 = fp16
257
+ # NOTE must matching training static_chunk_size
258
+ self.token_hop_len = 25
259
+ # NOTE increase token_hop_len incrementally to avoid duplicate inference
260
+ self.token_max_hop_len = 4 * self.token_hop_len
261
+ self.stream_scale_factor = 2
262
+ assert self.stream_scale_factor >= 1, 'stream_scale_factor should be greater than 1, change it according to your actual rtf'
263
+ # hift cache
264
+ self.mel_cache_len = 8
265
+ self.source_cache_len = int(self.mel_cache_len * 480)
266
+ # speech fade in out
267
+ self.speech_window = np.hamming(2 * self.source_cache_len)
268
+ # rtf and decoding related
269
+ self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
270
+ self.lock = threading.Lock()
271
+ # dict used to store session related variable
272
+ self.tts_speech_token_dict = {}
273
+ self.llm_end_dict = {}
274
+ self.hift_cache_dict = {}
275
+ self.silent_tokens = []
276
+
277
+ def load_jit(self, flow_encoder_model):
278
+ flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
279
+ self.flow.encoder = flow_encoder
280
+
281
+ def load_vllm(self, model_dir):
282
+ export_cosyvoice2_vllm(self.llm, model_dir, self.device)
283
+ from vllm import EngineArgs, LLMEngine
284
+ engine_args = EngineArgs(model=model_dir,
285
+ skip_tokenizer_init=True,
286
+ enable_prompt_embeds=True,
287
+ gpu_memory_utilization=0.2)
288
+ self.llm.vllm = LLMEngine.from_engine_args(engine_args)
289
+ self.llm.lock = threading.Lock()
290
+ del self.llm.llm.model.model.layers
291
+
292
+ def token2wav(self, token, prompt_token, prompt_feat, embedding, token_offset, uuid, stream=False, finalize=False, speed=1.0):
293
+ with torch.cuda.amp.autocast(self.fp16):
294
+ tts_mel, _ = self.flow.inference(token=token.to(self.device, dtype=torch.int32),
295
+ token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
296
+ prompt_token=prompt_token.to(self.device),
297
+ prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
298
+ prompt_feat=prompt_feat.to(self.device),
299
+ prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
300
+ embedding=embedding.to(self.device),
301
+ streaming=stream,
302
+ finalize=finalize)
303
+ tts_mel = tts_mel[:, :, token_offset * self.flow.token_mel_ratio:]
304
+ # append hift cache
305
+ if self.hift_cache_dict[uuid] is not None:
306
+ hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
307
+ tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
308
+ else:
309
+ hift_cache_source = torch.zeros(1, 1, 0)
310
+ # keep overlap mel and hift cache
311
+ if finalize is False:
312
+ tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
313
+ if self.hift_cache_dict[uuid] is not None:
314
+ tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
315
+ self.hift_cache_dict[uuid] = {'mel': tts_mel[:, :, -self.mel_cache_len:],
316
+ 'source': tts_source[:, :, -self.source_cache_len:],
317
+ 'speech': tts_speech[:, -self.source_cache_len:]}
318
+ tts_speech = tts_speech[:, :-self.source_cache_len]
319
+ else:
320
+ if speed != 1.0:
321
+ assert self.hift_cache_dict[uuid] is None, 'speed change only support non-stream inference mode'
322
+ tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
323
+ tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
324
+ if self.hift_cache_dict[uuid] is not None:
325
+ tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
326
+ return tts_speech
327
+
328
+ def tts(self, text=torch.zeros(1, 0, dtype=torch.int32), flow_embedding=torch.zeros(0, 192), llm_embedding=torch.zeros(0, 192),
329
+ prompt_text=torch.zeros(1, 0, dtype=torch.int32),
330
+ llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
331
+ flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
332
+ prompt_speech_feat=torch.zeros(1, 0, 80), source_speech_token=torch.zeros(1, 0, dtype=torch.int32), stream=False, speed=1.0, **kwargs):
333
+ # this_uuid is used to track variables related to this inference thread
334
+ this_uuid = str(uuid.uuid1())
335
+ with self.lock:
336
+ self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = [], False
337
+ self.hift_cache_dict[this_uuid] = None
338
+ if source_speech_token.shape[1] == 0:
339
+ p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
340
+ else:
341
+ p = threading.Thread(target=self.vc_job, args=(source_speech_token, this_uuid))
342
+ p.start()
343
+ if stream is True:
344
+ token_offset = 0
345
+ 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])
346
+ while True:
347
+ time.sleep(0.1)
348
+ this_token_hop_len = self.token_hop_len + prompt_token_pad if token_offset == 0 else self.token_hop_len
349
+ if len(self.tts_speech_token_dict[this_uuid]) - token_offset >= this_token_hop_len + self.flow.pre_lookahead_len:
350
+ 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)
351
+ this_tts_speech = self.token2wav(token=this_tts_speech_token,
352
+ prompt_token=flow_prompt_speech_token,
353
+ prompt_feat=prompt_speech_feat,
354
+ embedding=flow_embedding,
355
+ token_offset=token_offset,
356
+ uuid=this_uuid,
357
+ stream=stream,
358
+ finalize=False)
359
+ token_offset += this_token_hop_len
360
+ self.token_hop_len = min(self.token_max_hop_len, self.token_hop_len * self.stream_scale_factor)
361
+ yield {'tts_speech': this_tts_speech.cpu()}
362
+ 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:
363
+ break
364
+ p.join()
365
+ # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
366
+ this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
367
+ this_tts_speech = self.token2wav(token=this_tts_speech_token,
368
+ prompt_token=flow_prompt_speech_token,
369
+ prompt_feat=prompt_speech_feat,
370
+ embedding=flow_embedding,
371
+ token_offset=token_offset,
372
+ uuid=this_uuid,
373
+ finalize=True)
374
+ yield {'tts_speech': this_tts_speech.cpu()}
375
+ else:
376
+ # deal with all tokens
377
+ p.join()
378
+ this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
379
+ this_tts_speech = self.token2wav(token=this_tts_speech_token,
380
+ prompt_token=flow_prompt_speech_token,
381
+ prompt_feat=prompt_speech_feat,
382
+ embedding=flow_embedding,
383
+ token_offset=0,
384
+ uuid=this_uuid,
385
+ finalize=True,
386
+ speed=speed)
387
+ yield {'tts_speech': this_tts_speech.cpu()}
388
+ with self.lock:
389
+ self.tts_speech_token_dict.pop(this_uuid)
390
+ self.llm_end_dict.pop(this_uuid)
391
+ self.hift_cache_dict.pop(this_uuid)
392
+ if torch.cuda.is_available():
393
+ torch.cuda.empty_cache()
394
+ torch.cuda.current_stream().synchronize()
395
+
396
+
397
+ class CosyVoice3Model(CosyVoice2Model):
398
+
399
+ def __init__(self,
400
+ llm: torch.nn.Module,
401
+ flow: torch.nn.Module,
402
+ hift: torch.nn.Module,
403
+ fp16: bool = False):
404
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
405
+ self.llm = llm
406
+ self.flow = flow
407
+ self.hift = hift
408
+ self.fp16 = fp16
409
+ # NOTE must matching training static_chunk_size
410
+ self.token_hop_len = 25
411
+ # NOTE increase token_hop_len incrementally to avoid duplicate inference
412
+ self.token_max_hop_len = 4 * self.token_hop_len
413
+ self.stream_scale_factor = 2
414
+ assert self.stream_scale_factor >= 1, 'stream_scale_factor should be greater than 1, change it according to your actual rtf'
415
+ # rtf and decoding related
416
+ self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
417
+ self.lock = threading.Lock()
418
+ # dict used to store session related variable
419
+ self.tts_speech_token_dict = {}
420
+ self.llm_end_dict = {}
421
+ self.hift_cache_dict = {}
422
+ # FSQ silent and breath token
423
+ self.silent_tokens = [1, 2, 28, 29, 55, 248, 494, 2241, 2242, 2322, 2323]
424
+
425
+ def token2wav(self, token, prompt_token, prompt_feat, embedding, token_offset, uuid, stream=False, finalize=False, speed=1.0):
426
+ with torch.cuda.amp.autocast(self.fp16):
427
+ tts_mel, _ = self.flow.inference(token=token.to(self.device, dtype=torch.int32),
428
+ token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
429
+ prompt_token=prompt_token.to(self.device),
430
+ prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
431
+ prompt_feat=prompt_feat.to(self.device),
432
+ prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
433
+ embedding=embedding.to(self.device),
434
+ streaming=stream,
435
+ finalize=finalize)
436
+ tts_mel = tts_mel[:, :, token_offset * self.flow.token_mel_ratio:]
437
+ # append mel cache
438
+ if self.hift_cache_dict[uuid] is not None:
439
+ hift_cache_mel = self.hift_cache_dict[uuid]['mel']
440
+ tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
441
+ self.hift_cache_dict[uuid]['mel'] = tts_mel
442
+ else:
443
+ self.hift_cache_dict[uuid] = {'mel': tts_mel, 'speech_offset': 0}
444
+ if speed != 1.0:
445
+ assert token_offset == 0 and finalize is True, 'speed change only support non-stream inference mode'
446
+ tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
447
+ tts_speech, _ = self.hift.inference(speech_feat=tts_mel, finalize=finalize)
448
+ tts_speech = tts_speech[:, self.hift_cache_dict[uuid]['speech_offset']:]
449
+ self.hift_cache_dict[uuid]['speech_offset'] += tts_speech.shape[1]
450
+ return tts_speech
cosyvoice/dataset/__pycache__/dataset.cpython-310.pyc ADDED
Binary file (4.6 kB). View file
 
cosyvoice/flow/DiT/__pycache__/dit.cpython-310.pyc ADDED
Binary file (4.96 kB). View file
 
cosyvoice/flow/DiT/__pycache__/modules.cpython-310.pyc ADDED
Binary file (15.9 kB). View file
 
cosyvoice/flow/DiT/dit.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ ein notation:
4
+ b - batch
5
+ n - sequence
6
+ nt - text sequence
7
+ nw - raw wave length
8
+ d - dimension
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import torch
14
+ from torch import nn
15
+ import torch.nn.functional as F
16
+ from einops import repeat
17
+ from x_transformers.x_transformers import RotaryEmbedding
18
+ from cosyvoice.utils.mask import add_optional_chunk_mask
19
+ from cosyvoice.flow.DiT.modules import (
20
+ TimestepEmbedding,
21
+ ConvNeXtV2Block,
22
+ CausalConvPositionEmbedding,
23
+ DiTBlock,
24
+ AdaLayerNormZero_Final,
25
+ precompute_freqs_cis,
26
+ get_pos_embed_indices,
27
+ )
28
+
29
+
30
+ # Text embedding
31
+
32
+
33
+ class TextEmbedding(nn.Module):
34
+ def __init__(self, text_num_embeds, text_dim, conv_layers=0, conv_mult=2):
35
+ super().__init__()
36
+ self.text_embed = nn.Embedding(text_num_embeds + 1, text_dim) # use 0 as filler token
37
+
38
+ if conv_layers > 0:
39
+ self.extra_modeling = True
40
+ self.precompute_max_pos = 4096 # ~44s of 24khz audio
41
+ self.register_buffer("freqs_cis", precompute_freqs_cis(text_dim, self.precompute_max_pos), persistent=False)
42
+ self.text_blocks = nn.Sequential(
43
+ *[ConvNeXtV2Block(text_dim, text_dim * conv_mult) for _ in range(conv_layers)]
44
+ )
45
+ else:
46
+ self.extra_modeling = False
47
+
48
+ def forward(self, text: int["b nt"], seq_len, drop_text=False): # noqa: F722
49
+ batch, text_len = text.shape[0], text.shape[1]
50
+ text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx()
51
+ text = text[:, :seq_len] # curtail if character tokens are more than the mel spec tokens
52
+ text = F.pad(text, (0, seq_len - text_len), value=0)
53
+
54
+ if drop_text: # cfg for text
55
+ text = torch.zeros_like(text)
56
+
57
+ text = self.text_embed(text) # b n -> b n d
58
+
59
+ # possible extra modeling
60
+ if self.extra_modeling:
61
+ # sinus pos emb
62
+ batch_start = torch.zeros((batch,), dtype=torch.long)
63
+ pos_idx = get_pos_embed_indices(batch_start, seq_len, max_pos=self.precompute_max_pos)
64
+ text_pos_embed = self.freqs_cis[pos_idx]
65
+ text = text + text_pos_embed
66
+
67
+ # convnextv2 blocks
68
+ text = self.text_blocks(text)
69
+
70
+ return text
71
+
72
+
73
+ # noised input audio and context mixing embedding
74
+
75
+
76
+ class InputEmbedding(nn.Module):
77
+ def __init__(self, mel_dim, text_dim, out_dim, spk_dim=None):
78
+ super().__init__()
79
+ spk_dim = 0 if spk_dim is None else spk_dim
80
+ self.spk_dim = spk_dim
81
+ self.proj = nn.Linear(mel_dim * 2 + text_dim + spk_dim, out_dim)
82
+ self.conv_pos_embed = CausalConvPositionEmbedding(dim=out_dim)
83
+
84
+ def forward(
85
+ self,
86
+ x: float["b n d"],
87
+ cond: float["b n d"],
88
+ text_embed: float["b n d"],
89
+ spks: float["b d"],
90
+ ):
91
+ to_cat = [x, cond, text_embed]
92
+ if self.spk_dim > 0:
93
+ spks = repeat(spks, "b c -> b t c", t=x.shape[1])
94
+ to_cat.append(spks)
95
+
96
+ x = self.proj(torch.cat(to_cat, dim=-1))
97
+ x = self.conv_pos_embed(x) + x
98
+ return x
99
+
100
+
101
+ # Transformer backbone using DiT blocks
102
+
103
+
104
+ class DiT(nn.Module):
105
+ def __init__(
106
+ self,
107
+ *,
108
+ dim,
109
+ depth=8,
110
+ heads=8,
111
+ dim_head=64,
112
+ dropout=0.1,
113
+ ff_mult=4,
114
+ mel_dim=80,
115
+ mu_dim=None,
116
+ long_skip_connection=False,
117
+ spk_dim=None,
118
+ out_channels=None,
119
+ static_chunk_size=50,
120
+ num_decoding_left_chunks=2
121
+ ):
122
+ super().__init__()
123
+
124
+ self.time_embed = TimestepEmbedding(dim)
125
+ if mu_dim is None:
126
+ mu_dim = mel_dim
127
+ self.input_embed = InputEmbedding(mel_dim, mu_dim, dim, spk_dim)
128
+
129
+ self.rotary_embed = RotaryEmbedding(dim_head)
130
+
131
+ self.dim = dim
132
+ self.depth = depth
133
+
134
+ self.transformer_blocks = nn.ModuleList(
135
+ [DiTBlock(dim=dim, heads=heads, dim_head=dim_head, ff_mult=ff_mult, dropout=dropout) for _ in range(depth)]
136
+ )
137
+ self.long_skip_connection = nn.Linear(dim * 2, dim, bias=False) if long_skip_connection else None
138
+
139
+ self.norm_out = AdaLayerNormZero_Final(dim) # final modulation
140
+ self.proj_out = nn.Linear(dim, mel_dim)
141
+ self.out_channels = out_channels
142
+ self.static_chunk_size = static_chunk_size
143
+ self.num_decoding_left_chunks = num_decoding_left_chunks
144
+
145
+ def forward(self, x, mask, mu, t, spks=None, cond=None, streaming=False):
146
+ x = x.transpose(1, 2)
147
+ mu = mu.transpose(1, 2)
148
+ cond = cond.transpose(1, 2)
149
+ spks = spks.unsqueeze(dim=1)
150
+ batch, seq_len = x.shape[0], x.shape[1]
151
+ if t.ndim == 0:
152
+ t = t.repeat(batch)
153
+
154
+ # t: conditioning time, c: context (text + masked cond audio), x: noised input audio
155
+ t = self.time_embed(t)
156
+ x = self.input_embed(x, cond, mu, spks.squeeze(1))
157
+
158
+ rope = self.rotary_embed.forward_from_seq_len(seq_len)
159
+
160
+ if self.long_skip_connection is not None:
161
+ residual = x
162
+
163
+ if streaming is True:
164
+ attn_mask = add_optional_chunk_mask(x, mask.bool(), False, False, 0, self.static_chunk_size, -1).unsqueeze(dim=1)
165
+ else:
166
+ attn_mask = add_optional_chunk_mask(x, mask.bool(), False, False, 0, 0, -1).repeat(1, x.size(1), 1).unsqueeze(dim=1)
167
+
168
+ for block in self.transformer_blocks:
169
+ x = block(x, t, mask=attn_mask.bool(), rope=rope)
170
+
171
+ if self.long_skip_connection is not None:
172
+ x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
173
+
174
+ x = self.norm_out(x, t)
175
+ output = self.proj_out(x).transpose(1, 2)
176
+ return output
cosyvoice/flow/DiT/modules.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ ein notation:
4
+ b - batch
5
+ n - sequence
6
+ nt - text sequence
7
+ nw - raw wave length
8
+ d - dimension
9
+ """
10
+
11
+ from __future__ import annotations
12
+ from typing import Optional
13
+ import math
14
+
15
+ import torch
16
+ from torch import nn
17
+ import torch.nn.functional as F
18
+ import torchaudio
19
+
20
+ from x_transformers.x_transformers import apply_rotary_pos_emb
21
+
22
+
23
+ # raw wav to mel spec
24
+ class MelSpec(nn.Module):
25
+ def __init__(
26
+ self,
27
+ filter_length=1024,
28
+ hop_length=256,
29
+ win_length=1024,
30
+ n_mel_channels=100,
31
+ target_sample_rate=24_000,
32
+ normalize=False,
33
+ power=1,
34
+ norm=None,
35
+ center=True,
36
+ ):
37
+ super().__init__()
38
+ self.n_mel_channels = n_mel_channels
39
+
40
+ self.mel_stft = torchaudio.transforms.MelSpectrogram(
41
+ sample_rate=target_sample_rate,
42
+ n_fft=filter_length,
43
+ win_length=win_length,
44
+ hop_length=hop_length,
45
+ n_mels=n_mel_channels,
46
+ power=power,
47
+ center=center,
48
+ normalized=normalize,
49
+ norm=norm,
50
+ )
51
+
52
+ self.register_buffer("dummy", torch.tensor(0), persistent=False)
53
+
54
+ def forward(self, inp):
55
+ if len(inp.shape) == 3:
56
+ inp = inp.squeeze(1) # 'b 1 nw -> b nw'
57
+
58
+ assert len(inp.shape) == 2
59
+
60
+ if self.dummy.device != inp.device:
61
+ self.to(inp.device)
62
+
63
+ mel = self.mel_stft(inp)
64
+ mel = mel.clamp(min=1e-5).log()
65
+ return mel
66
+
67
+
68
+ # sinusoidal position embedding
69
+
70
+
71
+ class SinusPositionEmbedding(nn.Module):
72
+ def __init__(self, dim):
73
+ super().__init__()
74
+ self.dim = dim
75
+
76
+ def forward(self, x, scale=1000):
77
+ device = x.device
78
+ half_dim = self.dim // 2
79
+ emb = math.log(10000) / (half_dim - 1)
80
+ emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
81
+ emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
82
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
83
+ return emb
84
+
85
+
86
+ # convolutional position embedding
87
+
88
+
89
+ class ConvPositionEmbedding(nn.Module):
90
+ def __init__(self, dim, kernel_size=31, groups=16):
91
+ super().__init__()
92
+ assert kernel_size % 2 != 0
93
+ self.conv1d = nn.Sequential(
94
+ nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
95
+ nn.Mish(),
96
+ nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2),
97
+ nn.Mish(),
98
+ )
99
+
100
+ def forward(self, x: float["b n d"], mask: bool["b n"] | None = None): # noqa: F722
101
+ if mask is not None:
102
+ mask = mask[..., None]
103
+ x = x.masked_fill(~mask, 0.0)
104
+
105
+ x = x.permute(0, 2, 1)
106
+ x = self.conv1d(x)
107
+ out = x.permute(0, 2, 1)
108
+
109
+ if mask is not None:
110
+ out = out.masked_fill(~mask, 0.0)
111
+
112
+ return out
113
+
114
+
115
+ class CausalConvPositionEmbedding(nn.Module):
116
+ def __init__(self, dim, kernel_size=31, groups=16):
117
+ super().__init__()
118
+ assert kernel_size % 2 != 0
119
+ self.kernel_size = kernel_size
120
+ self.conv1 = nn.Sequential(
121
+ nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=0),
122
+ nn.Mish(),
123
+ )
124
+ self.conv2 = nn.Sequential(
125
+ nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=0),
126
+ nn.Mish(),
127
+ )
128
+
129
+ def forward(self, x: float["b n d"], mask: bool["b n"] | None = None): # noqa: F722
130
+ if mask is not None:
131
+ mask = mask[..., None]
132
+ x = x.masked_fill(~mask, 0.0)
133
+
134
+ x = x.permute(0, 2, 1)
135
+ x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
136
+ x = self.conv1(x)
137
+ x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
138
+ x = self.conv2(x)
139
+ out = x.permute(0, 2, 1)
140
+
141
+ if mask is not None:
142
+ out = out.masked_fill(~mask, 0.0)
143
+
144
+ return out
145
+
146
+
147
+ # rotary positional embedding related
148
+
149
+
150
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0, theta_rescale_factor=1.0):
151
+ # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
152
+ # has some connection to NTK literature
153
+ # https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/
154
+ # https://github.com/lucidrains/rotary-embedding-torch/blob/main/rotary_embedding_torch/rotary_embedding_torch.py
155
+ theta *= theta_rescale_factor ** (dim / (dim - 2))
156
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
157
+ t = torch.arange(end, device=freqs.device) # type: ignore
158
+ freqs = torch.outer(t, freqs).float() # type: ignore
159
+ freqs_cos = torch.cos(freqs) # real part
160
+ freqs_sin = torch.sin(freqs) # imaginary part
161
+ return torch.cat([freqs_cos, freqs_sin], dim=-1)
162
+
163
+
164
+ def get_pos_embed_indices(start, length, max_pos, scale=1.0):
165
+ # length = length if isinstance(length, int) else length.max()
166
+ scale = scale * torch.ones_like(start, dtype=torch.float32) # in case scale is a scalar
167
+ pos = (
168
+ start.unsqueeze(1)
169
+ + (torch.arange(length, device=start.device, dtype=torch.float32).unsqueeze(0) * scale.unsqueeze(1)).long()
170
+ )
171
+ # avoid extra long error.
172
+ pos = torch.where(pos < max_pos, pos, max_pos - 1)
173
+ return pos
174
+
175
+
176
+ # Global Response Normalization layer (Instance Normalization ?)
177
+
178
+
179
+ class GRN(nn.Module):
180
+ def __init__(self, dim):
181
+ super().__init__()
182
+ self.gamma = nn.Parameter(torch.zeros(1, 1, dim))
183
+ self.beta = nn.Parameter(torch.zeros(1, 1, dim))
184
+
185
+ def forward(self, x):
186
+ Gx = torch.norm(x, p=2, dim=1, keepdim=True)
187
+ Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
188
+ return self.gamma * (x * Nx) + self.beta + x
189
+
190
+
191
+ # ConvNeXt-V2 Block https://github.com/facebookresearch/ConvNeXt-V2/blob/main/models/convnextv2.py
192
+ # ref: https://github.com/bfs18/e2_tts/blob/main/rfwave/modules.py#L108
193
+
194
+
195
+ class ConvNeXtV2Block(nn.Module):
196
+ def __init__(
197
+ self,
198
+ dim: int,
199
+ intermediate_dim: int,
200
+ dilation: int = 1,
201
+ ):
202
+ super().__init__()
203
+ padding = (dilation * (7 - 1)) // 2
204
+ self.dwconv = nn.Conv1d(
205
+ dim, dim, kernel_size=7, padding=padding, groups=dim, dilation=dilation
206
+ ) # depthwise conv
207
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
208
+ self.pwconv1 = nn.Linear(dim, intermediate_dim) # pointwise/1x1 convs, implemented with linear layers
209
+ self.act = nn.GELU()
210
+ self.grn = GRN(intermediate_dim)
211
+ self.pwconv2 = nn.Linear(intermediate_dim, dim)
212
+
213
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
214
+ residual = x
215
+ x = x.transpose(1, 2) # b n d -> b d n
216
+ x = self.dwconv(x)
217
+ x = x.transpose(1, 2) # b d n -> b n d
218
+ x = self.norm(x)
219
+ x = self.pwconv1(x)
220
+ x = self.act(x)
221
+ x = self.grn(x)
222
+ x = self.pwconv2(x)
223
+ return residual + x
224
+
225
+
226
+ # AdaLayerNormZero
227
+ # return with modulated x for attn input, and params for later mlp modulation
228
+
229
+
230
+ class AdaLayerNormZero(nn.Module):
231
+ def __init__(self, dim):
232
+ super().__init__()
233
+
234
+ self.silu = nn.SiLU()
235
+ self.linear = nn.Linear(dim, dim * 6)
236
+
237
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
238
+
239
+ def forward(self, x, emb=None):
240
+ emb = self.linear(self.silu(emb))
241
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = torch.chunk(emb, 6, dim=1)
242
+
243
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
244
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
245
+
246
+
247
+ # AdaLayerNormZero for final layer
248
+ # return only with modulated x for attn input, cuz no more mlp modulation
249
+
250
+
251
+ class AdaLayerNormZero_Final(nn.Module):
252
+ def __init__(self, dim):
253
+ super().__init__()
254
+
255
+ self.silu = nn.SiLU()
256
+ self.linear = nn.Linear(dim, dim * 2)
257
+
258
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
259
+
260
+ def forward(self, x, emb):
261
+ emb = self.linear(self.silu(emb))
262
+ scale, shift = torch.chunk(emb, 2, dim=1)
263
+
264
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
265
+ return x
266
+
267
+
268
+ # FeedForward
269
+
270
+
271
+ class FeedForward(nn.Module):
272
+ def __init__(self, dim, dim_out=None, mult=4, dropout=0.0, approximate: str = "none"):
273
+ super().__init__()
274
+ inner_dim = int(dim * mult)
275
+ dim_out = dim_out if dim_out is not None else dim
276
+
277
+ activation = nn.GELU(approximate=approximate)
278
+ project_in = nn.Sequential(nn.Linear(dim, inner_dim), activation)
279
+ self.ff = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))
280
+
281
+ def forward(self, x):
282
+ return self.ff(x)
283
+
284
+
285
+ # Attention with possible joint part
286
+ # modified from diffusers/src/diffusers/models/attention_processor.py
287
+
288
+
289
+ class Attention(nn.Module):
290
+ def __init__(
291
+ self,
292
+ processor: JointAttnProcessor | AttnProcessor,
293
+ dim: int,
294
+ heads: int = 8,
295
+ dim_head: int = 64,
296
+ dropout: float = 0.0,
297
+ context_dim: Optional[int] = None, # if not None -> joint attention
298
+ context_pre_only=None,
299
+ ):
300
+ super().__init__()
301
+
302
+ if not hasattr(F, "scaled_dot_product_attention"):
303
+ raise ImportError("Attention equires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
304
+
305
+ self.processor = processor
306
+
307
+ self.dim = dim
308
+ self.heads = heads
309
+ self.inner_dim = dim_head * heads
310
+ self.dropout = dropout
311
+
312
+ self.context_dim = context_dim
313
+ self.context_pre_only = context_pre_only
314
+
315
+ self.to_q = nn.Linear(dim, self.inner_dim)
316
+ self.to_k = nn.Linear(dim, self.inner_dim)
317
+ self.to_v = nn.Linear(dim, self.inner_dim)
318
+
319
+ if self.context_dim is not None:
320
+ self.to_k_c = nn.Linear(context_dim, self.inner_dim)
321
+ self.to_v_c = nn.Linear(context_dim, self.inner_dim)
322
+ if self.context_pre_only is not None:
323
+ self.to_q_c = nn.Linear(context_dim, self.inner_dim)
324
+
325
+ self.to_out = nn.ModuleList([])
326
+ self.to_out.append(nn.Linear(self.inner_dim, dim))
327
+ self.to_out.append(nn.Dropout(dropout))
328
+
329
+ if self.context_pre_only is not None and not self.context_pre_only:
330
+ self.to_out_c = nn.Linear(self.inner_dim, dim)
331
+
332
+ def forward(
333
+ self,
334
+ x: float["b n d"], # noised input x # noqa: F722
335
+ c: float["b n d"] = None, # context c # noqa: F722
336
+ mask: bool["b n"] | None = None, # noqa: F722
337
+ rope=None, # rotary position embedding for x
338
+ c_rope=None, # rotary position embedding for c
339
+ ) -> torch.Tensor:
340
+ if c is not None:
341
+ return self.processor(self, x, c=c, mask=mask, rope=rope, c_rope=c_rope)
342
+ else:
343
+ return self.processor(self, x, mask=mask, rope=rope)
344
+
345
+
346
+ # Attention processor
347
+
348
+
349
+ class AttnProcessor:
350
+ def __init__(self):
351
+ pass
352
+
353
+ def __call__(
354
+ self,
355
+ attn: Attention,
356
+ x: float["b n d"], # noised input x # noqa: F722
357
+ mask: bool["b n"] | None = None, # noqa: F722
358
+ rope=None, # rotary position embedding
359
+ ) -> torch.FloatTensor:
360
+ batch_size = x.shape[0]
361
+
362
+ # `sample` projections.
363
+ query = attn.to_q(x)
364
+ key = attn.to_k(x)
365
+ value = attn.to_v(x)
366
+
367
+ # apply rotary position embedding
368
+ if rope is not None:
369
+ freqs, xpos_scale = rope
370
+ q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
371
+
372
+ query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
373
+ key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
374
+
375
+ # attention
376
+ inner_dim = key.shape[-1]
377
+ head_dim = inner_dim // attn.heads
378
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
379
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
380
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
381
+
382
+ # mask. e.g. inference got a batch with different target durations, mask out the padding
383
+ if mask is not None:
384
+ attn_mask = mask
385
+ if attn_mask.dim() == 2:
386
+ attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n'
387
+ attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2])
388
+ else:
389
+ attn_mask = None
390
+
391
+ x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
392
+ x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
393
+ x = x.to(query.dtype)
394
+
395
+ # linear proj
396
+ x = attn.to_out[0](x)
397
+ # dropout
398
+ x = attn.to_out[1](x)
399
+
400
+ if mask is not None:
401
+ if mask.dim() == 2:
402
+ mask = mask.unsqueeze(-1)
403
+ else:
404
+ mask = mask[:, 0, -1].unsqueeze(-1)
405
+ x = x.masked_fill(~mask, 0.0)
406
+
407
+ return x
408
+
409
+
410
+ # Joint Attention processor for MM-DiT
411
+ # modified from diffusers/src/diffusers/models/attention_processor.py
412
+
413
+
414
+ class JointAttnProcessor:
415
+ def __init__(self):
416
+ pass
417
+
418
+ def __call__(
419
+ self,
420
+ attn: Attention,
421
+ x: float["b n d"], # noised input x # noqa: F722
422
+ c: float["b nt d"] = None, # context c, here text # noqa: F722
423
+ mask: bool["b n"] | None = None, # noqa: F722
424
+ rope=None, # rotary position embedding for x
425
+ c_rope=None, # rotary position embedding for c
426
+ ) -> torch.FloatTensor:
427
+ residual = x
428
+
429
+ batch_size = c.shape[0]
430
+
431
+ # `sample` projections.
432
+ query = attn.to_q(x)
433
+ key = attn.to_k(x)
434
+ value = attn.to_v(x)
435
+
436
+ # `context` projections.
437
+ c_query = attn.to_q_c(c)
438
+ c_key = attn.to_k_c(c)
439
+ c_value = attn.to_v_c(c)
440
+
441
+ # apply rope for context and noised input independently
442
+ if rope is not None:
443
+ freqs, xpos_scale = rope
444
+ q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
445
+ query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
446
+ key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
447
+ if c_rope is not None:
448
+ freqs, xpos_scale = c_rope
449
+ q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
450
+ c_query = apply_rotary_pos_emb(c_query, freqs, q_xpos_scale)
451
+ c_key = apply_rotary_pos_emb(c_key, freqs, k_xpos_scale)
452
+
453
+ # attention
454
+ query = torch.cat([query, c_query], dim=1)
455
+ key = torch.cat([key, c_key], dim=1)
456
+ value = torch.cat([value, c_value], dim=1)
457
+
458
+ inner_dim = key.shape[-1]
459
+ head_dim = inner_dim // attn.heads
460
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
461
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
462
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
463
+
464
+ # mask. e.g. inference got a batch with different target durations, mask out the padding
465
+ if mask is not None:
466
+ attn_mask = F.pad(mask, (0, c.shape[1]), value=True) # no mask for c (text)
467
+ attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n'
468
+ attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2])
469
+ else:
470
+ attn_mask = None
471
+
472
+ x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
473
+ x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
474
+ x = x.to(query.dtype)
475
+
476
+ # Split the attention outputs.
477
+ x, c = (
478
+ x[:, : residual.shape[1]],
479
+ x[:, residual.shape[1]:],
480
+ )
481
+
482
+ # linear proj
483
+ x = attn.to_out[0](x)
484
+ # dropout
485
+ x = attn.to_out[1](x)
486
+ if not attn.context_pre_only:
487
+ c = attn.to_out_c(c)
488
+
489
+ if mask is not None:
490
+ mask = mask.unsqueeze(-1)
491
+ x = x.masked_fill(~mask, 0.0)
492
+ # c = c.masked_fill(~mask, 0.) # no mask for c (text)
493
+
494
+ return x, c
495
+
496
+
497
+ # DiT Block
498
+
499
+
500
+ class DiTBlock(nn.Module):
501
+ def __init__(self, dim, heads, dim_head, ff_mult=4, dropout=0.1):
502
+ super().__init__()
503
+
504
+ self.attn_norm = AdaLayerNormZero(dim)
505
+ self.attn = Attention(
506
+ processor=AttnProcessor(),
507
+ dim=dim,
508
+ heads=heads,
509
+ dim_head=dim_head,
510
+ dropout=dropout,
511
+ )
512
+
513
+ self.ff_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
514
+ self.ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
515
+
516
+ def forward(self, x, t, mask=None, rope=None): # x: noised input, t: time embedding
517
+ # pre-norm & modulation for attention input
518
+ norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
519
+
520
+ # attention
521
+ attn_output = self.attn(x=norm, mask=mask, rope=rope)
522
+
523
+ # process attention output for input x
524
+ x = x + gate_msa.unsqueeze(1) * attn_output
525
+
526
+ ff_norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
527
+ ff_output = self.ff(ff_norm)
528
+ x = x + gate_mlp.unsqueeze(1) * ff_output
529
+
530
+ return x
531
+
532
+
533
+ # MMDiT Block https://arxiv.org/abs/2403.03206
534
+
535
+
536
+ class MMDiTBlock(nn.Module):
537
+ r"""
538
+ modified from diffusers/src/diffusers/models/attention.py
539
+
540
+ notes.
541
+ _c: context related. text, cond, etc. (left part in sd3 fig2.b)
542
+ _x: noised input related. (right part)
543
+ context_pre_only: last layer only do prenorm + modulation cuz no more ffn
544
+ """
545
+
546
+ def __init__(self, dim, heads, dim_head, ff_mult=4, dropout=0.1, context_pre_only=False):
547
+ super().__init__()
548
+
549
+ self.context_pre_only = context_pre_only
550
+
551
+ self.attn_norm_c = AdaLayerNormZero_Final(dim) if context_pre_only else AdaLayerNormZero(dim)
552
+ self.attn_norm_x = AdaLayerNormZero(dim)
553
+ self.attn = Attention(
554
+ processor=JointAttnProcessor(),
555
+ dim=dim,
556
+ heads=heads,
557
+ dim_head=dim_head,
558
+ dropout=dropout,
559
+ context_dim=dim,
560
+ context_pre_only=context_pre_only,
561
+ )
562
+
563
+ if not context_pre_only:
564
+ self.ff_norm_c = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
565
+ self.ff_c = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
566
+ else:
567
+ self.ff_norm_c = None
568
+ self.ff_c = None
569
+ self.ff_norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
570
+ self.ff_x = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
571
+
572
+ def forward(self, x, c, t, mask=None, rope=None, c_rope=None): # x: noised input, c: context, t: time embedding
573
+ # pre-norm & modulation for attention input
574
+ if self.context_pre_only:
575
+ norm_c = self.attn_norm_c(c, t)
576
+ else:
577
+ norm_c, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.attn_norm_c(c, emb=t)
578
+ norm_x, x_gate_msa, x_shift_mlp, x_scale_mlp, x_gate_mlp = self.attn_norm_x(x, emb=t)
579
+
580
+ # attention
581
+ x_attn_output, c_attn_output = self.attn(x=norm_x, c=norm_c, mask=mask, rope=rope, c_rope=c_rope)
582
+
583
+ # process attention output for context c
584
+ if self.context_pre_only:
585
+ c = None
586
+ else: # if not last layer
587
+ c = c + c_gate_msa.unsqueeze(1) * c_attn_output
588
+
589
+ norm_c = self.ff_norm_c(c) * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
590
+ c_ff_output = self.ff_c(norm_c)
591
+ c = c + c_gate_mlp.unsqueeze(1) * c_ff_output
592
+
593
+ # process attention output for input x
594
+ x = x + x_gate_msa.unsqueeze(1) * x_attn_output
595
+
596
+ norm_x = self.ff_norm_x(x) * (1 + x_scale_mlp[:, None]) + x_shift_mlp[:, None]
597
+ x_ff_output = self.ff_x(norm_x)
598
+ x = x + x_gate_mlp.unsqueeze(1) * x_ff_output
599
+
600
+ return c, x
601
+
602
+
603
+ # time step conditioning embedding
604
+
605
+
606
+ class TimestepEmbedding(nn.Module):
607
+ def __init__(self, dim, freq_embed_dim=256):
608
+ super().__init__()
609
+ self.time_embed = SinusPositionEmbedding(freq_embed_dim)
610
+ self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
611
+
612
+ def forward(self, timestep: float["b"]): # noqa: F821
613
+ time_hidden = self.time_embed(timestep)
614
+ time_hidden = time_hidden.to(timestep.dtype)
615
+ time = self.time_mlp(time_hidden) # b d
616
+ return time
cosyvoice/flow/__pycache__/flow_matching.cpython-310.pyc ADDED
Binary file (7.23 kB). View file
 
cosyvoice/flow/decoder.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Tuple
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from einops import pack, rearrange, repeat
19
+ from cosyvoice.utils.common import mask_to_bias
20
+ from cosyvoice.utils.mask import add_optional_chunk_mask
21
+ from matcha.models.components.decoder import SinusoidalPosEmb, Block1D, ResnetBlock1D, Downsample1D, TimestepEmbedding, Upsample1D
22
+ from matcha.models.components.transformer import BasicTransformerBlock
23
+
24
+
25
+ class Transpose(torch.nn.Module):
26
+ def __init__(self, dim0: int, dim1: int):
27
+ super().__init__()
28
+ self.dim0 = dim0
29
+ self.dim1 = dim1
30
+
31
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
32
+ x = torch.transpose(x, self.dim0, self.dim1)
33
+ return x
34
+
35
+
36
+ class CausalConv1d(torch.nn.Conv1d):
37
+ def __init__(
38
+ self,
39
+ in_channels: int,
40
+ out_channels: int,
41
+ kernel_size: int,
42
+ stride: int = 1,
43
+ dilation: int = 1,
44
+ groups: int = 1,
45
+ bias: bool = True,
46
+ padding_mode: str = 'zeros',
47
+ device=None,
48
+ dtype=None
49
+ ) -> None:
50
+ super(CausalConv1d, self).__init__(in_channels, out_channels,
51
+ kernel_size, stride,
52
+ padding=0, dilation=dilation,
53
+ groups=groups, bias=bias,
54
+ padding_mode=padding_mode,
55
+ device=device, dtype=dtype)
56
+ assert stride == 1
57
+ self.causal_padding = kernel_size - 1
58
+
59
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
60
+ x = F.pad(x, (self.causal_padding, 0), value=0.0)
61
+ x = super(CausalConv1d, self).forward(x)
62
+ return x
63
+
64
+
65
+ class CausalBlock1D(Block1D):
66
+ def __init__(self, dim: int, dim_out: int):
67
+ super(CausalBlock1D, self).__init__(dim, dim_out)
68
+ self.block = torch.nn.Sequential(
69
+ CausalConv1d(dim, dim_out, 3),
70
+ Transpose(1, 2),
71
+ nn.LayerNorm(dim_out),
72
+ Transpose(1, 2),
73
+ nn.Mish(),
74
+ )
75
+
76
+ def forward(self, x: torch.Tensor, mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
77
+ output = self.block(x * mask)
78
+ return output * mask
79
+
80
+
81
+ class CausalResnetBlock1D(ResnetBlock1D):
82
+ def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
83
+ super(CausalResnetBlock1D, self).__init__(dim, dim_out, time_emb_dim, groups)
84
+ self.block1 = CausalBlock1D(dim, dim_out)
85
+ self.block2 = CausalBlock1D(dim_out, dim_out)
86
+
87
+
88
+ class ConditionalDecoder(nn.Module):
89
+ def __init__(
90
+ self,
91
+ in_channels,
92
+ out_channels,
93
+ channels=(256, 256),
94
+ dropout=0.05,
95
+ attention_head_dim=64,
96
+ n_blocks=1,
97
+ num_mid_blocks=2,
98
+ num_heads=4,
99
+ act_fn="snake",
100
+ ):
101
+ """
102
+ This decoder requires an input with the same shape of the target. So, if your text content
103
+ is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
104
+ """
105
+ super().__init__()
106
+ channels = tuple(channels)
107
+ self.in_channels = in_channels
108
+ self.out_channels = out_channels
109
+
110
+ self.time_embeddings = SinusoidalPosEmb(in_channels)
111
+ time_embed_dim = channels[0] * 4
112
+ self.time_mlp = TimestepEmbedding(
113
+ in_channels=in_channels,
114
+ time_embed_dim=time_embed_dim,
115
+ act_fn="silu",
116
+ )
117
+ self.down_blocks = nn.ModuleList([])
118
+ self.mid_blocks = nn.ModuleList([])
119
+ self.up_blocks = nn.ModuleList([])
120
+
121
+ output_channel = in_channels
122
+ for i in range(len(channels)): # pylint: disable=consider-using-enumerate
123
+ input_channel = output_channel
124
+ output_channel = channels[i]
125
+ is_last = i == len(channels) - 1
126
+ resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
127
+ transformer_blocks = nn.ModuleList(
128
+ [
129
+ BasicTransformerBlock(
130
+ dim=output_channel,
131
+ num_attention_heads=num_heads,
132
+ attention_head_dim=attention_head_dim,
133
+ dropout=dropout,
134
+ activation_fn=act_fn,
135
+ )
136
+ for _ in range(n_blocks)
137
+ ]
138
+ )
139
+ downsample = (
140
+ Downsample1D(output_channel) if not is_last else nn.Conv1d(output_channel, output_channel, 3, padding=1)
141
+ )
142
+ self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
143
+
144
+ for _ in range(num_mid_blocks):
145
+ input_channel = channels[-1]
146
+ out_channels = channels[-1]
147
+ resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
148
+
149
+ transformer_blocks = nn.ModuleList(
150
+ [
151
+ BasicTransformerBlock(
152
+ dim=output_channel,
153
+ num_attention_heads=num_heads,
154
+ attention_head_dim=attention_head_dim,
155
+ dropout=dropout,
156
+ activation_fn=act_fn,
157
+ )
158
+ for _ in range(n_blocks)
159
+ ]
160
+ )
161
+
162
+ self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
163
+
164
+ channels = channels[::-1] + (channels[0],)
165
+ for i in range(len(channels) - 1):
166
+ input_channel = channels[i] * 2
167
+ output_channel = channels[i + 1]
168
+ is_last = i == len(channels) - 2
169
+ resnet = ResnetBlock1D(
170
+ dim=input_channel,
171
+ dim_out=output_channel,
172
+ time_emb_dim=time_embed_dim,
173
+ )
174
+ transformer_blocks = nn.ModuleList(
175
+ [
176
+ BasicTransformerBlock(
177
+ dim=output_channel,
178
+ num_attention_heads=num_heads,
179
+ attention_head_dim=attention_head_dim,
180
+ dropout=dropout,
181
+ activation_fn=act_fn,
182
+ )
183
+ for _ in range(n_blocks)
184
+ ]
185
+ )
186
+ upsample = (
187
+ Upsample1D(output_channel, use_conv_transpose=True)
188
+ if not is_last
189
+ else nn.Conv1d(output_channel, output_channel, 3, padding=1)
190
+ )
191
+ self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
192
+ self.final_block = Block1D(channels[-1], channels[-1])
193
+ self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
194
+ self.initialize_weights()
195
+
196
+ def initialize_weights(self):
197
+ for m in self.modules():
198
+ if isinstance(m, nn.Conv1d):
199
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
200
+ if m.bias is not None:
201
+ nn.init.constant_(m.bias, 0)
202
+ elif isinstance(m, nn.GroupNorm):
203
+ nn.init.constant_(m.weight, 1)
204
+ nn.init.constant_(m.bias, 0)
205
+ elif isinstance(m, nn.Linear):
206
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
207
+ if m.bias is not None:
208
+ nn.init.constant_(m.bias, 0)
209
+
210
+ def forward(self, x, mask, mu, t, spks=None, cond=None, streaming=False):
211
+ """Forward pass of the UNet1DConditional model.
212
+
213
+ Args:
214
+ x (torch.Tensor): shape (batch_size, in_channels, time)
215
+ mask (_type_): shape (batch_size, 1, time)
216
+ t (_type_): shape (batch_size)
217
+ spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None.
218
+ cond (_type_, optional): placeholder for future use. Defaults to None.
219
+
220
+ Raises:
221
+ ValueError: _description_
222
+ ValueError: _description_
223
+
224
+ Returns:
225
+ _type_: _description_
226
+ """
227
+
228
+ t = self.time_embeddings(t).to(t.dtype)
229
+ t = self.time_mlp(t)
230
+
231
+ x = pack([x, mu], "b * t")[0]
232
+
233
+ if spks is not None:
234
+ spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
235
+ x = pack([x, spks], "b * t")[0]
236
+ if cond is not None:
237
+ x = pack([x, cond], "b * t")[0]
238
+
239
+ hiddens = []
240
+ masks = [mask]
241
+ for resnet, transformer_blocks, downsample in self.down_blocks:
242
+ mask_down = masks[-1]
243
+ x = resnet(x, mask_down, t)
244
+ x = rearrange(x, "b c t -> b t c").contiguous()
245
+ attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, 0, -1).repeat(1, x.size(1), 1)
246
+ attn_mask = mask_to_bias(attn_mask, x.dtype)
247
+ for transformer_block in transformer_blocks:
248
+ x = transformer_block(
249
+ hidden_states=x,
250
+ attention_mask=attn_mask,
251
+ timestep=t,
252
+ )
253
+ x = rearrange(x, "b t c -> b c t").contiguous()
254
+ hiddens.append(x) # Save hidden states for skip connections
255
+ x = downsample(x * mask_down)
256
+ masks.append(mask_down[:, :, ::2])
257
+ masks = masks[:-1]
258
+ mask_mid = masks[-1]
259
+
260
+ for resnet, transformer_blocks in self.mid_blocks:
261
+ x = resnet(x, mask_mid, t)
262
+ x = rearrange(x, "b c t -> b t c").contiguous()
263
+ attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, 0, -1).repeat(1, x.size(1), 1)
264
+ attn_mask = mask_to_bias(attn_mask, x.dtype)
265
+ for transformer_block in transformer_blocks:
266
+ x = transformer_block(
267
+ hidden_states=x,
268
+ attention_mask=attn_mask,
269
+ timestep=t,
270
+ )
271
+ x = rearrange(x, "b t c -> b c t").contiguous()
272
+
273
+ for resnet, transformer_blocks, upsample in self.up_blocks:
274
+ mask_up = masks.pop()
275
+ skip = hiddens.pop()
276
+ x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
277
+ x = resnet(x, mask_up, t)
278
+ x = rearrange(x, "b c t -> b t c").contiguous()
279
+ attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, 0, -1).repeat(1, x.size(1), 1)
280
+ attn_mask = mask_to_bias(attn_mask, x.dtype)
281
+ for transformer_block in transformer_blocks:
282
+ x = transformer_block(
283
+ hidden_states=x,
284
+ attention_mask=attn_mask,
285
+ timestep=t,
286
+ )
287
+ x = rearrange(x, "b t c -> b c t").contiguous()
288
+ x = upsample(x * mask_up)
289
+ x = self.final_block(x, mask_up)
290
+ output = self.final_proj(x * mask_up)
291
+ return output * mask
292
+
293
+
294
+ class CausalConditionalDecoder(ConditionalDecoder):
295
+ def __init__(
296
+ self,
297
+ in_channels,
298
+ out_channels,
299
+ channels=(256, 256),
300
+ dropout=0.05,
301
+ attention_head_dim=64,
302
+ n_blocks=1,
303
+ num_mid_blocks=2,
304
+ num_heads=4,
305
+ act_fn="snake",
306
+ static_chunk_size=50,
307
+ num_decoding_left_chunks=2,
308
+ ):
309
+ """
310
+ This decoder requires an input with the same shape of the target. So, if your text content
311
+ is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
312
+ """
313
+ torch.nn.Module.__init__(self)
314
+ channels = tuple(channels)
315
+ self.in_channels = in_channels
316
+ self.out_channels = out_channels
317
+ self.time_embeddings = SinusoidalPosEmb(in_channels)
318
+ time_embed_dim = channels[0] * 4
319
+ self.time_mlp = TimestepEmbedding(
320
+ in_channels=in_channels,
321
+ time_embed_dim=time_embed_dim,
322
+ act_fn="silu",
323
+ )
324
+ self.static_chunk_size = static_chunk_size
325
+ self.num_decoding_left_chunks = num_decoding_left_chunks
326
+ self.down_blocks = nn.ModuleList([])
327
+ self.mid_blocks = nn.ModuleList([])
328
+ self.up_blocks = nn.ModuleList([])
329
+
330
+ output_channel = in_channels
331
+ for i in range(len(channels)): # pylint: disable=consider-using-enumerate
332
+ input_channel = output_channel
333
+ output_channel = channels[i]
334
+ is_last = i == len(channels) - 1
335
+ resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
336
+ transformer_blocks = nn.ModuleList(
337
+ [
338
+ BasicTransformerBlock(
339
+ dim=output_channel,
340
+ num_attention_heads=num_heads,
341
+ attention_head_dim=attention_head_dim,
342
+ dropout=dropout,
343
+ activation_fn=act_fn,
344
+ )
345
+ for _ in range(n_blocks)
346
+ ]
347
+ )
348
+ downsample = (
349
+ Downsample1D(output_channel) if not is_last else CausalConv1d(output_channel, output_channel, 3)
350
+ )
351
+ self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
352
+
353
+ for _ in range(num_mid_blocks):
354
+ input_channel = channels[-1]
355
+ out_channels = channels[-1]
356
+ resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
357
+
358
+ transformer_blocks = nn.ModuleList(
359
+ [
360
+ BasicTransformerBlock(
361
+ dim=output_channel,
362
+ num_attention_heads=num_heads,
363
+ attention_head_dim=attention_head_dim,
364
+ dropout=dropout,
365
+ activation_fn=act_fn,
366
+ )
367
+ for _ in range(n_blocks)
368
+ ]
369
+ )
370
+
371
+ self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
372
+
373
+ channels = channels[::-1] + (channels[0],)
374
+ for i in range(len(channels) - 1):
375
+ input_channel = channels[i] * 2
376
+ output_channel = channels[i + 1]
377
+ is_last = i == len(channels) - 2
378
+ resnet = CausalResnetBlock1D(
379
+ dim=input_channel,
380
+ dim_out=output_channel,
381
+ time_emb_dim=time_embed_dim,
382
+ )
383
+ transformer_blocks = nn.ModuleList(
384
+ [
385
+ BasicTransformerBlock(
386
+ dim=output_channel,
387
+ num_attention_heads=num_heads,
388
+ attention_head_dim=attention_head_dim,
389
+ dropout=dropout,
390
+ activation_fn=act_fn,
391
+ )
392
+ for _ in range(n_blocks)
393
+ ]
394
+ )
395
+ upsample = (
396
+ Upsample1D(output_channel, use_conv_transpose=True)
397
+ if not is_last
398
+ else CausalConv1d(output_channel, output_channel, 3)
399
+ )
400
+ self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
401
+ self.final_block = CausalBlock1D(channels[-1], channels[-1])
402
+ self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
403
+ self.initialize_weights()
404
+
405
+ def forward(self, x, mask, mu, t, spks=None, cond=None, streaming=False):
406
+ """Forward pass of the UNet1DConditional model.
407
+
408
+ Args:
409
+ x (torch.Tensor): shape (batch_size, in_channels, time)
410
+ mask (_type_): shape (batch_size, 1, time)
411
+ t (_type_): shape (batch_size)
412
+ spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None.
413
+ cond (_type_, optional): placeholder for future use. Defaults to None.
414
+
415
+ Raises:
416
+ ValueError: _description_
417
+ ValueError: _description_
418
+
419
+ Returns:
420
+ _type_: _description_
421
+ """
422
+ t = self.time_embeddings(t).to(t.dtype)
423
+ t = self.time_mlp(t)
424
+
425
+ x = pack([x, mu], "b * t")[0]
426
+
427
+ if spks is not None:
428
+ spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
429
+ x = pack([x, spks], "b * t")[0]
430
+ if cond is not None:
431
+ x = pack([x, cond], "b * t")[0]
432
+
433
+ hiddens = []
434
+ masks = [mask]
435
+ for resnet, transformer_blocks, downsample in self.down_blocks:
436
+ mask_down = masks[-1]
437
+ x = resnet(x, mask_down, t)
438
+ x = rearrange(x, "b c t -> b t c").contiguous()
439
+ if streaming is True:
440
+ attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, self.static_chunk_size, -1)
441
+ else:
442
+ attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, 0, -1).repeat(1, x.size(1), 1)
443
+ attn_mask = mask_to_bias(attn_mask, x.dtype)
444
+ for transformer_block in transformer_blocks:
445
+ x = transformer_block(
446
+ hidden_states=x,
447
+ attention_mask=attn_mask,
448
+ timestep=t,
449
+ )
450
+ x = rearrange(x, "b t c -> b c t").contiguous()
451
+ hiddens.append(x) # Save hidden states for skip connections
452
+ x = downsample(x * mask_down)
453
+ masks.append(mask_down[:, :, ::2])
454
+ masks = masks[:-1]
455
+ mask_mid = masks[-1]
456
+
457
+ for resnet, transformer_blocks in self.mid_blocks:
458
+ x = resnet(x, mask_mid, t)
459
+ x = rearrange(x, "b c t -> b t c").contiguous()
460
+ if streaming is True:
461
+ attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, self.static_chunk_size, -1)
462
+ else:
463
+ attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, 0, -1).repeat(1, x.size(1), 1)
464
+ attn_mask = mask_to_bias(attn_mask, x.dtype)
465
+ for transformer_block in transformer_blocks:
466
+ x = transformer_block(
467
+ hidden_states=x,
468
+ attention_mask=attn_mask,
469
+ timestep=t,
470
+ )
471
+ x = rearrange(x, "b t c -> b c t").contiguous()
472
+
473
+ for resnet, transformer_blocks, upsample in self.up_blocks:
474
+ mask_up = masks.pop()
475
+ skip = hiddens.pop()
476
+ x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
477
+ x = resnet(x, mask_up, t)
478
+ x = rearrange(x, "b c t -> b t c").contiguous()
479
+ if streaming is True:
480
+ attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, self.static_chunk_size, -1)
481
+ else:
482
+ attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, 0, -1).repeat(1, x.size(1), 1)
483
+ attn_mask = mask_to_bias(attn_mask, x.dtype)
484
+ for transformer_block in transformer_blocks:
485
+ x = transformer_block(
486
+ hidden_states=x,
487
+ attention_mask=attn_mask,
488
+ timestep=t,
489
+ )
490
+ x = rearrange(x, "b t c -> b c t").contiguous()
491
+ x = upsample(x * mask_up)
492
+ x = self.final_block(x, mask_up)
493
+ output = self.final_proj(x * mask_up)
494
+ return output * mask
cosyvoice/flow/flow_matching.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
2
+ # 2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou)
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from matcha.models.components.flow_matching import BASECFM
18
+ from cosyvoice.utils.common import set_all_random_seed
19
+
20
+
21
+ class ConditionalCFM(BASECFM):
22
+ def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator: torch.nn.Module = None):
23
+ super().__init__(
24
+ n_feats=in_channels,
25
+ cfm_params=cfm_params,
26
+ n_spks=n_spks,
27
+ spk_emb_dim=spk_emb_dim,
28
+ )
29
+ self.t_scheduler = cfm_params.t_scheduler
30
+ self.training_cfg_rate = cfm_params.training_cfg_rate
31
+ self.inference_cfg_rate = cfm_params.inference_cfg_rate
32
+ in_channels = in_channels + (spk_emb_dim if n_spks > 0 else 0)
33
+ # Just change the architecture of the estimator here
34
+ self.estimator = estimator
35
+
36
+ @torch.inference_mode()
37
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None, prompt_len=0, cache=torch.zeros(1, 80, 0, 2)):
38
+ """Forward diffusion
39
+
40
+ Args:
41
+ mu (torch.Tensor): output of encoder
42
+ shape: (batch_size, n_feats, mel_timesteps)
43
+ mask (torch.Tensor): output_mask
44
+ shape: (batch_size, 1, mel_timesteps)
45
+ n_timesteps (int): number of diffusion steps
46
+ temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
47
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
48
+ shape: (batch_size, spk_emb_dim)
49
+ cond: Not used but kept for future purposes
50
+
51
+ Returns:
52
+ sample: generated mel-spectrogram
53
+ shape: (batch_size, n_feats, mel_timesteps)
54
+ """
55
+
56
+ z = torch.randn_like(mu).to(mu.device).to(mu.dtype) * temperature
57
+ cache_size = cache.shape[2]
58
+ # fix prompt and overlap part mu and z
59
+ if cache_size != 0:
60
+ z[:, :, :cache_size] = cache[:, :, :, 0]
61
+ mu[:, :, :cache_size] = cache[:, :, :, 1]
62
+ z_cache = torch.concat([z[:, :, :prompt_len], z[:, :, -34:]], dim=2)
63
+ mu_cache = torch.concat([mu[:, :, :prompt_len], mu[:, :, -34:]], dim=2)
64
+ cache = torch.stack([z_cache, mu_cache], dim=-1)
65
+
66
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
67
+ if self.t_scheduler == 'cosine':
68
+ t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
69
+ return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), cache
70
+
71
+ def solve_euler(self, x, t_span, mu, mask, spks, cond, streaming=False):
72
+ """
73
+ Fixed euler solver for ODEs.
74
+ Args:
75
+ x (torch.Tensor): random noise
76
+ t_span (torch.Tensor): n_timesteps interpolated
77
+ shape: (n_timesteps + 1,)
78
+ mu (torch.Tensor): output of encoder
79
+ shape: (batch_size, n_feats, mel_timesteps)
80
+ mask (torch.Tensor): output_mask
81
+ shape: (batch_size, 1, mel_timesteps)
82
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
83
+ shape: (batch_size, spk_emb_dim)
84
+ cond: Not used but kept for future purposes
85
+ """
86
+ t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
87
+ t = t.unsqueeze(dim=0)
88
+
89
+ # I am storing this because I can later plot it by putting a debugger here and saving it to a file
90
+ # Or in future might add like a return_all_steps flag
91
+ sol = []
92
+
93
+ # Do not use concat, it may cause memory format changed and trt infer with wrong results!
94
+ # NOTE when flow run in amp mode, x.dtype is float32, which cause nan in trt fp16 inference, so set dtype=spks.dtype
95
+ x_in = torch.zeros([2, 80, x.size(2)], device=x.device, dtype=spks.dtype)
96
+ mask_in = torch.zeros([2, 1, x.size(2)], device=x.device, dtype=spks.dtype)
97
+ mu_in = torch.zeros([2, 80, x.size(2)], device=x.device, dtype=spks.dtype)
98
+ t_in = torch.zeros([2], device=x.device, dtype=spks.dtype)
99
+ spks_in = torch.zeros([2, 80], device=x.device, dtype=spks.dtype)
100
+ cond_in = torch.zeros([2, 80, x.size(2)], device=x.device, dtype=spks.dtype)
101
+ for step in range(1, len(t_span)):
102
+ # Classifier-Free Guidance inference introduced in VoiceBox
103
+ x_in[:] = x
104
+ mask_in[:] = mask
105
+ mu_in[0] = mu
106
+ t_in[:] = t.unsqueeze(0)
107
+ spks_in[0] = spks
108
+ cond_in[0] = cond
109
+ dphi_dt = self.forward_estimator(
110
+ x_in, mask_in,
111
+ mu_in, t_in,
112
+ spks_in,
113
+ cond_in,
114
+ streaming
115
+ )
116
+ dphi_dt, cfg_dphi_dt = torch.split(dphi_dt, [x.size(0), x.size(0)], dim=0)
117
+ dphi_dt = ((1.0 + self.inference_cfg_rate) * dphi_dt - self.inference_cfg_rate * cfg_dphi_dt)
118
+ x = x + dt * dphi_dt
119
+ t = t + dt
120
+ sol.append(x)
121
+ if step < len(t_span) - 1:
122
+ dt = t_span[step + 1] - t
123
+
124
+ return sol[-1].float()
125
+
126
+ def forward_estimator(self, x, mask, mu, t, spks, cond, streaming=False):
127
+ if isinstance(self.estimator, torch.nn.Module):
128
+ return self.estimator(x, mask, mu, t, spks, cond, streaming=streaming)
129
+ else:
130
+ [estimator, stream], trt_engine = self.estimator.acquire_estimator()
131
+ # NOTE need to synchronize when switching stream
132
+ torch.cuda.current_stream().synchronize()
133
+ with stream:
134
+ estimator.set_input_shape('x', (2, 80, x.size(2)))
135
+ estimator.set_input_shape('mask', (2, 1, x.size(2)))
136
+ estimator.set_input_shape('mu', (2, 80, x.size(2)))
137
+ estimator.set_input_shape('t', (2,))
138
+ estimator.set_input_shape('spks', (2, 80))
139
+ estimator.set_input_shape('cond', (2, 80, x.size(2)))
140
+ data_ptrs = [x.contiguous().data_ptr(),
141
+ mask.contiguous().data_ptr(),
142
+ mu.contiguous().data_ptr(),
143
+ t.contiguous().data_ptr(),
144
+ spks.contiguous().data_ptr(),
145
+ cond.contiguous().data_ptr(),
146
+ x.data_ptr()]
147
+ for i, j in enumerate(data_ptrs):
148
+ estimator.set_tensor_address(trt_engine.get_tensor_name(i), j)
149
+ # run trt engine
150
+ assert estimator.execute_async_v3(torch.cuda.current_stream().cuda_stream) is True
151
+ torch.cuda.current_stream().synchronize()
152
+ self.estimator.release_estimator(estimator, stream)
153
+ return x
154
+
155
+ def compute_loss(self, x1, mask, mu, spks=None, cond=None, streaming=False):
156
+ """Computes diffusion loss
157
+
158
+ Args:
159
+ x1 (torch.Tensor): Target
160
+ shape: (batch_size, n_feats, mel_timesteps)
161
+ mask (torch.Tensor): target mask
162
+ shape: (batch_size, 1, mel_timesteps)
163
+ mu (torch.Tensor): output of encoder
164
+ shape: (batch_size, n_feats, mel_timesteps)
165
+ spks (torch.Tensor, optional): speaker embedding. Defaults to None.
166
+ shape: (batch_size, spk_emb_dim)
167
+
168
+ Returns:
169
+ loss: conditional flow matching loss
170
+ y: conditional flow
171
+ shape: (batch_size, n_feats, mel_timesteps)
172
+ """
173
+ b, _, t = mu.shape
174
+
175
+ # random timestep
176
+ t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
177
+
178
+ # sample noise p(x_0)
179
+ z = torch.randn_like(x1)
180
+
181
+ y = (1 - (1 - self.sigma_min) * t) * z + t * x1
182
+ u = x1 - (1 - self.sigma_min) * z
183
+
184
+ # during training, we randomly drop condition to trade off mode coverage and sample fidelity
185
+ if self.training_cfg_rate > 0:
186
+ cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
187
+ mu = mu * cfg_mask.view(-1, 1, 1)
188
+ spks = spks * cfg_mask.view(-1, 1)
189
+ cond = cond * cfg_mask.view(-1, 1, 1)
190
+
191
+ pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond, streaming=streaming)
192
+ loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1])
193
+ return loss, y
194
+
195
+
196
+ class CausalConditionalCFM(ConditionalCFM):
197
+ def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator: torch.nn.Module = None):
198
+ super().__init__(in_channels, cfm_params, n_spks, spk_emb_dim, estimator)
199
+ set_all_random_seed(0)
200
+ self.rand_noise = torch.randn([1, 80, 50 * 300])
201
+
202
+ @torch.inference_mode()
203
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None, streaming=False):
204
+ """Forward diffusion
205
+
206
+ Args:
207
+ mu (torch.Tensor): output of encoder
208
+ shape: (batch_size, n_feats, mel_timesteps)
209
+ mask (torch.Tensor): output_mask
210
+ shape: (batch_size, 1, mel_timesteps)
211
+ n_timesteps (int): number of diffusion steps
212
+ temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
213
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
214
+ shape: (batch_size, spk_emb_dim)
215
+ cond: Not used but kept for future purposes
216
+
217
+ Returns:
218
+ sample: generated mel-spectrogram
219
+ shape: (batch_size, n_feats, mel_timesteps)
220
+ """
221
+
222
+ z = self.rand_noise[:, :, :mu.size(2)].to(mu.device).to(mu.dtype) * temperature
223
+ # fix prompt and overlap part mu and z
224
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
225
+ if self.t_scheduler == 'cosine':
226
+ t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
227
+ return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond, streaming=streaming), None
cosyvoice/flow/length_regulator.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Tuple
15
+ import torch.nn as nn
16
+ import torch
17
+ from torch.nn import functional as F
18
+ from cosyvoice.utils.mask import make_pad_mask
19
+
20
+
21
+ class InterpolateRegulator(nn.Module):
22
+ def __init__(
23
+ self,
24
+ channels: int,
25
+ sampling_ratios: Tuple,
26
+ out_channels: int = None,
27
+ groups: int = 1,
28
+ ):
29
+ super().__init__()
30
+ self.sampling_ratios = sampling_ratios
31
+ out_channels = out_channels or channels
32
+ model = nn.ModuleList([])
33
+ if len(sampling_ratios) > 0:
34
+ for _ in sampling_ratios:
35
+ module = nn.Conv1d(channels, channels, 3, 1, 1)
36
+ norm = nn.GroupNorm(groups, channels)
37
+ act = nn.Mish()
38
+ model.extend([module, norm, act])
39
+ model.append(
40
+ nn.Conv1d(channels, out_channels, 1, 1)
41
+ )
42
+ self.model = nn.Sequential(*model)
43
+
44
+ def forward(self, x, ylens=None):
45
+ # x in (B, T, D)
46
+ mask = (~make_pad_mask(ylens)).to(x).unsqueeze(-1)
47
+ x = F.interpolate(x.transpose(1, 2).contiguous(), size=ylens.max(), mode='linear')
48
+ out = self.model(x).transpose(1, 2).contiguous()
49
+ olens = ylens
50
+ return out * mask, olens
51
+
52
+ def inference(self, x1, x2, mel_len1, mel_len2, input_frame_rate=50):
53
+ # in inference mode, interploate prompt token and token(head/mid/tail) seprately, so we can get a clear separation point of mel
54
+ # NOTE 20 corresponds to token_overlap_len in cosyvoice/cli/model.py
55
+ # x in (B, T, D)
56
+ if x2.shape[1] > 40:
57
+ x2_head = F.interpolate(x2[:, :20].transpose(1, 2).contiguous(), size=int(20 / input_frame_rate * 22050 / 256), mode='linear')
58
+ x2_mid = F.interpolate(x2[:, 20:-20].transpose(1, 2).contiguous(), size=mel_len2 - int(20 / input_frame_rate * 22050 / 256) * 2,
59
+ mode='linear')
60
+ x2_tail = F.interpolate(x2[:, -20:].transpose(1, 2).contiguous(), size=int(20 / input_frame_rate * 22050 / 256), mode='linear')
61
+ x2 = torch.concat([x2_head, x2_mid, x2_tail], dim=2)
62
+ else:
63
+ x2 = F.interpolate(x2.transpose(1, 2).contiguous(), size=mel_len2, mode='linear')
64
+ if x1.shape[1] != 0:
65
+ x1 = F.interpolate(x1.transpose(1, 2).contiguous(), size=mel_len1, mode='linear')
66
+ x = torch.concat([x1, x2], dim=2)
67
+ else:
68
+ x = x2
69
+ out = self.model(x).transpose(1, 2).contiguous()
70
+ return out, mel_len1 + mel_len2
cosyvoice/hifigan/__pycache__/discriminator.cpython-310.pyc ADDED
Binary file (8.75 kB). View file
 
cosyvoice/hifigan/__pycache__/f0_predictor.cpython-310.pyc ADDED
Binary file (2.66 kB). View file
 
cosyvoice/hifigan/__pycache__/generator.cpython-310.pyc ADDED
Binary file (19.9 kB). View file
 
cosyvoice/hifigan/__pycache__/hifigan.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
cosyvoice/hifigan/generator.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Kai Hu)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """HIFI-GAN"""
16
+
17
+ from typing import Dict, Optional, List
18
+ import numpy as np
19
+ from scipy.signal import get_window
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from torch.nn import Conv1d
24
+ from torch.nn import ConvTranspose1d
25
+ from torch.nn.utils import remove_weight_norm
26
+ try:
27
+ from torch.nn.utils.parametrizations import weight_norm
28
+ except ImportError:
29
+ from torch.nn.utils import weight_norm
30
+ from torch.distributions.uniform import Uniform
31
+ from cosyvoice.transformer.convolution import CausalConv1d, CausalConv1dDownSample, CausalConv1dUpsample
32
+ from cosyvoice.transformer.activation import Snake
33
+ from cosyvoice.utils.common import get_padding
34
+ from cosyvoice.utils.common import init_weights
35
+
36
+
37
+ """hifigan based generator implementation.
38
+
39
+ This code is modified from https://github.com/jik876/hifi-gan
40
+ ,https://github.com/kan-bayashi/ParallelWaveGAN and
41
+ https://github.com/NVIDIA/BigVGAN
42
+
43
+ """
44
+
45
+
46
+ class ResBlock(torch.nn.Module):
47
+ """Residual block module in HiFiGAN/BigVGAN."""
48
+ def __init__(
49
+ self,
50
+ channels: int = 512,
51
+ kernel_size: int = 3,
52
+ dilations: List[int] = [1, 3, 5],
53
+ causal: bool = False,
54
+ ):
55
+ super(ResBlock, self).__init__()
56
+ self.causal = causal
57
+ self.convs1 = nn.ModuleList()
58
+ self.convs2 = nn.ModuleList()
59
+
60
+ for dilation in dilations:
61
+ self.convs1.append(
62
+ weight_norm(
63
+ Conv1d(
64
+ channels,
65
+ channels,
66
+ kernel_size,
67
+ 1,
68
+ dilation=dilation,
69
+ padding=get_padding(kernel_size, dilation)) if causal is False else
70
+ CausalConv1d(
71
+ channels,
72
+ channels,
73
+ kernel_size,
74
+ 1,
75
+ dilation=dilation,
76
+ causal_type='left'
77
+ )
78
+ )
79
+ )
80
+ self.convs2.append(
81
+ weight_norm(
82
+ Conv1d(
83
+ channels,
84
+ channels,
85
+ kernel_size,
86
+ 1,
87
+ dilation=1,
88
+ padding=get_padding(kernel_size, 1)) if causal is False else
89
+ CausalConv1d(
90
+ channels,
91
+ channels,
92
+ kernel_size,
93
+ 1,
94
+ dilation=1,
95
+ causal_type='left'
96
+ )
97
+ )
98
+ )
99
+ self.convs1.apply(init_weights)
100
+ self.convs2.apply(init_weights)
101
+ self.activations1 = nn.ModuleList([
102
+ Snake(channels, alpha_logscale=False)
103
+ for _ in range(len(self.convs1))
104
+ ])
105
+ self.activations2 = nn.ModuleList([
106
+ Snake(channels, alpha_logscale=False)
107
+ for _ in range(len(self.convs2))
108
+ ])
109
+
110
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
111
+ for idx in range(len(self.convs1)):
112
+ xt = self.activations1[idx](x)
113
+ xt = self.convs1[idx](xt)
114
+ xt = self.activations2[idx](xt)
115
+ xt = self.convs2[idx](xt)
116
+ x = xt + x
117
+ return x
118
+
119
+ def remove_weight_norm(self):
120
+ for idx in range(len(self.convs1)):
121
+ remove_weight_norm(self.convs1[idx])
122
+ remove_weight_norm(self.convs2[idx])
123
+
124
+
125
+ class SineGen(torch.nn.Module):
126
+ """ Definition of sine generator
127
+ SineGen(samp_rate, harmonic_num = 0,
128
+ sine_amp = 0.1, noise_std = 0.003,
129
+ voiced_threshold = 0,
130
+ flag_for_pulse=False)
131
+ samp_rate: sampling rate in Hz
132
+ harmonic_num: number of harmonic overtones (default 0)
133
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
134
+ noise_std: std of Gaussian noise (default 0.003)
135
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
136
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
137
+ Note: when flag_for_pulse is True, the first time step of a voiced
138
+ segment is always sin(np.pi) or cos(0)
139
+ """
140
+
141
+ def __init__(self, samp_rate, harmonic_num=0,
142
+ sine_amp=0.1, noise_std=0.003,
143
+ voiced_threshold=0):
144
+ super(SineGen, self).__init__()
145
+ self.sine_amp = sine_amp
146
+ self.noise_std = noise_std
147
+ self.harmonic_num = harmonic_num
148
+ self.sampling_rate = samp_rate
149
+ self.voiced_threshold = voiced_threshold
150
+
151
+ def _f02uv(self, f0):
152
+ # generate uv signal
153
+ uv = (f0 > self.voiced_threshold).type(torch.float32)
154
+ return uv
155
+
156
+ @torch.no_grad()
157
+ def forward(self, f0):
158
+ """ sine_tensor, uv = forward(f0)
159
+ input F0: tensor(batchsize=1, dim=1, length)
160
+ f0 for unvoiced steps should be 0
161
+ output sine_tensor: tensor(batchsize=1, length, dim)
162
+ output uv: tensor(batchsize=1, length, 1)
163
+ """
164
+ f0 = f0.transpose(1, 2)
165
+ F_mat = torch.zeros((f0.size(0), self.harmonic_num + 1, f0.size(-1))).to(f0.device)
166
+ for i in range(self.harmonic_num + 1):
167
+ F_mat[:, i: i + 1, :] = f0 * (i + 1) / self.sampling_rate
168
+
169
+ theta_mat = 2 * np.pi * (torch.cumsum(F_mat, dim=-1) % 1)
170
+ u_dist = Uniform(low=-np.pi, high=np.pi)
171
+ phase_vec = u_dist.sample(sample_shape=(f0.size(0), self.harmonic_num + 1, 1)).to(F_mat.device)
172
+ phase_vec[:, 0, :] = 0
173
+
174
+ # generate sine waveforms
175
+ sine_waves = self.sine_amp * torch.sin(theta_mat + phase_vec)
176
+
177
+ # generate uv signal
178
+ uv = self._f02uv(f0)
179
+
180
+ # noise: for unvoiced should be similar to sine_amp
181
+ # std = self.sine_amp/3 -> max value ~ self.sine_amp
182
+ # . for voiced regions is self.noise_std
183
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
184
+ noise = noise_amp * torch.randn_like(sine_waves)
185
+
186
+ # first: set the unvoiced part to 0 by uv
187
+ # then: additive noise
188
+ sine_waves = sine_waves * uv + noise
189
+ return sine_waves.transpose(1, 2), uv.transpose(1, 2), noise
190
+
191
+
192
+ class SineGen2(torch.nn.Module):
193
+ """ Definition of sine generator
194
+ SineGen(samp_rate, harmonic_num = 0,
195
+ sine_amp = 0.1, noise_std = 0.003,
196
+ voiced_threshold = 0,
197
+ flag_for_pulse=False)
198
+ samp_rate: sampling rate in Hz
199
+ harmonic_num: number of harmonic overtones (default 0)
200
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
201
+ noise_std: std of Gaussian noise (default 0.003)
202
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
203
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
204
+ Note: when flag_for_pulse is True, the first time step of a voiced
205
+ segment is always sin(np.pi) or cos(0)
206
+ """
207
+
208
+ def __init__(self, samp_rate, upsample_scale, harmonic_num=0,
209
+ sine_amp=0.1, noise_std=0.003,
210
+ voiced_threshold=0,
211
+ flag_for_pulse=False,
212
+ causal=False):
213
+ super(SineGen2, self).__init__()
214
+ self.sine_amp = sine_amp
215
+ self.noise_std = noise_std
216
+ self.harmonic_num = harmonic_num
217
+ self.dim = self.harmonic_num + 1
218
+ self.sampling_rate = samp_rate
219
+ self.voiced_threshold = voiced_threshold
220
+ self.flag_for_pulse = flag_for_pulse
221
+ self.upsample_scale = upsample_scale
222
+ self.causal = causal
223
+ if causal is True:
224
+ self.rand_ini = torch.rand(1, 9)
225
+ self.rand_ini[:, 0] = 0
226
+ self.sine_waves = torch.rand(1, 300 * 24000, 9)
227
+
228
+ def _f02uv(self, f0):
229
+ # generate uv signal
230
+ uv = (f0 > self.voiced_threshold).type(torch.float32)
231
+ return uv
232
+
233
+ def _f02sine(self, f0_values):
234
+ """ f0_values: (batchsize, length, dim)
235
+ where dim indicates fundamental tone and overtones
236
+ """
237
+ # convert to F0 in rad. The interger part n can be ignored
238
+ # because 2 * np.pi * n doesn't affect phase
239
+ rad_values = (f0_values / self.sampling_rate) % 1
240
+
241
+ # initial phase noise (no noise for fundamental component)
242
+ if self.training is False and self.causal is True:
243
+ rad_values[:, 0, :] = rad_values[:, 0, :] + self.rand_ini.to(rad_values.device)
244
+ else:
245
+ rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], device=f0_values.device)
246
+ rand_ini[:, 0] = 0
247
+ rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
248
+
249
+ # instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad)
250
+ if not self.flag_for_pulse:
251
+ rad_values = torch.nn.functional.interpolate(rad_values.transpose(1, 2),
252
+ scale_factor=1 / self.upsample_scale,
253
+ mode="linear").transpose(1, 2)
254
+
255
+ phase = torch.cumsum(rad_values, dim=1) * 2 * np.pi
256
+ phase = torch.nn.functional.interpolate(phase.transpose(1, 2) * self.upsample_scale,
257
+ scale_factor=self.upsample_scale, mode="nearest" if self.causal is True else 'linear').transpose(1, 2)
258
+ sines = torch.sin(phase)
259
+ else:
260
+ # If necessary, make sure that the first time step of every
261
+ # voiced segments is sin(pi) or cos(0)
262
+ # This is used for pulse-train generation
263
+
264
+ # identify the last time step in unvoiced segments
265
+ uv = self._f02uv(f0_values)
266
+ uv_1 = torch.roll(uv, shifts=-1, dims=1)
267
+ uv_1[:, -1, :] = 1
268
+ u_loc = (uv < 1) * (uv_1 > 0)
269
+
270
+ # get the instantanouse phase
271
+ tmp_cumsum = torch.cumsum(rad_values, dim=1)
272
+ # different batch needs to be processed differently
273
+ for idx in range(f0_values.shape[0]):
274
+ temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :]
275
+ temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :]
276
+ # stores the accumulation of i.phase within
277
+ # each voiced segments
278
+ tmp_cumsum[idx, :, :] = 0
279
+ tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum
280
+
281
+ # rad_values - tmp_cumsum: remove the accumulation of i.phase
282
+ # within the previous voiced segment.
283
+ i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1)
284
+
285
+ # get the sines
286
+ sines = torch.cos(i_phase * 2 * np.pi)
287
+ return sines
288
+
289
+ def forward(self, f0):
290
+ """ sine_tensor, uv = forward(f0)
291
+ input F0: tensor(batchsize=1, length, dim=1)
292
+ f0 for unvoiced steps should be 0
293
+ output sine_tensor: tensor(batchsize=1, length, dim)
294
+ output uv: tensor(batchsize=1, length, 1)
295
+ """
296
+ # fundamental component
297
+ fn = torch.multiply(f0, torch.FloatTensor([[range(1, self.harmonic_num + 2)]]).to(f0.device))
298
+
299
+ # generate sine waveforms
300
+ sine_waves = self._f02sine(fn) * self.sine_amp
301
+
302
+ # generate uv signal
303
+ uv = self._f02uv(f0)
304
+
305
+ # noise: for unvoiced should be similar to sine_amp
306
+ # std = self.sine_amp/3 -> max value ~ self.sine_amp
307
+ # . for voiced regions is self.noise_std
308
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
309
+ if self.training is False and self.causal is True:
310
+ noise = noise_amp * self.sine_waves[:, :sine_waves.shape[1]].to(sine_waves.device)
311
+ else:
312
+ noise = noise_amp * torch.randn_like(sine_waves)
313
+
314
+ # first: set the unvoiced part to 0 by uv
315
+ # then: additive noise
316
+ sine_waves = sine_waves * uv + noise
317
+ return sine_waves, uv, noise
318
+
319
+
320
+ class SourceModuleHnNSF(torch.nn.Module):
321
+ """ SourceModule for hn-nsf
322
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
323
+ add_noise_std=0.003, voiced_threshod=0)
324
+ sampling_rate: sampling_rate in Hz
325
+ harmonic_num: number of harmonic above F0 (default: 0)
326
+ sine_amp: amplitude of sine source signal (default: 0.1)
327
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
328
+ note that amplitude of noise in unvoiced is decided
329
+ by sine_amp
330
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
331
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
332
+ F0_sampled (batchsize, length, 1)
333
+ Sine_source (batchsize, length, 1)
334
+ noise_source (batchsize, length 1)
335
+ uv (batchsize, length, 1)
336
+ """
337
+
338
+ def __init__(self, sampling_rate, upsample_scale, harmonic_num=0, sine_amp=0.1,
339
+ add_noise_std=0.003, voiced_threshod=0, sinegen_type='1', causal=False):
340
+ super(SourceModuleHnNSF, self).__init__()
341
+
342
+ self.sine_amp = sine_amp
343
+ self.noise_std = add_noise_std
344
+
345
+ # to produce sine waveforms
346
+ if sinegen_type == '1':
347
+ self.l_sin_gen = SineGen(sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod)
348
+ else:
349
+ self.l_sin_gen = SineGen2(sampling_rate, upsample_scale, harmonic_num, sine_amp, add_noise_std, voiced_threshod, causal=causal)
350
+
351
+ # to merge source harmonics into a single excitation
352
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
353
+ self.l_tanh = torch.nn.Tanh()
354
+ self.causal = causal
355
+ if causal is True:
356
+ self.uv = torch.rand(1, 300 * 24000, 1)
357
+
358
+ def forward(self, x):
359
+ """
360
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
361
+ F0_sampled (batchsize, length, 1)
362
+ Sine_source (batchsize, length, 1)
363
+ noise_source (batchsize, length 1)
364
+ """
365
+ # source for harmonic branch
366
+ with torch.no_grad():
367
+ sine_wavs, uv, _ = self.l_sin_gen(x)
368
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
369
+
370
+ # source for noise branch, in the same shape as uv
371
+ if self.training is False and self.causal is True:
372
+ noise = self.uv[:, :uv.shape[1]] * self.sine_amp / 3
373
+ else:
374
+ noise = torch.randn_like(uv) * self.sine_amp / 3
375
+ return sine_merge, noise, uv
376
+
377
+
378
+ class HiFTGenerator(nn.Module):
379
+ """
380
+ HiFTNet Generator: Neural Source Filter + ISTFTNet
381
+ https://arxiv.org/abs/2309.09493
382
+ """
383
+ def __init__(
384
+ self,
385
+ in_channels: int = 80,
386
+ base_channels: int = 512,
387
+ nb_harmonics: int = 8,
388
+ sampling_rate: int = 22050,
389
+ nsf_alpha: float = 0.1,
390
+ nsf_sigma: float = 0.003,
391
+ nsf_voiced_threshold: float = 10,
392
+ upsample_rates: List[int] = [8, 8],
393
+ upsample_kernel_sizes: List[int] = [16, 16],
394
+ istft_params: Dict[str, int] = {"n_fft": 16, "hop_len": 4},
395
+ resblock_kernel_sizes: List[int] = [3, 7, 11],
396
+ resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
397
+ source_resblock_kernel_sizes: List[int] = [7, 11],
398
+ source_resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5]],
399
+ lrelu_slope: float = 0.1,
400
+ audio_limit: float = 0.99,
401
+ f0_predictor: torch.nn.Module = None,
402
+ ):
403
+ super(HiFTGenerator, self).__init__()
404
+
405
+ self.out_channels = 1
406
+ self.nb_harmonics = nb_harmonics
407
+ self.sampling_rate = sampling_rate
408
+ self.istft_params = istft_params
409
+ self.lrelu_slope = lrelu_slope
410
+ self.audio_limit = audio_limit
411
+
412
+ self.num_kernels = len(resblock_kernel_sizes)
413
+ self.num_upsamples = len(upsample_rates)
414
+ # NOTE in CosyVoice2, we use the original SineGen implementation
415
+ self.m_source = SourceModuleHnNSF(
416
+ sampling_rate=sampling_rate,
417
+ upsample_scale=np.prod(upsample_rates) * istft_params["hop_len"],
418
+ harmonic_num=nb_harmonics,
419
+ sine_amp=nsf_alpha,
420
+ add_noise_std=nsf_sigma,
421
+ voiced_threshod=nsf_voiced_threshold,
422
+ sinegen_type='1' if self.sampling_rate == 22050 else '2',
423
+ causal=False)
424
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates) * istft_params["hop_len"])
425
+
426
+ self.conv_pre = weight_norm(
427
+ Conv1d(in_channels, base_channels, 7, 1, padding=3)
428
+ )
429
+
430
+ # Up
431
+ self.ups = nn.ModuleList()
432
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
433
+ self.ups.append(
434
+ weight_norm(
435
+ ConvTranspose1d(
436
+ base_channels // (2**i),
437
+ base_channels // (2**(i + 1)),
438
+ k,
439
+ u,
440
+ padding=(k - u) // 2,
441
+ )
442
+ )
443
+ )
444
+
445
+ # Down
446
+ self.source_downs = nn.ModuleList()
447
+ self.source_resblocks = nn.ModuleList()
448
+ downsample_rates = [1] + upsample_rates[::-1][:-1]
449
+ downsample_cum_rates = np.cumprod(downsample_rates)
450
+ for i, (u, k, d) in enumerate(zip(downsample_cum_rates[::-1], source_resblock_kernel_sizes, source_resblock_dilation_sizes)):
451
+ if u == 1:
452
+ self.source_downs.append(
453
+ Conv1d(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), 1, 1)
454
+ )
455
+ else:
456
+ self.source_downs.append(
457
+ Conv1d(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), u * 2, u, padding=(u // 2))
458
+ )
459
+
460
+ self.source_resblocks.append(
461
+ ResBlock(base_channels // (2 ** (i + 1)), k, d)
462
+ )
463
+
464
+ self.resblocks = nn.ModuleList()
465
+ for i in range(len(self.ups)):
466
+ ch = base_channels // (2**(i + 1))
467
+ for _, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
468
+ self.resblocks.append(ResBlock(ch, k, d))
469
+
470
+ self.conv_post = weight_norm(Conv1d(ch, istft_params["n_fft"] + 2, 7, 1, padding=3))
471
+ self.ups.apply(init_weights)
472
+ self.conv_post.apply(init_weights)
473
+ self.reflection_pad = nn.ReflectionPad1d((1, 0))
474
+ self.stft_window = torch.from_numpy(get_window("hann", istft_params["n_fft"], fftbins=True).astype(np.float32))
475
+ self.f0_predictor = f0_predictor
476
+
477
+ def remove_weight_norm(self):
478
+ print('Removing weight norm...')
479
+ for l in self.ups:
480
+ remove_weight_norm(l)
481
+ for l in self.resblocks:
482
+ l.remove_weight_norm()
483
+ remove_weight_norm(self.conv_pre)
484
+ remove_weight_norm(self.conv_post)
485
+ self.m_source.remove_weight_norm()
486
+ for l in self.source_downs:
487
+ remove_weight_norm(l)
488
+ for l in self.source_resblocks:
489
+ l.remove_weight_norm()
490
+
491
+ def _stft(self, x):
492
+ spec = torch.stft(
493
+ x,
494
+ self.istft_params["n_fft"], self.istft_params["hop_len"], self.istft_params["n_fft"], window=self.stft_window.to(x.device),
495
+ return_complex=True)
496
+ spec = torch.view_as_real(spec) # [B, F, TT, 2]
497
+ return spec[..., 0], spec[..., 1]
498
+
499
+ def _istft(self, magnitude, phase):
500
+ magnitude = torch.clip(magnitude, max=1e2)
501
+ real = magnitude * torch.cos(phase)
502
+ img = magnitude * torch.sin(phase)
503
+ inverse_transform = torch.istft(torch.complex(real, img), self.istft_params["n_fft"], self.istft_params["hop_len"],
504
+ self.istft_params["n_fft"], window=self.stft_window.to(magnitude.device))
505
+ return inverse_transform
506
+
507
+ def decode(self, x: torch.Tensor, s: torch.Tensor = torch.zeros(1, 1, 0)) -> torch.Tensor:
508
+ s_stft_real, s_stft_imag = self._stft(s.squeeze(1))
509
+ s_stft = torch.cat([s_stft_real, s_stft_imag], dim=1)
510
+
511
+ x = self.conv_pre(x)
512
+ for i in range(self.num_upsamples):
513
+ x = F.leaky_relu(x, self.lrelu_slope)
514
+ x = self.ups[i](x)
515
+
516
+ if i == self.num_upsamples - 1:
517
+ x = self.reflection_pad(x)
518
+
519
+ # fusion
520
+ si = self.source_downs[i](s_stft)
521
+ si = self.source_resblocks[i](si)
522
+ x = x + si
523
+
524
+ xs = None
525
+ for j in range(self.num_kernels):
526
+ if xs is None:
527
+ xs = self.resblocks[i * self.num_kernels + j](x)
528
+ else:
529
+ xs += self.resblocks[i * self.num_kernels + j](x)
530
+ x = xs / self.num_kernels
531
+
532
+ x = F.leaky_relu(x)
533
+ x = self.conv_post(x)
534
+ magnitude = torch.exp(x[:, :self.istft_params["n_fft"] // 2 + 1, :])
535
+ phase = torch.sin(x[:, self.istft_params["n_fft"] // 2 + 1:, :]) # actually, sin is redundancy
536
+
537
+ x = self._istft(magnitude, phase)
538
+ x = torch.clamp(x, -self.audio_limit, self.audio_limit)
539
+ return x
540
+
541
+ def forward(
542
+ self,
543
+ batch: dict,
544
+ device: torch.device,
545
+ ) -> Dict[str, Optional[torch.Tensor]]:
546
+ speech_feat = batch['speech_feat'].transpose(1, 2).to(device)
547
+ # mel->f0
548
+ f0 = self.f0_predictor(speech_feat)
549
+ # f0->source
550
+ s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
551
+ s, _, _ = self.m_source(s)
552
+ s = s.transpose(1, 2)
553
+ # mel+source->speech
554
+ generated_speech = self.decode(x=speech_feat, s=s)
555
+ return generated_speech, f0
556
+
557
+ @torch.inference_mode()
558
+ def inference(self, speech_feat: torch.Tensor, cache_source: torch.Tensor = torch.zeros(1, 1, 0)) -> torch.Tensor:
559
+ # mel->f0
560
+ f0 = self.f0_predictor(speech_feat)
561
+ # f0->source
562
+ s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
563
+ s, _, _ = self.m_source(s)
564
+ s = s.transpose(1, 2)
565
+ # use cache_source to avoid glitch
566
+ if cache_source.shape[2] != 0:
567
+ s[:, :, :cache_source.shape[2]] = cache_source
568
+ generated_speech = self.decode(x=speech_feat, s=s)
569
+ return generated_speech, s
570
+
571
+
572
+ class CausalHiFTGenerator(HiFTGenerator):
573
+ """
574
+ HiFTNet Generator: Neural Source Filter + ISTFTNet
575
+ https://arxiv.org/abs/2309.09493
576
+ """
577
+ def __init__(
578
+ self,
579
+ in_channels: int = 80,
580
+ base_channels: int = 512,
581
+ nb_harmonics: int = 8,
582
+ sampling_rate: int = 22050,
583
+ nsf_alpha: float = 0.1,
584
+ nsf_sigma: float = 0.003,
585
+ nsf_voiced_threshold: float = 10,
586
+ upsample_rates: List[int] = [8, 8],
587
+ upsample_kernel_sizes: List[int] = [16, 16],
588
+ istft_params: Dict[str, int] = {"n_fft": 16, "hop_len": 4},
589
+ resblock_kernel_sizes: List[int] = [3, 7, 11],
590
+ resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
591
+ source_resblock_kernel_sizes: List[int] = [7, 11],
592
+ source_resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5]],
593
+ lrelu_slope: float = 0.1,
594
+ audio_limit: float = 0.99,
595
+ conv_pre_look_right: int = 4,
596
+ f0_predictor: torch.nn.Module = None,
597
+ ):
598
+ torch.nn.Module.__init__(self)
599
+
600
+ self.out_channels = 1
601
+ self.nb_harmonics = nb_harmonics
602
+ self.sampling_rate = sampling_rate
603
+ self.istft_params = istft_params
604
+ self.lrelu_slope = lrelu_slope
605
+ self.audio_limit = audio_limit
606
+
607
+ self.num_kernels = len(resblock_kernel_sizes)
608
+ self.num_upsamples = len(upsample_rates)
609
+ self.m_source = SourceModuleHnNSF(
610
+ sampling_rate=sampling_rate,
611
+ upsample_scale=np.prod(upsample_rates) * istft_params["hop_len"],
612
+ harmonic_num=nb_harmonics,
613
+ sine_amp=nsf_alpha,
614
+ add_noise_std=nsf_sigma,
615
+ voiced_threshod=nsf_voiced_threshold,
616
+ sinegen_type='1' if self.sampling_rate == 22050 else '2',
617
+ causal=True)
618
+ self.upsample_rates = upsample_rates
619
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates) * istft_params["hop_len"])
620
+
621
+ self.conv_pre = weight_norm(
622
+ CausalConv1d(in_channels, base_channels, conv_pre_look_right + 1, 1, causal_type='right')
623
+ )
624
+
625
+ # Up
626
+ self.ups = nn.ModuleList()
627
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
628
+ self.ups.append(
629
+ weight_norm(
630
+ CausalConv1dUpsample(
631
+ base_channels // (2**i),
632
+ base_channels // (2**(i + 1)),
633
+ k,
634
+ u,
635
+ )
636
+ )
637
+ )
638
+
639
+ # Down
640
+ self.source_downs = nn.ModuleList()
641
+ self.source_resblocks = nn.ModuleList()
642
+ downsample_rates = [1] + upsample_rates[::-1][:-1]
643
+ downsample_cum_rates = np.cumprod(downsample_rates)
644
+ for i, (u, k, d) in enumerate(zip(downsample_cum_rates[::-1], source_resblock_kernel_sizes, source_resblock_dilation_sizes)):
645
+ if u == 1:
646
+ self.source_downs.append(
647
+ CausalConv1d(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), 1, 1, causal_type='left')
648
+ )
649
+ else:
650
+ self.source_downs.append(
651
+ CausalConv1dDownSample(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), u * 2, u)
652
+ )
653
+
654
+ self.source_resblocks.append(
655
+ ResBlock(base_channels // (2 ** (i + 1)), k, d, causal=True)
656
+ )
657
+
658
+ self.resblocks = nn.ModuleList()
659
+ for i in range(len(self.ups)):
660
+ ch = base_channels // (2**(i + 1))
661
+ for _, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
662
+ self.resblocks.append(ResBlock(ch, k, d, causal=True))
663
+
664
+ self.conv_post = weight_norm(CausalConv1d(ch, istft_params["n_fft"] + 2, 7, 1, causal_type='left'))
665
+ self.ups.apply(init_weights)
666
+ self.conv_post.apply(init_weights)
667
+ self.reflection_pad = nn.ReflectionPad1d((1, 0))
668
+ self.stft_window = torch.from_numpy(get_window("hann", istft_params["n_fft"], fftbins=True).astype(np.float32))
669
+ self.conv_pre_look_right = conv_pre_look_right
670
+ self.f0_predictor = f0_predictor
671
+
672
+ def decode(self, x: torch.Tensor, s: torch.Tensor = torch.zeros(1, 1, 0), finalize: bool = True) -> torch.Tensor:
673
+ s_stft_real, s_stft_imag = self._stft(s.squeeze(1))
674
+ if finalize is True:
675
+ x = self.conv_pre(x)
676
+ else:
677
+ x = self.conv_pre(x[:, :, :-self.conv_pre_look_right], x[:, :, -self.conv_pre_look_right:])
678
+ s_stft_real = s_stft_real[:, :, :-int(np.prod(self.upsample_rates) * self.conv_pre_look_right)]
679
+ s_stft_imag = s_stft_imag[:, :, :-int(np.prod(self.upsample_rates) * self.conv_pre_look_right)]
680
+ s_stft = torch.cat([s_stft_real, s_stft_imag], dim=1)
681
+
682
+ for i in range(self.num_upsamples):
683
+ x = F.leaky_relu(x, self.lrelu_slope)
684
+ x = self.ups[i](x)
685
+
686
+ if i == self.num_upsamples - 1:
687
+ x = self.reflection_pad(x)
688
+
689
+ # fusion
690
+ si = self.source_downs[i](s_stft)
691
+ si = self.source_resblocks[i](si)
692
+ x = x + si
693
+
694
+ xs = None
695
+ for j in range(self.num_kernels):
696
+ if xs is None:
697
+ xs = self.resblocks[i * self.num_kernels + j](x)
698
+ else:
699
+ xs += self.resblocks[i * self.num_kernels + j](x)
700
+ x = xs / self.num_kernels
701
+
702
+ x = F.leaky_relu(x)
703
+ x = self.conv_post(x)
704
+ magnitude = torch.exp(x[:, :self.istft_params["n_fft"] // 2 + 1, :])
705
+ phase = torch.sin(x[:, self.istft_params["n_fft"] // 2 + 1:, :]) # actually, sin is redundancy
706
+
707
+ x = self._istft(magnitude, phase)
708
+ if finalize is False:
709
+ x = x[:, :-int(np.prod(self.upsample_rates) * self.istft_params['hop_len'])]
710
+ x = torch.clamp(x, -self.audio_limit, self.audio_limit)
711
+ return x
712
+
713
+ @torch.inference_mode()
714
+ def inference(self, speech_feat: torch.Tensor, finalize: bool = True) -> torch.Tensor:
715
+ # mel->f0 NOTE f0_predictor precision is crucial for causal inference, move self.f0_predictor to cpu if necessary
716
+ self.f0_predictor.to(torch.float64)
717
+ f0 = self.f0_predictor(speech_feat.to(torch.float64), finalize=finalize).to(speech_feat)
718
+ # f0->source
719
+ s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
720
+ s, _, _ = self.m_source(s)
721
+ s = s.transpose(1, 2)
722
+ if finalize is True:
723
+ generated_speech = self.decode(x=speech_feat, s=s, finalize=finalize)
724
+ else:
725
+ generated_speech = self.decode(x=speech_feat[:, :, :-self.f0_predictor.condnet[0].causal_padding], s=s, finalize=finalize)
726
+ return generated_speech, s
727
+
728
+
729
+ if __name__ == '__main__':
730
+ torch.backends.cudnn.deterministic = True
731
+ torch.backends.cudnn.benchmark = False
732
+ from hyperpyyaml import load_hyperpyyaml
733
+ with open('./pretrained_models/Fun-CosyVoice3-0.5B/cosyvoice3.yaml', 'r') as f:
734
+ configs = load_hyperpyyaml(f, overrides={'llm': None, 'flow': None})
735
+ model = configs['hift']
736
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
737
+ model.to(device)
738
+ model.eval()
739
+ max_len, chunk_size, context_size = 300, 30, 8
740
+ mel = torch.rand(1, 80, max_len).to(device)
741
+ pred_gt, _ = model.inference(mel)
742
+ for i in range(0, max_len, chunk_size):
743
+ finalize = True if i + chunk_size + context_size >= max_len else False
744
+ pred_chunk, _ = model.inference(mel[:, :, : i + chunk_size + context_size], finalize=finalize)
745
+ pred_chunk = pred_chunk[:, i * 480:]
746
+ print((pred_gt[:, i * 480:i * 480 + pred_chunk.shape[1]] - pred_chunk).abs().max().item())
cosyvoice/hifigan/hifigan.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from matcha.hifigan.models import feature_loss, generator_loss, discriminator_loss
6
+ from cosyvoice.utils.losses import tpr_loss, mel_loss
7
+
8
+
9
+ class HiFiGan(nn.Module):
10
+ def __init__(self, generator, discriminator, mel_spec_transform,
11
+ multi_mel_spectral_recon_loss_weight=45, feat_match_loss_weight=2.0,
12
+ tpr_loss_weight=1.0, tpr_loss_tau=0.04):
13
+ super(HiFiGan, self).__init__()
14
+ self.generator = generator
15
+ self.discriminator = discriminator
16
+ self.mel_spec_transform = mel_spec_transform
17
+ self.multi_mel_spectral_recon_loss_weight = multi_mel_spectral_recon_loss_weight
18
+ self.feat_match_loss_weight = feat_match_loss_weight
19
+ self.tpr_loss_weight = tpr_loss_weight
20
+ self.tpr_loss_tau = tpr_loss_tau
21
+
22
+ def forward(
23
+ self,
24
+ batch: dict,
25
+ device: torch.device,
26
+ ) -> Dict[str, Optional[torch.Tensor]]:
27
+ if batch['turn'] == 'generator':
28
+ return self.forward_generator(batch, device)
29
+ else:
30
+ return self.forward_discriminator(batch, device)
31
+
32
+ def forward_generator(self, batch, device):
33
+ real_speech = batch['speech'].to(device)
34
+ pitch_feat = batch['pitch_feat'].to(device)
35
+ # 1. calculate generator outputs
36
+ generated_speech, generated_f0 = self.generator(batch, device)
37
+ # 2. calculate discriminator outputs
38
+ y_d_rs, y_d_gs, fmap_rs, fmap_gs = self.discriminator(real_speech, generated_speech)
39
+ # 3. calculate generator losses, feature loss, mel loss, tpr losses [Optional]
40
+ loss_gen, _ = generator_loss(y_d_gs)
41
+ loss_fm = feature_loss(fmap_rs, fmap_gs)
42
+ loss_mel = mel_loss(real_speech, generated_speech, self.mel_spec_transform)
43
+ if self.tpr_loss_weight != 0:
44
+ loss_tpr = tpr_loss(y_d_gs, y_d_rs, self.tpr_loss_tau)
45
+ else:
46
+ loss_tpr = torch.zeros(1).to(device)
47
+ loss_f0 = F.l1_loss(generated_f0, pitch_feat)
48
+ loss = loss_gen + self.feat_match_loss_weight * loss_fm + \
49
+ self.multi_mel_spectral_recon_loss_weight * loss_mel + \
50
+ self.tpr_loss_weight * loss_tpr + loss_f0
51
+ return {'loss': loss, 'loss_gen': loss_gen, 'loss_fm': loss_fm, 'loss_mel': loss_mel, 'loss_tpr': loss_tpr, 'loss_f0': loss_f0}
52
+
53
+ def forward_discriminator(self, batch, device):
54
+ real_speech = batch['speech'].to(device)
55
+ # 1. calculate generator outputs
56
+ with torch.no_grad():
57
+ generated_speech, generated_f0 = self.generator(batch, device)
58
+ # 2. calculate discriminator outputs
59
+ y_d_rs, y_d_gs, fmap_rs, fmap_gs = self.discriminator(real_speech, generated_speech.detach())
60
+ # 3. calculate discriminator losses, tpr losses [Optional]
61
+ loss_disc, _, _ = discriminator_loss(y_d_rs, y_d_gs)
62
+ if self.tpr_loss_weight != 0:
63
+ loss_tpr = tpr_loss(y_d_rs, y_d_gs, self.tpr_loss_tau)
64
+ else:
65
+ loss_tpr = torch.zeros(1).to(device)
66
+ loss = loss_disc + self.tpr_loss_weight * loss_tpr
67
+ return {'loss': loss, 'loss_disc': loss_disc, 'loss_tpr': loss_tpr}
cosyvoice/llm/__pycache__/llm.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
cosyvoice/tokenizer/__pycache__/tokenizer.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
cosyvoice/transformer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (161 Bytes). View file
 
cosyvoice/transformer/__pycache__/activation.cpython-310.pyc ADDED
Binary file (2.49 kB). View file
 
cosyvoice/transformer/__pycache__/convolution.cpython-310.pyc ADDED
Binary file (6.29 kB). View file
 
cosyvoice/transformer/__pycache__/positionwise_feed_forward.cpython-310.pyc ADDED
Binary file (3.8 kB). View file
 
cosyvoice/transformer/__pycache__/upsample_encoder.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
cosyvoice/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (155 Bytes). View file
 
cosyvoice/utils/__pycache__/class_utils.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
cosyvoice/utils/__pycache__/file_utils.cpython-310.pyc ADDED
Binary file (3.66 kB). View file
 
cosyvoice/utils/__pycache__/frontend_utils.cpython-310.pyc ADDED
Binary file (3.05 kB). View file
 
cosyvoice/utils/__pycache__/onnx.cpython-310.pyc ADDED
Binary file (2.49 kB). View file
 
cosyvoice/utils/common.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
2
+ # 2024 Alibaba Inc (authors: Xiang Lyu)
3
+ # 2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # Modified from ESPnet(https://github.com/espnet/espnet)
17
+ """Unility functions for Transformer."""
18
+
19
+ import queue
20
+ import random
21
+ from typing import List
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+ IGNORE_ID = -1
27
+
28
+ instruct_list = ["You are a helpful assistant. 请用广东话表达。<|endofprompt|>",
29
+ "You are a helpful assistant. 请用东北话表达。<|endofprompt|>",
30
+ "You are a helpful assistant. 请用甘肃话表达。<|endofprompt|>",
31
+ "You are a helpful assistant. 请用贵州话表达。<|endofprompt|>",
32
+ "You are a helpful assistant. 请用河南话表达。<|endofprompt|>",
33
+ "You are a helpful assistant. 请用湖北话表达。<|endofprompt|>",
34
+ "You are a helpful assistant. 请用湖南话表达。<|endofprompt|>",
35
+ "You are a helpful assistant. 请用江西话表达。<|endofprompt|>",
36
+ "You are a helpful assistant. 请用闽南话表达。<|endofprompt|>",
37
+ "You are a helpful assistant. 请用宁夏话表达。<|endofprompt|>",
38
+ "You are a helpful assistant. 请用山西话表达。<|endofprompt|>",
39
+ "You are a helpful assistant. 请用陕西话表达。<|endofprompt|>",
40
+ "You are a helpful assistant. 请用山东话表达。<|endofprompt|>",
41
+ "You are a helpful assistant. 请用上海话表达。<|endofprompt|>",
42
+ "You are a helpful assistant. 请用四川话表达。<|endofprompt|>",
43
+ "You are a helpful assistant. 请用天津话表达。<|endofprompt|>",
44
+ "You are a helpful assistant. 请用云南话表达。<|endofprompt|>",
45
+ "You are a helpful assistant. Please say a sentence as loudly as possible.<|endofprompt|>",
46
+ "You are a helpful assistant. Please say a sentence in a very soft voice.<|endofprompt|>",
47
+ "You are a helpful assistant. 请用尽可能慢地语速说一句话。<|endofprompt|>",
48
+ "You are a helpful assistant. 请用尽可能快地语速说一句话。<|endofprompt|>",
49
+ "You are a helpful assistant. 请非常开心地说一句话。<|endofprompt|>",
50
+ "You are a helpful assistant. 请非常伤心地说一句话。<|endofprompt|>",
51
+ "You are a helpful assistant. 请非常生气地说一句话。<|endofprompt|>",
52
+ "You are a helpful assistant. 我想体验一下小猪佩奇风格,可以吗?<|endofprompt|>",
53
+ "You are a helpful assistant. 你可以尝试用机器人的方式解答吗?<|endofprompt|>"]
54
+
55
+
56
+ def pad_list(xs: List[torch.Tensor], pad_value: int):
57
+ """Perform padding for the list of tensors.
58
+
59
+ Args:
60
+ xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)].
61
+ pad_value (float): Value for padding.
62
+
63
+ Returns:
64
+ Tensor: Padded tensor (B, Tmax, `*`).
65
+
66
+ Examples:
67
+ >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)]
68
+ >>> x
69
+ [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])]
70
+ >>> pad_list(x, 0)
71
+ tensor([[1., 1., 1., 1.],
72
+ [1., 1., 0., 0.],
73
+ [1., 0., 0., 0.]])
74
+
75
+ """
76
+ max_len = max([len(item) for item in xs])
77
+ batchs = len(xs)
78
+ ndim = xs[0].ndim
79
+ if ndim == 1:
80
+ pad_res = torch.zeros(batchs,
81
+ max_len,
82
+ dtype=xs[0].dtype,
83
+ device=xs[0].device)
84
+ elif ndim == 2:
85
+ pad_res = torch.zeros(batchs,
86
+ max_len,
87
+ xs[0].shape[1],
88
+ dtype=xs[0].dtype,
89
+ device=xs[0].device)
90
+ elif ndim == 3:
91
+ pad_res = torch.zeros(batchs,
92
+ max_len,
93
+ xs[0].shape[1],
94
+ xs[0].shape[2],
95
+ dtype=xs[0].dtype,
96
+ device=xs[0].device)
97
+ else:
98
+ raise ValueError(f"Unsupported ndim: {ndim}")
99
+ pad_res.fill_(pad_value)
100
+ for i in range(batchs):
101
+ pad_res[i, :len(xs[i])] = xs[i]
102
+ return pad_res
103
+
104
+
105
+ def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor,
106
+ ignore_label: int) -> torch.Tensor:
107
+ """Calculate accuracy.
108
+
109
+ Args:
110
+ pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
111
+ pad_targets (LongTensor): Target label tensors (B, Lmax).
112
+ ignore_label (int): Ignore label id.
113
+
114
+ Returns:
115
+ torch.Tensor: Accuracy value (0.0 - 1.0).
116
+
117
+ """
118
+ pad_pred = pad_outputs.view(pad_targets.size(0), pad_targets.size(1),
119
+ pad_outputs.size(1)).argmax(2)
120
+ mask = pad_targets != ignore_label
121
+ numerator = torch.sum(
122
+ pad_pred.masked_select(mask) == pad_targets.masked_select(mask))
123
+ denominator = torch.sum(mask)
124
+ return (numerator / denominator).detach()
125
+
126
+
127
+ def get_padding(kernel_size, dilation=1):
128
+ return int((kernel_size * dilation - dilation) / 2)
129
+
130
+
131
+ def init_weights(m, mean=0.0, std=0.01):
132
+ classname = m.__class__.__name__
133
+ if classname.find("Conv") != -1:
134
+ m.weight.data.normal_(mean, std)
135
+
136
+
137
+ # Repetition Aware Sampling in VALL-E 2
138
+ def ras_sampling(weighted_scores, decoded_tokens, sampling, top_p=0.8, top_k=25, win_size=10, tau_r=0.1):
139
+ top_ids = nucleus_sampling(weighted_scores, top_p=top_p, top_k=top_k)
140
+ rep_num = (torch.tensor(decoded_tokens[-win_size:]).to(weighted_scores.device) == top_ids).sum().item()
141
+ if rep_num >= win_size * tau_r:
142
+ weighted_scores[top_ids] = -float('inf')
143
+ top_ids = random_sampling(weighted_scores, decoded_tokens, sampling)
144
+ return top_ids
145
+
146
+
147
+ def nucleus_sampling(weighted_scores, top_p=0.8, top_k=25):
148
+ prob, indices = [], []
149
+ cum_prob = 0.0
150
+ sorted_value, sorted_idx = weighted_scores.softmax(dim=0).sort(descending=True, stable=True)
151
+ for i in range(len(sorted_idx)):
152
+ # sampling both top-p and numbers.
153
+ if cum_prob < top_p and len(prob) < top_k:
154
+ cum_prob += sorted_value[i]
155
+ prob.append(sorted_value[i])
156
+ indices.append(sorted_idx[i])
157
+ else:
158
+ break
159
+ prob = torch.tensor(prob).to(weighted_scores)
160
+ indices = torch.tensor(indices, dtype=torch.long).to(weighted_scores.device)
161
+ top_ids = indices[prob.multinomial(1, replacement=True)].item()
162
+ return top_ids
163
+
164
+
165
+ def random_sampling(weighted_scores, decoded_tokens, sampling):
166
+ top_ids = weighted_scores.softmax(dim=0).multinomial(1, replacement=True).item()
167
+ return top_ids
168
+
169
+
170
+ def fade_in_out(fade_in_mel, fade_out_mel, window):
171
+ device = fade_in_mel.device
172
+ fade_in_mel, fade_out_mel = fade_in_mel.cpu(), fade_out_mel.cpu()
173
+ mel_overlap_len = int(window.shape[0] / 2)
174
+ if fade_in_mel.device == torch.device('cpu'):
175
+ fade_in_mel = fade_in_mel.clone()
176
+ fade_in_mel[..., :mel_overlap_len] = fade_in_mel[..., :mel_overlap_len] * window[:mel_overlap_len] + \
177
+ fade_out_mel[..., -mel_overlap_len:] * window[mel_overlap_len:]
178
+ return fade_in_mel.to(device)
179
+
180
+
181
+ def set_all_random_seed(seed):
182
+ random.seed(seed)
183
+ np.random.seed(seed)
184
+ torch.manual_seed(seed)
185
+ torch.cuda.manual_seed_all(seed)
186
+
187
+
188
+ def mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
189
+ assert mask.dtype == torch.bool
190
+ assert dtype in [torch.float32, torch.bfloat16, torch.float16]
191
+ mask = mask.to(dtype)
192
+ # attention mask bias
193
+ # NOTE(Mddct): torch.finfo jit issues
194
+ # chunk_masks = (1.0 - chunk_masks) * torch.finfo(dtype).min
195
+ mask = (1.0 - mask) * -1.0e+10
196
+ return mask
197
+
198
+
199
+ class TrtContextWrapper:
200
+ def __init__(self, trt_engine, trt_concurrent=1, device='cuda:0'):
201
+ self.trt_context_pool = queue.Queue(maxsize=trt_concurrent)
202
+ self.trt_engine = trt_engine
203
+ for _ in range(trt_concurrent):
204
+ trt_context = trt_engine.create_execution_context()
205
+ trt_stream = torch.cuda.stream(torch.cuda.Stream(device))
206
+ assert trt_context is not None, 'failed to create trt context, maybe not enough CUDA memory, try reduce current trt concurrent {}'.format(trt_concurrent)
207
+ self.trt_context_pool.put([trt_context, trt_stream])
208
+ assert self.trt_context_pool.empty() is False, 'no avaialbe estimator context'
209
+
210
+ def acquire_estimator(self):
211
+ return self.trt_context_pool.get(), self.trt_engine
212
+
213
+ def release_estimator(self, context, stream):
214
+ self.trt_context_pool.put([context, stream])
cosyvoice/utils/executor.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
2
+ # 2024 Alibaba Inc (authors: Xiang Lyu)
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ from contextlib import nullcontext
18
+ import os
19
+
20
+ import torch
21
+ import torch.distributed as dist
22
+
23
+ from cosyvoice.utils.train_utils import update_parameter_and_lr, log_per_step, log_per_save, batch_forward, batch_backward, save_model, cosyvoice_join
24
+
25
+
26
+ class Executor:
27
+
28
+ def __init__(self, gan: bool = False, ref_model: torch.nn.Module = None, dpo_loss: torch.nn.Module = None):
29
+ self.gan = gan
30
+ self.ref_model = ref_model
31
+ self.dpo_loss = dpo_loss
32
+ self.step = 0
33
+ self.epoch = 0
34
+ self.rank = int(os.environ.get('RANK', 0))
35
+ self.device = torch.device('cuda:{}'.format(self.rank))
36
+
37
+ def train_one_epoc(self, model, optimizer, scheduler, train_data_loader, cv_data_loader, writer, info_dict, scaler, group_join, ref_model=None):
38
+ ''' Train one epoch
39
+ '''
40
+
41
+ lr = optimizer.param_groups[0]['lr']
42
+ logging.info('Epoch {} TRAIN info lr {} rank {}'.format(self.epoch, lr, self.rank))
43
+ logging.info('using accumulate grad, new batch size is {} times'
44
+ ' larger than before'.format(info_dict['accum_grad']))
45
+ # A context manager to be used in conjunction with an instance of
46
+ # torch.nn.parallel.DistributedDataParallel to be able to train
47
+ # with uneven inputs across participating processes.
48
+ model.train()
49
+ if self.ref_model is not None:
50
+ self.ref_model.eval()
51
+ model_context = model.join if info_dict['train_engine'] == 'torch_ddp' else nullcontext
52
+ with model_context():
53
+ for batch_idx, batch_dict in enumerate(train_data_loader):
54
+ info_dict["tag"] = "TRAIN"
55
+ info_dict["step"] = self.step
56
+ info_dict["epoch"] = self.epoch
57
+ info_dict["batch_idx"] = batch_idx
58
+ if cosyvoice_join(group_join, info_dict):
59
+ break
60
+
61
+ # Disable gradient synchronizations across DDP processes.
62
+ # Within this context, gradients will be accumulated on module
63
+ # variables, which will later be synchronized.
64
+ if info_dict['train_engine'] == 'torch_ddp' and (batch_idx + 1) % info_dict["accum_grad"] != 0:
65
+ context = model.no_sync
66
+ # Used for single gpu training and DDP gradient synchronization
67
+ # processes.
68
+ else:
69
+ context = nullcontext
70
+
71
+ with context():
72
+ info_dict = batch_forward(model, batch_dict, scaler, info_dict, ref_model=self.ref_model, dpo_loss=self.dpo_loss)
73
+ info_dict = batch_backward(model, scaler, info_dict)
74
+
75
+ info_dict = update_parameter_and_lr(model, optimizer, scheduler, scaler, info_dict)
76
+ log_per_step(writer, info_dict)
77
+ # NOTE specify save_per_step in cosyvoice.yaml if you want to enable step save
78
+ if info_dict['save_per_step'] > 0 and (self.step + 1) % info_dict['save_per_step'] == 0 and \
79
+ (batch_idx + 1) % info_dict["accum_grad"] == 0:
80
+ dist.barrier()
81
+ self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=False)
82
+ model.train()
83
+ if (batch_idx + 1) % info_dict["accum_grad"] == 0:
84
+ self.step += 1
85
+ dist.barrier()
86
+ self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=True)
87
+
88
+ def train_one_epoc_gan(self, model, optimizer, scheduler, optimizer_d, scheduler_d, train_data_loader, cv_data_loader,
89
+ writer, info_dict, scaler, group_join):
90
+ ''' Train one epoch
91
+ '''
92
+
93
+ lr = optimizer.param_groups[0]['lr']
94
+ logging.info('Epoch {} TRAIN info lr {} rank {}'.format(self.epoch, lr, self.rank))
95
+ logging.info('using accumulate grad, new batch size is {} times'
96
+ ' larger than before'.format(info_dict['accum_grad']))
97
+ # A context manager to be used in conjunction with an instance of
98
+ # torch.nn.parallel.DistributedDataParallel to be able to train
99
+ # with uneven inputs across participating processes.
100
+ model.train()
101
+ model_context = model.join if info_dict['train_engine'] == 'torch_ddp' else nullcontext
102
+ with model_context():
103
+ for batch_idx, batch_dict in enumerate(train_data_loader):
104
+ info_dict["tag"] = "TRAIN"
105
+ info_dict["step"] = self.step
106
+ info_dict["epoch"] = self.epoch
107
+ info_dict["batch_idx"] = batch_idx
108
+ if cosyvoice_join(group_join, info_dict):
109
+ break
110
+
111
+ # Disable gradient synchronizations across DDP processes.
112
+ # Within this context, gradients will be accumulated on module
113
+ # variables, which will later be synchronized.
114
+ if info_dict['train_engine'] == 'torch_ddp' and (batch_idx + 1) % info_dict["accum_grad"] != 0:
115
+ context = model.no_sync
116
+ # Used for single gpu training and DDP gradient synchronization
117
+ # processes.
118
+ else:
119
+ context = nullcontext
120
+
121
+ with context():
122
+ batch_dict['turn'] = 'discriminator'
123
+ info_dict = batch_forward(model, batch_dict, scaler, info_dict)
124
+ info_dict = batch_backward(model, scaler, info_dict)
125
+ info_dict = update_parameter_and_lr(model, optimizer_d, scheduler_d, scaler, info_dict)
126
+ optimizer.zero_grad()
127
+ log_per_step(writer, info_dict)
128
+ with context():
129
+ batch_dict['turn'] = 'generator'
130
+ info_dict = batch_forward(model, batch_dict, scaler, info_dict)
131
+ info_dict = batch_backward(model, scaler, info_dict)
132
+ info_dict = update_parameter_and_lr(model, optimizer, scheduler, scaler, info_dict)
133
+ optimizer_d.zero_grad()
134
+ log_per_step(writer, info_dict)
135
+ # NOTE specify save_per_step in cosyvoice.yaml if you want to enable step save
136
+ if info_dict['save_per_step'] > 0 and (self.step + 1) % info_dict['save_per_step'] == 0 and \
137
+ (batch_idx + 1) % info_dict["accum_grad"] == 0:
138
+ dist.barrier()
139
+ self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=False)
140
+ model.train()
141
+ if (batch_idx + 1) % info_dict["accum_grad"] == 0:
142
+ self.step += 1
143
+ dist.barrier()
144
+ self.cv(model, cv_data_loader, writer, info_dict, on_batch_end=True)
145
+
146
+ @torch.inference_mode()
147
+ def cv(self, model, cv_data_loader, writer, info_dict, on_batch_end=True):
148
+ ''' Cross validation on
149
+ '''
150
+ logging.info('Epoch {} Step {} on_batch_end {} CV rank {}'.format(self.epoch, self.step + 1, on_batch_end, self.rank))
151
+ model.eval()
152
+ total_num_utts, total_loss_dict = 0, {} # avoid division by 0
153
+ for batch_idx, batch_dict in enumerate(cv_data_loader):
154
+ info_dict["tag"] = "CV"
155
+ info_dict["step"] = self.step
156
+ info_dict["epoch"] = self.epoch
157
+ info_dict["batch_idx"] = batch_idx
158
+
159
+ num_utts = len(batch_dict["utts"])
160
+ total_num_utts += num_utts
161
+
162
+ if self.gan is True:
163
+ batch_dict['turn'] = 'generator'
164
+ info_dict = batch_forward(model, batch_dict, None, info_dict)
165
+
166
+ for k, v in info_dict['loss_dict'].items():
167
+ if k not in total_loss_dict:
168
+ total_loss_dict[k] = []
169
+ total_loss_dict[k].append(v.mean().item() * num_utts)
170
+ log_per_step(None, info_dict)
171
+ for k, v in total_loss_dict.items():
172
+ total_loss_dict[k] = sum(v) / total_num_utts
173
+ info_dict['loss_dict'] = total_loss_dict
174
+ log_per_save(writer, info_dict)
175
+ model_name = 'epoch_{}_whole'.format(self.epoch) if on_batch_end else 'epoch_{}_step_{}'.format(self.epoch, self.step + 1)
176
+ save_model(model, model_name, info_dict)
cosyvoice/utils/file_utils.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang)
2
+ # 2024 Alibaba Inc (authors: Xiang Lyu, Zetao Hu)
3
+ # 2025 Alibaba Inc (authors: Xiang Lyu, Yabin Li)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import json
19
+ import torch
20
+ import torchaudio
21
+ import logging
22
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
23
+ logging.basicConfig(level=logging.DEBUG,
24
+ format='%(asctime)s %(levelname)s %(message)s')
25
+
26
+
27
+ def read_lists(list_file):
28
+ lists = []
29
+ with open(list_file, 'r', encoding='utf8') as fin:
30
+ for line in fin:
31
+ lists.append(line.strip())
32
+ return lists
33
+
34
+
35
+ def read_json_lists(list_file):
36
+ lists = read_lists(list_file)
37
+ results = {}
38
+ for fn in lists:
39
+ with open(fn, 'r', encoding='utf8') as fin:
40
+ results.update(json.load(fin))
41
+ return results
42
+
43
+
44
+ def load_wav(wav, target_sr, min_sr=16000):
45
+ speech, sample_rate = torchaudio.load(wav, backend='soundfile')
46
+ speech = speech.mean(dim=0, keepdim=True)
47
+ if sample_rate != target_sr:
48
+ assert sample_rate >= min_sr, 'wav sample rate {} must be greater than {}'.format(sample_rate, target_sr)
49
+ speech = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=target_sr)(speech)
50
+ return speech
51
+
52
+
53
+ def convert_onnx_to_trt(trt_model, trt_kwargs, onnx_model, fp16):
54
+ import tensorrt as trt
55
+ logging.info("Converting onnx to trt...")
56
+ network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
57
+ logger = trt.Logger(trt.Logger.INFO)
58
+ builder = trt.Builder(logger)
59
+ network = builder.create_network(network_flags)
60
+ parser = trt.OnnxParser(network, logger)
61
+ config = builder.create_builder_config()
62
+ config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 32) # 4GB
63
+ if fp16:
64
+ config.set_flag(trt.BuilderFlag.FP16)
65
+ profile = builder.create_optimization_profile()
66
+ # load onnx model
67
+ with open(onnx_model, "rb") as f:
68
+ if not parser.parse(f.read()):
69
+ for error in range(parser.num_errors):
70
+ print(parser.get_error(error))
71
+ raise ValueError('failed to parse {}'.format(onnx_model))
72
+ # set input shapes
73
+ for i in range(len(trt_kwargs['input_names'])):
74
+ profile.set_shape(trt_kwargs['input_names'][i], trt_kwargs['min_shape'][i], trt_kwargs['opt_shape'][i], trt_kwargs['max_shape'][i])
75
+ tensor_dtype = trt.DataType.HALF if fp16 else trt.DataType.FLOAT
76
+ # set input and output data type
77
+ for i in range(network.num_inputs):
78
+ input_tensor = network.get_input(i)
79
+ input_tensor.dtype = tensor_dtype
80
+ for i in range(network.num_outputs):
81
+ output_tensor = network.get_output(i)
82
+ output_tensor.dtype = tensor_dtype
83
+ config.add_optimization_profile(profile)
84
+ engine_bytes = builder.build_serialized_network(network, config)
85
+ # save trt engine
86
+ with open(trt_model, "wb") as f:
87
+ f.write(engine_bytes)
88
+ logging.info("Succesfully convert onnx to trt...")
89
+
90
+
91
+ # NOTE do not support bistream inference as only speech token embedding/head is kept
92
+ def export_cosyvoice2_vllm(model, model_path, device):
93
+ if os.path.exists(model_path):
94
+ return
95
+
96
+ dtype = torch.bfloat16
97
+ # lm_head
98
+ use_bias = True if model.llm_decoder.bias is not None else False
99
+ model.llm.model.lm_head = model.llm_decoder
100
+ # embed_tokens
101
+ embed_tokens = model.llm.model.model.embed_tokens
102
+ model.llm.model.set_input_embeddings(model.speech_embedding)
103
+ model.llm.model.to(device)
104
+ model.llm.model.to(dtype)
105
+ tmp_vocab_size = model.llm.model.config.vocab_size
106
+ tmp_tie_embedding = model.llm.model.config.tie_word_embeddings
107
+ del model.llm.model.generation_config.eos_token_id
108
+ del model.llm.model.config.bos_token_id
109
+ del model.llm.model.config.eos_token_id
110
+ model.llm.model.config.vocab_size = model.speech_embedding.num_embeddings
111
+ model.llm.model.config.tie_word_embeddings = False
112
+ model.llm.model.config.use_bias = use_bias
113
+ model.llm.model.save_pretrained(model_path)
114
+ if use_bias is True:
115
+ os.system('sed -i s@Qwen2ForCausalLM@CosyVoice2ForCausalLM@g {}/config.json'.format(os.path.abspath(model_path)))
116
+ model.llm.model.config.vocab_size = tmp_vocab_size
117
+ model.llm.model.config.tie_word_embeddings = tmp_tie_embedding
118
+ model.llm.model.set_input_embeddings(embed_tokens)
cosyvoice/utils/frontend_utils.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ import regex
17
+ chinese_char_pattern = re.compile(r'[\u4e00-\u9fff]+')
18
+
19
+
20
+ # whether contain chinese character
21
+ def contains_chinese(text):
22
+ return bool(chinese_char_pattern.search(text))
23
+
24
+
25
+ # replace special symbol
26
+ def replace_corner_mark(text):
27
+ text = text.replace('²', '平方')
28
+ text = text.replace('³', '立方')
29
+ return text
30
+
31
+
32
+ # remove meaningless symbol
33
+ def remove_bracket(text):
34
+ text = text.replace('(', '').replace(')', '')
35
+ text = text.replace('【', '').replace('】', '')
36
+ text = text.replace('`', '').replace('`', '')
37
+ text = text.replace("——", " ")
38
+ return text
39
+
40
+
41
+ # spell Arabic numerals
42
+ def spell_out_number(text: str, inflect_parser):
43
+ new_text = []
44
+ st = None
45
+ for i, c in enumerate(text):
46
+ if not c.isdigit():
47
+ if st is not None:
48
+ num_str = inflect_parser.number_to_words(text[st: i])
49
+ new_text.append(num_str)
50
+ st = None
51
+ new_text.append(c)
52
+ else:
53
+ if st is None:
54
+ st = i
55
+ if st is not None and st < len(text):
56
+ num_str = inflect_parser.number_to_words(text[st:])
57
+ new_text.append(num_str)
58
+ return ''.join(new_text)
59
+
60
+
61
+ # split paragrah logic:
62
+ # 1. per sentence max len token_max_n, min len token_min_n, merge if last sentence len less than merge_len
63
+ # 2. cal sentence len according to lang
64
+ # 3. split sentence according to puncatation
65
+ def split_paragraph(text: str, tokenize, lang="zh", token_max_n=80, token_min_n=60, merge_len=20, comma_split=False):
66
+ def calc_utt_length(_text: str):
67
+ if lang == "zh":
68
+ return len(_text)
69
+ else:
70
+ return len(tokenize(_text))
71
+
72
+ def should_merge(_text: str):
73
+ if lang == "zh":
74
+ return len(_text) < merge_len
75
+ else:
76
+ return len(tokenize(_text)) < merge_len
77
+
78
+ if lang == "zh":
79
+ pounc = ['。', '?', '!', ';', ':', '、', '.', '?', '!', ';']
80
+ else:
81
+ pounc = ['.', '?', '!', ';', ':']
82
+ if comma_split:
83
+ pounc.extend([',', ','])
84
+
85
+ if text[-1] not in pounc:
86
+ if lang == "zh":
87
+ text += "。"
88
+ else:
89
+ text += "."
90
+
91
+ st = 0
92
+ utts = []
93
+ for i, c in enumerate(text):
94
+ if c in pounc:
95
+ if len(text[st: i]) > 0:
96
+ utts.append(text[st: i] + c)
97
+ if i + 1 < len(text) and text[i + 1] in ['"', '”']:
98
+ tmp = utts.pop(-1)
99
+ utts.append(tmp + text[i + 1])
100
+ st = i + 2
101
+ else:
102
+ st = i + 1
103
+
104
+ final_utts = []
105
+ cur_utt = ""
106
+ for utt in utts:
107
+ if calc_utt_length(cur_utt + utt) > token_max_n and calc_utt_length(cur_utt) > token_min_n:
108
+ final_utts.append(cur_utt)
109
+ cur_utt = ""
110
+ cur_utt = cur_utt + utt
111
+ if len(cur_utt) > 0:
112
+ if should_merge(cur_utt) and len(final_utts) != 0:
113
+ final_utts[-1] = final_utts[-1] + cur_utt
114
+ else:
115
+ final_utts.append(cur_utt)
116
+
117
+ return final_utts
118
+
119
+
120
+ # remove blank between chinese character
121
+ def replace_blank(text: str):
122
+ out_str = []
123
+ for i, c in enumerate(text):
124
+ if c == " ":
125
+ if ((text[i + 1].isascii() and text[i + 1] != " ") and
126
+ (text[i - 1].isascii() and text[i - 1] != " ")):
127
+ out_str.append(c)
128
+ else:
129
+ out_str.append(c)
130
+ return "".join(out_str)
131
+
132
+
133
+ def is_only_punctuation(text):
134
+ # Regular expression: Match strings that consist only of punctuation marks or are empty.
135
+ punctuation_pattern = r'^[\p{P}\p{S}]*$'
136
+ return bool(regex.fullmatch(punctuation_pattern, text))
cosyvoice/utils/mask.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2019 Shigeki Karita
2
+ # 2020 Mobvoi Inc (Binbin Zhang)
3
+ # 2024 Alibaba Inc (authors: Xiang Lyu)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import torch
18
+ '''
19
+ def subsequent_mask(
20
+ size: int,
21
+ device: torch.device = torch.device("cpu"),
22
+ ) -> torch.Tensor:
23
+ """Create mask for subsequent steps (size, size).
24
+
25
+ This mask is used only in decoder which works in an auto-regressive mode.
26
+ This means the current step could only do attention with its left steps.
27
+
28
+ In encoder, fully attention is used when streaming is not necessary and
29
+ the sequence is not long. In this case, no attention mask is needed.
30
+
31
+ When streaming is need, chunk-based attention is used in encoder. See
32
+ subsequent_chunk_mask for the chunk-based attention mask.
33
+
34
+ Args:
35
+ size (int): size of mask
36
+ str device (str): "cpu" or "cuda" or torch.Tensor.device
37
+ dtype (torch.device): result dtype
38
+
39
+ Returns:
40
+ torch.Tensor: mask
41
+
42
+ Examples:
43
+ >>> subsequent_mask(3)
44
+ [[1, 0, 0],
45
+ [1, 1, 0],
46
+ [1, 1, 1]]
47
+ """
48
+ ret = torch.ones(size, size, device=device, dtype=torch.bool)
49
+ return torch.tril(ret)
50
+ '''
51
+
52
+
53
+ def subsequent_mask(
54
+ size: int,
55
+ device: torch.device = torch.device("cpu"),
56
+ ) -> torch.Tensor:
57
+ """Create mask for subsequent steps (size, size).
58
+
59
+ This mask is used only in decoder which works in an auto-regressive mode.
60
+ This means the current step could only do attention with its left steps.
61
+
62
+ In encoder, fully attention is used when streaming is not necessary and
63
+ the sequence is not long. In this case, no attention mask is needed.
64
+
65
+ When streaming is need, chunk-based attention is used in encoder. See
66
+ subsequent_chunk_mask for the chunk-based attention mask.
67
+
68
+ Args:
69
+ size (int): size of mask
70
+ str device (str): "cpu" or "cuda" or torch.Tensor.device
71
+ dtype (torch.device): result dtype
72
+
73
+ Returns:
74
+ torch.Tensor: mask
75
+
76
+ Examples:
77
+ >>> subsequent_mask(3)
78
+ [[1, 0, 0],
79
+ [1, 1, 0],
80
+ [1, 1, 1]]
81
+ """
82
+ arange = torch.arange(size, device=device)
83
+ mask = arange.expand(size, size)
84
+ arange = arange.unsqueeze(-1)
85
+ mask = mask <= arange
86
+ return mask
87
+
88
+
89
+ def subsequent_chunk_mask_deprecated(
90
+ size: int,
91
+ chunk_size: int,
92
+ num_left_chunks: int = -1,
93
+ device: torch.device = torch.device("cpu"),
94
+ ) -> torch.Tensor:
95
+ """Create mask for subsequent steps (size, size) with chunk size,
96
+ this is for streaming encoder
97
+
98
+ Args:
99
+ size (int): size of mask
100
+ chunk_size (int): size of chunk
101
+ num_left_chunks (int): number of left chunks
102
+ <0: use full chunk
103
+ >=0: use num_left_chunks
104
+ device (torch.device): "cpu" or "cuda" or torch.Tensor.device
105
+
106
+ Returns:
107
+ torch.Tensor: mask
108
+
109
+ Examples:
110
+ >>> subsequent_chunk_mask(4, 2)
111
+ [[1, 1, 0, 0],
112
+ [1, 1, 0, 0],
113
+ [1, 1, 1, 1],
114
+ [1, 1, 1, 1]]
115
+ """
116
+ ret = torch.zeros(size, size, device=device, dtype=torch.bool)
117
+ for i in range(size):
118
+ if num_left_chunks < 0:
119
+ start = 0
120
+ else:
121
+ start = max((i // chunk_size - num_left_chunks) * chunk_size, 0)
122
+ ending = min((i // chunk_size + 1) * chunk_size, size)
123
+ ret[i, start:ending] = True
124
+ return ret
125
+
126
+
127
+ def subsequent_chunk_mask(
128
+ size: int,
129
+ chunk_size: int,
130
+ num_left_chunks: int = -1,
131
+ device: torch.device = torch.device("cpu"),
132
+ ) -> torch.Tensor:
133
+ """Create mask for subsequent steps (size, size) with chunk size,
134
+ this is for streaming encoder
135
+
136
+ Args:
137
+ size (int): size of mask
138
+ chunk_size (int): size of chunk
139
+ num_left_chunks (int): number of left chunks
140
+ <0: use full chunk
141
+ >=0: use num_left_chunks
142
+ device (torch.device): "cpu" or "cuda" or torch.Tensor.device
143
+
144
+ Returns:
145
+ torch.Tensor: mask
146
+
147
+ Examples:
148
+ >>> subsequent_chunk_mask(4, 2)
149
+ [[1, 1, 0, 0],
150
+ [1, 1, 0, 0],
151
+ [1, 1, 1, 1],
152
+ [1, 1, 1, 1]]
153
+ """
154
+ # NOTE this modified implementation meets onnx export requirements, but it doesn't support num_left_chunks
155
+ pos_idx = torch.arange(size, device=device)
156
+ block_value = (torch.div(pos_idx, chunk_size, rounding_mode='trunc') + 1) * chunk_size
157
+ ret = pos_idx.unsqueeze(0) < block_value.unsqueeze(1)
158
+ return ret
159
+
160
+
161
+ def add_optional_chunk_mask(xs: torch.Tensor,
162
+ masks: torch.Tensor,
163
+ use_dynamic_chunk: bool,
164
+ use_dynamic_left_chunk: bool,
165
+ decoding_chunk_size: int,
166
+ static_chunk_size: int,
167
+ num_decoding_left_chunks: int,
168
+ enable_full_context: bool = True):
169
+ """ Apply optional mask for encoder.
170
+
171
+ Args:
172
+ xs (torch.Tensor): padded input, (B, L, D), L for max length
173
+ mask (torch.Tensor): mask for xs, (B, 1, L)
174
+ use_dynamic_chunk (bool): whether to use dynamic chunk or not
175
+ use_dynamic_left_chunk (bool): whether to use dynamic left chunk for
176
+ training.
177
+ decoding_chunk_size (int): decoding chunk size for dynamic chunk, it's
178
+ 0: default for training, use random dynamic chunk.
179
+ <0: for decoding, use full chunk.
180
+ >0: for decoding, use fixed chunk size as set.
181
+ static_chunk_size (int): chunk size for static chunk training/decoding
182
+ if it's greater than 0, if use_dynamic_chunk is true,
183
+ this parameter will be ignored
184
+ num_decoding_left_chunks: number of left chunks, this is for decoding,
185
+ the chunk size is decoding_chunk_size.
186
+ >=0: use num_decoding_left_chunks
187
+ <0: use all left chunks
188
+ enable_full_context (bool):
189
+ True: chunk size is either [1, 25] or full context(max_len)
190
+ False: chunk size ~ U[1, 25]
191
+
192
+ Returns:
193
+ torch.Tensor: chunk mask of the input xs.
194
+ """
195
+ # Whether to use chunk mask or not
196
+ if use_dynamic_chunk:
197
+ max_len = xs.size(1)
198
+ if decoding_chunk_size < 0:
199
+ chunk_size = max_len
200
+ num_left_chunks = -1
201
+ elif decoding_chunk_size > 0:
202
+ chunk_size = decoding_chunk_size
203
+ num_left_chunks = num_decoding_left_chunks
204
+ else:
205
+ # chunk size is either [1, 25] or full context(max_len).
206
+ # Since we use 4 times subsampling and allow up to 1s(100 frames)
207
+ # delay, the maximum frame is 100 / 4 = 25.
208
+ chunk_size = torch.randint(1, max_len, (1, )).item()
209
+ num_left_chunks = -1
210
+ if chunk_size > max_len // 2 and enable_full_context:
211
+ chunk_size = max_len
212
+ else:
213
+ chunk_size = chunk_size % 25 + 1
214
+ if use_dynamic_left_chunk:
215
+ max_left_chunks = (max_len - 1) // chunk_size
216
+ num_left_chunks = torch.randint(0, max_left_chunks,
217
+ (1, )).item()
218
+ chunk_masks = subsequent_chunk_mask(xs.size(1), chunk_size,
219
+ num_left_chunks,
220
+ xs.device) # (L, L)
221
+ chunk_masks = chunk_masks.unsqueeze(0) # (1, L, L)
222
+ chunk_masks = masks & chunk_masks # (B, L, L)
223
+ elif static_chunk_size > 0:
224
+ num_left_chunks = num_decoding_left_chunks
225
+ chunk_masks = subsequent_chunk_mask(xs.size(1), static_chunk_size,
226
+ num_left_chunks,
227
+ xs.device) # (L, L)
228
+ chunk_masks = chunk_masks.unsqueeze(0) # (1, L, L)
229
+ chunk_masks = masks & chunk_masks # (B, L, L)
230
+ else:
231
+ chunk_masks = masks
232
+ assert chunk_masks.dtype == torch.bool
233
+ if (chunk_masks.sum(dim=-1) == 0).sum().item() != 0:
234
+ print('get chunk_masks all false at some timestep, force set to true, make sure they are masked in futuer computation!')
235
+ chunk_masks[chunk_masks.sum(dim=-1) == 0] = True
236
+ return chunk_masks
237
+
238
+
239
+ def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
240
+ """Make mask tensor containing indices of padded part.
241
+
242
+ See description of make_non_pad_mask.
243
+
244
+ Args:
245
+ lengths (torch.Tensor): Batch of lengths (B,).
246
+ Returns:
247
+ torch.Tensor: Mask tensor containing indices of padded part.
248
+
249
+ Examples:
250
+ >>> lengths = [5, 3, 2]
251
+ >>> make_pad_mask(lengths)
252
+ masks = [[0, 0, 0, 0 ,0],
253
+ [0, 0, 0, 1, 1],
254
+ [0, 0, 1, 1, 1]]
255
+ """
256
+ batch_size = lengths.size(0)
257
+ max_len = max_len if max_len > 0 else lengths.max().item()
258
+ seq_range = torch.arange(0,
259
+ max_len,
260
+ dtype=torch.int64,
261
+ device=lengths.device)
262
+ seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
263
+ seq_length_expand = lengths.unsqueeze(-1)
264
+ mask = seq_range_expand >= seq_length_expand
265
+ return mask
cosyvoice/utils/onnx.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import onnxruntime
2
+ import torch, random
3
+ import os
4
+ import torchaudio.compliance.kaldi as kaldi
5
+
6
+
7
+ class SpeechTokenExtractor():
8
+ def __init__(self, model_path):
9
+ self.local_rank = int(os.environ.get("LOCAL_RANK", 0))
10
+ option = onnxruntime.SessionOptions()
11
+ option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
12
+ option.intra_op_num_threads = 1
13
+ self.speech_tokenizer_session = onnxruntime.InferenceSession(model_path,
14
+ sess_options=option,
15
+ providers=[("CUDAExecutionProvider", {'device_id': self.local_rank})])
16
+
17
+ def inference(self, feat, feat_lengths, device):
18
+ speech_token = self.speech_tokenizer_session.run(None,
19
+ {self.speech_tokenizer_session.get_inputs()[0].name:
20
+ feat.transpose(1, 2).detach().cpu().numpy(),
21
+ self.speech_tokenizer_session.get_inputs()[1].name:
22
+ feat_lengths.detach().cpu().numpy()})[0]
23
+ return torch.tensor(speech_token).to(torch.int32).to(device), (feat_lengths / 4).to(torch.int32).to(device)
24
+
25
+
26
+ class EmbeddingExtractor():
27
+ def __init__(self, model_path):
28
+ option = onnxruntime.SessionOptions()
29
+ option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
30
+ option.intra_op_num_threads = 1
31
+ self.max_len = 10 * 16000
32
+ self.campplus_session = onnxruntime.InferenceSession(model_path,
33
+ sess_options=option,
34
+ providers=["CPUExecutionProvider"])
35
+
36
+ def inference(self, speech):
37
+ if speech.shape[1] > self.max_len:
38
+ start_index = random.randint(0, speech.shape[1] - self.max_len)
39
+ speech = speech[:, start_index: start_index + self.max_len]
40
+ feat = kaldi.fbank(speech,
41
+ num_mel_bins=80,
42
+ dither=0,
43
+ sample_frequency=16000)
44
+ feat = feat - feat.mean(dim=0, keepdim=True)
45
+ embedding = self.campplus_session.run(None,
46
+ {self.campplus_session.get_inputs()[0].name: feat.unsqueeze(dim=0).cpu().numpy()})[0].flatten().tolist()
47
+ return torch.tensor(embedding).to(speech.device)
48
+
49
+ # singleton mode, only initialized once
50
+ onnx_path = os.environ.get('onnx_path')
51
+ if onnx_path is not None:
52
+ embedding_extractor, online_feature = EmbeddingExtractor(model_path=os.path.join(onnx_path, 'campplus.onnx')), True
53
+ else:
54
+ embedding_extractor, online_feature = None, False
cosyvoice/utils/scheduler.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
2
+ # 2022 Ximalaya Inc (Yuguang Yang)
3
+ # 2024 Alibaba Inc (authors: Xiang Lyu)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # Modified from ESPnet(https://github.com/espnet/espnet)
17
+ # NeMo(https://github.com/NVIDIA/NeMo)
18
+
19
+ from typing import Union
20
+
21
+ import math
22
+ import warnings
23
+ import torch
24
+ from torch.optim.lr_scheduler import _LRScheduler
25
+
26
+
27
+ class WarmupLR(_LRScheduler):
28
+ """The WarmupLR scheduler
29
+
30
+ This scheduler is almost same as NoamLR Scheduler except for following
31
+ difference:
32
+
33
+ NoamLR:
34
+ lr = optimizer.lr * model_size ** -0.5
35
+ * min(step ** -0.5, step * warmup_step ** -1.5)
36
+ WarmupLR:
37
+ lr = optimizer.lr * warmup_step ** 0.5
38
+ * min(step ** -0.5, step * warmup_step ** -1.5)
39
+
40
+ Note that the maximum lr equals to optimizer.lr in this scheduler.
41
+
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ optimizer: torch.optim.Optimizer,
47
+ warmup_steps: Union[int, float] = 25000,
48
+ last_epoch: int = -1,
49
+ ):
50
+ self.warmup_steps = warmup_steps
51
+
52
+ # __init__() must be invoked before setting field
53
+ # because step() is also invoked in __init__()
54
+ super().__init__(optimizer, last_epoch)
55
+
56
+ def __repr__(self):
57
+ return f"{self.__class__.__name__}(warmup_steps={self.warmup_steps})"
58
+
59
+ def get_lr(self):
60
+ step_num = self.last_epoch + 1
61
+ if self.warmup_steps == 0:
62
+ return [lr * step_num**-0.5 for lr in self.base_lrs]
63
+ else:
64
+ return [
65
+ lr * self.warmup_steps**0.5 *
66
+ min(step_num**-0.5, step_num * self.warmup_steps**-1.5)
67
+ for lr in self.base_lrs
68
+ ]
69
+
70
+ def set_step(self, step: int):
71
+ self.last_epoch = step
72
+
73
+
74
+ class WarmupPolicy(_LRScheduler):
75
+ """Adds warmup kwargs and warmup logic to lr policy.
76
+ All arguments should be passed as kwargs for clarity,
77
+ Args:
78
+ warmup_steps: Number of training steps in warmup stage
79
+ warmup_ratio: Ratio of warmup steps to total steps
80
+ max_steps: Total number of steps while training or `None` for
81
+ infinite training
82
+ """
83
+
84
+ def __init__(self,
85
+ optimizer,
86
+ *,
87
+ warmup_steps=None,
88
+ warmup_ratio=None,
89
+ max_steps=None,
90
+ min_lr=0.0,
91
+ last_epoch=-1):
92
+ assert not (warmup_steps is not None and warmup_ratio is not None),\
93
+ "Either use particular number of step or ratio"
94
+ assert warmup_ratio is None or max_steps is not None, \
95
+ "If there is a ratio, there should be a total steps"
96
+
97
+ # It is necessary to assign all attributes *before* __init__,
98
+ # as class is wrapped by an inner class.
99
+ self.max_steps = max_steps
100
+ if warmup_steps is not None:
101
+ self.warmup_steps = warmup_steps
102
+ elif warmup_ratio is not None:
103
+ self.warmup_steps = int(warmup_ratio * max_steps)
104
+ else:
105
+ self.warmup_steps = 0
106
+
107
+ self.min_lr = min_lr
108
+ super().__init__(optimizer, last_epoch)
109
+
110
+ def get_lr(self):
111
+ if not self._get_lr_called_within_step:
112
+ warnings.warn(
113
+ "To get the last learning rate computed "
114
+ "by the scheduler, please use `get_last_lr()`.",
115
+ UserWarning,
116
+ stacklevel=2)
117
+
118
+ step = self.last_epoch
119
+
120
+ if step <= self.warmup_steps and self.warmup_steps > 0:
121
+ return self._get_warmup_lr(step)
122
+
123
+ if step > self.max_steps:
124
+ return [self.min_lr for _ in self.base_lrs]
125
+
126
+ return self._get_lr(step)
127
+
128
+ def _get_warmup_lr(self, step):
129
+ lr_val = (step + 1) / (self.warmup_steps + 1)
130
+ return [initial_lr * lr_val for initial_lr in self.base_lrs]
131
+
132
+ def _get_lr(self, step):
133
+ """Simple const lr policy"""
134
+ return self.base_lrs
135
+
136
+
137
+ class SquareRootConstantPolicy(_LRScheduler):
138
+ """Adds warmup kwargs and warmup logic to lr policy.
139
+ All arguments should be passed as kwargs for clarity,
140
+ Args:
141
+ warmup_steps: Number of training steps in warmup stage
142
+ warmup_ratio: Ratio of warmup steps to total steps
143
+ max_steps: Total number of steps while training or `None` for
144
+ infinite training
145
+ """
146
+
147
+ def __init__(self,
148
+ optimizer,
149
+ *,
150
+ constant_steps=None,
151
+ constant_ratio=None,
152
+ max_steps=None,
153
+ min_lr=0.0,
154
+ last_epoch=-1):
155
+ assert not (constant_steps is not None
156
+ and constant_ratio is not None), \
157
+ "Either use particular number of step or ratio"
158
+ assert constant_ratio is None or max_steps is not None, \
159
+ "If there is a ratio, there should be a total steps"
160
+
161
+ # It is necessary to assign all attributes *before* __init__,
162
+ # as class is wrapped by an inner class.
163
+ self.max_steps = max_steps
164
+ if constant_steps is not None:
165
+ self.constant_steps = constant_steps
166
+ elif constant_ratio is not None:
167
+ self.constant_steps = int(constant_ratio * max_steps)
168
+ else:
169
+ self.constant_steps = 0
170
+
171
+ self.constant_lr = 1 / (constant_steps**0.5)
172
+ self.min_lr = min_lr
173
+ super().__init__(optimizer, last_epoch)
174
+
175
+ def get_lr(self):
176
+ if not self._get_lr_called_within_step:
177
+ warnings.warn(
178
+ "To get the last learning rate computed "
179
+ "by the scheduler, please use `get_last_lr()`.",
180
+ UserWarning,
181
+ stacklevel=2)
182
+
183
+ step = self.last_epoch
184
+
185
+ if step <= self.constant_steps:
186
+ return [self.constant_lr for _ in self.base_lrs]
187
+
188
+ if step > self.max_steps:
189
+ return [self.min_lr for _ in self.base_lrs]
190
+
191
+ return self._get_lr(step)
192
+
193
+ def _get_lr(self, step):
194
+ """Simple const lr policy"""
195
+ return self.base_lrs
196
+
197
+
198
+ class WarmupHoldPolicy(WarmupPolicy):
199
+ """Variant of WarmupPolicy which maintains high
200
+ learning rate for a defined number of steps.
201
+ All arguments should be passed as kwargs for clarity,
202
+ Args:
203
+ warmup_steps: Number of training steps in warmup stage
204
+ warmup_ratio: Ratio of warmup steps to total steps
205
+ hold_steps: Number of training steps to
206
+ hold the learning rate after warm up
207
+ hold_ratio: Ratio of hold steps to total steps
208
+ max_steps: Total number of steps while training or `None` for
209
+ infinite training
210
+ """
211
+
212
+ def __init__(
213
+ self,
214
+ optimizer,
215
+ *,
216
+ warmup_steps=None,
217
+ warmup_ratio=None,
218
+ hold_steps=None,
219
+ hold_ratio=None,
220
+ max_steps=None,
221
+ min_lr=0.0,
222
+ last_epoch=-1,
223
+ ):
224
+ assert not (hold_steps is not None and hold_ratio is not None), \
225
+ "Either use particular number of step or ratio"
226
+ assert hold_ratio is None or max_steps is not None, \
227
+ "If there is a ratio, there should be a total steps"
228
+
229
+ self.min_lr = min_lr
230
+ self._last_warmup_lr = 0.0
231
+
232
+ # Necessary to duplicate as class attributes are hidden in inner class
233
+ self.max_steps = max_steps
234
+ if warmup_steps is not None:
235
+ self.warmup_steps = warmup_steps
236
+ elif warmup_ratio is not None:
237
+ self.warmup_steps = int(warmup_ratio * max_steps)
238
+ else:
239
+ self.warmup_steps = 0
240
+
241
+ if hold_steps is not None:
242
+ self.hold_steps = hold_steps + self.warmup_steps
243
+ elif hold_ratio is not None:
244
+ self.hold_steps = int(hold_ratio * max_steps) + self.warmup_steps
245
+ else:
246
+ self.hold_steps = 0
247
+
248
+ super().__init__(
249
+ optimizer,
250
+ warmup_steps=warmup_steps,
251
+ warmup_ratio=warmup_ratio,
252
+ max_steps=max_steps,
253
+ last_epoch=last_epoch,
254
+ min_lr=min_lr,
255
+ )
256
+
257
+ def get_lr(self):
258
+ if not self._get_lr_called_within_step:
259
+ warnings.warn(
260
+ "To get the last learning rate computed by the scheduler,"
261
+ " "
262
+ "please use `get_last_lr()`.",
263
+ UserWarning,
264
+ stacklevel=2)
265
+
266
+ step = self.last_epoch
267
+
268
+ # Warmup phase
269
+ if step <= self.warmup_steps and self.warmup_steps > 0:
270
+ return self._get_warmup_lr(step)
271
+
272
+ # Hold phase
273
+ if (step >= self.warmup_steps) and (step < self.hold_steps):
274
+ return self.base_lrs
275
+
276
+ if step > self.max_steps:
277
+ return [self.min_lr for _ in self.base_lrs]
278
+
279
+ return self._get_lr(step)
280
+
281
+
282
+ class WarmupAnnealHoldPolicy(_LRScheduler):
283
+ """Adds warmup kwargs and warmup logic to lr policy.
284
+ All arguments should be passed as kwargs for clarity,
285
+ Args:
286
+ warmup_steps: Number of training steps in warmup stage
287
+ warmup_ratio: Ratio of warmup steps to total steps
288
+ max_steps: Total number of steps while training or `None` for
289
+ infinite training
290
+ min_lr: Minimum lr to hold the learning rate after decay at.
291
+ constant_steps: Number of steps to keep lr constant at.
292
+ constant_ratio: Ratio of steps to keep lr constant.
293
+ """
294
+
295
+ def __init__(
296
+ self,
297
+ optimizer,
298
+ *,
299
+ warmup_steps=None,
300
+ warmup_ratio=None,
301
+ constant_steps=None,
302
+ constant_ratio=None,
303
+ max_steps=None,
304
+ min_lr=0.0,
305
+ last_epoch=-1,
306
+ ):
307
+ assert not (warmup_steps is not None
308
+ and warmup_ratio is not None), \
309
+ "Either use particular number of step or ratio"
310
+ assert not (constant_steps is not None
311
+ and constant_ratio is not None), \
312
+ "Either use constant_steps or constant_ratio"
313
+ assert warmup_ratio is None or max_steps is not None, \
314
+ "If there is a ratio, there should be a total steps"
315
+
316
+ # It is necessary to assign all attributes *before* __init__,
317
+ # as class is wrapped by an inner class.
318
+ self.max_steps = max_steps
319
+
320
+ if warmup_steps is not None:
321
+ self.warmup_steps = warmup_steps
322
+ elif warmup_ratio is not None:
323
+ self.warmup_steps = int(warmup_ratio * max_steps)
324
+ else:
325
+ self.warmup_steps = 0
326
+
327
+ if constant_steps is not None:
328
+ self.constant_steps = constant_steps
329
+ elif constant_ratio is not None:
330
+ self.constant_steps = int(constant_ratio * max_steps)
331
+ else:
332
+ self.constant_steps = 0
333
+
334
+ self.decay_steps = max_steps - (self.constant_steps +
335
+ self.warmup_steps)
336
+
337
+ self.min_lr = min_lr
338
+ super().__init__(optimizer, last_epoch)
339
+
340
+ def get_lr(self):
341
+ if not self._get_lr_called_within_step:
342
+ warnings.warn(
343
+ "To get the last learning rate computed "
344
+ "by the scheduler, please use `get_last_lr()`.",
345
+ UserWarning,
346
+ stacklevel=2)
347
+
348
+ step = self.last_epoch
349
+
350
+ # Warmup steps
351
+ if self.warmup_steps > 0 and step <= self.warmup_steps:
352
+ return self._get_warmup_lr(step)
353
+
354
+ # Constant steps after warmup and decay
355
+ if self.constant_steps > 0 and (
356
+ self.warmup_steps + self.decay_steps) < step <= self.max_steps:
357
+ return self._get_constant_lr(step)
358
+
359
+ # Min lr after max steps of updates
360
+ if step > self.max_steps:
361
+ return [self.min_lr for _ in self.base_lrs]
362
+
363
+ return self._get_lr(step)
364
+
365
+ def _get_warmup_lr(self, step):
366
+ lr_val = (step + 1) / (self.warmup_steps + 1)
367
+ return [initial_lr * lr_val for initial_lr in self.base_lrs]
368
+
369
+ def _get_constant_lr(self, step):
370
+ return [self.min_lr for _ in self.base_lrs]
371
+
372
+ def _get_lr(self, step):
373
+ """Simple const lr policy"""
374
+ return self.base_lrs
375
+
376
+
377
+ def _squareroot_annealing(initial_lr, step, max_steps, min_lr):
378
+ mult = ((max_steps - step) / max_steps)**0.5
379
+ out_lr = initial_lr * mult
380
+ out_lr = max(out_lr, min_lr)
381
+ return out_lr
382
+
383
+
384
+ def _square_annealing(initial_lr, step, max_steps, min_lr):
385
+ mult = ((max_steps - step) / max_steps)**2
386
+ out_lr = initial_lr * mult
387
+ out_lr = max(out_lr, min_lr)
388
+ return out_lr
389
+
390
+
391
+ def _cosine_annealing(initial_lr, step, max_steps, min_lr):
392
+ mult = 0.5 * (1 + math.cos(math.pi * step / max_steps))
393
+ out_lr = (initial_lr - min_lr) * mult + min_lr
394
+ return out_lr
395
+
396
+
397
+ def _linear_warmup_with_cosine_annealing(max_lr, warmup_steps, step,
398
+ decay_steps, min_lr):
399
+ assert max_lr > min_lr
400
+ # Use linear warmup for the initial part.
401
+ if warmup_steps > 0 and step <= warmup_steps:
402
+ return max_lr * float(step) / float(warmup_steps)
403
+
404
+ # For any steps larger than `decay_steps`, use `min_lr`.
405
+ if step > warmup_steps + decay_steps:
406
+ return min_lr
407
+
408
+ # If we are done with the warmup period, use the decay style.
409
+ num_steps_ = step - warmup_steps
410
+ decay_steps_ = decay_steps
411
+ decay_ratio = float(num_steps_) / float(decay_steps_)
412
+ assert decay_ratio >= 0.0
413
+ assert decay_ratio <= 1.0
414
+ delta_lr = max_lr - min_lr
415
+
416
+ coeff = 0.5 * (math.cos(math.pi * decay_ratio) + 1.0)
417
+
418
+ return min_lr + coeff * delta_lr
419
+
420
+
421
+ def _poly_decay(initial_lr, step, decay_steps, power, min_lr, cycle):
422
+ if cycle:
423
+ multiplier = 1.0 if step == 0 else math.ceil(step / decay_steps)
424
+ decay_steps *= multiplier
425
+ else:
426
+ step = min(step, decay_steps)
427
+ p = step / decay_steps
428
+ lr = (initial_lr - min_lr) * math.pow(1.0 - p, power)
429
+ lr += min_lr
430
+ return lr
431
+
432
+
433
+ def _noam_hold_annealing(initial_lr, step, warmup_steps, hold_steps,
434
+ decay_rate, min_lr):
435
+ # hold_steps = total number of steps
436
+ # to hold the LR, not the warmup + hold steps.
437
+ T_warmup_decay = max(1, warmup_steps**decay_rate)
438
+ T_hold_decay = max(1, (step - hold_steps)**decay_rate)
439
+ lr = (initial_lr * T_warmup_decay) / T_hold_decay
440
+ lr = max(lr, min_lr)
441
+ return lr
442
+
443
+
444
+ class SquareAnnealing(WarmupPolicy):
445
+
446
+ def __init__(self,
447
+ optimizer,
448
+ *,
449
+ max_steps,
450
+ min_lr=1e-5,
451
+ last_epoch=-1,
452
+ **kwargs):
453
+ super().__init__(optimizer=optimizer,
454
+ max_steps=max_steps,
455
+ last_epoch=last_epoch,
456
+ min_lr=min_lr,
457
+ **kwargs)
458
+
459
+ def _get_lr(self, step):
460
+ new_lrs = [
461
+ _square_annealing(
462
+ initial_lr=initial_lr,
463
+ step=step - self.warmup_steps,
464
+ max_steps=self.max_steps - self.warmup_steps,
465
+ min_lr=self.min_lr,
466
+ ) for initial_lr in self.base_lrs
467
+ ]
468
+ return new_lrs
469
+
470
+
471
+ class SquareRootAnnealing(WarmupPolicy):
472
+
473
+ def __init__(self,
474
+ optimizer,
475
+ *,
476
+ max_steps,
477
+ min_lr=0,
478
+ last_epoch=-1,
479
+ **kwargs):
480
+ super().__init__(optimizer=optimizer,
481
+ max_steps=max_steps,
482
+ last_epoch=last_epoch,
483
+ min_lr=min_lr,
484
+ **kwargs)
485
+
486
+ def _get_lr(self, step):
487
+ new_lrs = [
488
+ _squareroot_annealing(initial_lr=initial_lr,
489
+ step=step,
490
+ max_steps=self.max_steps,
491
+ min_lr=self.min_lr)
492
+ for initial_lr in self.base_lrs
493
+ ]
494
+ return new_lrs
495
+
496
+
497
+ class CosineAnnealing(WarmupAnnealHoldPolicy):
498
+
499
+ def __init__(self,
500
+ optimizer,
501
+ *,
502
+ max_steps,
503
+ min_lr=0,
504
+ last_epoch=-1,
505
+ **kwargs):
506
+ super().__init__(optimizer=optimizer,
507
+ max_steps=max_steps,
508
+ last_epoch=last_epoch,
509
+ min_lr=min_lr,
510
+ **kwargs)
511
+
512
+ def _get_lr(self, step):
513
+ for initial_lr in self.base_lrs:
514
+ if initial_lr < self.min_lr:
515
+ raise ValueError(
516
+ f"{self} received an initial learning rate "
517
+ f"that was lower than the minimum learning rate.")
518
+
519
+ if self.constant_steps is None or self.constant_steps == 0:
520
+ new_lrs = [
521
+ _cosine_annealing(
522
+ initial_lr=initial_lr,
523
+ step=step - self.warmup_steps,
524
+ max_steps=self.max_steps - self.warmup_steps,
525
+ min_lr=self.min_lr,
526
+ ) for initial_lr in self.base_lrs
527
+ ]
528
+ else:
529
+ new_lrs = self._get_linear_warmup_with_cosine_annealing_lr(step)
530
+ return new_lrs
531
+
532
+ def _get_warmup_lr(self, step):
533
+ if self.constant_steps is None or self.constant_steps == 0:
534
+ return super()._get_warmup_lr(step)
535
+ else:
536
+ # Use linear warmup for the initial part.
537
+ return self._get_linear_warmup_with_cosine_annealing_lr(step)
538
+
539
+ def _get_constant_lr(self, step):
540
+ # Only called when `constant_steps` > 0.
541
+ return self._get_linear_warmup_with_cosine_annealing_lr(step)
542
+
543
+ def _get_linear_warmup_with_cosine_annealing_lr(self, step):
544
+ # Cosine Schedule for Megatron LM,
545
+ # slightly different warmup schedule + constant LR at the end.
546
+ new_lrs = [
547
+ _linear_warmup_with_cosine_annealing(
548
+ max_lr=self.base_lrs[0],
549
+ warmup_steps=self.warmup_steps,
550
+ step=step,
551
+ decay_steps=self.decay_steps,
552
+ min_lr=self.min_lr,
553
+ ) for _ in self.base_lrs
554
+ ]
555
+ return new_lrs
556
+
557
+
558
+ class NoamAnnealing(_LRScheduler):
559
+
560
+ def __init__(self,
561
+ optimizer,
562
+ *,
563
+ d_model,
564
+ warmup_steps=None,
565
+ warmup_ratio=None,
566
+ max_steps=None,
567
+ min_lr=0.0,
568
+ last_epoch=-1):
569
+ self._normalize = d_model**(-0.5)
570
+ assert not (warmup_steps is not None and warmup_ratio is not None), \
571
+ "Either use particular number of step or ratio"
572
+ assert warmup_ratio is None or max_steps is not None, \
573
+ "If there is a ratio, there should be a total steps"
574
+
575
+ # It is necessary to assign all attributes *before* __init__,
576
+ # as class is wrapped by an inner class.
577
+ self.max_steps = max_steps
578
+ if warmup_steps is not None:
579
+ self.warmup_steps = warmup_steps
580
+ elif warmup_ratio is not None:
581
+ self.warmup_steps = int(warmup_ratio * max_steps)
582
+ else:
583
+ self.warmup_steps = 0
584
+
585
+ self.min_lr = min_lr
586
+ super().__init__(optimizer, last_epoch)
587
+
588
+ def get_lr(self):
589
+ if not self._get_lr_called_within_step:
590
+ warnings.warn(
591
+ "To get the last learning rate computed "
592
+ "by the scheduler, please use `get_last_lr()`.",
593
+ UserWarning,
594
+ stacklevel=2)
595
+
596
+ step = max(1, self.last_epoch)
597
+
598
+ for initial_lr in self.base_lrs:
599
+ if initial_lr < self.min_lr:
600
+ raise ValueError(
601
+ f"{self} received an initial learning rate "
602
+ f"that was lower than the minimum learning rate.")
603
+
604
+ new_lrs = [
605
+ self._noam_annealing(initial_lr=initial_lr, step=step)
606
+ for initial_lr in self.base_lrs
607
+ ]
608
+ return new_lrs
609
+
610
+ def _noam_annealing(self, initial_lr, step):
611
+ if self.warmup_steps > 0:
612
+ mult = self._normalize * min(step**(-0.5),
613
+ step * (self.warmup_steps**(-1.5)))
614
+ else:
615
+ mult = self._normalize * step**(-0.5)
616
+
617
+ out_lr = initial_lr * mult
618
+ if step > self.warmup_steps:
619
+ out_lr = max(out_lr, self.min_lr)
620
+ return out_lr
621
+
622
+
623
+ class NoamHoldAnnealing(WarmupHoldPolicy):
624
+
625
+ def __init__(self,
626
+ optimizer,
627
+ *,
628
+ max_steps,
629
+ decay_rate=0.5,
630
+ min_lr=0.0,
631
+ last_epoch=-1,
632
+ **kwargs):
633
+ """
634
+ From Nemo:
635
+ Implementation of the Noam Hold Annealing policy
636
+ from the SqueezeFormer paper.
637
+
638
+ Unlike NoamAnnealing, the peak learning rate
639
+ can be explicitly set for this scheduler.
640
+ The schedule first performs linear warmup,
641
+ then holds the peak LR, then decays with some schedule for
642
+ the remainder of the steps.
643
+ Therefore the min-lr is still dependent
644
+ on the hyper parameters selected.
645
+
646
+ It's schedule is determined by three factors-
647
+
648
+ Warmup Steps: Initial stage, where linear warmup
649
+ occurs uptil the peak LR is reached. Unlike NoamAnnealing,
650
+ the peak LR is explicitly stated here instead of a scaling factor.
651
+
652
+ Hold Steps: Intermediate stage, where the peak LR
653
+ is maintained for some number of steps. In this region,
654
+ the high peak LR allows the model to converge faster
655
+ if training is stable. However the high LR
656
+ may also cause instability during training.
657
+ Should usually be a significant fraction of training
658
+ steps (around 30-40% of the entire training steps).
659
+
660
+ Decay Steps: Final stage, where the LR rapidly decays
661
+ with some scaling rate (set by decay rate).
662
+ To attain Noam decay, use 0.5,
663
+ for Squeezeformer recommended decay, use 1.0.
664
+ The fast decay after prolonged high LR during
665
+ hold phase allows for rapid convergence.
666
+
667
+ References:
668
+ - [Squeezeformer:
669
+ An Efficient Transformer for Automatic Speech Recognition]
670
+ (https://arxiv.org/abs/2206.00888)
671
+
672
+ Args:
673
+ optimizer: Pytorch compatible Optimizer object.
674
+ warmup_steps: Number of training steps in warmup stage
675
+ warmup_ratio: Ratio of warmup steps to total steps
676
+ hold_steps: Number of training steps to
677
+ hold the learning rate after warm up
678
+ hold_ratio: Ratio of hold steps to total steps
679
+ max_steps: Total number of steps while training or `None` for
680
+ infinite training
681
+ decay_rate: Float value describing the polynomial decay
682
+ after the hold period. Default value
683
+ of 0.5 corresponds to Noam decay.
684
+ min_lr: Minimum learning rate.
685
+ """
686
+ self.decay_rate = decay_rate
687
+ super().__init__(optimizer=optimizer,
688
+ max_steps=max_steps,
689
+ last_epoch=last_epoch,
690
+ min_lr=min_lr,
691
+ **kwargs)
692
+
693
+ def _get_lr(self, step):
694
+ if self.warmup_steps is None or self.warmup_steps == 0:
695
+ raise ValueError(
696
+ "Noam scheduler cannot be used without warmup steps")
697
+
698
+ if self.hold_steps > 0:
699
+ hold_steps = self.hold_steps - self.warmup_steps
700
+ else:
701
+ hold_steps = 0
702
+
703
+ new_lrs = [
704
+ _noam_hold_annealing(
705
+ initial_lr,
706
+ step=step,
707
+ warmup_steps=self.warmup_steps,
708
+ hold_steps=hold_steps,
709
+ decay_rate=self.decay_rate,
710
+ min_lr=self.min_lr,
711
+ ) for initial_lr in self.base_lrs
712
+ ]
713
+ return new_lrs
714
+
715
+ def set_step(self, step: int):
716
+ self.last_epoch = step
717
+
718
+
719
+ class ConstantLR(_LRScheduler):
720
+ """The ConstantLR scheduler
721
+
722
+ This scheduler keeps a constant lr
723
+
724
+ """
725
+
726
+ def __init__(
727
+ self,
728
+ optimizer: torch.optim.Optimizer,
729
+ ):
730
+ # __init__() must be invoked before setting field
731
+ # because step() is also invoked in __init__()
732
+ super().__init__(optimizer)
733
+
734
+ def get_lr(self):
735
+ return self.base_lrs
736
+
737
+ def set_step(self, step: int):
738
+ self.last_epoch = step
cosyvoice/utils/train_utils.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang)
2
+ # 2023 Horizon Inc. (authors: Xingchen Song)
3
+ # 2024 Alibaba Inc (authors: Xiang Lyu)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ import os
19
+ import torch
20
+ import json
21
+ import re
22
+ import datetime
23
+ import yaml
24
+
25
+ import deepspeed
26
+ import torch.optim as optim
27
+ import torch.distributed as dist
28
+
29
+ from torch.utils.tensorboard import SummaryWriter
30
+ from torch.utils.data import DataLoader
31
+ from torch.nn.utils import clip_grad_norm_
32
+
33
+ from deepspeed.runtime.zero.stage_1_and_2 import estimate_zero2_model_states_mem_needs_all_live
34
+
35
+ from cosyvoice.dataset.dataset import Dataset
36
+ from cosyvoice.utils.scheduler import WarmupLR, NoamHoldAnnealing, ConstantLR
37
+
38
+
39
+ def init_distributed(args):
40
+ world_size = int(os.environ.get('WORLD_SIZE', 1))
41
+ local_rank = int(os.environ.get('LOCAL_RANK', 0))
42
+ rank = int(os.environ.get('RANK', 0))
43
+ logging.info('training on multiple gpus, this gpu {}'.format(local_rank) +
44
+ ', rank {}, world_size {}'.format(rank, world_size))
45
+ if args.train_engine == 'torch_ddp':
46
+ torch.cuda.set_device(local_rank)
47
+ dist.init_process_group(args.dist_backend)
48
+ else:
49
+ deepspeed.init_distributed(dist_backend=args.dist_backend)
50
+ return world_size, local_rank, rank
51
+
52
+
53
+ def init_dataset_and_dataloader(args, configs, gan, dpo):
54
+ data_pipeline = configs['data_pipeline_gan'] if gan is True else configs['data_pipeline']
55
+ train_dataset = Dataset(args.train_data, data_pipeline=data_pipeline, mode='train', gan=gan, dpo=dpo, shuffle=True, partition=True)
56
+ cv_dataset = Dataset(args.cv_data, data_pipeline=data_pipeline, mode='dev', gan=gan, dpo=dpo, shuffle=False, partition=False)
57
+
58
+ # do not use persistent_workers=True, as whisper tokenizer opens tiktoken file each time when the for loop starts
59
+ train_data_loader = DataLoader(train_dataset,
60
+ batch_size=None,
61
+ pin_memory=args.pin_memory,
62
+ num_workers=args.num_workers,
63
+ prefetch_factor=args.prefetch)
64
+ cv_data_loader = DataLoader(cv_dataset,
65
+ batch_size=None,
66
+ pin_memory=args.pin_memory,
67
+ num_workers=args.num_workers,
68
+ prefetch_factor=args.prefetch)
69
+ return train_dataset, cv_dataset, train_data_loader, cv_data_loader
70
+
71
+
72
+ def check_modify_and_save_config(args, configs):
73
+ if args.train_engine == "torch_ddp":
74
+ configs['train_conf']["dtype"] = 'bf16' if args.use_amp is True else 'fp32'
75
+ else:
76
+ with open(args.deepspeed_config, 'r') as fin:
77
+ ds_configs = json.load(fin)
78
+ if "fp16" in ds_configs and ds_configs["fp16"]["enabled"]:
79
+ configs['train_conf']["dtype"] = "fp16"
80
+ elif "bf16" in ds_configs and ds_configs["bf16"]["enabled"]:
81
+ configs['train_conf']["dtype"] = "bf16"
82
+ else:
83
+ configs['train_conf']["dtype"] = "fp32"
84
+ assert ds_configs["train_micro_batch_size_per_gpu"] == 1
85
+ # if use deepspeed, override ddp config
86
+ configs['train_conf']['save_per_step'] = int(configs['train_conf']['save_per_step'] *
87
+ configs['train_conf']['accum_grad'] / ds_configs["gradient_accumulation_steps"])
88
+ configs['train_conf']['accum_grad'] = ds_configs["gradient_accumulation_steps"]
89
+ configs['train_conf']['grad_clip'] = ds_configs["gradient_clipping"]
90
+ configs['train_conf']['log_interval'] = ds_configs["steps_per_print"]
91
+ return configs
92
+
93
+
94
+ def wrap_cuda_model(args, model):
95
+ local_world_size = int(os.environ.get('LOCAL_WORLD_SIZE', 1))
96
+ world_size = int(os.environ.get('WORLD_SIZE', 1))
97
+ if args.train_engine == "torch_ddp": # native pytorch ddp
98
+ assert (torch.cuda.is_available())
99
+ model.cuda()
100
+ model = torch.nn.parallel.DistributedDataParallel(model, find_unused_parameters=True)
101
+ else:
102
+ if int(os.environ.get('RANK', 0)) == 0:
103
+ logging.info("Estimating model states memory needs (zero2)...")
104
+ estimate_zero2_model_states_mem_needs_all_live(
105
+ model,
106
+ num_gpus_per_node=local_world_size,
107
+ num_nodes=world_size // local_world_size)
108
+ return model
109
+
110
+
111
+ def init_optimizer_and_scheduler(args, configs, model, gan):
112
+ if gan is False:
113
+ if configs['train_conf']['optim'] == 'adam':
114
+ optimizer = optim.Adam(model.parameters(), **configs['train_conf']['optim_conf'])
115
+ elif configs['train_conf']['optim'] == 'adamw':
116
+ optimizer = optim.AdamW(model.parameters(), **configs['train_conf']['optim_conf'])
117
+ else:
118
+ raise ValueError("unknown optimizer: " + configs['train_conf'])
119
+
120
+ if configs['train_conf']['scheduler'] == 'warmuplr':
121
+ scheduler_type = WarmupLR
122
+ scheduler = WarmupLR(optimizer, **configs['train_conf']['scheduler_conf'])
123
+ elif configs['train_conf']['scheduler'] == 'NoamHoldAnnealing':
124
+ scheduler_type = NoamHoldAnnealing
125
+ scheduler = NoamHoldAnnealing(optimizer, **configs['train_conf']['scheduler_conf'])
126
+ elif configs['train_conf']['scheduler'] == 'constantlr':
127
+ scheduler_type = ConstantLR
128
+ scheduler = ConstantLR(optimizer)
129
+ else:
130
+ raise ValueError("unknown scheduler: " + configs['train_conf'])
131
+
132
+ # use deepspeed optimizer for speedup
133
+ if args.train_engine == "deepspeed":
134
+ def scheduler(opt):
135
+ return scheduler_type(opt, **configs['train_conf']['scheduler_conf'])
136
+ model, optimizer, _, scheduler = deepspeed.initialize(
137
+ args=args,
138
+ model=model,
139
+ optimizer=None,
140
+ lr_scheduler=scheduler,
141
+ model_parameters=model.parameters())
142
+
143
+ optimizer_d, scheduler_d = None, None
144
+
145
+ else:
146
+ # currently we wrap generator and discriminator in one model, so we cannot use deepspeed
147
+ if configs['train_conf']['optim'] == 'adam':
148
+ optimizer = optim.Adam(model.module.generator.parameters(), **configs['train_conf']['optim_conf'])
149
+ elif configs['train_conf']['optim'] == 'adamw':
150
+ optimizer = optim.AdamW(model.module.generator.parameters(), **configs['train_conf']['optim_conf'])
151
+ else:
152
+ raise ValueError("unknown optimizer: " + configs['train_conf'])
153
+
154
+ if configs['train_conf']['scheduler'] == 'warmuplr':
155
+ scheduler_type = WarmupLR
156
+ scheduler = WarmupLR(optimizer, **configs['train_conf']['scheduler_conf'])
157
+ elif configs['train_conf']['scheduler'] == 'NoamHoldAnnealing':
158
+ scheduler_type = NoamHoldAnnealing
159
+ scheduler = NoamHoldAnnealing(optimizer, **configs['train_conf']['scheduler_conf'])
160
+ elif configs['train_conf']['scheduler'] == 'constantlr':
161
+ scheduler_type = ConstantLR
162
+ scheduler = ConstantLR(optimizer)
163
+ else:
164
+ raise ValueError("unknown scheduler: " + configs['train_conf'])
165
+
166
+ if configs['train_conf']['optim_d'] == 'adam':
167
+ optimizer_d = optim.Adam(model.module.discriminator.parameters(), **configs['train_conf']['optim_conf_d'])
168
+ elif configs['train_conf']['optim_d'] == 'adamw':
169
+ optimizer_d = optim.AdamW(model.module.discriminator.parameters(), **configs['train_conf']['optim_conf_d'])
170
+ else:
171
+ raise ValueError("unknown optimizer: " + configs['train_conf'])
172
+
173
+ if configs['train_conf']['scheduler_d'] == 'warmuplr':
174
+ scheduler_type = WarmupLR
175
+ scheduler_d = WarmupLR(optimizer_d, **configs['train_conf']['scheduler_d'])
176
+ elif configs['train_conf']['scheduler_d'] == 'NoamHoldAnnealing':
177
+ scheduler_type = NoamHoldAnnealing
178
+ scheduler_d = NoamHoldAnnealing(optimizer_d, **configs['train_conf']['scheduler_d'])
179
+ elif configs['train_conf']['scheduler'] == 'constantlr':
180
+ scheduler_type = ConstantLR
181
+ scheduler_d = ConstantLR(optimizer_d)
182
+ else:
183
+ raise ValueError("unknown scheduler: " + configs['train_conf'])
184
+ return model, optimizer, scheduler, optimizer_d, scheduler_d
185
+
186
+
187
+ def init_summarywriter(args):
188
+ writer = None
189
+ if int(os.environ.get('RANK', 0)) == 0:
190
+ os.makedirs(args.model_dir, exist_ok=True)
191
+ writer = SummaryWriter(args.tensorboard_dir)
192
+ return writer
193
+
194
+
195
+ def save_model(model, model_name, info_dict):
196
+ rank = int(os.environ.get('RANK', 0))
197
+ model_dir = info_dict["model_dir"]
198
+ save_model_path = os.path.join(model_dir, '{}.pt'.format(model_name))
199
+
200
+ if info_dict["train_engine"] == "torch_ddp":
201
+ if rank == 0:
202
+ torch.save({**model.module.state_dict(), 'epoch': info_dict['epoch'], 'step': info_dict['step']}, save_model_path)
203
+ else:
204
+ with torch.no_grad():
205
+ model.save_checkpoint(save_dir=model_dir,
206
+ tag=model_name,
207
+ client_state=info_dict)
208
+ if rank == 0:
209
+ info_path = re.sub('.pt$', '.yaml', save_model_path)
210
+ info_dict['save_time'] = datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
211
+ with open(info_path, 'w') as fout:
212
+ data = yaml.dump(info_dict)
213
+ fout.write(data)
214
+ logging.info('[Rank {}] Checkpoint: save to checkpoint {}'.format(rank, save_model_path))
215
+
216
+
217
+ def cosyvoice_join(group_join, info_dict):
218
+ world_size = int(os.environ.get('WORLD_SIZE', 1))
219
+ local_rank = int(os.environ.get('LOCAL_RANK', 0))
220
+ rank = int(os.environ.get('RANK', 0))
221
+
222
+ if info_dict["batch_idx"] != 0:
223
+ # we try to join all rank in both ddp and deepspeed mode, in case different rank has different lr
224
+ try:
225
+ dist.monitored_barrier(group=group_join,
226
+ timeout=group_join.options._timeout)
227
+ return False
228
+ except RuntimeError as e:
229
+ logging.info("Detected uneven workload distribution: {}\n".format(e) +
230
+ "Break current worker to manually join all workers, " +
231
+ "world_size {}, current rank {}, current local_rank {}\n".
232
+ format(world_size, rank, local_rank))
233
+ return True
234
+ else:
235
+ return False
236
+
237
+
238
+ def batch_forward(model, batch, scaler, info_dict, ref_model=None, dpo_loss=None):
239
+ device = int(os.environ.get('LOCAL_RANK', 0))
240
+
241
+ dtype = info_dict["dtype"]
242
+ if dtype == "fp16":
243
+ dtype = torch.float16
244
+ elif dtype == "bf16":
245
+ dtype = torch.bfloat16
246
+ else: # fp32
247
+ dtype = torch.float32
248
+
249
+ if info_dict['train_engine'] == 'torch_ddp':
250
+ autocast = torch.cuda.amp.autocast(enabled=scaler is not None, dtype=dtype)
251
+ else:
252
+ autocast = torch.cuda.amp.autocast(enabled=True, dtype=dtype, cache_enabled=False)
253
+
254
+ with autocast:
255
+ info_dict['loss_dict'] = model(batch, device)
256
+ if ref_model is not None and dpo_loss is not None:
257
+ chosen_logps = info_dict['loss_dict']["chosen_logps"]
258
+ rejected_logps = info_dict['loss_dict']["rejected_logps"]
259
+ sft_loss = info_dict['loss_dict']['loss']
260
+ with torch.no_grad():
261
+ ref_loss_dict = ref_model(batch, device)
262
+ reference_chosen_logps = ref_loss_dict["chosen_logps"]
263
+ reference_rejected_logps = ref_loss_dict["rejected_logps"]
264
+ preference_loss, chosen_reward, reject_reward = dpo_loss(
265
+ chosen_logps, rejected_logps, reference_chosen_logps, reference_rejected_logps
266
+ )
267
+ dpo_acc = (chosen_reward > reject_reward).float().mean()
268
+ info_dict['loss_dict']["loss"] = preference_loss + sft_loss
269
+ info_dict['loss_dict']["sft_loss"] = sft_loss
270
+ info_dict['loss_dict']["dpo_loss"] = preference_loss
271
+ info_dict['loss_dict']["dpo_acc"] = dpo_acc
272
+ info_dict['loss_dict']["chosen_reward"] = chosen_reward.mean()
273
+ info_dict['loss_dict']["reject_reward"] = reject_reward.mean()
274
+ return info_dict
275
+
276
+
277
+ def batch_backward(model, scaler, info_dict):
278
+ if info_dict["train_engine"] == "deepspeed":
279
+ scaled_loss = model.backward(info_dict['loss_dict']['loss'])
280
+ else:
281
+ scaled_loss = info_dict['loss_dict']['loss'] / info_dict['accum_grad']
282
+ if scaler is not None:
283
+ scaler.scale(scaled_loss).backward()
284
+ else:
285
+ scaled_loss.backward()
286
+
287
+ info_dict['loss_dict']['loss'] = scaled_loss
288
+ return info_dict
289
+
290
+
291
+ def update_parameter_and_lr(model, optimizer, scheduler, scaler, info_dict):
292
+ grad_norm = 0.0
293
+ if info_dict['train_engine'] == "deepspeed":
294
+ info_dict["is_gradient_accumulation_boundary"] = model.is_gradient_accumulation_boundary()
295
+ model.step()
296
+ grad_norm = model.get_global_grad_norm()
297
+ elif (info_dict['batch_idx'] + 1) % info_dict["accum_grad"] == 0:
298
+ # Use mixed precision training
299
+ if scaler is not None:
300
+ scaler.unscale_(optimizer)
301
+ grad_norm = clip_grad_norm_(model.parameters(), info_dict['grad_clip'])
302
+ # We don't check grad here since that if the gradient
303
+ # has inf/nan values, scaler.step will skip
304
+ # optimizer.step().
305
+ if torch.isfinite(grad_norm):
306
+ scaler.step(optimizer)
307
+ else:
308
+ logging.warning('get infinite grad_norm, check your code/data if it appears frequently')
309
+ scaler.update()
310
+ else:
311
+ grad_norm = clip_grad_norm_(model.parameters(), info_dict['grad_clip'])
312
+ if torch.isfinite(grad_norm):
313
+ optimizer.step()
314
+ else:
315
+ logging.warning('get infinite grad_norm, check your code/data if it appears frequently')
316
+ optimizer.zero_grad()
317
+ scheduler.step()
318
+ info_dict["lr"] = optimizer.param_groups[0]['lr']
319
+ info_dict["grad_norm"] = grad_norm
320
+ return info_dict
321
+
322
+
323
+ def log_per_step(writer, info_dict):
324
+ tag = info_dict["tag"]
325
+ epoch = info_dict.get('epoch', 0)
326
+ step = info_dict["step"]
327
+ batch_idx = info_dict["batch_idx"]
328
+ loss_dict = info_dict['loss_dict']
329
+ rank = int(os.environ.get('RANK', 0))
330
+
331
+ # only rank 0 write to tensorboard to avoid multi-process write
332
+ if writer is not None:
333
+ if (info_dict['train_engine'] == 'deepspeed' and info_dict['is_gradient_accumulation_boundary'] is True) or \
334
+ (info_dict['train_engine'] == 'torch_ddp' and (info_dict['batch_idx'] + 1) % info_dict['accum_grad'] == 0):
335
+ for k in ['epoch', 'lr', 'grad_norm']:
336
+ writer.add_scalar('{}/{}'.format(tag, k), info_dict[k], step + 1)
337
+ for k, v in loss_dict.items():
338
+ writer.add_scalar('{}/{}'.format(tag, k), v, step + 1)
339
+
340
+ # TRAIN & CV, Shell log (stdout)
341
+ if (info_dict['batch_idx'] + 1) % info_dict['log_interval'] == 0:
342
+ log_str = '{} Batch {}/{} '.format(tag, epoch, batch_idx + 1)
343
+ for name, value in loss_dict.items():
344
+ log_str += '{} {:.6f} '.format(name, value)
345
+ if tag == "TRAIN":
346
+ log_str += 'lr {:.8f} grad_norm {:.6f}'.format(
347
+ info_dict["lr"], info_dict['grad_norm'])
348
+ log_str += ' rank {}'.format(rank)
349
+ logging.debug(log_str)
350
+
351
+
352
+ def log_per_save(writer, info_dict):
353
+ tag = info_dict["tag"]
354
+ epoch = info_dict["epoch"]
355
+ step = info_dict["step"]
356
+ loss_dict = info_dict["loss_dict"]
357
+ lr = info_dict['lr']
358
+ rank = int(os.environ.get('RANK', 0))
359
+ logging.info(
360
+ 'Epoch {} Step {} CV info lr {} {} rank {}'.format(
361
+ epoch, step + 1, lr, rank, ' '.join(['{} {}'.format(k, v) for k, v in loss_dict.items()])))
362
+
363
+ if writer is not None:
364
+ for k in ['epoch', 'lr']:
365
+ writer.add_scalar('{}/{}'.format(tag, k), info_dict[k], step + 1)
366
+ for k, v in loss_dict.items():
367
+ writer.add_scalar('{}/{}'.format(tag, k), v, step + 1)