A very simple tool to rewrite parameters such as attributes and constants for OPs in ONNX models. Simple Attribute and Constant Modifier for ONNX.

Overview

sam4onnx

A very simple tool to rewrite parameters such as attributes and constants for OPs in ONNX models. Simple Attribute and Constant Modifier for ONNX.

https://github.com/PINTO0309/simple-onnx-processing-tools

Downloads GitHub PyPI CodeQL

Key concept

  • Specify an arbitrary OP name and Constant type INPUT name or an arbitrary OP name and Attribute name, and pass the modified constants to rewrite the parameters of the relevant OP.
  • Two types of input are accepted: .onnx file input and onnx.ModelProto format objects.
  • To design the operation to be simple, only a single OP can be specified.
  • Attributes and constants are forcibly rewritten, so the integrity of the entire graph is not checked in detail.

1. Setup

1-1. HostPC

### option
$ echo export PATH="~/.local/bin:$PATH" >> ~/.bashrc \
&& source ~/.bashrc

### run
$ pip install -U onnx \
&& python3 -m pip install -U onnx_graphsurgeon --index-url https://pypi.ngc.nvidia.com \
&& pip install -U sam4onnx

1-2. Docker

### docker pull
$ docker pull pinto0309/sam4onnx:latest

### docker build
$ docker build -t pinto0309/sam4onnx:latest .

### docker run
$ docker run --rm -it -v `pwd`:/workdir pinto0309/sam4onnx:latest
$ cd /workdir

2. CLI Usage

$ sam4onnx -h

usage:
    sam4onnx [-h]
    --input_onnx_file_path INPUT_ONNX_FILE_PATH
    --output_onnx_file_path OUTPUT_ONNX_FILE_PATH
    [--op_name OP_NAME]
    [--attributes NAME DTYPE VALUE]
    [--input_constants NAME DTYPE VALUE]
    [--non_verbose]

optional arguments:
  -h, --help
        show this help message and exit

  --input_onnx_file_path INPUT_ONNX_FILE_PATH
        Input onnx file path.

  --output_onnx_file_path OUTPUT_ONNX_FILE_PATH
        Output onnx file path.

  --op_name OP_NAME
        OP name of the attributes to be changed.
        When --attributes is specified, --op_name must always be specified.
        e.g. --op_name aaa

  --attributes NAME DTYPE VALUE
        Parameter to change the attribute of the OP specified in --op_name.
        If the OP specified in --op_name has no attributes,
        it is ignored. attributes can be specified multiple times.
        --attributes name dtype value dtype is one of
        "float32" or "float64" or "int32" or "int64" or "str".
        https://github.com/onnx/onnx/blob/main/docs/Operators.md

        e.g.
        --attributes alpha float32 [[1.0]]
        --attributes beta float32 [1.0]
        --attributes transA int64 0
        --attributes transB int64 0

  --input_constants NAME DTYPE VALUE
        Specifies the name of the constant to be changed.
        If you want to change only the constant,
        you do not need to specify --op_name and --attributes.
        input_constants can be specified multiple times.
        --input_constants constant_name numpy.dtype value

        e.g.
        --input_constants constant_name1 int64 0
        --input_constants constant_name2 float32 [[1.0,2.0,3.0],[4.0,5.0,6.0]]

  --non_verbose
        Do not show all information logs. Only error logs are displayed.

3. In-script Usage

$ python
>>> from sam4onnx import modify
>>> help(modify)
Help on function modify in module sam4onnx.onnx_attr_const_modify:

modify(
    input_onnx_file_path: Union[str, NoneType] = '',
    output_onnx_file_path: Union[str, NoneType] = '',
    onnx_graph: Union[onnx.onnx_ml_pb2.ModelProto, NoneType] = None,
    op_name: Union[str, NoneType] = '',
    attributes: Union[dict, NoneType] = None,
    input_constants: Union[dict, NoneType] = None,
    non_verbose: Union[bool, NoneType] = False
) -> onnx.onnx_ml_pb2.ModelProto

    Parameters
    ----------
    input_onnx_file_path: Optional[str]
        Input onnx file path.
        Either input_onnx_file_path or onnx_graph must be specified.

    output_onnx_file_path: Optional[str]
        Output onnx file path.
        If output_onnx_file_path is not specified, no .onnx file is output.

    onnx_graph: Optional[onnx.ModelProto]
        onnx.ModelProto.
        Either input_onnx_file_path or onnx_graph must be specified.
        onnx_graph If specified, ignore input_onnx_file_path and process onnx_graph.

    op_name: Optional[str]
        OP name of the attributes to be changed.
        When --attributes is specified, --op_name must always be specified.
        Default: ''
        https://github.com/onnx/onnx/blob/main/docs/Operators.md

    attributes: Optional[dict]
        Specify output attributes for the OP to be generated.
        See below for the attributes that can be specified.

        {"attr_name1": numpy.ndarray, "attr_name2": numpy.ndarray, ...}

        e.g. attributes =
            {
                "alpha": np.asarray(1.0, dtype=np.float32),
                "beta": np.asarray(1.0, dtype=np.float32),
                "transA": np.asarray(0, dtype=np.int64),
                "transB": np.asarray(0, dtype=np.int64)
            }
        Default: None
        https://github.com/onnx/onnx/blob/main/docs/Operators.md

    input_constants: Optional[dict]
        Specifies the name of the constant to be changed.
        If you want to change only the constant,
        you do not need to specify --op_name and --attributes.
        {"constant_name1": numpy.ndarray, "constant_name2": numpy.ndarray, ...}

        e.g.
        input_constants =
            {
                "constant_name1": np.asarray(0, dtype=np.int64),
                "constant_name2": np.asarray([[1.0,2.0,3.0],[4.0,5.0,6.0]], dtype=np.float32)
            }
        Default: None
        https://github.com/onnx/onnx/blob/main/docs/Operators.md

    non_verbose: Optional[bool]
        Do not show all information logs. Only error logs are displayed.
        Default: False

    Returns
    -------
    modified_graph: onnx.ModelProto
        Mddified onnx ModelProto

4. CLI Execution

$ sam4onnx \
--op_name Transpose_17 \
--input_onnx_file_path input.onnx \
--output_onnx_file_path output.onnx \
--attributes perm int64 [0,1]

5. In-script Execution

from sam4onnx import modify

modified_graph = modify(
    onnx_graph=graph,
    input_constants={"241": np.asarray([1], dtype=np.int64)},
    non_verbose=True,
)

6. Sample

6-1. Transpose - update perm

image

$ sam4onnx \
--op_name Transpose_17 \
--input_onnx_file_path hitnet_sf_finalpass_720x1280_nonopt.onnx \
--output_onnx_file_path hitnet_sf_finalpass_720x1280_nonopt_mod.onnx \
--attributes perm int64 [0,1]

image

6-2. Mul - update Constant (170) - From: 2, To: 1

image

$ sam4onnx \
--input_onnx_file_path hitnet_sf_finalpass_720x1280_nonopt.onnx \
--output_onnx_file_path hitnet_sf_finalpass_720x1280_nonopt_mod.onnx \
--input_constants 170 float32 1

image

6-3. Reshape - update Constant (241) - From: [-1], To: [1]

image

$ sam4onnx \
--input_onnx_file_path hitnet_sf_finalpass_720x1280_nonopt.onnx \
--output_onnx_file_path hitnet_sf_finalpass_720x1280_nonopt_mod.onnx \
--input_constants 241 int64 [1]

image

7. Issues

https://github.com/PINTO0309/simple-onnx-processing-tools/issues

You might also like...
Simple ONNX operation generator. Simple Operation Generator for ONNX.
Simple ONNX operation generator. Simple Operation Generator for ONNX.

sog4onnx Simple ONNX operation generator. Simple Operation Generator for ONNX. https://github.com/PINTO0309/simple-onnx-processing-tools Key concept V

Milano is a tool for automating hyper-parameters search for your models on a backend of your choice.
Milano is a tool for automating hyper-parameters search for your models on a backend of your choice.

Milano (This is a research project, not an official NVIDIA product.) Documentation https://nvidia.github.io/Milano Milano (Machine learning autotuner

CBREN: Convolutional Neural Networks for Constant Bit Rate Video Quality Enhancement

CBREN This is the Pytorch implementation for our IEEE TCSVT paper : CBREN: Convolutional Neural Networks for Constant Bit Rate Video Quality Enhanceme

ONNX Runtime Web demo is an interactive demo portal showing real use cases running ONNX Runtime Web in VueJS.

ONNX Runtime Web demo is an interactive demo portal showing real use cases running ONNX Runtime Web in VueJS. It currently supports four examples for you to quickly experience the power of ONNX Runtime Web.

ONNX-GLPDepth - Python scripts for performing monocular depth estimation using the GLPDepth model in ONNX
ONNX-GLPDepth - Python scripts for performing monocular depth estimation using the GLPDepth model in ONNX

ONNX-GLPDepth - Python scripts for performing monocular depth estimation using the GLPDepth model in ONNX

ONNX-PackNet-SfM: Python scripts for performing monocular depth estimation using the PackNet-SfM model in ONNX
ONNX-PackNet-SfM: Python scripts for performing monocular depth estimation using the PackNet-SfM model in ONNX

Python scripts for performing monocular depth estimation using the PackNet-SfM model in ONNX

Quickly comparing your image classification models with the state-of-the-art models (such as DenseNet, ResNet, ...)
Quickly comparing your image classification models with the state-of-the-art models (such as DenseNet, ResNet, ...)

Image Classification Project Killer in PyTorch This repo is designed for those who want to start their experiments two days before the deadline and ki

Ranger deep learning optimizer rewrite to use newest components
Ranger deep learning optimizer rewrite to use newest components

Ranger21 - integrating the latest deep learning components into a single optimizer Ranger deep learning optimizer rewrite to use newest components Ran

Releases(1.0.12)
  • 1.0.12(Jan 2, 2023)

    What's Changed

    • Support for models with custom domains by @PINTO0309 in https://github.com/PINTO0309/sam4onnx/pull/2

    New Contributors

    • @PINTO0309 made their first contribution in https://github.com/PINTO0309/sam4onnx/pull/2

    Full Changelog: https://github.com/PINTO0309/sam4onnx/compare/1.0.11...1.0.12

    Source code(tar.gz)
    Source code(zip)
  • 1.0.11(Sep 8, 2022)

    • Add short form parameter
      $ sam4onnx -h
      
      usage:
          sam4onnx [-h]
          -if INPUT_ONNX_FILE_PATH
          -of OUTPUT_ONNX_FILE_PATH
          [-on OP_NAME]
          [-a NAME DTYPE VALUE]
          [-da DELETE_ATTRIBUTES [DELETE_ATTRIBUTES ...]]
          [-ic NAME DTYPE VALUE]
          [-n]
      
      optional arguments:
        -h, --help
          show this help message and exit
      
        -if INPUT_ONNX_FILE_PATH, --input_onnx_file_path INPUT_ONNX_FILE_PATH
          Input onnx file path.
      
        -of OUTPUT_ONNX_FILE_PATH, --output_onnx_file_path OUTPUT_ONNX_FILE_PATH
          Output onnx file path.
      
        -on OP_NAME, --op_name OP_NAME
          OP name of the attributes to be changed.
          When --attributes is specified, --op_name must always be specified.
          e.g. --op_name aaa
      
        -a ATTRIBUTES ATTRIBUTES ATTRIBUTES, --attributes ATTRIBUTES ATTRIBUTES ATTRIBUTES
          Parameter to change the attribute of the OP specified in --op_name.
          If the OP specified in --op_name has no attributes,
          it is ignored. attributes can be specified multiple times.
          --attributes name dtype value dtype is one of
          "float32" or "float64" or "int32" or "int64" or "str".
          https://github.com/onnx/onnx/blob/main/docs/Operators.md
      
          e.g.
          --attributes alpha float32 [[1.0]]
          --attributes beta float32 [1.0]
          --attributes transA int64 0
          --attributes transB int64 0
      
        -da DELETE_ATTRIBUTES [DELETE_ATTRIBUTES ...], --delete_attributes DELETE_ATTRIBUTES [DELETE_ATTRIBUTES ...]
          Parameter to delete the attribute of the OP specified in --op_name.
          If the OP specified in --op_name has no attributes,
          it is ignored. delete_attributes can be specified multiple times.
          --delete_attributes name1 name2 name3
          https://github.com/onnx/onnx/blob/main/docs/Operators.md
      
          e.g. --delete_attributes alpha beta
      
        -ic INPUT_CONSTANTS INPUT_CONSTANTS INPUT_CONSTANTS, --input_constants INPUT_CONSTANTS INPUT_CONSTANTS INPUT_CONSTANTS
          Specifies the name of the constant to be changed.
          If you want to change only the constant,
          you do not need to specify --op_name and --attributes.
          input_constants can be specified multiple times.
          --input_constants constant_name numpy.dtype value
      
          e.g.
          --input_constants constant_name1 int64 0
          --input_constants constant_name2 float32 [[1.0,2.0,3.0],[4.0,5.0,6.0]]
          --input_constants constant_name3 float32 [\'-Infinity\']
      
        -n, --non_verbose
          Do not show all information logs. Only error logs are displayed.
      
    Source code(tar.gz)
    Source code(zip)
  • 1.0.10(Aug 7, 2022)

  • 1.0.9(Jul 17, 2022)

    • Support for constant rewriting when the same constant is shared. Valid only when op_name is specified. Generates a new constant that is different from the shared constant.

    • Reshape_156 onnx::Reshape_391 int64 [1, -1, 85] image

    • Reshape_174 onnx::Reshape_391 int64 [1, -1, 85] image

      sam4onnx \
      --input_onnx_file_path yolov7-tiny_test_sim.onnx \
      --output_onnx_file_path yolov7-tiny_test_sim_mod.onnx \
      --op_name Reshape_156 \
      --input_constants onnx::Reshape_391 int64 [1,14400,85]
      
    • Reshape_156 onnx::Reshape_391 int64 [1, -1, 85] -> Reshape_156 onnx::Reshape_391_mod_3 int64 [1, 14400, 85] image

    • Reshape_174 onnx::Reshape_391 int64 [1, -1, 85] image

    Source code(tar.gz)
    Source code(zip)
  • 1.0.8(Jun 7, 2022)

  • 1.0.7(May 25, 2022)

  • 1.0.6(May 15, 2022)

  • 1.0.5(May 12, 2022)

  • 1.0.4(May 5, 2022)

  • 1.0.3(May 5, 2022)

    • Support for additional attributes
      • Note that the correct attribute set according to the OP's opset is not checked, so any attribute can be added.
      • The figure below shows the addition of the attribute perm to Reshape, which does not originally exist. image
    Source code(tar.gz)
    Source code(zip)
  • 1.0.2(May 3, 2022)

  • 1.0.1(Apr 16, 2022)

  • 1.0.0(Apr 15, 2022)

Owner
Katsuya Hyodo
Hobby programmer. Intel Software Innovator Program member.
Katsuya Hyodo
This project provides a stock market environment using OpenGym with Deep Q-learning and Policy Gradient.

Stock Trading Market OpenAI Gym Environment with Deep Reinforcement Learning using Keras Overview This project provides a general environment for stoc

Kim, Ki Hyun 769 Dec 25, 2022
SubOmiEmbed: Self-supervised Representation Learning of Multi-omics Data for Cancer Type Classification

SubOmiEmbed: Self-supervised Representation Learning of Multi-omics Data for Cancer Type Classification

Sayed Hashim 3 Nov 15, 2022
Tiny Object Detection in Aerial Images.

AI-TOD AI-TOD is a dataset for tiny object detection in aerial images. [Paper] [Dataset] Description AI-TOD comes with 700,621 object instances for ei

jwwangchn 116 Dec 30, 2022
Official PyTorch implemention of our paper "Learning to Rectify for Robust Learning with Noisy Labels".

WarPI The official PyTorch implemention of our paper "Learning to Rectify for Robust Learning with Noisy Labels". Run python main.py --corruption_type

Haoliang Sun 3 Sep 03, 2022
This repository is an implementation of paper : Improving the Training of Graph Neural Networks with Consistency Regularization

CRGNN Paper : Improving the Training of Graph Neural Networks with Consistency Regularization Environments Implementing environment: GeForce RTX™ 3090

THUDM 28 Dec 09, 2022
Performant, differentiable reinforcement learning

deluca Performant, differentiable reinforcement learning Notes This is pre-alpha software and is undergoing a number of core changes. Updates to follo

Google 114 Dec 27, 2022
Text Extraction Formulation + Feedback Loop for state-of-the-art WSD (EMNLP 2021)

ConSeC is a novel approach to Word Sense Disambiguation (WSD), accepted at EMNLP 2021. It frames WSD as a text extraction task and features a feedback loop strategy that allows the disambiguation of

Sapienza NLP group 36 Dec 13, 2022
Attention for PyTorch with Linear Memory Footprint

Attention for PyTorch with Linear Memory Footprint Unofficially implements https://arxiv.org/abs/2112.05682 to get Linear Memory Cost on Attention (+

11 Jan 09, 2022
Athena is the only tool that you will ever need to optimize your portfolio.

Athena Portfolio optimization is the process of selecting the best portfolio (asset distribution), out of the set of all portfolios being considered,

Indrajit 1 Mar 25, 2022
Dynamic Environments with Deformable Objects (DEDO)

DEDO - Dynamic Environments with Deformable Objects DEDO is a lightweight and customizable suite of environments with deformable objects. It is aimed

Rika 32 Dec 22, 2022
Linear algebra python - Number of operations and problems in Linear Algebra and Numerical Linear Algebra

Linear algebra in python Number of operations and problems in Linear Algebra and

Alireza 5 Oct 09, 2022
3D Avatar Lip Syncronization from speech (JALI based face-rigging)

visemenet-inference Inference Demo of "VisemeNet-tensorflow" VisemeNet is an audio-driven animator centric speech animation driving a JALI or standard

Junhwan Jang 17 Dec 20, 2022
Official implementation for “Unsupervised Low-Light Image Enhancement via Histogram Equalization Prior”

HEP Unsupervised Low-Light Image Enhancement via Histogram Equalization Prior Implementation Python3 PyTorch=1.0 NVIDIA GPU+CUDA Training process The

FengZhang 34 Dec 04, 2022
Custom studies about block sparse attention.

Block Sparse Attention 研究总结 本人近半年来对Block Sparse Attention(块稀疏注意力)的研究总结(持续更新中)。按时间顺序,主要分为如下三部分: PyTorch 自定义 CUDA 算子——以矩阵乘法为例 基于 Triton 的 Block Sparse A

Chen Kai 2 Jan 09, 2022
验证码识别 深度学习 tensorflow 神经网络

captcha_tf2 验证码识别 深度学习 tensorflow 神经网络 使用卷积神经网络,对字符,数字类型验证码进行识别,tensorflow使用2.0以上 目前项目还在更新中,诸多bug,欢迎提出issue和PR, 希望和你一起共同完善项目。 实例demo 训练过程 优化器选择: Adam

5 Apr 28, 2022
[CVPR2021] Domain Consensus Clustering for Universal Domain Adaptation

[CVPR2021] Domain Consensus Clustering for Universal Domain Adaptation [Paper] Prerequisites To install requirements: pip install -r requirements.txt

Guangrui Li 84 Dec 26, 2022
The official implementation of A Unified Game-Theoretic Interpretation of Adversarial Robustness.

This repository is the official implementation of A Unified Game-Theoretic Interpretation of Adversarial Robustness. Requirements pip install -r requi

Jie Ren 17 Dec 12, 2022
DGCNN - Dynamic Graph CNN for Learning on Point Clouds

DGCNN is the author's re-implementation of Dynamic Graph CNN, which achieves state-of-the-art performance on point-cloud-related high-level tasks including category classification, semantic segmentat

Wang, Yue 1.3k Dec 26, 2022
🔅 Shapash makes Machine Learning models transparent and understandable by everyone

🎉 What's new ? Version New Feature Description Tutorial 1.6.x Explainability Quality Metrics To help increase confidence in explainability methods, y

MAIF 2.1k Dec 27, 2022
Incremental Transformer Structure Enhanced Image Inpainting with Masking Positional Encoding (CVPR2022)

Incremental Transformer Structure Enhanced Image Inpainting with Masking Positional Encoding by Qiaole Dong*, Chenjie Cao*, Yanwei Fu Paper and Supple

Qiaole Dong 190 Dec 27, 2022