export_model.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import json
  2. from typing import Union, Dict
  3. from pathlib import Path
  4. import os
  5. import logging
  6. import torch
  7. from funasr.export.models import get_model
  8. import numpy as np
  9. import random
  10. from funasr.utils.types import str2bool, str2triple_str
  11. # torch_version = float(".".join(torch.__version__.split(".")[:2]))
  12. # assert torch_version > 1.9
  13. class ModelExport:
  14. def __init__(
  15. self,
  16. cache_dir: Union[Path, str] = None,
  17. onnx: bool = True,
  18. device: str = "cpu",
  19. quant: bool = True,
  20. fallback_num: int = 0,
  21. audio_in: str = None,
  22. calib_num: int = 200,
  23. model_revision: str = None,
  24. ):
  25. self.set_all_random_seed(0)
  26. self.cache_dir = cache_dir
  27. self.export_config = dict(
  28. feats_dim=560,
  29. onnx=False,
  30. )
  31. self.onnx = onnx
  32. self.device = device
  33. self.quant = quant
  34. self.fallback_num = fallback_num
  35. self.frontend = None
  36. self.audio_in = audio_in
  37. self.calib_num = calib_num
  38. self.model_revision = model_revision
  39. def _export(
  40. self,
  41. model,
  42. tag_name: str = None,
  43. verbose: bool = False,
  44. ):
  45. export_dir = self.cache_dir
  46. os.makedirs(export_dir, exist_ok=True)
  47. # export encoder1
  48. self.export_config["model_name"] = "model"
  49. models = get_model(
  50. model,
  51. self.export_config,
  52. )
  53. if not isinstance(models, tuple):
  54. models = (models,)
  55. for i, model in enumerate(models):
  56. model.eval()
  57. if self.onnx:
  58. self._export_onnx(model, verbose, export_dir)
  59. else:
  60. self._export_torchscripts(model, verbose, export_dir)
  61. print("output dir: {}".format(export_dir))
  62. def _torch_quantize(self, model):
  63. def _run_calibration_data(m):
  64. # using dummy inputs for a example
  65. if self.audio_in is not None:
  66. feats, feats_len = self.load_feats(self.audio_in)
  67. for i, (feat, len) in enumerate(zip(feats, feats_len)):
  68. with torch.no_grad():
  69. m(feat, len)
  70. else:
  71. dummy_input = model.get_dummy_inputs()
  72. m(*dummy_input)
  73. from torch_quant.module import ModuleFilter
  74. from torch_quant.quantizer import Backend, Quantizer
  75. from funasr.export.models.modules.decoder_layer import DecoderLayerSANM
  76. from funasr.export.models.modules.encoder_layer import EncoderLayerSANM
  77. module_filter = ModuleFilter(include_classes=[EncoderLayerSANM, DecoderLayerSANM])
  78. module_filter.exclude_op_types = [torch.nn.Conv1d]
  79. quantizer = Quantizer(
  80. module_filter=module_filter,
  81. backend=Backend.FBGEMM,
  82. )
  83. model.eval()
  84. calib_model = quantizer.calib(model)
  85. _run_calibration_data(calib_model)
  86. if self.fallback_num > 0:
  87. # perform automatic mixed precision quantization
  88. amp_model = quantizer.amp(model)
  89. _run_calibration_data(amp_model)
  90. quantizer.fallback(amp_model, num=self.fallback_num)
  91. print('Fallback layers:')
  92. print('\n'.join(quantizer.module_filter.exclude_names))
  93. quant_model = quantizer.quantize(model)
  94. return quant_model
  95. def _export_torchscripts(self, model, verbose, path, enc_size=None):
  96. if enc_size:
  97. dummy_input = model.get_dummy_inputs(enc_size)
  98. else:
  99. dummy_input = model.get_dummy_inputs()
  100. if self.device == 'cuda':
  101. model = model.cuda()
  102. dummy_input = tuple([i.cuda() for i in dummy_input])
  103. # model_script = torch.jit.script(model)
  104. model_script = torch.jit.trace(model, dummy_input)
  105. model_script.save(os.path.join(path, f'{model.model_name}.torchscripts'))
  106. if self.quant:
  107. quant_model = self._torch_quantize(model)
  108. model_script = torch.jit.trace(quant_model, dummy_input)
  109. model_script.save(os.path.join(path, f'{model.model_name}_quant.torchscripts'))
  110. def set_all_random_seed(self, seed: int):
  111. random.seed(seed)
  112. np.random.seed(seed)
  113. torch.random.manual_seed(seed)
  114. def parse_audio_in(self, audio_in):
  115. wav_list, name_list = [], []
  116. if audio_in.endswith(".scp"):
  117. f = open(audio_in, 'r')
  118. lines = f.readlines()[:self.calib_num]
  119. for line in lines:
  120. name, path = line.strip().split()
  121. name_list.append(name)
  122. wav_list.append(path)
  123. else:
  124. wav_list = [audio_in,]
  125. name_list = ["test",]
  126. return wav_list, name_list
  127. def load_feats(self, audio_in: str = None):
  128. import torchaudio
  129. wav_list, name_list = self.parse_audio_in(audio_in)
  130. feats = []
  131. feats_len = []
  132. for line in wav_list:
  133. path = line.strip()
  134. waveform, sampling_rate = torchaudio.load(path)
  135. if sampling_rate != self.frontend.fs:
  136. waveform = torchaudio.transforms.Resample(orig_freq=sampling_rate,
  137. new_freq=self.frontend.fs)(waveform)
  138. fbank, fbank_len = self.frontend(waveform, [waveform.size(1)])
  139. feats.append(fbank)
  140. feats_len.append(fbank_len)
  141. return feats, feats_len
  142. def export(self,
  143. tag_name: str = 'damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
  144. mode: str = None,
  145. ):
  146. model_dir = tag_name
  147. if model_dir.startswith('damo'):
  148. from modelscope.hub.snapshot_download import snapshot_download
  149. model_dir = snapshot_download(model_dir, cache_dir=self.cache_dir, revision=self.model_revision)
  150. self.cache_dir = model_dir
  151. if mode is None:
  152. import json
  153. json_file = os.path.join(model_dir, 'configuration.json')
  154. with open(json_file, 'r') as f:
  155. config_data = json.load(f)
  156. if config_data['task'] == "punctuation":
  157. mode = config_data['model']['punc_model_config']['mode']
  158. else:
  159. mode = config_data['model']['model_config']['mode']
  160. if mode.startswith('paraformer'):
  161. from funasr.tasks.asr import ASRTaskParaformer as ASRTask
  162. config = os.path.join(model_dir, 'config.yaml')
  163. model_file = os.path.join(model_dir, 'model.pb')
  164. cmvn_file = os.path.join(model_dir, 'am.mvn')
  165. model, asr_train_args = ASRTask.build_model_from_file(
  166. config, model_file, cmvn_file, 'cpu'
  167. )
  168. self.frontend = model.frontend
  169. self.export_config["feats_dim"] = 560
  170. elif mode.startswith('offline'):
  171. from funasr.tasks.vad import VADTask
  172. config = os.path.join(model_dir, 'vad.yaml')
  173. model_file = os.path.join(model_dir, 'vad.pb')
  174. cmvn_file = os.path.join(model_dir, 'vad.mvn')
  175. model, vad_infer_args = VADTask.build_model_from_file(
  176. config, model_file, cmvn_file=cmvn_file, device='cpu'
  177. )
  178. self.export_config["feats_dim"] = 400
  179. self.frontend = model.frontend
  180. elif mode.startswith('punc'):
  181. from funasr.tasks.punctuation import PunctuationTask as PUNCTask
  182. punc_train_config = os.path.join(model_dir, 'config.yaml')
  183. punc_model_file = os.path.join(model_dir, 'punc.pb')
  184. model, punc_train_args = PUNCTask.build_model_from_file(
  185. punc_train_config, punc_model_file, 'cpu'
  186. )
  187. elif mode.startswith('punc_VadRealtime'):
  188. from funasr.tasks.punctuation import PunctuationTask as PUNCTask
  189. punc_train_config = os.path.join(model_dir, 'config.yaml')
  190. punc_model_file = os.path.join(model_dir, 'punc.pb')
  191. model, punc_train_args = PUNCTask.build_model_from_file(
  192. punc_train_config, punc_model_file, 'cpu'
  193. )
  194. self._export(model, tag_name)
  195. def _export_onnx(self, model, verbose, path, enc_size=None):
  196. if enc_size:
  197. dummy_input = model.get_dummy_inputs(enc_size)
  198. else:
  199. dummy_input = model.get_dummy_inputs()
  200. # model_script = torch.jit.script(model)
  201. model_script = model #torch.jit.trace(model)
  202. model_path = os.path.join(path, f'{model.model_name}.onnx')
  203. if not os.path.exists(model_path):
  204. torch.onnx.export(
  205. model_script,
  206. dummy_input,
  207. model_path,
  208. verbose=verbose,
  209. opset_version=14,
  210. input_names=model.get_input_names(),
  211. output_names=model.get_output_names(),
  212. dynamic_axes=model.get_dynamic_axes()
  213. )
  214. if self.quant:
  215. from onnxruntime.quantization import QuantType, quantize_dynamic
  216. import onnx
  217. quant_model_path = os.path.join(path, f'{model.model_name}_quant.onnx')
  218. if not os.path.exists(quant_model_path):
  219. onnx_model = onnx.load(model_path)
  220. nodes = [n.name for n in onnx_model.graph.node]
  221. nodes_to_exclude = [m for m in nodes if 'output' in m]
  222. quantize_dynamic(
  223. model_input=model_path,
  224. model_output=quant_model_path,
  225. op_types_to_quantize=['MatMul'],
  226. per_channel=True,
  227. reduce_range=False,
  228. weight_type=QuantType.QUInt8,
  229. nodes_to_exclude=nodes_to_exclude,
  230. )
  231. if __name__ == '__main__':
  232. import argparse
  233. parser = argparse.ArgumentParser()
  234. # parser.add_argument('--model-name', type=str, required=True)
  235. parser.add_argument('--model-name', type=str, action="append", required=True, default=[])
  236. parser.add_argument('--export-dir', type=str, required=True)
  237. parser.add_argument('--type', type=str, default='onnx', help='["onnx", "torch"]')
  238. parser.add_argument('--device', type=str, default='cpu', help='["cpu", "cuda"]')
  239. parser.add_argument('--quantize', type=str2bool, default=False, help='export quantized model')
  240. parser.add_argument('--fallback-num', type=int, default=0, help='amp fallback number')
  241. parser.add_argument('--audio_in', type=str, default=None, help='["wav", "wav.scp"]')
  242. parser.add_argument('--calib_num', type=int, default=200, help='calib max num')
  243. parser.add_argument('--model_revision', type=str, default=None, help='model_revision')
  244. args = parser.parse_args()
  245. export_model = ModelExport(
  246. cache_dir=args.export_dir,
  247. onnx=args.type == 'onnx',
  248. device=args.device,
  249. quant=args.quantize,
  250. fallback_num=args.fallback_num,
  251. audio_in=args.audio_in,
  252. calib_num=args.calib_num,
  253. model_revision=args.model_revision,
  254. )
  255. for model_name in args.model_name:
  256. print("export model: {}".format(model_name))
  257. export_model.export(model_name)