export_model.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import json
  2. from typing import Union, Dict
  3. from pathlib import Path
  4. from typeguard import check_argument_types
  5. import os
  6. import logging
  7. import torch
  8. from funasr.export.models import get_model
  9. import numpy as np
  10. import random
  11. # torch_version = float(".".join(torch.__version__.split(".")[:2]))
  12. # assert torch_version > 1.9
  13. class ASRModelExportParaformer:
  14. def __init__(
  15. self, cache_dir: Union[Path, str] = None, onnx: bool = True, quant: bool = True
  16. ):
  17. assert check_argument_types()
  18. self.set_all_random_seed(0)
  19. if cache_dir is None:
  20. cache_dir = Path.home() / ".cache" / "export"
  21. self.cache_dir = Path(cache_dir)
  22. self.export_config = dict(
  23. feats_dim=560,
  24. onnx=False,
  25. )
  26. print("output dir: {}".format(self.cache_dir))
  27. self.onnx = onnx
  28. self.quant = quant
  29. def _export(
  30. self,
  31. model,
  32. tag_name: str = None,
  33. verbose: bool = False,
  34. ):
  35. export_dir = self.cache_dir / tag_name.replace(' ', '-')
  36. os.makedirs(export_dir, exist_ok=True)
  37. # export encoder1
  38. self.export_config["model_name"] = "model"
  39. model = get_model(
  40. model,
  41. self.export_config,
  42. )
  43. model.eval()
  44. # self._export_onnx(model, verbose, export_dir)
  45. if self.onnx:
  46. self._export_onnx(model, verbose, export_dir)
  47. else:
  48. self._export_torchscripts(model, verbose, export_dir)
  49. print("output dir: {}".format(export_dir))
  50. def _torch_quantize(self, model):
  51. from torch_quant.module import ModuleFilter
  52. from torch_quant.observer import HistogramObserver
  53. from torch_quant.quantizer import Backend, Quantizer
  54. from funasr.export.models.modules.decoder_layer import DecoderLayerSANM
  55. from funasr.export.models.modules.encoder_layer import EncoderLayerSANM
  56. module_filter = ModuleFilter(include_classes=[EncoderLayerSANM, DecoderLayerSANM])
  57. module_filter.exclude_op_types = [torch.nn.Conv1d]
  58. quantizer = Quantizer(
  59. module_filter=module_filter,
  60. backend=Backend.FBGEMM,
  61. act_ob_ctr=HistogramObserver,
  62. )
  63. model.eval()
  64. calib_model = quantizer.calib(model)
  65. # run calibration data
  66. # using dummy inputs for a example
  67. dummy_input = model.get_dummy_inputs()
  68. _ = calib_model(*dummy_input)
  69. quant_model = quantizer.quantize(model)
  70. return quant_model
  71. def _export_torchscripts(self, model, verbose, path, enc_size=None):
  72. if enc_size:
  73. dummy_input = model.get_dummy_inputs(enc_size)
  74. else:
  75. dummy_input = model.get_dummy_inputs()
  76. # model_script = torch.jit.script(model)
  77. model_script = torch.jit.trace(model, dummy_input)
  78. model_script.save(os.path.join(path, f'{model.model_name}.torchscripts'))
  79. if self.quant:
  80. quant_model = self._torch_quantize(model)
  81. model_script = torch.jit.trace(quant_model, dummy_input)
  82. model_script.save(os.path.join(path, f'{model.model_name}_quant.torchscripts'))
  83. def set_all_random_seed(self, seed: int):
  84. random.seed(seed)
  85. np.random.seed(seed)
  86. torch.random.manual_seed(seed)
  87. def export(self,
  88. tag_name: str = 'damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
  89. mode: str = 'paraformer',
  90. ):
  91. model_dir = tag_name
  92. if model_dir.startswith('damo/'):
  93. from modelscope.hub.snapshot_download import snapshot_download
  94. model_dir = snapshot_download(model_dir, cache_dir=self.cache_dir)
  95. asr_train_config = os.path.join(model_dir, 'config.yaml')
  96. asr_model_file = os.path.join(model_dir, 'model.pb')
  97. cmvn_file = os.path.join(model_dir, 'am.mvn')
  98. json_file = os.path.join(model_dir, 'configuration.json')
  99. if mode is None:
  100. import json
  101. with open(json_file, 'r') as f:
  102. config_data = json.load(f)
  103. mode = config_data['model']['model_config']['mode']
  104. if mode.startswith('paraformer'):
  105. from funasr.tasks.asr import ASRTaskParaformer as ASRTask
  106. elif mode.startswith('uniasr'):
  107. from funasr.tasks.asr import ASRTaskUniASR as ASRTask
  108. model, asr_train_args = ASRTask.build_model_from_file(
  109. asr_train_config, asr_model_file, cmvn_file, 'cpu'
  110. )
  111. self._export(model, tag_name)
  112. def _export_onnx(self, model, verbose, path, enc_size=None):
  113. if enc_size:
  114. dummy_input = model.get_dummy_inputs(enc_size)
  115. else:
  116. dummy_input = model.get_dummy_inputs()
  117. # model_script = torch.jit.script(model)
  118. model_script = model #torch.jit.trace(model)
  119. model_path = os.path.join(path, f'{model.model_name}.onnx')
  120. torch.onnx.export(
  121. model_script,
  122. dummy_input,
  123. model_path,
  124. verbose=verbose,
  125. opset_version=14,
  126. input_names=model.get_input_names(),
  127. output_names=model.get_output_names(),
  128. dynamic_axes=model.get_dynamic_axes()
  129. )
  130. if self.quant:
  131. from onnxruntime.quantization import QuantType, quantize_dynamic
  132. quant_model_path = os.path.join(path, f'{model.model_name}_quant.onnx')
  133. quantize_dynamic(
  134. model_input=model_path,
  135. model_output=quant_model_path,
  136. weight_type=QuantType.QUInt8,
  137. )
  138. if __name__ == '__main__':
  139. import sys
  140. model_path = sys.argv[1]
  141. output_dir = sys.argv[2]
  142. onnx = sys.argv[3]
  143. quant = sys.argv[4]
  144. onnx = onnx.lower()
  145. onnx = onnx == 'true'
  146. quant = quant == 'true'
  147. # model_path = 'damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch'
  148. # output_dir = "../export"
  149. export_model = ASRModelExportParaformer(cache_dir=output_dir, onnx=onnx, quant=quant)
  150. export_model.export(model_path)
  151. # export_model.export('/root/cache/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch')