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
Anomaly Transformer: Time Series Anomaly Detection with Association Discrepancy" (ICLR 2022 Spotlight)

About Code release for Anomaly Transformer: Time Series Anomaly Detection with Association Discrepancy (ICLR 2022 Spotlight)

THUML @ Tsinghua University 221 Dec 31, 2022
Script that receives an Image (original) and a set of images to be used as "pixels" in reconstruction of the Original image using the set of images as "pixels"

picinpics Script that receives an Image (original) and a set of images to be used as "pixels" in reconstruction of the Original image using the set of

RodrigoCMoraes 1 Oct 24, 2021
Finite-temperature variational Monte Carlo calculation of uniform electron gas using neural canonical transformation.

CoulombGas This code implements the neural canonical transformation approach to the thermodynamic properties of uniform electron gas. Building on JAX,

FermiFlow 9 Mar 03, 2022
Stereo Radiance Fields (SRF): Learning View Synthesis for Sparse Views of Novel Scenes

Stereo Radiance Fields (SRF): Learning View Synthesis for Sparse Views of Novel Scenes

111 Dec 29, 2022
YOLOv5🚀 reproduction by Guo Quanhao using PaddlePaddle

YOLOv5-Paddle YOLOv5 🚀 reproduction by Guo Quanhao using PaddlePaddle 支持AutoBatch 支持AutoAnchor 支持GPU Memory 快速开始 使用AIStudio高性能环境快速构建YOLOv5训练(PaddlePa

QuanHao Guo 20 Nov 14, 2022
Experimental solutions to selected exercises from the book [Advances in Financial Machine Learning by Marcos Lopez De Prado]

Advances in Financial Machine Learning Exercises Experimental solutions to selected exercises from the book Advances in Financial Machine Learning by

Brian 1.4k Jan 04, 2023
PyTorch implementations of the beta divergence loss.

Beta Divergence Loss - PyTorch Implementation This repository contains code for a PyTorch implementation of the beta divergence loss. Dependencies Thi

Billy Carson 7 Nov 09, 2022
library for nonlinear optimization, wrapping many algorithms for global and local, constrained or unconstrained, optimization

NLopt is a library for nonlinear local and global optimization, for functions with and without gradient information. It is designed as a simple, unifi

Steven G. Johnson 1.4k Dec 25, 2022
Code repo for realtime multi-person pose estimation in CVPR'17 (Oral)

Realtime Multi-Person Pose Estimation By Zhe Cao, Tomas Simon, Shih-En Wei, Yaser Sheikh. Introduction Code repo for winning 2016 MSCOCO Keypoints Cha

Zhe Cao 4.9k Dec 31, 2022
Utility tools for the "Divide and Remaster" dataset, introduced as part of the Cocktail Fork problem paper

Divide and Remaster Utility Tools Utility tools for the "Divide and Remaster" dataset, introduced as part of the Cocktail Fork problem paper The DnR d

Darius Petermann 46 Dec 11, 2022
The official code repo of "HTS-AT: A Hierarchical Token-Semantic Audio Transformer for Sound Classification and Detection"

Hierarchical Token Semantic Audio Transformer Introduction The Code Repository for "HTS-AT: A Hierarchical Token-Semantic Audio Transformer for Sound

Knut(Ke) Chen 134 Jan 01, 2023
A tensorflow/keras implementation of StyleGAN to generate images of new Pokemon.

PokeGAN A tensorflow/keras implementation of StyleGAN to generate images of new Pokemon. Dataset The model has been trained on dataset that includes 8

19 Jul 26, 2022
Codes for the AAAI'22 paper "TransZero: Attribute-guided Transformer for Zero-Shot Learning"

TransZero [arXiv] This repository contains the testing code for the paper "TransZero: Attribute-guided Transformer for Zero-Shot Learning" accepted to

Shiming Chen 52 Jan 01, 2023
Pytorch implementation of our paper under review -- 1xN Pattern for Pruning Convolutional Neural Networks

1xN Pattern for Pruning Convolutional Neural Networks (paper) . This is Pytorch re-implementation of "1xN Pattern for Pruning Convolutional Neural Net

Mingbao Lin (林明宝) 29 Nov 29, 2022
Bachelor's Thesis in Computer Science: Privacy-Preserving Federated Learning Applied to Decentralized Data

federated is the source code for the Bachelor's Thesis Privacy-Preserving Federated Learning Applied to Decentralized Data (Spring 2021, NTNU) Federat

Dilawar Mahmood 25 Nov 30, 2022
This is the repository for Learning to Generate Piano Music With Sustain Pedals

SusPedal-Gen This is the official repository of Learning to Generate Piano Music With Sustain Pedals Demo Page Dataset The dataset used in this projec

Joann Ching 12 Sep 02, 2022
This repository contains the reference implementation for our proposed Convolutional CRFs.

ConvCRF This repository contains the reference implementation for our proposed Convolutional CRFs in PyTorch (Tensorflow planned). The two main entry-

Marvin Teichmann 553 Dec 07, 2022
Experiment about Deep Person Re-identification with EfficientNet-v2

We evaluated the baseline with Resnet50 and Efficienet-v2 without using pretrained models. Also Resnet50-IBN-A and Efficientnet-v2 using pretrained on ImageNet. We used two datasets: Market-1501 and

lan.nguyen2k 77 Jan 03, 2023
pix2pix in tensorflow.js

pix2pix in tensorflow.js This repo is moved to https://github.com/yining1023/pix2pix_tensorflowjs_lite See a live demo here: https://yining1023.github

Yining Shi 47 Oct 04, 2022
YOLOv5 detection interface - PyQt5 implementation

所有代码已上传,直接clone后,运行yolo_win.py即可开启界面。 2021/9/29:加入置信度选择 界面是在ultralytics的yolov5基础上建立的,界面使用pyqt5实现,内容较简单,娱乐而已。 功能: 模型选择 本地文件选择(视频图片均可) 开关摄像头

487 Dec 27, 2022