minicpmo-utils 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. cosyvoice/__init__.py +17 -0
  2. cosyvoice/bin/average_model.py +93 -0
  3. cosyvoice/bin/export_jit.py +103 -0
  4. cosyvoice/bin/export_onnx.py +120 -0
  5. cosyvoice/bin/inference_deprecated.py +126 -0
  6. cosyvoice/bin/train.py +195 -0
  7. cosyvoice/cli/__init__.py +0 -0
  8. cosyvoice/cli/cosyvoice.py +209 -0
  9. cosyvoice/cli/frontend.py +238 -0
  10. cosyvoice/cli/model.py +386 -0
  11. cosyvoice/dataset/__init__.py +0 -0
  12. cosyvoice/dataset/dataset.py +151 -0
  13. cosyvoice/dataset/processor.py +434 -0
  14. cosyvoice/flow/decoder.py +494 -0
  15. cosyvoice/flow/flow.py +281 -0
  16. cosyvoice/flow/flow_matching.py +227 -0
  17. cosyvoice/flow/length_regulator.py +70 -0
  18. cosyvoice/hifigan/discriminator.py +230 -0
  19. cosyvoice/hifigan/f0_predictor.py +58 -0
  20. cosyvoice/hifigan/generator.py +582 -0
  21. cosyvoice/hifigan/hifigan.py +67 -0
  22. cosyvoice/llm/llm.py +610 -0
  23. cosyvoice/tokenizer/assets/multilingual_zh_ja_yue_char_del.tiktoken +58836 -0
  24. cosyvoice/tokenizer/tokenizer.py +279 -0
  25. cosyvoice/transformer/__init__.py +0 -0
  26. cosyvoice/transformer/activation.py +84 -0
  27. cosyvoice/transformer/attention.py +330 -0
  28. cosyvoice/transformer/convolution.py +145 -0
  29. cosyvoice/transformer/decoder.py +396 -0
  30. cosyvoice/transformer/decoder_layer.py +132 -0
  31. cosyvoice/transformer/embedding.py +302 -0
  32. cosyvoice/transformer/encoder.py +474 -0
  33. cosyvoice/transformer/encoder_layer.py +236 -0
  34. cosyvoice/transformer/label_smoothing_loss.py +96 -0
  35. cosyvoice/transformer/positionwise_feed_forward.py +115 -0
  36. cosyvoice/transformer/subsampling.py +383 -0
  37. cosyvoice/transformer/upsample_encoder.py +320 -0
  38. cosyvoice/utils/__init__.py +0 -0
  39. cosyvoice/utils/class_utils.py +83 -0
  40. cosyvoice/utils/common.py +186 -0
  41. cosyvoice/utils/executor.py +176 -0
  42. cosyvoice/utils/file_utils.py +129 -0
  43. cosyvoice/utils/frontend_utils.py +136 -0
  44. cosyvoice/utils/losses.py +57 -0
  45. cosyvoice/utils/mask.py +265 -0
  46. cosyvoice/utils/scheduler.py +738 -0
  47. cosyvoice/utils/train_utils.py +367 -0
  48. cosyvoice/vllm/cosyvoice2.py +103 -0
  49. matcha/__init__.py +0 -0
  50. matcha/app.py +357 -0
  51. matcha/cli.py +418 -0
  52. matcha/hifigan/__init__.py +0 -0
  53. matcha/hifigan/config.py +28 -0
  54. matcha/hifigan/denoiser.py +64 -0
  55. matcha/hifigan/env.py +17 -0
  56. matcha/hifigan/meldataset.py +217 -0
  57. matcha/hifigan/models.py +368 -0
  58. matcha/hifigan/xutils.py +60 -0
  59. matcha/models/__init__.py +0 -0
  60. matcha/models/baselightningmodule.py +209 -0
  61. matcha/models/components/__init__.py +0 -0
  62. matcha/models/components/decoder.py +443 -0
  63. matcha/models/components/flow_matching.py +132 -0
  64. matcha/models/components/text_encoder.py +410 -0
  65. matcha/models/components/transformer.py +316 -0
  66. matcha/models/matcha_tts.py +239 -0
  67. matcha/onnx/__init__.py +0 -0
  68. matcha/onnx/export.py +181 -0
  69. matcha/onnx/infer.py +168 -0
  70. matcha/text/__init__.py +53 -0
  71. matcha/text/cleaners.py +116 -0
  72. matcha/text/numbers.py +71 -0
  73. matcha/text/symbols.py +17 -0
  74. matcha/train.py +122 -0
  75. matcha/utils/__init__.py +5 -0
  76. matcha/utils/audio.py +82 -0
  77. matcha/utils/generate_data_statistics.py +111 -0
  78. matcha/utils/instantiators.py +56 -0
  79. matcha/utils/logging_utils.py +53 -0
  80. matcha/utils/model.py +90 -0
  81. matcha/utils/monotonic_align/__init__.py +22 -0
  82. matcha/utils/monotonic_align/setup.py +7 -0
  83. matcha/utils/pylogger.py +21 -0
  84. matcha/utils/rich_utils.py +101 -0
  85. matcha/utils/utils.py +219 -0
  86. minicpmo/__init__.py +24 -0
  87. minicpmo/utils.py +636 -0
  88. minicpmo/version.py +2 -0
  89. minicpmo_utils-0.1.0.dist-info/METADATA +72 -0
  90. minicpmo_utils-0.1.0.dist-info/RECORD +148 -0
  91. minicpmo_utils-0.1.0.dist-info/WHEEL +5 -0
  92. minicpmo_utils-0.1.0.dist-info/top_level.txt +5 -0
  93. s3tokenizer/__init__.py +153 -0
  94. s3tokenizer/assets/BAC009S0764W0121.wav +0 -0
  95. s3tokenizer/assets/BAC009S0764W0122.wav +0 -0
  96. s3tokenizer/assets/mel_filters.npz +0 -0
  97. s3tokenizer/cli.py +183 -0
  98. s3tokenizer/model.py +546 -0
  99. s3tokenizer/model_v2.py +605 -0
  100. s3tokenizer/utils.py +390 -0
  101. stepaudio2/__init__.py +40 -0
  102. stepaudio2/cosyvoice2/__init__.py +1 -0
  103. stepaudio2/cosyvoice2/flow/__init__.py +0 -0
  104. stepaudio2/cosyvoice2/flow/decoder_dit.py +585 -0
  105. stepaudio2/cosyvoice2/flow/flow.py +230 -0
  106. stepaudio2/cosyvoice2/flow/flow_matching.py +205 -0
  107. stepaudio2/cosyvoice2/transformer/__init__.py +0 -0
  108. stepaudio2/cosyvoice2/transformer/attention.py +328 -0
  109. stepaudio2/cosyvoice2/transformer/embedding.py +119 -0
  110. stepaudio2/cosyvoice2/transformer/encoder_layer.py +163 -0
  111. stepaudio2/cosyvoice2/transformer/positionwise_feed_forward.py +56 -0
  112. stepaudio2/cosyvoice2/transformer/subsampling.py +79 -0
  113. stepaudio2/cosyvoice2/transformer/upsample_encoder_v2.py +483 -0
  114. stepaudio2/cosyvoice2/utils/__init__.py +1 -0
  115. stepaudio2/cosyvoice2/utils/class_utils.py +41 -0
  116. stepaudio2/cosyvoice2/utils/common.py +101 -0
  117. stepaudio2/cosyvoice2/utils/mask.py +49 -0
  118. stepaudio2/flashcosyvoice/__init__.py +0 -0
  119. stepaudio2/flashcosyvoice/cli.py +424 -0
  120. stepaudio2/flashcosyvoice/config.py +80 -0
  121. stepaudio2/flashcosyvoice/cosyvoice2.py +160 -0
  122. stepaudio2/flashcosyvoice/cosyvoice3.py +1 -0
  123. stepaudio2/flashcosyvoice/engine/__init__.py +0 -0
  124. stepaudio2/flashcosyvoice/engine/block_manager.py +114 -0
  125. stepaudio2/flashcosyvoice/engine/llm_engine.py +125 -0
  126. stepaudio2/flashcosyvoice/engine/model_runner.py +310 -0
  127. stepaudio2/flashcosyvoice/engine/scheduler.py +77 -0
  128. stepaudio2/flashcosyvoice/engine/sequence.py +90 -0
  129. stepaudio2/flashcosyvoice/modules/__init__.py +0 -0
  130. stepaudio2/flashcosyvoice/modules/flow.py +198 -0
  131. stepaudio2/flashcosyvoice/modules/flow_components/__init__.py +0 -0
  132. stepaudio2/flashcosyvoice/modules/flow_components/estimator.py +974 -0
  133. stepaudio2/flashcosyvoice/modules/flow_components/upsample_encoder.py +998 -0
  134. stepaudio2/flashcosyvoice/modules/hifigan.py +249 -0
  135. stepaudio2/flashcosyvoice/modules/hifigan_components/__init__.py +0 -0
  136. stepaudio2/flashcosyvoice/modules/hifigan_components/layers.py +433 -0
  137. stepaudio2/flashcosyvoice/modules/qwen2.py +92 -0
  138. stepaudio2/flashcosyvoice/modules/qwen2_components/__init__.py +0 -0
  139. stepaudio2/flashcosyvoice/modules/qwen2_components/layers.py +616 -0
  140. stepaudio2/flashcosyvoice/modules/sampler.py +231 -0
  141. stepaudio2/flashcosyvoice/utils/__init__.py +0 -0
  142. stepaudio2/flashcosyvoice/utils/audio.py +77 -0
  143. stepaudio2/flashcosyvoice/utils/context.py +28 -0
  144. stepaudio2/flashcosyvoice/utils/loader.py +116 -0
  145. stepaudio2/flashcosyvoice/utils/memory.py +19 -0
  146. stepaudio2/stepaudio2.py +204 -0
  147. stepaudio2/token2wav.py +248 -0
  148. stepaudio2/utils.py +91 -0
@@ -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='train', 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"] = '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'])
168
+ elif configs['train_conf']['optim_d'] == 'adamw':
169
+ optimizer_d = optim.AdamW(model.module.discriminator.parameters(), **configs['train_conf']['optim_conf'])
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_conf'])
176
+ elif configs['train_conf']['scheduler_d'] == 'NoamHoldAnnealing':
177
+ scheduler_type = NoamHoldAnnealing
178
+ scheduler_d = NoamHoldAnnealing(optimizer_d, **configs['train_conf']['scheduler_conf'])
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)
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)
@@ -0,0 +1,103 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+
3
+ # Adapted from
4
+ # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/qwen2/modeling_qwen2.py
5
+ # Copyright 2024 The Qwen team.
6
+ # Copyright 2023 The vLLM team.
7
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
10
+ # and OPT implementations in this library. It has been modified from its
11
+ # original forms to accommodate minor architectural differences compared
12
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
13
+ #
14
+ # Licensed under the Apache License, Version 2.0 (the "License");
15
+ # you may not use this file except in compliance with the License.
16
+ # You may obtain a copy of the License at
17
+ #
18
+ # http://www.apache.org/licenses/LICENSE-2.0
19
+ #
20
+ # Unless required by applicable law or agreed to in writing, software
21
+ # distributed under the License is distributed on an "AS IS" BASIS,
22
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ # See the License for the specific language governing permissions and
24
+ # limitations under the License.
25
+ """Inference-only Qwen2 model compatible with HuggingFace weights."""
26
+ from vllm.model_executor.models.qwen2 import *
27
+
28
+
29
+ class CosyVoice2ForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
30
+ packed_modules_mapping = {
31
+ "qkv_proj": [
32
+ "q_proj",
33
+ "k_proj",
34
+ "v_proj",
35
+ ],
36
+ "gate_up_proj": [
37
+ "gate_proj",
38
+ "up_proj",
39
+ ],
40
+ }
41
+
42
+ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
43
+ super().__init__()
44
+ config = vllm_config.model_config.hf_config
45
+ quant_config = vllm_config.quant_config
46
+ lora_config = vllm_config.lora_config
47
+
48
+ self.config = config
49
+ self.lora_config = lora_config
50
+
51
+ self.quant_config = quant_config
52
+ self.model = Qwen2Model(vllm_config=vllm_config,
53
+ prefix=maybe_prefix(prefix, "model"))
54
+
55
+ if get_pp_group().is_last_rank:
56
+ if config.tie_word_embeddings:
57
+ self.lm_head = self.model.embed_tokens
58
+ else:
59
+ self.lm_head = ParallelLMHead(config.vocab_size,
60
+ config.hidden_size,
61
+ True,
62
+ quant_config=quant_config,
63
+ prefix=maybe_prefix(
64
+ prefix, "lm_head"))
65
+ else:
66
+ self.lm_head = PPMissingLayer()
67
+
68
+ self.logits_processor = LogitsProcessor(config.vocab_size)
69
+
70
+ self.make_empty_intermediate_tensors = (
71
+ self.model.make_empty_intermediate_tensors)
72
+
73
+ def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
74
+ return self.model.get_input_embeddings(input_ids)
75
+
76
+ def forward(
77
+ self,
78
+ input_ids: torch.Tensor,
79
+ positions: torch.Tensor,
80
+ intermediate_tensors: Optional[IntermediateTensors] = None,
81
+ inputs_embeds: Optional[torch.Tensor] = None,
82
+ ) -> Union[torch.Tensor, IntermediateTensors]:
83
+ hidden_states = self.model(input_ids, positions, intermediate_tensors,
84
+ inputs_embeds)
85
+ return hidden_states
86
+
87
+ def compute_logits(
88
+ self,
89
+ hidden_states: torch.Tensor,
90
+ sampling_metadata: SamplingMetadata,
91
+ ) -> Optional[torch.Tensor]:
92
+ logits = self.logits_processor(self.lm_head, hidden_states,
93
+ sampling_metadata, self.lm_head.bias)
94
+ return logits
95
+
96
+ def load_weights(self, weights: Iterable[tuple[str,
97
+ torch.Tensor]]) -> set[str]:
98
+ loader = AutoWeightsLoader(
99
+ self,
100
+ skip_prefixes=(["lm_head."]
101
+ if self.config.tie_word_embeddings else None),
102
+ )
103
+ return loader.load_weights(weights)
matcha/__init__.py ADDED
File without changes