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
A Deep Learning Framework for Neural Derivative Hedging

NNHedge NNHedge is a PyTorch based framework for Neural Derivative Hedging. The following repository was implemented to ease the experiments of our pa

GUIJIN SON 17 Nov 14, 2022
Code for generating a single image pretraining dataset

Single Image Pretraining of Visual Representations As shown in the paper A critical analysis of self-supervision, or what we can learn from a single i

Yuki M. Asano 12 Dec 19, 2022
Multiview Neural Surface Reconstruction by Disentangling Geometry and Appearance

Multiview Neural Surface Reconstruction by Disentangling Geometry and Appearance Project Page | Paper | Data This repository contains an implementatio

Lior Yariv 521 Dec 30, 2022
Duke Machine Learning Winter School: Computer Vision 2022

mlwscv2002 Welcome to the Duke Machine Learning Winter School: Computer Vision 2022! The MLWS-CV includes 3 hands-on training sessions on implementing

Duke + Data Science (+DS) 9 May 25, 2022
[SIGGRAPH'22] StyleGAN-XL: Scaling StyleGAN to Large Diverse Datasets

[Project] [PDF] This repository contains code for our SIGGRAPH'22 paper "StyleGAN-XL: Scaling StyleGAN to Large Diverse Datasets" by Axel Sauer, Katja

742 Jan 04, 2023
A fast and easy to use, moddable, Python based Minecraft server!

PyMine PyMine - The fastest, easiest to use, Python-based Minecraft Server! Features Note: This list is not always up to date, and doesn't contain all

PyMine 144 Dec 30, 2022
Implicit MLE: Backpropagating Through Discrete Exponential Family Distributions

torch-imle Concise and self-contained PyTorch library implementing the I-MLE gradient estimator proposed in our NeurIPS 2021 paper Implicit MLE: Backp

UCL Natural Language Processing 249 Jan 03, 2023
This program will stylize your photos with fast neural style transfer.

Neural Style Transfer (NST) Using TensorFlow Demo TensorFlow TensorFlow is an end-to-end open source platform for machine learning. It has a comprehen

Ismail Boularbah 1 Aug 08, 2022
A faster pytorch implementation of faster r-cnn

A Faster Pytorch Implementation of Faster R-CNN Write at the beginning [05/29/2020] This repo was initaited about two years ago, developed as the firs

Jianwei Yang 7.1k Jan 01, 2023
Tracing Versus Freehand for Evaluating Computer-Generated Drawings (SIGGRAPH 2021)

Tracing Versus Freehand for Evaluating Computer-Generated Drawings (SIGGRAPH 2021) Zeyu Wang, Sherry Qiu, Nicole Feng, Holly Rushmeier, Leonard McMill

Zach Zeyu Wang 23 Dec 09, 2022
Edison AT is software Depression Assistant personal.

Edison AT Edison AT is software / program Depression Assistant personal. Feature: Analyze emotional real-time from face. Audio Edison(Comingsoon relea

Ananda Rauf 2 Apr 24, 2022
Code accompanying the paper Shared Independent Component Analysis for Multi-subject Neuroimaging

ShICA Code accompanying the paper Shared Independent Component Analysis for Multi-subject Neuroimaging Install Move into the ShICA directory cd ShICA

8 Nov 07, 2022
This thesis is mainly concerned with state-space methods for a class of deep Gaussian process (DGP) regression problems

Doctoral dissertation of Zheng Zhao This thesis is mainly concerned with state-space methods for a class of deep Gaussian process (DGP) regression pro

Zheng Zhao 21 Nov 14, 2022
Discovering Interpretable GAN Controls [NeurIPS 2020]

GANSpace: Discovering Interpretable GAN Controls Figure 1: Sequences of image edits performed using control discovered with our method, applied to thr

Erik Härkönen 1.7k Jan 03, 2023
code for TCL: Vision-Language Pre-Training with Triple Contrastive Learning, CVPR 2022

Vision-Language Pre-Training with Triple Contrastive Learning, CVPR 2022 News (03/16/2022) upload retrieval checkpoints finetuned on COCO and Flickr T

187 Jan 02, 2023
code for "AttentiveNAS Improving Neural Architecture Search via Attentive Sampling"

code for "AttentiveNAS Improving Neural Architecture Search via Attentive Sampling"

Facebook Research 94 Oct 26, 2022
This code is a near-infrared spectrum modeling method based on PCA and pls

Nirs-Pls-Corn This code is a near-infrared spectrum modeling method based on PCA and pls 近红外光谱分析技术属于交叉领域,需要化学、计算机科学、生物科学等多领域的合作。为此,在(北邮邮电大学杨辉华老师团队)指导下

Fu Pengyou 6 Dec 17, 2022
[NeurIPS 2021] “Improving Contrastive Learning on Imbalanced Data via Open-World Sampling”,

Improving Contrastive Learning on Imbalanced Data via Open-World Sampling Introduction Contrastive learning approaches have achieved great success in

VITA 24 Dec 17, 2022
ZeroGen: Efficient Zero-shot Learning via Dataset Generation

ZEROGEN This repository contains the code for our paper “ZeroGen: Efficient Zero

Jiacheng Ye 31 Dec 30, 2022
Pixel Consensus Voting for Panoptic Segmentation (CVPR 2020)

Implementation for Pixel Consensus Voting (CVPR 2020). This codebase contains the essential ingredients of PCV, including various spatial discretizati

Haochen 23 Oct 25, 2022