onnx-tool

ThanatosShinjiMIT更新放缓

解析、编辑、优化和性能分析 ONNX 模型的 Python 工具,方便查看模型结构、修改计算图并定位推理瓶颈。

A tool for parsing, editing, optimizing, and profiling ONNX models.

暂无版本494star68fork同步于 2026-11-07 07:30 UTC

怎么上手

由 README 提炼,执行前请确认
pip install onnx-tool
硬件要求按 README 说明

README 未说明显存或 GPU 型号要求;延迟估算表按 Ultra-358H、Arc-B70、RTX-4090、RTX-5090 等硬件规格推算,并非实测。

支持 Apple Silicon
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

解析、编辑、优化并剖析 ONNX 模型的 Python 工具库,支持 LLM 与扩散模型

解析、编辑、优化和性能分析 ONNX 模型的 Python 工具,方便查看模型结构、修改计算图并定位推理瓶颈。

核心能力

  • 用 Model/graph/nodemap 接口直接改节点属性和张量
  • 做常量折叠与算子融合的图变换
  • 快速形状推导并统计 MACs、参数量与稀疏度
  • 复用临时缓冲区压缩激活内存,典型降幅超 90%
  • 内置 PyTorch 后端推理引擎,注册 40+ 算子内核

容易踩的坑

推理引擎依赖 PyTorch 后端,需另行安装;剖析 LLM 需先自行导出对应 ONNX 模型;延迟数据由硬件规格推算而非实测,不能直接当基准。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    📄 简体中文 | ✨ New Project: AI-Enhancement-Filter (powered by onnx-tool)


    onnx-tool

    A comprehensive toolkit for analyzing, optimizing, and transforming ONNX models with advanced capabilities for LLMs, diffusion models, and computer vision architectures.

    • LLM Optimization: Build and profile large language models with KV cache analysis (example)
    • Graph Transformation:
      • Constant folding (docs)
      • Operator fusion (docs)
    • Advanced Profiling:
      • Rapid shape inference
      • MACs/parameter statistics with sparsity awareness
    • Compute Graph Engine: Runtime shape computation with minimal overhead (details)
    • Inference Engine: PyTorch-backed graph inference with memory pool (details)
      • 40+ registered op kernels (Conv, Add, Relu, Gemm, etc.)
      • Up to 11.3x faster than PyTorch in dynamic resolution scenarios
      • 54% memory reduction via two-pass compression algorithm
    • Memory Compression:
      • Activation memory optimization (up to 95% reduction)
      • Weight quantization (FP16, INT8/INT4 with per-tensor/channel/block schemes)
    • Quantization & Sparsity: Full support for quantized and sparse model analysis

    🤖 Supported Model Architectures

    DomainModels
    NLPBERT, T5, GPT, LLaMa, MPT, Qwen3, Qwen3.5 (Dense & MoE), DeepSeek-V4 (Flash/Pro, MLA+MoE), MiniMax-M2.7 (MoE) (TransformerModel)
    DiffusionStable Diffusion (TextEncoder, VAE, UNet)
    CVDetic, BEVFormer, SSD300_VGG16, ConvNeXt, Mask R-CNN, Silero VAD
    AudioSovits, LPCNet

    🆕 Qwen3.5 Series: Full support for Qwen3.5 hybrid architecture including:

    • Gated DeltaNet (GDN) layers with linear attention
    • QKV Gating (Q projection with built-in gate, applied before O-projection)
    • Sparse Mixture-of-Experts (MoE) with routed + shared experts
    • Mixed layer types (linear_attention / full_attention) per config
    • Multimodal Vision Encoder (ViT + MLP Projector) with resolution-aware profiling

    ⚡ Build & Profile LLMs in Seconds

    Profile 10 Hugging Face models in under one second. Export ONNX models with llama.cpp-like simplicity (code).

    Model Statistics (1k token input)

    model name(1k input)MACs(G)Parameters(G)KV Cache(G)
    Phi-3-mini-4k40833.821080.201327
    Phi-3-small-8k-instruct79127.801670.0671089
    Phi-3-medium-4k-instruct1466513.96020.104858
    Llama3-8B80298.030260.0671089
    Llama-3.1-70B-Japanese-Instruct-24077288870.55370.167772
    Qwen3.5-4B-Instruct 🆕48074.6510.067109
    Qwen3.5-35B-A3B-Instruct 🆕 (MoE)357434.7050.041943
    DeepSeek-V4-Flash 🆕 (MoE/MLA)15681283.8110.045089
    DeepSeek-V4-Pro 🆕 (MoE/MLA)557011571.7420.063963
    MiniMax-M2.7 🆕 (MoE)12554230.3150.130023

    Multimodal: Vision Encoder vs LLM MACs 🆕

    Vision encoder (ViT-24L + MLP Projector) vs LLM backbone. LLM input seq_len = vision patches + 1K text tokens. Both models share the same ViT architecture. See benchmark/vision_llm_compare.py.

    ResolutionPatchesTotal TokensVision(G)4B LLM(G)4B Vis/LLM(%)35B LLM(G)35B Vis/LLM(%)
    224×2242561,280846,0801.44,5571.8
    448×4481,0242,04838910,0703.97,7195.0
    672×6722,3043,3281,06117,2926.113,7027.7
    896×8964,0965,1202,35028,5998.223,5769.9
    1344×8966,1447,1684,31743,23310.037,00011.6
    1344×13449,21610,2408,25968,60712.061,41413.4

    💡 Vision MACs scale with O(p²), LLM MACs with O(t²) where t = patches + text. At 448×448, vision is ~4-5% of LLM; at 1344×1344, ~12-13%. Vision is always the minor component.

    MoE Activated Parameters vs Sequence Length

    Activated parameters = sum of all nodes' static_params (weights actually accessed during forward pass). S=32: Qwen3.5-35B-A3B & MiniMax-M2.7 experts fully activated (gap ≈ embedding); DeepSeek-V4 not yet saturated (top-6 × 32 = 192 < num_experts).

    modelTotal(G)S=1S=2S=4S=8S=16S=32
    Qwen3.5-35B-A3B (MoE)34.32.443.445.469.4817.5433.64
    MiniMax-M2.7 (MoE)230.310.4217.4431.4859.56115.73228.08
    DeepSeek-V4-Flash (MoE)283.812.7519.2432.2358.20110.14214.03
    DeepSeek-V4-Pro (MoE)1571.747.6071.77120.13216.84410.27797.12

    Latency Estimation (4-bit weights, 16-bit KV cache)

    Prefill Throughput (tokens/s, 1k input)

    modelUltra-358HArc-B70RTX-4090RTX-5090
    Phi-3-mini-4k6658.921279.819896.025567.0
    Phi-3-small-8k-instruct3599.511316.910429.813334.3
    Phi-3-medium-4k-instruct1964.86151.85649.17213.2
    Llama3-8B3499.911053.210226.713092.7
    Llama-3.1-70B-Japanese-Instruct-2407401.21249.31141.81455.5
    Qwen3.5-4B-Instruct 🆕5705.018162.016923.121720.3
    Qwen3.5-35B-A3B-Instruct 🆕 (MoE)4660.918458.321970.029367.3
    MiniMax-M2.7 🆕 (MoE)970.54285.16090.49083.3

    Decode Throughput (tokens/s)

    modelUltra-358HArc-B70RTX-4090RTX-5090
    Phi-3-mini-4k56.4267.9444.2789.7
    Phi-3-small-8k-instruct33.4158.5262.8467.2
    Phi-3-medium-4k-instruct18.085.4141.6251.8
    Llama3-8B32.9156.1258.9460.2
    Llama-3.1-70B-Japanese-Instruct-24073.617.328.751.0
    Qwen3.5-4B-Instruct 🆕56.5268.4444.9791.0
    Qwen3.5-35B-A3B-Instruct 🆕 (MoE)79.0375.0621.81105.4
    MiniMax-M2.7 🆕 (MoE)23.4111.0184.1327.3

    💡 Latencies computed from hardware specs – no actual inference required. Uses BF16/FP16 compute with FP32 accumulate as the standard.


    🔧 Basic Parsing & Editing

    Intuitive API for model manipulation:

    from onnx_tool import Model
    
    model = Model('model.onnx')          # Load any ONNX file
    graph = model.graph                  # Access computation graph
    node = graph.nodemap['Conv_0']       # Modify operator attributes
    tensor = graph.tensormap['weight']   # Edit tensor data/types
    model.save_model('modified.onnx')    # Persist changes
    

    See comprehensive examples in benchmark/examples.py.


    📊 Shape Inference & Profiling

    All profiling relies on precise shape inference:

    Profiling Capabilities

    • Standard profiling: MACs, parameters, memory footprint
    • Sparse-aware profiling: Quantify sparsity impact on compute

    📚 Learn more:


    ⚙️ Compute Graph & Shape Engine

    Transform exported ONNX graphs into efficient Compute Graphs by removing shape-calculation overhead:

    • Compute Graph: Minimal graph containing only compute operations
    • Shape Engine: Runtime shape resolver for dynamic models

    Use Cases:

    • Integration with custom inference engines (guide)
    • Shape regression testing (example)

    💾 Memory Compression

    Activation Memory Compression

    Reuses temporary buffers to minimize peak memory usage – critical for LLMs and high-res CV models.

    modelNative Memory Size(MB)Compressed Memory Size(MB)Compression Ratio(%)
    StableDiffusion(VAE_encoder)14,2455403.7
    StableDiffusion(VAE_decoder)25,4171,1404.48
    StableDiffusion(Text_encoder)21552.5
    StableDiffusion(UNet)36,1352,2326.2
    GPT24026.9
    BERT2,170271.25

    ✅ Typical models achieve >90% activation memory reduction
    📌 Implementation: benchmark/compression.py

    The compress_memory() algorithm has been patched with two improvements (see onnx_tool/graph.py):

    1. Size-sorted allocation: New tensors within each node are allocated in descending size order, reducing fragmentation
    2. Tail compression: Unused space at the end of the memory pool is trimmed
    3. List reference fix: Each tensor's [offset, size] is stored as an independent copy, preventing accidental cross-tensor aliasing

    Benchmark results across models:

    modelNative(MB)Compressed(MB)Ratio(%)
    VAE encoder11,313.6512.04.53
    VAE decoder19,816.2896.14.52
    Text encoder172.53.72.12
    GPT2381.116.14.23
    ResNet50279.310.73.84

    ✅ Optimized algorithm achieves up to 54% additional pool reduction (ResNet50: 21.4→10.7 MB vs original)

    Inference Engine

    The inference/ module provides a complete PyTorch-backed inference engine built on the compressed memory pool:

    • MemoryPool: Zero-copy tensor views into a pre-allocated contiguous buffer
    • Kernel Registry: 40+ registered op kernels (Conv, Add, Relu, Gemm, MatMul, etc.)
    • GraphInfer: Graph-level inference with shape engine integration

    Performance highlights (ResNet18 on Intel XPU):

    MetricPyTorchGraphInferImprovement
    Single inference (1080p)0.0151s0.0167s0.91x (on par)
    Sequential 7 resolutions1820ms162ms11.3x faster
    Peak XPU memory (4K)2338 MB1926 MB17.6% less
    Memory pool (4K)—1012 MBFixed size

    📌 See inference/README.md for full benchmark details

    Weight Compression

    Essential for deploying large models on memory-constrained devices:

    Quantization SchemeSize vs FP32Example (7B model)
    FP32 (baseline)1.00×28 GB
    FP160.50×14 GB
    INT8 (per-channel)0.25×7 GB
    INT4 (block=32, symmetric) – llama.cpp0.156×4.4 GB

    Supported schemes:

    • ✅ FP16
    • ✅ INT8: symmetric/asymmetric × per-tensor/channel/block
    • ✅ INT4: symmetric/asymmetric × per-tensor/channel/block

    📌 See benchmark/examples.py for implementation examples.


    🚀 Installation

    # PyPI (recommended)
    pip install onnx-tool
    
    # Latest development version
    pip install --upgrade git+https://github.com/ThanatosShinji/onnx-tool.git
    

    Requirements: Python ≥ 3.6

    ⚠️ Troubleshooting: If ONNX installation fails, try:

    pip install onnx==1.8.1 && pip install onnx-tool
    

    Known Issues

    • Loop op is not supported
    • Sequence type is not supported

    📈 Model Zoo Results

    Comprehensive profiling of ONNX Model Zoo and SOTA models. Input shapes defined in data/public/config.py.

    📥 Download pre-profiled models (with full tensor shapes):

    ModelParams(M)MACs(M)
    GPT-J 1 layer464173,398
    MPT 1 layer26179,894
    text_encoder123.136,782
    UNet2DCondition859.52888,870
    VAE_encoder34.16566,371
    VAE_decoder49.491,271,959
    SqueezeNet 1.01.23351
    AlexNet60.96665
    GoogleNet6.991,606
    googlenet_age5.981,605
    LResNet100E-IR65.2212,102
    BERT-Squad113.6122,767
    BiDAF18.089.87
    EfficientNet-Lite412.961,361
    Emotion12.95877
    Mask R-CNN46.7792,077
    ModelParams(M)MACs(M)
    LLaMa 1 layer618211,801
    BEVFormer Tiny33.7210,838
    rvm_mobilenetv33.734,289
    yolov464.333,319
    ConvNeXt-L229.7934,872
    edgenext_small5.581,357
    SSD19.98216,598
    RealESRGAN16.6973,551
    ShuffleNet2.29146
    GPT-2137.021,103
    T5-encoder109.62686
    T5-decoder162.621,113
    RoBERTa-BASE124.64688
    Faster R-CNN44.1046,018
    FCN ResNet-5035.2937,056
    ResNet50253,868

    🤝 Contributing

    Contributions are welcome! Please open an issue or PR for:

    • Bug reports
    • Feature requests
    • Documentation improvements
    • New model support