file_utils.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang)
  2. # 2024 Alibaba Inc (authors: Xiang Lyu, Zetao Hu)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. import torchaudio
  17. import logging
  18. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  19. logging.basicConfig(level=logging.DEBUG,
  20. format='%(asctime)s %(levelname)s %(message)s')
  21. def read_lists(list_file):
  22. lists = []
  23. with open(list_file, 'r', encoding='utf8') as fin:
  24. for line in fin:
  25. lists.append(line.strip())
  26. return lists
  27. def read_json_lists(list_file):
  28. lists = read_lists(list_file)
  29. results = {}
  30. for fn in lists:
  31. with open(fn, 'r', encoding='utf8') as fin:
  32. results.update(json.load(fin))
  33. return results
  34. def load_wav(wav, target_sr):
  35. speech, sample_rate = torchaudio.load(wav, backend='soundfile')
  36. speech = speech.mean(dim=0, keepdim=True)
  37. if sample_rate != target_sr:
  38. assert sample_rate > target_sr, 'wav sample rate {} must be greater than {}'.format(sample_rate, target_sr)
  39. speech = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=target_sr)(speech)
  40. return speech
  41. def convert_onnx_to_trt(trt_model, trt_kwargs, onnx_model, fp16):
  42. import tensorrt as trt
  43. logging.info("Converting onnx to trt...")
  44. network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
  45. logger = trt.Logger(trt.Logger.INFO)
  46. builder = trt.Builder(logger)
  47. network = builder.create_network(network_flags)
  48. parser = trt.OnnxParser(network, logger)
  49. config = builder.create_builder_config()
  50. config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 33) # 8GB
  51. if fp16:
  52. config.set_flag(trt.BuilderFlag.FP16)
  53. profile = builder.create_optimization_profile()
  54. # load onnx model
  55. with open(onnx_model, "rb") as f:
  56. if not parser.parse(f.read()):
  57. for error in range(parser.num_errors):
  58. print(parser.get_error(error))
  59. raise ValueError('failed to parse {}'.format(onnx_model))
  60. # set input shapes
  61. for i in range(len(trt_kwargs['input_names'])):
  62. profile.set_shape(trt_kwargs['input_names'][i], trt_kwargs['min_shape'][i], trt_kwargs['opt_shape'][i], trt_kwargs['max_shape'][i])
  63. tensor_dtype = trt.DataType.HALF if fp16 else trt.DataType.FLOAT
  64. # set input and output data type
  65. for i in range(network.num_inputs):
  66. input_tensor = network.get_input(i)
  67. input_tensor.dtype = tensor_dtype
  68. for i in range(network.num_outputs):
  69. output_tensor = network.get_output(i)
  70. output_tensor.dtype = tensor_dtype
  71. config.add_optimization_profile(profile)
  72. engine_bytes = builder.build_serialized_network(network, config)
  73. # save trt engine
  74. with open(trt_model, "wb") as f:
  75. f.write(engine_bytes)
  76. logging.info("Succesfully convert onnx to trt...")