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
FIGARO: Generating Symbolic Music with Fine-Grained Artistic Control

FIGARO: Generating Symbolic Music with Fine-Grained Artistic Control by Dimitri von Rütte, Luca Biggio, Yannic Kilcher, Thomas Hofmann FIGARO: Generat

Dimitri 83 Jan 07, 2023
Codebase of deep learning models for inferring stability of mRNA molecules

Kaggle OpenVaccine Models Codebase of deep learning models for inferring stability of mRNA molecules, corresponding to the Kaggle Open Vaccine Challen

Eternagame 40 Dec 29, 2022
Python with OpenCV - MediaPip Framework Hand Detection

Python HandDetection Python with OpenCV - MediaPip Framework Hand Detection Explore the docs » Contact Me About The Project It is a Computer vision pa

2 Jan 07, 2022
Manifold-Mixup implementation for fastai V2

Manifold Mixup Unofficial implementation of ManifoldMixup (Proceedings of ICML 19) for fast.ai (V2) based on Shivam Saboo's pytorch implementation of

Nestor Demeure 16 Jul 25, 2022
Contrastive Learning of Image Representations with Cross-Video Cycle-Consistency

Contrastive Learning of Image Representations with Cross-Video Cycle-Consistency This is a official implementation of the CycleContrast introduced in

13 Nov 14, 2022
202 Jan 06, 2023
IEGAN — Official PyTorch Implementation Independent Encoder for Deep Hierarchical Unsupervised Image-to-Image Translation

IEGAN — Official PyTorch Implementation Independent Encoder for Deep Hierarchical Unsupervised Image-to-Image Translation Independent Encoder for Deep

30 Nov 05, 2022
OBBDetection: an oriented object detection toolbox modified from MMdetection

OBBDetection note: If you have questions or good suggestions, feel free to propose issues and contact me. introduction OBBDetection is an oriented obj

MIXIAOXIN_HO 3 Nov 11, 2022
Geometric Vector Perceptron --- a rotation-equivariant GNN for learning from biomolecular structure

Geometric Vector Perceptron Code to accompany Learning from Protein Structure with Geometric Vector Perceptrons by B Jing, S Eismann, P Suriana, RJL T

Dror Lab 85 Dec 29, 2022
The pytorch implementation of DG-Font: Deformable Generative Networks for Unsupervised Font Generation

DG-Font: Deformable Generative Networks for Unsupervised Font Generation The source code for 'DG-Font: Deformable Generative Networks for Unsupervised

130 Dec 05, 2022
A universal memory dumper using Frida

Fridump Fridump (v0.1) is an open source memory dumping tool, primarily aimed to penetration testers and developers. Fridump is using the Frida framew

551 Jan 07, 2023
Pytorch implementation of FlowNet by Dosovitskiy et al.

FlowNetPytorch Pytorch implementation of FlowNet by Dosovitskiy et al. This repository is a torch implementation of FlowNet, by Alexey Dosovitskiy et

Clément Pinard 762 Jan 02, 2023
Source code for our CVPR 2019 paper - PPGNet: Learning Point-Pair Graph for Line Segment Detection

PPGNet: Learning Point-Pair Graph for Line Segment Detection PyTorch implementation of our CVPR 2019 paper: PPGNet: Learning Point-Pair Graph for Line

SVIP Lab 170 Oct 25, 2022
Source code of our BMVC 2021 paper: AniFormer: Data-driven 3D Animation with Transformer

AniFormer This is the PyTorch implementation of our BMVC 2021 paper AniFormer: Data-driven 3D Animation with Transformer. Haoyu Chen, Hao Tang, Nicu S

24 Nov 02, 2022
This repository provides the official code for GeNER (an automated dataset Generation framework for NER).

GeNER This repository provides the official code for GeNER (an automated dataset Generation framework for NER). Overview of GeNER GeNER allows you to

DMIS Laboratory - Korea University 50 Nov 30, 2022
Official codebase for Legged Robots that Keep on Learning: Fine-Tuning Locomotion Policies in the Real World

Legged Robots that Keep on Learning Official codebase for Legged Robots that Keep on Learning: Fine-Tuning Locomotion Policies in the Real World, whic

Laura Smith 70 Dec 07, 2022
SBINN: Systems-biology informed neural network

SBINN: Systems-biology informed neural network The source code for the paper M. Daneker, Z. Zhang, G. E. Karniadakis, & L. Lu. Systems biology: Identi

Lu Group 15 Nov 19, 2022
The implementation of the lifelong infinite mixture model

Lifelong infinite mixture model 📋 This is the implementation of the Lifelong infinite mixture model 📋 Accepted by ICCV 2021 Title : Lifelong Infinit

Fei Ye 5 Oct 20, 2022
This repo contains the official implementations of EigenDamage: Structured Pruning in the Kronecker-Factored Eigenbasis

EigenDamage: Structured Pruning in the Kronecker-Factored Eigenbasis This repo contains the official implementations of EigenDamage: Structured Prunin

Chaoqi Wang 107 Apr 20, 2022
Implementation of the paper "Fine-Tuning Transformers: Vocabulary Transfer"

Transformer-vocabulary-transfer Implementation of the paper "Fine-Tuning Transfo

LEYA 13 Nov 30, 2022