|
| 1 | +import os |
| 2 | +import torch |
| 3 | +import argparse |
| 4 | +from bonito.util import load_model |
| 5 | + |
| 6 | +parser = argparse.ArgumentParser(description='Use this script to prepare OpenVINO IR for trained model') |
| 7 | +parser.add_argument("model_directory") |
| 8 | +parser.add_argument("--half", action="store_true", default=False) |
| 9 | +parser.add_argument("--weights", default="0", type=str) |
| 10 | +args = parser.parse_args() |
| 11 | + |
| 12 | +__dir__ = os.path.dirname(os.path.dirname(__file__)) |
| 13 | +__models__ = os.path.join(__dir__, "models") |
| 14 | +dirname = args.model_directory |
| 15 | +if not os.path.isdir(dirname) and os.path.isdir(os.path.join(__models__, dirname)): |
| 16 | + dirname = os.path.join(__models__, dirname) |
| 17 | + |
| 18 | +model = load_model(dirname, 'cpu', weights=int(args.weights), half=args.half) |
| 19 | + |
| 20 | + |
| 21 | +# Convert to ONNX |
| 22 | +onnx_path = os.path.join(dirname, model.config['model']) + '.onnx' |
| 23 | +inp = torch.randn(1, 1, 1000) # Just dummy input shape. We will reshape model later |
| 24 | +model.eval() |
| 25 | +with torch.no_grad(): |
| 26 | + torch.onnx.export(model, inp, onnx_path, |
| 27 | + input_names=['input'], |
| 28 | + output_names=['output'], |
| 29 | + operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK) |
| 30 | + |
| 31 | + |
| 32 | +# Convert to IR |
| 33 | +import mo_onnx |
| 34 | +import subprocess |
| 35 | +model_name = model.config['model'] + ('_fp16' if args.half else '') |
| 36 | +subprocess.call([mo_onnx.__file__, |
| 37 | + '--input_model', onnx_path, |
| 38 | + '--extension', os.path.join(os.path.dirname(__file__), 'mo_extension'), |
| 39 | + '--keep_shape_ops', |
| 40 | + '--model_name', model_name, |
| 41 | + '--data_type', 'FP16' if args.half else 'FP32', |
| 42 | + '--input_shape=[1,1,1,1000]', |
| 43 | + '--output_dir', dirname]) |
0 commit comments