Repository navigation
Expand file tree
/
Copy pathbenchmark.py
More file actions
119 lines (104 loc) · 4.51 KB
/
Copy pathbenchmark.py
File metadata and controls
119 lines (104 loc) · 4.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""
Benchmark Script: Evaluates CPU inference latency and throughput
comparing PyTorch vs. ONNX Runtime for solar panel defect classification.
"""
import os
import time
import argparse
import numpy as np
import torch
import onnxruntime as ort
from src.model import SolarResNet
def run_benchmark(
pt_model_path="models/solar_panel_resnet50_best.pt",
onnx_model_path="models/solar_panel_resnet50.onnx",
num_classes=6,
num_iterations=100,
warmup_iterations=10
):
print("=" * 68)
print(" INFERENCE BENCHMARK: PYTORCH CPU vs. ONNX RUNTIME CPU ")
print("=" * 68)
# 1. Check file existence
if not os.path.exists(pt_model_path):
raise FileNotFoundError(f"PyTorch model not found at {pt_model_path}")
if not os.path.exists(onnx_model_path):
raise FileNotFoundError(f"ONNX model not found at {onnx_model_path}. Run export_onnx.py first.")
# 2. Load PyTorch Model on CPU
print(f"Loading PyTorch model from: {pt_model_path}")
pt_model = SolarResNet(num_classes=num_classes)
pt_model.load_state_dict(torch.load(pt_model_path, map_location="cpu"))
pt_model.eval()
# 3. Load ONNX Runtime Session on CPU
print(f"Loading ONNX model from: {onnx_model_path}")
session_options = ort.SessionOptions()
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
ort_session = ort.InferenceSession(
onnx_model_path,
sess_options=session_options,
providers=["CPUExecutionProvider"]
)
input_name = ort_session.get_inputs()[0].name
# 4. Generate representative test tensor (1, 3, 224, 224)
dummy_np = np.random.randn(1, 3, 224, 224).astype(np.float32)
dummy_torch = torch.from_numpy(dummy_np)
print(f"\nConfiguration: {warmup_iterations} warmup runs, {num_iterations} timed iterations (Batch Size = 1)")
print("Running benchmarks...")
# --- Warm-up ---
for _ in range(warmup_iterations):
with torch.no_grad():
_ = pt_model(dummy_torch)
_ = ort_session.run(None, {input_name: dummy_np})
# --- Benchmark PyTorch CPU ---
pt_latencies = []
for _ in range(num_iterations):
start = time.perf_counter()
with torch.no_grad():
_ = pt_model(dummy_torch)
end = time.perf_counter()
pt_latencies.append((end - start) * 1000.0)
# --- Benchmark ONNX Runtime CPU ---
ort_latencies = []
for _ in range(num_iterations):
start = time.perf_counter()
_ = ort_session.run(None, {input_name: dummy_np})
end = time.perf_counter()
ort_latencies.append((end - start) * 1000.0)
# Compute statistics
pt_mean = float(np.mean(pt_latencies))
pt_median = float(np.median(pt_latencies))
pt_p95 = float(np.percentile(pt_latencies, 95))
pt_std = float(np.std(pt_latencies))
pt_fps = 1000.0 / pt_mean
ort_mean = float(np.mean(ort_latencies))
ort_median = float(np.median(ort_latencies))
ort_p95 = float(np.percentile(ort_latencies, 95))
ort_std = float(np.std(ort_latencies))
ort_fps = 1000.0 / ort_mean
speedup_pct = ((pt_mean - ort_mean) / pt_mean) * 100.0
throughput_gain = ort_fps / pt_fps
# Print Clean Summary Table
print("\n" + "-" * 68)
print(f"{'Metric':<24} | {'PyTorch (CPU)':<18} | {'ONNX Runtime (CPU)':<20}")
print("-" * 68)
print(f"{'Mean Latency':<24} | {pt_mean:>14.2f} ms | {ort_mean:>16.2f} ms")
print(f"{'Median (P50) Latency':<24} | {pt_median:>14.2f} ms | {ort_median:>16.2f} ms")
print(f"{'95th Percentile (P95)':<24} | {pt_p95:>14.2f} ms | {ort_p95:>16.2f} ms")
print(f"{'Std Deviation':<24} | {pt_std:>14.2f} ms | {ort_std:>16.2f} ms")
print(f"{'Throughput':<24} | {pt_fps:>12.1f} FPS | {ort_fps:>14.1f} FPS")
print("-" * 68)
print(f"🚀 Result: ONNX Runtime is {speedup_pct:.1f}% FASTER ({throughput_gain:.2f}x throughput) on CPU.")
print("=" * 68 + "\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Benchmark PyTorch vs ONNX Runtime inference latency on CPU")
parser.add_argument("--pt_model", type=str, default="models/solar_panel_resnet50_best.pt")
parser.add_argument("--onnx_model", type=str, default="models/solar_panel_resnet50.onnx")
parser.add_argument("--iterations", type=int, default=100)
parser.add_argument("--warmup", type=int, default=10)
args = parser.parse_args()
run_benchmark(
pt_model_path=args.pt_model,
onnx_model_path=args.onnx_model,
num_iterations=args.iterations,
warmup_iterations=args.warmup
)