export_model.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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,
  16. cache_dir: Union[Path, str] = None,
  17. onnx: bool = True,
  18. quant: bool = True,
  19. fallback_num: int = 0,
  20. ):
  21. assert check_argument_types()
  22. self.set_all_random_seed(0)
  23. if cache_dir is None:
  24. cache_dir = Path.home() / ".cache" / "export"
  25. self.cache_dir = Path(cache_dir)
  26. self.export_config = dict(
  27. feats_dim=560,
  28. onnx=False,
  29. )
  30. print("output dir: {}".format(self.cache_dir))
  31. self.onnx = onnx
  32. self.quant = quant
  33. self.fallback_num = fallback_num
  34. def _export(
  35. self,
  36. model,
  37. tag_name: str = None,
  38. verbose: bool = False,
  39. ):
  40. export_dir = self.cache_dir / tag_name.replace(' ', '-')
  41. os.makedirs(export_dir, exist_ok=True)
  42. # export encoder1
  43. self.export_config["model_name"] = "model"
  44. model = get_model(
  45. model,
  46. self.export_config,
  47. )
  48. model.eval()
  49. # self._export_onnx(model, verbose, export_dir)
  50. if self.onnx:
  51. self._export_onnx(model, verbose, export_dir)
  52. else:
  53. self._export_torchscripts(model, verbose, export_dir)
  54. print("output dir: {}".format(export_dir))
  55. def _torch_quantize(self, model):
  56. def _run_calibration_data(m):
  57. # using dummy inputs for a example
  58. dummy_input = model.get_dummy_inputs()
  59. m(*dummy_input)
  60. from torch_quant.module import ModuleFilter
  61. from torch_quant.quantizer import Backend, Quantizer
  62. from funasr.export.models.modules.decoder_layer import DecoderLayerSANM
  63. from funasr.export.models.modules.encoder_layer import EncoderLayerSANM
  64. module_filter = ModuleFilter(include_classes=[EncoderLayerSANM, DecoderLayerSANM])
  65. module_filter.exclude_op_types = [torch.nn.Conv1d]
  66. quantizer = Quantizer(
  67. module_filter=module_filter,
  68. backend=Backend.FBGEMM,
  69. )
  70. model.eval()
  71. calib_model = quantizer.calib(model)
  72. _run_calibration_data(calib_model)
  73. if self.fallback_num > 0:
  74. # perform automatic mixed precision quantization
  75. amp_model = quantizer.amp(model)
  76. _run_calibration_data(amp_model)
  77. quantizer.fallback(amp_model, num=self.fallback_num)
  78. print('Fallback layers:')
  79. print('\n'.join(quantizer.module_filter.exclude_names))
  80. quant_model = quantizer.quantize(model)
  81. return quant_model
  82. def _export_torchscripts(self, model, verbose, path, enc_size=None):
  83. if enc_size:
  84. dummy_input = model.get_dummy_inputs(enc_size)
  85. else:
  86. dummy_input = model.get_dummy_inputs()
  87. # model_script = torch.jit.script(model)
  88. model_script = torch.jit.trace(model, dummy_input)
  89. model_script.save(os.path.join(path, f'{model.model_name}.torchscripts'))
  90. if self.quant:
  91. quant_model = self._torch_quantize(model)
  92. model_script = torch.jit.trace(quant_model, dummy_input)
  93. model_script.save(os.path.join(path, f'{model.model_name}_quant.torchscripts'))
  94. def set_all_random_seed(self, seed: int):
  95. random.seed(seed)
  96. np.random.seed(seed)
  97. torch.random.manual_seed(seed)
  98. def export(self,
  99. tag_name: str = 'damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
  100. mode: str = 'paraformer',
  101. ):
  102. model_dir = tag_name
  103. if model_dir.startswith('damo/'):
  104. from modelscope.hub.snapshot_download import snapshot_download
  105. model_dir = snapshot_download(model_dir, cache_dir=self.cache_dir)
  106. asr_train_config = os.path.join(model_dir, 'config.yaml')
  107. asr_model_file = os.path.join(model_dir, 'model.pb')
  108. cmvn_file = os.path.join(model_dir, 'am.mvn')
  109. json_file = os.path.join(model_dir, 'configuration.json')
  110. if mode is None:
  111. import json
  112. with open(json_file, 'r') as f:
  113. config_data = json.load(f)
  114. mode = config_data['model']['model_config']['mode']
  115. if mode.startswith('paraformer'):
  116. from funasr.tasks.asr import ASRTaskParaformer as ASRTask
  117. elif mode.startswith('uniasr'):
  118. from funasr.tasks.asr import ASRTaskUniASR as ASRTask
  119. model, asr_train_args = ASRTask.build_model_from_file(
  120. asr_train_config, asr_model_file, cmvn_file, 'cpu'
  121. )
  122. self._export(model, tag_name)
  123. def _export_onnx(self, model, verbose, path, enc_size=None):
  124. if enc_size:
  125. dummy_input = model.get_dummy_inputs(enc_size)
  126. else:
  127. dummy_input = model.get_dummy_inputs()
  128. # model_script = torch.jit.script(model)
  129. model_script = model #torch.jit.trace(model)
  130. model_path = os.path.join(path, f'{model.model_name}.onnx')
  131. torch.onnx.export(
  132. model_script,
  133. dummy_input,
  134. model_path,
  135. verbose=verbose,
  136. opset_version=14,
  137. input_names=model.get_input_names(),
  138. output_names=model.get_output_names(),
  139. dynamic_axes=model.get_dynamic_axes()
  140. )
  141. if self.quant:
  142. from onnxruntime.quantization import QuantType, quantize_dynamic
  143. import onnx
  144. quant_model_path = os.path.join(path, f'{model.model_name}_quant.onnx')
  145. onnx_model = onnx.load(model_path)
  146. nodes = [n.name for n in onnx_model.graph.node]
  147. nodes_to_exclude = [m for m in nodes if 'output' in m]
  148. quantize_dynamic(
  149. model_input=model_path,
  150. model_output=quant_model_path,
  151. op_types_to_quantize=['MatMul'],
  152. per_channel=True,
  153. reduce_range=False,
  154. weight_type=QuantType.QUInt8,
  155. nodes_to_exclude=nodes_to_exclude,
  156. )
  157. if __name__ == '__main__':
  158. import argparse
  159. parser = argparse.ArgumentParser()
  160. parser.add_argument('--model-name', type=str, required=True)
  161. parser.add_argument('--export-dir', type=str, required=True)
  162. parser.add_argument('--type', type=str, default='onnx', help='["onnx", "torch"]')
  163. parser.add_argument('--quantize', action='store_true', help='export quantized model')
  164. parser.add_argument('--fallback-num', type=int, default=0, help='amp fallback number')
  165. args = parser.parse_args()
  166. export_model = ASRModelExportParaformer(
  167. cache_dir=args.export_dir,
  168. onnx=args.type == 'onnx',
  169. quant=args.quantize,
  170. fallback_num=args.fallback_num,
  171. )
  172. export_model.export(args.model_name)