export_model.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. from typing import Union, Dict
  2. from pathlib import Path
  3. from typeguard import check_argument_types
  4. import os
  5. import logging
  6. import torch
  7. from funasr.bin.asr_inference_paraformer import Speech2Text
  8. from funasr.export.models import get_model
  9. class ASRModelExportParaformer:
  10. def __init__(self, cache_dir: Union[Path, str] = None, onnx: bool = True):
  11. assert check_argument_types()
  12. if cache_dir is None:
  13. cache_dir = Path.home() / "cache" / "export"
  14. self.cache_dir = Path(cache_dir)
  15. self.export_config = dict(
  16. feats_dim=560,
  17. onnx=False,
  18. )
  19. logging.info("output dir: {}".format(self.cache_dir))
  20. self.onnx = onnx
  21. def export(
  22. self,
  23. model: Speech2Text,
  24. tag_name: str = None,
  25. verbose: bool = False,
  26. ):
  27. export_dir = self.cache_dir / tag_name.replace(' ', '-')
  28. os.makedirs(export_dir, exist_ok=True)
  29. # export encoder1
  30. self.export_config["model_name"] = "model"
  31. model = get_model(
  32. model,
  33. self.export_config,
  34. )
  35. self._export_onnx(model, verbose, export_dir)
  36. if self.onnx:
  37. self._export_onnx(model, verbose, export_dir)
  38. else:
  39. self._export_torchscripts(model, verbose, export_dir)
  40. logging.info("output dir: {}".format(export_dir))
  41. def _export_torchscripts(self, model, verbose, path, enc_size=None):
  42. if enc_size:
  43. dummy_input = model.get_dummy_inputs(enc_size)
  44. else:
  45. dummy_input = model.get_dummy_inputs_txt()
  46. # model_script = torch.jit.script(model)
  47. model_script = torch.jit.trace(model, dummy_input)
  48. model_script.save(os.path.join(path, f'{model.model_name}.torchscripts'))
  49. def export_from_modelscope(
  50. self,
  51. tag_name: str = 'damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
  52. ):
  53. from funasr.tasks.asr import ASRTaskParaformer as ASRTask
  54. from modelscope.hub.snapshot_download import snapshot_download
  55. model_dir = snapshot_download(tag_name, cache_dir=self.cache_dir)
  56. asr_train_config = os.path.join(model_dir, 'config.yaml')
  57. asr_model_file = os.path.join(model_dir, 'model.pb')
  58. cmvn_file = os.path.join(model_dir, 'am.mvn')
  59. model, asr_train_args = ASRTask.build_model_from_file(
  60. asr_train_config, asr_model_file, cmvn_file, 'cpu'
  61. )
  62. self.export(model, tag_name)
  63. def export_from_local(
  64. self,
  65. tag_name: str = '/root/cache/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
  66. ):
  67. from funasr.tasks.asr import ASRTaskParaformer as ASRTask
  68. model_dir = tag_name
  69. asr_train_config = os.path.join(model_dir, 'config.yaml')
  70. asr_model_file = os.path.join(model_dir, 'model.pb')
  71. cmvn_file = os.path.join(model_dir, 'am.mvn')
  72. model, asr_train_args = ASRTask.build_model_from_file(
  73. asr_train_config, asr_model_file, cmvn_file, 'cpu'
  74. )
  75. self.export(model, tag_name)
  76. def _export_onnx(self, model, verbose, path, enc_size=None):
  77. if enc_size:
  78. dummy_input = model.get_dummy_inputs(enc_size)
  79. else:
  80. dummy_input = model.get_dummy_inputs()
  81. # model_script = torch.jit.script(model)
  82. model_script = model #torch.jit.trace(model)
  83. torch.onnx.export(
  84. model_script,
  85. dummy_input,
  86. os.path.join(path, f'{model.model_name}.onnx'),
  87. verbose=verbose,
  88. opset_version=12,
  89. input_names=model.get_input_names(),
  90. output_names=model.get_output_names(),
  91. dynamic_axes=model.get_dynamic_axes()
  92. )
  93. if __name__ == '__main__':
  94. output_dir = "../export"
  95. export_model = ASRModelExportParaformer(cache_dir=output_dir, onnx=False)
  96. export_model.export_from_modelscope('damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch')
  97. # export_model.export_from_local('/root/cache/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch')