export_onnx.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. from __future__ import print_function
  16. import argparse
  17. import logging
  18. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  19. import os
  20. import sys
  21. import onnxruntime
  22. import random
  23. import torch
  24. from tqdm import tqdm
  25. ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
  26. sys.path.append('{}/../..'.format(ROOT_DIR))
  27. sys.path.append('{}/../../third_party/Matcha-TTS'.format(ROOT_DIR))
  28. from cosyvoice.cli.cosyvoice import CosyVoice, CosyVoice2
  29. def get_dummy_input(batch_size, seq_len, out_channels, device):
  30. x = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
  31. mask = torch.ones((batch_size, 1, seq_len), dtype=torch.float32, device=device)
  32. mu = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
  33. t = torch.rand((batch_size), dtype=torch.float32, device=device)
  34. spks = torch.rand((batch_size, out_channels), dtype=torch.float32, device=device)
  35. cond = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
  36. return x, mask, mu, t, spks, cond
  37. def get_args():
  38. parser = argparse.ArgumentParser(description='export your model for deployment')
  39. parser.add_argument('--model_dir',
  40. type=str,
  41. default='pretrained_models/CosyVoice-300M',
  42. help='local path')
  43. args = parser.parse_args()
  44. print(args)
  45. return args
  46. def main():
  47. args = get_args()
  48. logging.basicConfig(level=logging.DEBUG,
  49. format='%(asctime)s %(levelname)s %(message)s')
  50. try:
  51. model = CosyVoice(args.model_dir)
  52. except Exception:
  53. try:
  54. model = CosyVoice2(args.model_dir)
  55. except Exception:
  56. raise TypeError('no valid model_type!')
  57. # 1. export flow decoder estimator
  58. estimator = model.model.flow.decoder.estimator
  59. device = model.model.device
  60. batch_size, seq_len = 2, 256
  61. out_channels = model.model.flow.decoder.estimator.out_channels
  62. x, mask, mu, t, spks, cond = get_dummy_input(batch_size, seq_len, out_channels, device)
  63. torch.onnx.export(
  64. estimator,
  65. (x, mask, mu, t, spks, cond),
  66. '{}/flow.decoder.estimator.fp32.onnx'.format(args.model_dir),
  67. export_params=True,
  68. opset_version=18,
  69. do_constant_folding=True,
  70. input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
  71. output_names=['estimator_out'],
  72. dynamic_axes={
  73. 'x': {2: 'seq_len'},
  74. 'mask': {2: 'seq_len'},
  75. 'mu': {2: 'seq_len'},
  76. 'cond': {2: 'seq_len'},
  77. 'estimator_out': {2: 'seq_len'},
  78. }
  79. )
  80. # 2. test computation consistency
  81. option = onnxruntime.SessionOptions()
  82. option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
  83. option.intra_op_num_threads = 1
  84. providers = ['CUDAExecutionProvider' if torch.cuda.is_available() else 'CPUExecutionProvider']
  85. estimator_onnx = onnxruntime.InferenceSession('{}/flow.decoder.estimator.fp32.onnx'.format(args.model_dir),
  86. sess_options=option, providers=providers)
  87. for _ in tqdm(range(10)):
  88. x, mask, mu, t, spks, cond = get_dummy_input(batch_size, random.randint(16, 512), out_channels, device)
  89. output_pytorch = estimator(x, mask, mu, t, spks, cond)
  90. ort_inputs = {
  91. 'x': x.cpu().numpy(),
  92. 'mask': mask.cpu().numpy(),
  93. 'mu': mu.cpu().numpy(),
  94. 't': t.cpu().numpy(),
  95. 'spks': spks.cpu().numpy(),
  96. 'cond': cond.cpu().numpy()
  97. }
  98. output_onnx = estimator_onnx.run(None, ort_inputs)[0]
  99. torch.testing.assert_allclose(output_pytorch, torch.from_numpy(output_onnx).to(device), rtol=1e-2, atol=1e-4)
  100. if __name__ == "__main__":
  101. main()