ONNX
Open Neural Network Exchange
An open format for model interoperability between frameworks. Conversion between PyTorch and TensorFlow.
Open Neural Network Exchange
An open format for model interoperability between frameworks. Conversion between PyTorch and TensorFlow.
ONNX (Open Neural Network Exchange) is an open standard format that allows deep learning models to run on a variety of frameworks and hardware. It is used as an intermediate format when running inference in TensorFlow on a model trained in PyTorch, or when deploying to mobile/edge devices.
It was jointly announced by Facebook and Microsoft in 2017 and has since become a Linux Foundation project in which major companies such as Amazon, Google, and NVIDIA participate. Because models can be ported without framework dependencies, it has become established as a standard of the ML ecosystem.
ONNX stores a model's computational graph and operators in a standardized format. ONNX Runtime is an inference engine developed by Microsoft that supports optimized inference on a variety of hardware such as CPU/GPU/NPU, and delivers an average 2-3x improvement in inference speed.
In practice, ONNX is key at the model serving (deployment) stage. A common workflow is to research/develop in PyTorch, convert to ONNX, and then optimize and deploy to target platforms such as TensorRT (NVIDIA), OpenVINO (Intel), and CoreML (Apple).
# ONNX 변환 및 추론 예제
# pip install torch onnx onnxruntime
import torch
import torch.nn as nn
import onnx
import onnxruntime as ort
import numpy as np
# ===== 1. PyTorch 모델 정의 =====
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(10, 64)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(64, 2)
def forward(self, x):
x = self.relu(self.fc1(x))
return self.fc2(x)
model = SimpleModel()
model.eval()
# ===== 2. ONNX로 변환 =====
dummy_input = torch.randn(1, 10) # 예시 입력
torch.onnx.export(
model, # 모델
dummy_input, # 예시 입력
"model.onnx", # 출력 파일
export_params=True, # 가중치 포함
opset_version=17, # ONNX opset 버전
input_names=['input'], # 입력 이름
output_names=['output'], # 출력 이름
dynamic_axes={ # 동적 배치 크기
'input': {0: 'batch_size'},
'output': {0: 'batch_size'}
}
)
print("ONNX 모델 저장 완료: model.onnx")
# ===== 3. ONNX 모델 검증 =====
onnx_model = onnx.load("model.onnx")
onnx.checker.check_model(onnx_model)
print("ONNX 모델 검증 통과!")
# 모델 구조 확인
print(onnx.helper.printable_graph(onnx_model.graph))
# ===== 4. ONNX Runtime으로 추론 =====
# 세션 생성 (GPU 사용시: providers=['CUDAExecutionProvider'])
session = ort.InferenceSession(
"model.onnx",
providers=['CPUExecutionProvider']
)
# 추론 실행
input_data = np.random.randn(5, 10).astype(np.float32)
outputs = session.run(None, {'input': input_data})
print(f"추론 결과 shape: {outputs[0].shape}")
# ===== 5. 성능 비교 =====
import time
# PyTorch 추론 시간
torch_input = torch.from_numpy(input_data)
start = time.time()
for _ in range(1000):
_ = model(torch_input)
pytorch_time = time.time() - start
# ONNX Runtime 추론 시간
start = time.time()
for _ in range(1000):
_ = session.run(None, {'input': input_data})
onnx_time = time.time() - start
print(f"PyTorch: {pytorch_time:.3f}s, ONNX Runtime: {onnx_time:.3f}s")
print(f"속도 향상: {pytorch_time/onnx_time:.2f}x")
"When deploying a PyTorch model to production, converting it to ONNX enables 2-3x faster inference with ONNX Runtime. For NVIDIA GPUs, you can optimize further with TensorRT, and for Intel CPUs, with OpenVINO."
"ONNX is an open standard format for deep learning models that provides portability across frameworks. It stores the computational graph and operators in a standardized form, and enables optimized inference on a variety of hardware with ONNX Runtime. In practice, models are usually converted at the serving stage after training in PyTorch."
"If an error occurs during conversion, it could be an opset version issue. You can try lowering opset_version, or if there is an unsupported operator, you'll need to create a custom mapping with torch.onnx.register_custom_op_symbolic."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Some custom operations or the latest operators may not be supported in ONNX. Check compatibility before conversion.
Numerical errors may occur during conversion. Be sure to compare the outputs of the original model and the ONNX model for the same input.
Verify with onnx.checker before conversion, and check the output difference for the same input with np.allclose(). Set dynamic_axes to gain flexibility in batch size.