π¦ Real-World Context: Hardware-Agnostic Model Portability & High-Throughput Serving
Production inference teams frequently deploy models in environments where full PyTorch training packages are too heavy, where inference runs on specialized accelerators (NVIDIA TensorRT, Intel OpenVINO, Windows DirectML, AWS Neuron, or multi-core CPUs), or where serving services are written in C#, Rust, C++, Java, or Node.js. ONNX (Open Neural Network Exchange) provides a standardized computation-graph format, while ONNX Runtime (ORT) executes those graphs with operator fusion, memory reuse, and hardware-specific Execution Providers (EPs).
Production ONNX workflows cover ten core practices: exporting deterministic .eval() models via torch.onnx.export, declaring dynamic_axes for variable batch/sequence lengths, validating graphs with onnx.checker, tuning SessionOptions & GraphOptimizationLevel, selecting Execution Providers (CUDAExecutionProvider, TensorrtExecutionProvider, CPUExecutionProvider), using io_binding to eliminate host-device copies, applying dynamic/static INT8 quantization, and verifying strict numerical parity.
.eval() mode to an ONNX computation graph via torch.onnx.export with explicit input_names, output_names, and opset_version=17, then validating structural integrity with onnx.checker.check_model.
import io
import torch
import torch.nn as nn
class CreditRiskClassifier(nn.Module):
def __init__(self, in_dim: int = 20, num_classes: int = 3):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, 64),
nn.ReLU(),
nn.Linear(64, num_classes),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
torch.manual_seed(42)
model = CreditRiskClassifier(in_dim=20, num_classes=3).eval()
dummy_input = torch.randn(4, 20)
onnx_buffer = io.BytesIO()
torch.onnx.export(
model,
dummy_input,
onnx_buffer,
export_params=True,
opset_version=17,
do_constant_folding=True,
input_names=["features"],
output_names=["logits"],
)
onnx_bytes = onnx_buffer.getbuffer().nbytes
print(f"ONNX Export Succeeded | Opset: 17 | Input: 'features' (4,20) | Output: 'logits' (4,3) | Size: {onnx_bytes:,} bytes")
Output: ONNX Export Succeeded | Opset: 17 | Input: 'features' (4,20) | Output: 'logits' (4,3) | Size: 7,518 bytes
dynamic_axes={"input_ids": {0: "batch_size", 1: "seq_len"}, "logits": {0: "batch_size", 1: "seq_len"}} during ONNX export so real-time serving requests with variable batch sizes (e.g., batch=1 interactive chat vs. batch=32 batch scoring) and variable sequence lengths execute through a single exported .onnx graph.
import io
import torch
import torch.nn as nn
class SequenceEmbedEncoder(nn.Module):
def __init__(self, vocab_size: int = 1000, d_model: int = 64):
super().__init__()
self.emb = nn.Embedding(vocab_size, d_model)
self.proj = nn.Linear(d_model, 16)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.proj(self.emb(input_ids))
encoder = SequenceEmbedEncoder().eval()
sample_ids = torch.randint(0, 1000, (2, 8))
dynamic_axes_spec = {
"input_ids": {0: "batch_size", 1: "seq_len"},
"token_logits": {0: "batch_size", 1: "seq_len"},
}
buf = io.BytesIO()
torch.onnx.export(
encoder,
sample_ids,
buf,
opset_version=17,
input_names=["input_ids"],
output_names=["token_logits"],
dynamic_axes=dynamic_axes_spec,
)
print("Dynamic Axes Configured :", dynamic_axes_spec)
print("Exported Buffer Bytes :", f"{buf.getbuffer().nbytes:,} bytes (Supports Dynamic Batch & SeqLen)")
Output:
Dynamic Axes Configured : {'input_ids': {0: 'batch_size', 1: 'seq_len'}, 'token_logits': {0: 'batch_size', 1: 'seq_len'}}
Exported Buffer Bytes : 268,942 bytes (Supports Dynamic Batch & SeqLen)
do_constant_folding=True pre-computes static tensor expressions (such as constant scaling factors or fused bias shifts) at export time instead of recomputing them on every production inference request, reducing runtime graph nodes and latency.
import io
import torch
import torch.nn as nn
class ConstantScaleNet(nn.Module):
def __init__(self):
super().__init__()
self.register_buffer("gain", torch.ones(1, 16) * 0.25)
self.fc = nn.Linear(16, 4)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Constant expression (gain * 2.0) folds into a single static tensor at export
scaled_x = x * (self.gain * 2.0)
return self.fc(scaled_x)
net = ConstantScaleNet().eval()
x_in = torch.randn(2, 16)
buf_folded = io.BytesIO()
torch.onnx.export(net, x_in, buf_folded, opset_version=17, do_constant_folding=True)
buf_unfolded = io.BytesIO()
torch.onnx.export(net, x_in, buf_unfolded, opset_version=17, do_constant_folding=False)
print(f"Constant Folding ON Size : {buf_folded.getbuffer().nbytes:,} bytes")
print(f"Constant Folding OFF Size : {buf_unfolded.getbuffer().nbytes:,} bytes")
Output: Constant Folding ON Size : 3,812 bytes Constant Folding OFF Size : 4,196 bytes
onnxruntime.SessionOptions() with GraphOptimizationLevel.ORT_ENABLE_ALL, intra-op thread counts (intra_op_num_threads), and memory pattern reuse before running session.run(output_names, {input_name: np_input}) for low-latency serving.
# Production ONNX Runtime SessionOptions configuration
session_config = {
"graph_optimization_level": "ORT_ENABLE_ALL", # Constant folding + node elimination + layout/attention fusion
"intra_op_num_threads": 8, # Parallel worker threads within a single operator
"inter_op_num_threads": 2, # Parallel execution across independent graph branches
"enable_mem_pattern": True, # Reuses pre-planned tensor memory arenas across steps
"execution_mode": "ORT_SEQUENTIAL",
}
for k, v in session_config.items():
print(f"sess_options.{k:<26} = {v}")
print("Inference Call Pattern -> outputs = session.run(['logits'], {'features': x_numpy})")
Output:
sess_options.graph_optimization_level = ORT_ENABLE_ALL
sess_options.intra_op_num_threads = 8
sess_options.inter_op_num_threads = 2
sess_options.enable_mem_pattern = True
sess_options.execution_mode = ORT_SEQUENTIAL
Inference Call Pattern -> outputs = session.run(['logits'], {'features': x_numpy})
["TensorrtExecutionProvider", "CUDAExecutionProvider", "CPUExecutionProvider"]βso unsupported subgraphs gracefully fall back to CUDA or CPU without crashing production services.
# Ordered EP fallback list (highest accelerator priority first)
providers_priority = [
("TensorrtExecutionProvider", {"trt_fp16_enable": True, "trt_engine_cache_enable": True}),
("CUDAExecutionProvider", {"device_id": 0, "cudnn_conv_algo_search": "EXHAUSTIVE"}),
("CPUExecutionProvider", {}),
]
ep_names = [p[0] for p in providers_priority]
print("Execution Provider Fallback Chain :", " -> ".join(ep_names))
print("TensorRT Engine Cache Enabled :", providers_priority[0][1]["trt_engine_cache_enable"])
Output: Execution Provider Fallback Chain : TensorrtExecutionProvider -> CUDAExecutionProvider -> CPUExecutionProvider TensorRT Engine Cache Enabled : True
H2D) and device-to-host (D2H) PCIe memory copies during real-time GPU inference by binding existing CUDA tensor pointers directly via session.io_binding() (bind_input and bind_output).
# IoBinding workflow for GPU-resident tensors (avoids NumPy CPU round-trips):
# 1. io_binding = session.io_binding()
# 2. io_binding.bind_input(
# name="input",
# device_type="cuda",
# device_id=0,
# element_type=np.float32,
# shape=tuple(gpu_tensor.shape),
# buffer_ptr=gpu_tensor.data_ptr(),
# )
# 3. io_binding.bind_output(name="output", device_type="cuda", device_id=0)
# 4. session.run_with_iobinding(io_binding)
# 5. out_ort_val = io_binding.get_outputs()[0]
h2d_copy_saved_ms = 0.42
d2h_copy_saved_ms = 0.38
print(f"IoBinding PCIe Round-Trip Saved : {h2d_copy_saved_ms + d2h_copy_saved_ms:.2f} ms per batch (Zero Host Copies)")
Output: IoBinding PCIe Round-Trip Saved : 0.80 ms per batch (Zero Host Copies)
QInt8 via onnxruntime.quantization.quantize_dynamic(..., weight_type=QuantType.QInt8)βshrinking model artifact footprint by ~3.5Γβ4Γ and accelerating AVX-512 / VNNI CPU inference without needing a calibration dataset.
import torch
import torch.nn as nn
# Estimate FP32 vs INT8 weight size for a 4.2M-parameter MLP block
num_params = 4_200_000
fp32_mb = (num_params * 4) / (1024 * 1024)
int8_mb = (num_params * 1) / (1024 * 1024)
# Production call:
# from onnxruntime.quantization import quantize_dynamic, QuantType
# quantize_dynamic("model_fp32.onnx", "model_int8.onnx", weight_type=QuantType.QInt8)
print(f"FP32 Linear Weights : {fp32_mb:.2f} MB (4 bytes/param)")
print(f"INT8 Linear Weights : {int8_mb:.2f} MB (1 byte/param -> {fp32_mb/int8_mb:.1f}x Smaller)")
Output: FP32 Linear Weights : 16.02 MB (4 bytes/param) INT8 Linear Weights : 4.01 MB (1 byte/param -> 4.0x Smaller)
.onnx model to production: checking max absolute error (< 1e-5 for FP32) and cosine similarity (> 0.99999) across diverse test batches to catch export bugs early.
import torch
import torch.nn.functional as F
torch.manual_seed(77)
pytorch_logits = torch.randn(8, 5)
# Simulated ONNX Runtime output with tiny floating-point rounding drift
onnx_logits = pytorch_logits + torch.randn(8, 5) * 1e-6
max_abs_err = (pytorch_logits - onnx_logits).abs().max().item()
cos_sim = F.cosine_similarity(pytorch_logits.flatten(), onnx_logits.flatten(), dim=0).item()
passed = (max_abs_err < 1e-4) and (cos_sim > 0.99999)
print(f"Max Abs Error : {max_abs_err:.2e} (< 1e-4 threshold)")
print(f"Cosine Similarity : {cos_sim:.8f} (> 0.99999 threshold)")
print(f"CI Release Gate : {'PASSED -> Promote ONNX Artifact' if passed else 'FAILED -> Block Release'}")
Output: Max Abs Error : 2.31e-06 (< 1e-4 threshold) Cosine Similarity : 1.00000000 (> 0.99999 threshold) CI Release Gate : PASSED -> Promote ONNX Artifact
image_emb) with normalized user/context metadata (meta_vec) via a tuple of input tensors (image_emb, meta_vec) and named inputs ["image_emb", "meta_vec"].
import io
import torch
import torch.nn as nn
class MultimodalFusionScorer(nn.Module):
def __init__(self, img_dim: int = 128, meta_dim: int = 16, out_dim: int = 2):
super().__init__()
self.fusion_mlp = nn.Sequential(
nn.Linear(img_dim + meta_dim, 64),
nn.GELU(),
nn.Linear(64, out_dim),
)
def forward(self, image_emb: torch.Tensor, meta_vec: torch.Tensor) -> torch.Tensor:
fused = torch.cat([image_emb, meta_vec], dim=-1)
return self.fusion_mlp(fused)
scorer = MultimodalFusionScorer().eval()
img_x = torch.randn(4, 128)
meta_x = torch.randn(4, 16)
buf = io.BytesIO()
torch.onnx.export(
scorer,
(img_x, meta_x),
buf,
opset_version=17,
input_names=["image_emb", "meta_vec"],
output_names=["relevance_score"],
)
print("Multi-Input ONNX Exported | Inputs: ['image_emb', 'meta_vec'] | Output: 'relevance_score' (4, 2)")
Output: Multi-Input ONNX Exported | Inputs: ['image_emb', 'meta_vec'] | Output: 'relevance_score' (4, 2)
# Representative benchmark comparison (Batch=32, 200 steady-state runs after 25 warm-up runs)
benchmarks = {
"PyTorch Eager (.eval())": {"p50_ms": 4.85, "p99_ms": 7.12, "qps": 6597},
"ONNX Runtime (ORT_ENABLE_ALL)": {"p50_ms": 1.62, "p99_ms": 2.34, "qps": 19753},
}
baseline_qps = benchmarks["PyTorch Eager (.eval())"]["qps"]
for runtime, m in benchmarks.items():
speedup = m["qps"] / baseline_qps
print(f"{runtime:<30} | P50: {m['p50_ms']:>4.2f}ms | P99: {m['p99_ms']:>4.2f}ms | QPS: {m['qps']:>6,} ({speedup:.2f}x)")
Output: PyTorch Eager (.eval()) | P50: 4.85ms | P99: 7.12ms | QPS: 6,597 (1.00x) ONNX Runtime (ORT_ENABLE_ALL) | P50: 1.62ms | P99: 2.34ms | QPS: 19,753 (2.99x)