export_jit.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. from __future__ import print_function
  15. import argparse
  16. import logging
  17. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  18. import os
  19. import sys
  20. import torch
  21. ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
  22. sys.path.append('{}/../..'.format(ROOT_DIR))
  23. sys.path.append('{}/../../third_party/Matcha-TTS'.format(ROOT_DIR))
  24. from cosyvoice.cli.cosyvoice import CosyVoice
  25. def get_args():
  26. parser = argparse.ArgumentParser(description='export your model for deployment')
  27. parser.add_argument('--model_dir',
  28. type=str,
  29. default='pretrained_models/CosyVoice-300M',
  30. help='local path')
  31. args = parser.parse_args()
  32. print(args)
  33. return args
  34. def main():
  35. args = get_args()
  36. logging.basicConfig(level=logging.DEBUG,
  37. format='%(asctime)s %(levelname)s %(message)s')
  38. torch._C._jit_set_fusion_strategy([('STATIC', 1)])
  39. torch._C._jit_set_profiling_mode(False)
  40. torch._C._jit_set_profiling_executor(False)
  41. cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_onnx=False)
  42. # 1. export llm text_encoder
  43. llm_text_encoder = cosyvoice.model.llm.text_encoder.half()
  44. script = torch.jit.script(llm_text_encoder)
  45. script = torch.jit.freeze(script)
  46. script = torch.jit.optimize_for_inference(script)
  47. script.save('{}/llm.text_encoder.fp16.zip'.format(args.model_dir))
  48. # 2. export llm llm
  49. llm_llm = cosyvoice.model.llm.llm.half()
  50. script = torch.jit.script(llm_llm)
  51. script = torch.jit.freeze(script, preserved_attrs=['forward_chunk'])
  52. script = torch.jit.optimize_for_inference(script)
  53. script.save('{}/llm.llm.fp16.zip'.format(args.model_dir))
  54. # 3. export flow encoder
  55. flow_encoder = cosyvoice.model.flow.encoder
  56. script = torch.jit.script(flow_encoder)
  57. script = torch.jit.freeze(script)
  58. script = torch.jit.optimize_for_inference(script)
  59. script.save('{}/flow.encoder.fp32.zip'.format(args.model_dir))
  60. if __name__ == '__main__':
  61. main()