Open Neural Network Exchange - The Universal AI Format
弘益人間 · Benefit All Humanity
The Open Neural Network Exchange (ONNX) format was created in 2017 by Microsoft and Facebook (now Meta) as an open standard for representing machine learning models. ONNX has become the de facto interchange format for neural networks, enabling seamless model transfer between frameworks like PyTorch, TensorFlow, scikit-learn, and more.
ONNX is built on Protocol Buffers (protobuf), Google's language-neutral data serialization format. This choice provides efficient binary encoding, strong typing, and schema evolution capabilities essential for a production-grade format.
An ONNX model consists of several key components organized in a hierarchical structure:
The top-level container for the entire model:
message ModelProto {
int64 ir_version = 1; // ONNX IR version
repeated OpsetImport opset_import = 8; // Operator sets
string producer_name = 2; // Framework that created model
string producer_version = 3; // Framework version
string domain = 4; // Model domain
int64 model_version = 5; // Model version
string doc_string = 6; // Documentation
GraphProto graph = 7; // The computational graph
repeated StringStringEntryProto metadata_props = 14;
}
The computational graph defining the model's architecture:
message GraphProto {
repeated NodeProto node = 1; // Computation nodes
string name = 2; // Graph name
repeated TensorProto initializer = 5; // Constant tensors (weights)
string doc_string = 10; // Documentation
repeated ValueInfoProto input = 11; // Input specifications
repeated ValueInfoProto output = 12; // Output specifications
repeated ValueInfoProto value_info = 13; // Intermediate values
}
Individual operations in the computational graph:
message NodeProto {
repeated string input = 1; // Input tensor names
repeated string output = 2; // Output tensor names
string name = 3; // Node name
string op_type = 4; // Operation type (Conv, Gemm, etc.)
string domain = 7; // Operator domain
repeated AttributeProto attribute = 5; // Operation attributes
string doc_string = 6; // Documentation
}
ONNX defines operators through versioned operator sets (opsets). Each opset version introduces new operators or updates existing ones:
| Opset | Release | Key Features |
|---|---|---|
| 1-6 | 2017-2018 | Basic operations, CNNs |
| 7-10 | 2019 | RNNs, control flow |
| 11-13 | 2020-2021 | Transformers, dynamic shapes |
| 14-16 | 2022-2023 | Quantization, optimization |
| 17-18 | 2023-2024 | LLM operations, efficiency |
// Convolution
Conv: Convolution operation
- dilations, group, kernel_shape, pads, strides
- Input: X[N,C_in,H,W], W[C_out,C_in/group,kH,kW]
- Output: Y[N,C_out,H_out,W_out]
// Matrix Multiplication
Gemm: General Matrix Multiplication (Y = α·AB + β·C)
- alpha, beta, transA, transB
// Activation Functions
Relu, Sigmoid, Tanh, LeakyRelu, Elu, Selu, Swish
// Normalization
BatchNormalization, LayerNormalization, InstanceNormalization
// Pooling
MaxPool, AveragePool, GlobalMaxPool, GlobalAveragePool
// Attention (Opset 14+)
Attention, MultiHeadAttention
ONNX tensors use the TensorProto message for constant values and weights:
message TensorProto {
repeated int64 dims = 1; // Tensor dimensions
int32 data_type = 2; // Element data type
Segment segment = 3; // For large tensors
// Data storage (one of these):
repeated float float_data = 4; // FP32 values
repeated int32 int32_data = 5; // INT32 values
bytes raw_data = 9; // Raw binary data
// External data reference
repeated StringStringEntryProto external_data = 13;
DataLocation data_location = 14;
string name = 8; // Tensor name
string doc_string = 12; // Documentation
}
| Type | Value | Description |
|---|---|---|
| FLOAT | 1 | 32-bit IEEE 754 floating point |
| UINT8 | 2 | 8-bit unsigned integer |
| INT8 | 3 | 8-bit signed integer |
| UINT16 | 4 | 16-bit unsigned integer |
| INT16 | 5 | 16-bit signed integer |
| INT32 | 6 | 32-bit signed integer |
| INT64 | 7 | 64-bit signed integer |
| FLOAT16 | 10 | 16-bit IEEE 754 half precision |
| BFLOAT16 | 16 | 16-bit brain float |
Most major frameworks provide tools to export models to ONNX format:
import torch
import torch.onnx
# Load your trained model
model = MyModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()
# Create dummy input
dummy_input = torch.randn(1, 3, 224, 224)
# Export to ONNX
torch.onnx.export(
model,
dummy_input,
"model.onnx",
export_params=True,
opset_version=17,
do_constant_folding=True,
input_names=['input'],
output_names=['output'],
dynamic_axes={
'input': {0: 'batch_size'},
'output': {0: 'batch_size'}
}
)
import tensorflow as tf
import tf2onnx
# Load SavedModel
model = tf.saved_model.load('saved_model')
# Convert to ONNX
spec = (tf.TensorSpec((None, 224, 224, 3), tf.float32, name="input"),)
output_path = "model.onnx"
model_proto, _ = tf2onnx.convert.from_keras(
model,
input_signature=spec,
opset=17,
output_path=output_path
)
print(f"ONNX model saved to {output_path}")
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
# Train scikit-learn model
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# Define input type
initial_type = [('float_input', FloatTensorType([None, X_train.shape[1]]))]
# Convert to ONNX
onnx_model = convert_sklearn(
model,
initial_types=initial_type,
target_opset=17
)
# Save
with open("sklearn_model.onnx", "wb") as f:
f.write(onnx_model.SerializeToString())
ONNX Runtime is a high-performance inference engine optimized for ONNX models:
import onnxruntime as ort
import numpy as np
# Create inference session
session = ort.InferenceSession("model.onnx")
# Get input/output names
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
# Prepare input
input_data = np.random.randn(1, 3, 224, 224).astype(np.float32)
# Run inference
outputs = session.run(
[output_name],
{input_name: input_data}
)
print(f"Output shape: {outputs[0].shape}")
print(f"Predictions: {outputs[0]}")
# Configure session options
sess_options = ort.SessionOptions()
# Enable graph optimizations
sess_options.graph_optimization_level = \
ort.GraphOptimizationLevel.ORT_ENABLE_ALL
# Set number of threads
sess_options.intra_op_num_threads = 4
sess_options.inter_op_num_threads = 4
# Enable profiling
sess_options.enable_profiling = True
# Create optimized session
session = ort.InferenceSession(
"model.onnx",
sess_options,
providers=['CUDAExecutionProvider', 'CPUExecutionProvider']
)
# Check which provider is being used
print(f"Execution provider: {session.get_providers()}")
ONNX provides various optimization techniques to improve inference performance:
from onnxruntime.quantization import quantize_dynamic, quantize_static
# Dynamic Quantization (no calibration data needed)
quantize_dynamic(
model_input="model_fp32.onnx",
model_output="model_int8.onnx",
weight_type=QuantType.QInt8
)
# Static Quantization (requires calibration)
from onnxruntime.quantization import CalibrationDataReader
class DataReader(CalibrationDataReader):
def __init__(self, calibration_data):
self.data = calibration_data
self.index = 0
def get_next(self):
if self.index < len(self.data):
result = {"input": self.data[self.index]}
self.index += 1
return result
return None
quantize_static(
model_input="model_fp32.onnx",
model_output="model_int8_static.onnx",
calibration_data_reader=DataReader(calibration_dataset)
)
When standard ONNX operators don't cover your needs, you can define custom operators:
from onnx import helper, TensorProto
# Define custom operator
custom_op = helper.make_node(
'CustomOp',
inputs=['X'],
outputs=['Y'],
domain='ai.onnx.custom',
custom_attribute=42
)
# Register implementation in ONNX Runtime
import onnxruntime as ort
class CustomOpKernel:
def __init__(self, custom_attribute):
self.custom_attribute = custom_attribute
def compute(self, x):
# Your custom operation logic
return x * self.custom_attribute
# Register kernel
ort.register_custom_ops_library("custom_ops.so")
Several tools help analyze and debug ONNX models:
Netron is a popular tool for visualizing ONNX models:
# Install Netron
pip install netron
# View model in browser
netron model.onnx
# Or use Python API
import netron
netron.start('model.onnx', port=8080)
import onnx
# Load model
model = onnx.load("model.onnx")
# Check model validity
onnx.checker.check_model(model)
print("✓ Model is valid")
# Infer shapes
model = onnx.shape_inference.infer_shapes(model)
# Print model structure
for node in model.graph.node:
print(f"Node: {node.name}")
print(f" Op: {node.op_type}")
print(f" Inputs: {node.input}")
print(f" Outputs: {node.output}")
Follow these guidelines when working with ONNX models:
import torch
import onnxruntime as ort
import numpy as np
# Original PyTorch model
model_pt = load_pytorch_model()
model_pt.eval()
# ONNX model
session = ort.InferenceSession("model.onnx")
# Test input
test_input = np.random.randn(1, 3, 224, 224).astype(np.float32)
# PyTorch output
with torch.no_grad():
pt_output = model_pt(torch.from_numpy(test_input)).numpy()
# ONNX output
onnx_output = session.run(None, {"input": test_input})[0]
# Compare
diff = np.abs(pt_output - onnx_output)
print(f"Max difference: {diff.max():.2e}")
print(f"Mean difference: {diff.mean():.2e}")
assert diff.max() < 1e-5, "Outputs differ significantly!"
# Export with dynamic batch size and sequence length
torch.onnx.export(
model,
dummy_input,
"model.onnx",
dynamic_axes={
'input': {0: 'batch', 1: 'sequence'},
'output': {0: 'batch'}
}
)
# Now model can handle any batch size and sequence length
session = ort.InferenceSession("model.onnx")
input_shape = session.get_inputs()[0].shape
print(input_shape) # ['batch', 'sequence', 768]
# CPU optimization
session_cpu = ort.InferenceSession(
"model.onnx",
providers=['CPUExecutionProvider']
)
# GPU optimization (CUDA)
session_gpu = ort.InferenceSession(
"model.onnx",
providers=['CUDAExecutionProvider']
)
# TensorRT optimization (NVIDIA)
session_trt = ort.InferenceSession(
"model.onnx",
providers=['TensorrtExecutionProvider']
)
# Mobile optimization (CoreML for iOS)
from onnx_coreml import convert
coreml_model = convert(
model="model.onnx",
minimum_ios_deployment_target='13'
)
This chapter provided a comprehensive deep dive into the ONNX format. Key takeaways include:
Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.
Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.
Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.