onnx
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "onnx" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-77455dfe1fa317d8f7df63cc69d82b2ddbfb1e6cc0bd0932c7e284f015e9f92d. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
onnx: The Open Neural Network Exchange (ONNX) format and toolchain for cross-framework model interoperability. Used to export models from PyTorch, TensorFlow and others to ONNX, optimize with ONNX Runtime, and perform cross-platform inference and deployment on CPUs, GPUs, and edge devices.
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Tasks
- class SimpleModel(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(10, 64) self.relu = nn.ReLU() self.fc2 = nn.Linear(64, 3)
- Inputs and outputs
- print(f"Inputs: {[i.name for i in session.get_inputs()]}") print(f"Outputs: {[o.name for o in session.get_outputs()]}")
- Testing
- Not tested
Browse files
Frontmatter
name: onnx
description: |
Open Neural Network Exchange format for model interoperability across frameworks. Export
models from PyTorch, TensorFlow, and other frameworks to ONNX, optimize with ONNX Runtime,
and deploy for cross-platform inference on CPU, GPU, and edge devices.
license: Apache-2.0
compatibility: 'python 3.8+, onnxruntime 1.16+, Linux/macOS/Windows'
metadata:
author: terminal-skills
version: 1.0.0
category: data-ai
tags:
- model-interoperability
- optimization
- inference
- cross-platform
- edge-deploymentONNX
Installation
# Install ONNX and ONNX Runtime
pip install onnx onnxruntime
# For GPU inference
pip install onnxruntime-gpu
# For model optimization
pip install onnxoptimizer onnxsim
Export PyTorch Model to ONNX
# export_pytorch.py — Convert a PyTorch model to ONNX format
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(10, 64)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(64, 3)
def forward(self, x):
return self.fc2(self.relu(self.fc1(x)))
model = SimpleModel()
model.eval()
dummy_input = torch.randn(1, 10)
torch.onnx.export(
model,
dummy_input,
"model.onnx",
export_params=True,
opset_version=17,
input_names=["input"],
output_names=["output"],
dynamic_axes={
"input": {0: "batch_size"},
"output": {0: "batch_size"},
},
)
print("Exported model.onnx")
Export Hugging Face Transformers
# export_transformers.py — Export a Hugging Face model to ONNX using optimum
# pip install optimum[onnxruntime]
from optimum.onnxruntime import ORTModelForSequenceClassification
from transformers import AutoTokenizer
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
# Export and load in one step
model = ORTModelForSequenceClassification.from_pretrained(model_name, export=True)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Save the ONNX model
model.save_pretrained("./onnx_model")
tokenizer.save_pretrained("./onnx_model")
# Run inference
inputs = tokenizer("This movie was fantastic!", return_tensors="pt")
outputs = model(**inputs)
print(f"Logits: {outputs.logits}")
ONNX Runtime Inference
# inference.py — Run inference with ONNX Runtime for optimized performance
import onnxruntime as ort
import numpy as np
# Create session with optimization
session_options = ort.SessionOptions()
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
session_options.intra_op_num_threads = 4
# Use CPU or GPU provider
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
session = ort.InferenceSession("model.onnx", session_options, providers=providers)
# Get input/output details
print(f"Inputs: {[i.name for i in session.get_inputs()]}")
print(f"Outputs: {[o.name for o in session.get_outputs()]}")
# Run inference
input_data = np.random.randn(1, 10).astype(np.float32)
results = session.run(None, {"input": input_data})
print(f"Output shape: {results[0].shape}")
print(f"Predictions: {results[0]}")
Batch Inference
# batch_inference.py — Efficient batch processing with ONNX Runtime
import onnxruntime as ort
import numpy as np
import time
session = ort.InferenceSession("model.onnx", providers=["CPUExecutionProvider"])
# Batch of 1000 samples
batch_data = np.random.randn(1000, 10).astype(np.float32)
start = time.time()
results = session.run(None, {"input": batch_data})
elapsed = time.time() - start
print(f"Processed 1000 samples in {elapsed:.3f}s ({1000/elapsed:.0f} samples/sec)")
Model Optimization
# optimize.py — Optimize an ONNX model for faster inference
import onnx
from onnxruntime.transformers import optimizer
# Basic optimization with ONNX simplifier
# pip install onnxsim
import onnxsim
model = onnx.load("model.onnx")
optimized, check = onnxsim.simplify(model)
onnx.save(optimized, "model_simplified.onnx")
print(f"Simplified: {check}")
Quantization
# quantize.py — Reduce model size and speed up inference with quantization
from onnxruntime.quantization import quantize_dynamic, QuantType
quantize_dynamic(
model_input="model.onnx",
model_output="model_quantized.onnx",
weight_type=QuantType.QInt8,
)
import os
original = os.path.getsize("model.onnx")
quantized = os.path.getsize("model_quantized.onnx")
print(f"Original: {original/1024:.1f} KB")
print(f"Quantized: {quantized/1024:.1f} KB ({quantized/original*100:.1f}%)")
Validate ONNX Model
# validate.py — Check model validity and inspect structure
import onnx
model = onnx.load("model.onnx")
onnx.checker.check_model(model)
print("Model is valid!")
# Print model info
print(f"IR version: {model.ir_version}")
print(f"Opset: {model.opset_import[0].version}")
print(f"Graph inputs: {[i.name for i in model.graph.input]}")
print(f"Graph outputs: {[o.name for o in model.graph.output]}")
print(f"Nodes: {len(model.graph.node)}")
Edge Deployment (ONNX Runtime Mobile)
# mobile_export.py — Prepare a model for mobile/edge deployment
from onnxruntime.tools import ort_format_model
# Convert to ORT format for mobile
ort_format_model.convert_onnx_models_to_ort(
"model.onnx",
output_dir="./mobile_model",
optimization_level="all",
)
# Use the .ort file with ONNX Runtime Mobile SDK on iOS/Android
Key Concepts
- ONNX format: Framework-agnostic model representation — export from PyTorch/TF, run anywhere
- ONNX Runtime: High-performance inference engine with CPU, GPU, TensorRT, and DirectML support
- Dynamic axes: Allow variable batch sizes and sequence lengths in exported models
- Quantization: INT8 quantization reduces model size 2-4x with minimal accuracy loss
- Execution providers: Plug in hardware-specific backends (CUDA, TensorRT, OpenVINO, CoreML)
- Opset versions: Higher opset = more supported operations; use opset 17+ for modern models
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 解决AI模型跨框架互操作性的核心痛点
- 覆盖从导出到部署的完整生产流水线
- 支持CPU/GPU/边缘设备多平台推理
Highlights
- description精准描述核心功能边界
- 触发词覆盖模型导出、优化、部署全流程
Highlights
- Phase划分清晰,从安装到部署完整闭环
- 提供端到端可执行示例代码
- frontmatter完整包含兼容性信息
Areas to improve
-
缺少部分错误处理 Reported severity: Minor
示例代码中缺少try-catch等异常处理机制
Recommendation: 建议在关键操作处添加异常处理,如模型加载失败、推理错误等场景
Highlights
- 工具来源明确(onnx、onnxruntime等官方包)
- 参数配置合理,包含优化选项
- 覆盖量化、简化等生产级优化手段
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Save or modify files
Confirm the output directory and whether existing files will be replaced. Back up important files and prefer a new output directory.
Mentioned in main document · lines 157 -
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 27, 30, 33, 78, 153
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.