pesi
/

Luigi commited on
Commit
9f60e86
1 Parent(s): 1c5dc58

Add utility to convert ONNX model in FP32/16 mixed precision

Browse files
Files changed (1) hide show
  1. convert_to_mixed.py +68 -0
convert_to_mixed.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import numpy as np
3
+ from PIL import Image
4
+ import onnx
5
+ import onnxruntime as ort
6
+ from onnxconverter_common import auto_mixed_precision_model_path
7
+ import argparse
8
+
9
+ PROVIDERS=[('TensorrtExecutionProvider', {'trt_fp16_enable':True,}), 'CUDAExecutionProvider', 'CPUExecutionProvider']
10
+ RTOL=0.1
11
+ ATOL=0.1
12
+
13
+ def detect_model_input_size(model_path):
14
+ model = onnx.load(model_path)
15
+ for input_tensor in model.graph.input:
16
+ # Assuming the input node is named 'input'
17
+ if input_tensor.name == 'input':
18
+ tensor_shape = input_tensor.type.tensor_type.shape
19
+ # Extract the dimensions: (batch_size, channels, height, width)
20
+ dims = [dim.dim_value for dim in tensor_shape.dim]
21
+ # Replace dynamic batch size (-1 or 0) with 1
22
+ if dims[0] < 1:
23
+ dims[0] = 1
24
+ return tuple(dims[2:4]) # Return (height, width)
25
+ raise ValueError("Input node 'input' not found in the model")
26
+
27
+ def load_and_preprocess_image(image_path, size=(224, 224)):
28
+ image = Image.open(image_path).convert('RGB')
29
+ image = image.resize(size)
30
+ image = np.array(image).astype(np.float32) / 255.
31
+ image = np.transpose(image, (2, 0, 1))
32
+ image = np.expand_dims(image, axis=0)
33
+ return image
34
+
35
+ def infer(model_path, input_feed):
36
+ session = ort.InferenceSession(model_path, providers=PROVIDERS)
37
+ input_name = session.get_inputs()[0].name
38
+ result = session.run(None, {input_name: input_feed})
39
+ return result
40
+
41
+ def main(args):
42
+ model_input_size = detect_model_input_size(args.source_model_path)
43
+ input_feed = {'input':load_and_preprocess_image(args.test_image_path, size=model_input_size)}
44
+
45
+ auto_mixed_precision_model_path.auto_convert_mixed_precision_model_path(source_model_path=args.source_model_path,
46
+ input_feed=input_feed,
47
+ target_model_path=args.target_model_path,
48
+ customized_validate_func=None,
49
+ rtol=RTOL, atol=ATOL,
50
+ provider=PROVIDERS,
51
+ keep_io_types=True,
52
+ verbose=True)
53
+
54
+ original_result = infer(args.source_model_path, input_feed)
55
+ converted_result = infer(args.target_model_path, input_feed)
56
+
57
+ is_close = np.allclose(original_result[0], converted_result[0], rtol=RTOL, atol=ATOL)
58
+ print(f"Validation result: {'Success' if is_close else 'Failure'}")
59
+
60
+ if __name__ == "__main__":
61
+ parser = argparse.ArgumentParser(description="Convert an ONNX model to mixed precision format.")
62
+ parser.add_argument("source_model_path", type=str, help="Path to the source ONNX model.")
63
+ parser.add_argument("target_model_path", type=str, help="Path where the mixed precision model will be saved.")
64
+ parser.add_argument("test_image_path", type=str, help="Path to a test image for validating the model conversion.")
65
+
66
+ args = parser.parse_args()
67
+
68
+ main(args)