├── .github └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── onnx_opcounter ├── __init__.py ├── cli.py └── onnx_opcounter.py ├── requirements.txt ├── setup.py └── tests ├── test_calculate_macs.py └── test_calculate_params.py /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Python package 2 | 3 | on: 4 | workflow_dispatch: {} 5 | push: 6 | branches: [ "master" ] 7 | pull_request: 8 | branches: [ "master" ] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | python-version: ["3.8", "3.10", "3.12"] 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v3 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | python -m pip install pytest pytest-xdist thop onnxruntime torch --extra-index-url https://download.pytorch.org/whl/cpu 27 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 28 | pip install -e . 29 | - name: Test with pytest 30 | run: | 31 | pytest -n $(nproc) 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | *.onnx 132 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.md 3 | include requirements.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ONNX Operations Counter [WIP] 2 | 3 | [![GitHub License](https://img.shields.io/badge/Apache-2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | [![Downloads](https://pepy.tech/badge/onnx_opcounter)](https://pepy.tech/project/onnx_opcounter) 5 | ![PyPI](https://img.shields.io/pypi/v/onnx_opcounter.svg) 6 | 7 | Counts number of parameters / MACs for ONNX models. 8 | 9 | ## Installation 10 | 11 | ```bash 12 | pip install onnx_opcounter 13 | ``` 14 | 15 | ## Basic Usage 16 | 17 | ### Using CLI (calculate number of parameters) 18 | ```bash 19 | onnx_opcounter {path_to_onnx_model} 20 | ``` 21 | 22 | ### Using CLI (calculate number of parameters and MACs) 23 | ```bash 24 | onnx_opcounter --calculate-macs {path_to_onnx_model} 25 | ``` 26 | 27 | ### Using API 28 | ```python 29 | from onnx_opcounter import calculate_params 30 | import onnx 31 | 32 | model = onnx.load_model('./path/to/onnx/model') 33 | params = calculate_params(model) 34 | 35 | print('Number of params:', params) 36 | ``` 37 | 38 | ## License 39 | The software is covered by Apache License 2.0. 40 | -------------------------------------------------------------------------------- /onnx_opcounter/__init__.py: -------------------------------------------------------------------------------- 1 | from onnx_opcounter.onnx_opcounter import calculate_params, calculate_macs 2 | 3 | __all__ = ['calculate_params', 'calculate_macs'] 4 | -------------------------------------------------------------------------------- /onnx_opcounter/cli.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import math 3 | import onnx 4 | from onnx_opcounter import calculate_params, calculate_macs 5 | 6 | 7 | def main(): 8 | parser = argparse.ArgumentParser(description='ONNX opcounter') 9 | parser.add_argument('model', type=str, help='Path to an ONNX model.') 10 | parser.add_argument('--calculate-macs', action='store_true', help='Calculate MACs.') 11 | args = parser.parse_args() 12 | 13 | model = onnx.load(args.model) 14 | 15 | print('Number of parameters in the model: {}'.format(calculate_params(model))) 16 | 17 | if args.calculate_macs: 18 | macs = calculate_macs(model) 19 | print('Number of MACs in the model: {}'.format(macs), "log10:", math.log10(macs)) 20 | -------------------------------------------------------------------------------- /onnx_opcounter/onnx_opcounter.py: -------------------------------------------------------------------------------- 1 | import onnx 2 | import onnxruntime as rt 3 | import numpy as np 4 | from onnx import numpy_helper 5 | import time 6 | 7 | 8 | def calculate_params(model: onnx.ModelProto) -> int: 9 | onnx_weights = model.graph.initializer 10 | params = 0 11 | 12 | for onnx_w in onnx_weights: 13 | try: 14 | weight = numpy_helper.to_array(onnx_w) 15 | params += np.prod(weight.shape) 16 | except Exception as _: 17 | pass 18 | 19 | return params 20 | 21 | 22 | def onnx_node_attributes_to_dict(args): 23 | """ 24 | Parse ONNX attributes to Python dictionary 25 | :param args: ONNX attributes object 26 | :return: Python dictionary 27 | """ 28 | def onnx_attribute_to_dict(onnx_attr): 29 | """ 30 | Parse ONNX attribute 31 | :param onnx_attr: ONNX attribute 32 | :return: Python data type 33 | """ 34 | if onnx_attr.HasField('t'): 35 | return numpy_helper.to_array(getattr(onnx_attr, 't')) 36 | 37 | for attr_type in ['f', 'i', 's']: 38 | if onnx_attr.HasField(attr_type): 39 | return getattr(onnx_attr, attr_type) 40 | 41 | for attr_type in ['floats', 'ints', 'strings']: 42 | if getattr(onnx_attr, attr_type): 43 | return list(getattr(onnx_attr, attr_type)) 44 | return {arg.name: onnx_attribute_to_dict(arg) for arg in args} 45 | 46 | 47 | def calculate_macs(model: onnx.ModelProto) -> int: 48 | orig_model = model 49 | model = onnx.ModelProto() 50 | model.CopyFrom(orig_model) 51 | 52 | onnx_nodes = model.graph.node 53 | onnx_weights = model.graph.initializer 54 | 55 | graph_weights = [w.name for w in onnx_weights] 56 | graph_outputs = {i.name: i.name for i in model.graph.output} 57 | 58 | input_sample = {} 59 | type_mapping = { 60 | 1: np.float32, 61 | 7: np.int64, 62 | 11: np.float64 63 | } 64 | 65 | def to_dims(v: onnx.ValueInfoProto) -> [int]: 66 | return [i.dim_value for i in v.type.tensor_type.shape.dim] 67 | 68 | for graph_input in model.graph.input: 69 | if graph_input.name not in graph_weights: 70 | input_sample[graph_input.name] = \ 71 | np.zeros(to_dims(graph_input), 72 | dtype=type_mapping[graph_input.type.tensor_type.elem_type]) 73 | 74 | output_mapping = {k: i for i, k in enumerate(graph_outputs)} 75 | for n in onnx_nodes: 76 | for o in n.output: 77 | if o in graph_outputs: 78 | continue 79 | intermediate_layer_value_info = onnx.helper.ValueInfoProto() 80 | intermediate_layer_value_info.name = o 81 | model.graph.output.extend([intermediate_layer_value_info]) 82 | output_mapping[o] = len(graph_outputs) 83 | graph_outputs[o] = o 84 | assert len(model.graph.output) == len(graph_outputs) 85 | assert len(model.graph.output) == len(output_mapping) 86 | 87 | 88 | try: 89 | shaped_model = onnx.ModelProto() 90 | shaped_model.CopyFrom(orig_model) 91 | del shaped_model.graph.value_info[:] 92 | shaped_model = onnx.shape_inference.infer_shapes(shaped_model, data_prop=True, strict_mode=True) 93 | 94 | output_shapes = {**{i.name: to_dims(i) for i in shaped_model.graph.value_info}, 95 | **{i.name: to_dims(i) for i in shaped_model.graph.input}, 96 | **{i.name: to_dims(i) for i in shaped_model.graph.output}, 97 | } 98 | except onnx.shape_inference.InferenceError as e: 99 | print("Shape inference failure:", e) 100 | 101 | onnx.save(model, '+all-intermediate.onnx') 102 | 103 | provider = 'CPUExecutionProvider' 104 | # if 'CUDAExecutionProvider' in rt.get_available_providers(): 105 | # provider = 'CUDAExecutionProvider' 106 | 107 | sess = rt.InferenceSession('+all-intermediate.onnx', providers=[provider]) 108 | start = time.time() 109 | output = sess.run(list(graph_outputs.keys()), input_sample) 110 | print("inference(s):", time.time() - start) 111 | 112 | output_shapes = {**{k: input_sample[k].shape for k in input_sample}, 113 | **{i: output[output_mapping[i]].shape for i in output_mapping} 114 | } 115 | 116 | for w in model.graph.initializer: 117 | output_shapes[w.name] = list(w.dims) 118 | 119 | def conv_macs(node, input_shape, output_shape, attrs): 120 | kernel_ops = np.prod(attrs['kernel_shape']) # Kw x Kh 121 | bias_ops = len(node.input) == 3 122 | 123 | group = 1 124 | if 'group' in attrs: 125 | group = attrs['group'] 126 | 127 | in_channels = input_shape[1] 128 | 129 | return np.prod(output_shape) * (in_channels // group * kernel_ops) # + bias_ops 130 | 131 | def gemm_macs(node, input_shape, output_shape, attrs): 132 | return np.prod(input_shape) * output_shape[-1] 133 | 134 | def bn_macs(node, input_shape, output_shape, attrs): 135 | batch_macs = np.prod(output_shape) 136 | if len(node.input) == 5: 137 | batch_macs *= 2 138 | return batch_macs 139 | 140 | def upsample_macs(node, input_shape, output_shape, attrs): 141 | if 'mode' in attrs: 142 | if attrs['mode'].decode('utf-8') == 'nearest': 143 | return 0 144 | if attrs['mode'].decode('utf-8') == 'linear': 145 | return np.prod(output_shape) * 11 146 | else: 147 | return 0 148 | 149 | def relu_macs(node, input_shape, output_shape, attrs): 150 | return np.prod(input_shape) 151 | 152 | def no_macs(*args, **kwargs): 153 | return 0 154 | 155 | mac_calculators = { 156 | 'Conv': conv_macs, 157 | 'ConvTranspose': conv_macs, 158 | 'Constant': no_macs, 159 | 'Gemm': gemm_macs, 160 | 'MatMul': gemm_macs, 161 | 'BatchNormalization': bn_macs, 162 | 'Relu': relu_macs, 163 | 'Add': relu_macs, 164 | 'Reshape': no_macs, 165 | 'Slice': no_macs, 166 | 'Shape': no_macs, 167 | 'Gather': no_macs, 168 | 'ScatterND': no_macs, 169 | 'Tile': no_macs, 170 | 'Transpose': no_macs, 171 | 'Sign': no_macs, 172 | 'Squeeze': no_macs, 173 | 'Unsqueeze': no_macs, 174 | 'Split': no_macs, 175 | 'Cast': no_macs, 176 | 'Upsample': upsample_macs, 177 | 'Resize': upsample_macs, 178 | } 179 | 180 | macs = 0 181 | unsupported_ops = set() 182 | for node in onnx_nodes: 183 | node_output_shape = output_shapes[node.output[0]] 184 | if node.op_type in mac_calculators: 185 | node_input_shape = None 186 | if len(node.input) > 0: 187 | node_input_shape = output_shapes[node.input[0]] 188 | macs += mac_calculators[node.op_type]( 189 | node, node_input_shape, node_output_shape, onnx_node_attributes_to_dict(node.attribute) 190 | ) 191 | else: 192 | macs += np.prod(node_output_shape) 193 | if node.op_type in unsupported_ops: 194 | continue 195 | print("Unsupported op:", node.op_type) 196 | unsupported_ops.add(node.op_type) 197 | 198 | return macs 199 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | onnx 3 | # onnxruntime 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | 4 | def parse_requirements(filename): 5 | lineiter = (line.strip() for line in open(filename)) 6 | return [line for line in lineiter if line and not line.startswith("#")] 7 | 8 | 9 | reqs = parse_requirements('requirements.txt') 10 | 11 | setup(name='onnx_opcounter', 12 | version='0.0.4', 13 | description='ONNX flops / params counter', 14 | author='Grigory Malivenko', 15 | author_email='', 16 | packages=find_packages(), 17 | install_requires=reqs, 18 | zip_safe=False, 19 | entry_points={ 20 | 'console_scripts': [ 21 | 'onnx_opcounter = onnx_opcounter.cli:main', 22 | ], 23 | }, 24 | ) 25 | -------------------------------------------------------------------------------- /tests/test_calculate_macs.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from thop import profile 4 | import pytest 5 | from torch import nn 6 | import tempfile 7 | import os 8 | from onnx_opcounter import calculate_macs 9 | import onnx 10 | 11 | 12 | def check_macs(model, input): 13 | macs, params = profile(model, inputs=(input,)) 14 | 15 | with tempfile.TemporaryDirectory() as tmp: 16 | torch.onnx.export(model, input, os.path.join(tmp, "_model.onnx"), 17 | verbose=True, input_names=['input'], output_names=['output'], opset_version=16) 18 | onnx_model = onnx.load_model(os.path.join(tmp, "_model.onnx")) 19 | onnx_macs = calculate_macs(onnx_model) 20 | print('macs', macs) 21 | print('onnx_macs', onnx_macs) 22 | assert int(macs) == int(onnx_macs) 23 | 24 | 25 | @pytest.mark.parametrize('inputs', [1, 11, 12]) 26 | @pytest.mark.parametrize('outputs', [1, 11, 12]) 27 | @pytest.mark.parametrize('kernel_size', [1, 3, 5]) 28 | @pytest.mark.parametrize('padding', [0, 1, 2]) 29 | @pytest.mark.parametrize('stride', [1, 2]) 30 | @pytest.mark.parametrize('bias', [True, False]) 31 | @pytest.mark.parametrize('dilation', [1, 2, 3]) 32 | @pytest.mark.parametrize('groups', [1, 2, 3]) 33 | def test_conv2d_case1(inputs, outputs, kernel_size, padding, stride, bias, dilation, groups): 34 | model = nn.Sequential(nn.Conv2d( 35 | inputs * groups, outputs * groups, kernel_size=kernel_size, padding=padding, 36 | stride=stride, bias=bias, dilation=dilation, groups=groups 37 | ),) 38 | model.eval() 39 | 40 | input = torch.randn((1, inputs * groups, 224, 224)) 41 | check_macs(model, input) 42 | 43 | 44 | @pytest.mark.parametrize('kernel_size', [1, 3, 5, 7]) 45 | @pytest.mark.parametrize('padding', [0, 1, 3, 5]) 46 | @pytest.mark.parametrize('stride', [1]) 47 | @pytest.mark.parametrize('bias', [True, False]) 48 | @pytest.mark.parametrize('dilation', [1, 2, 3]) 49 | @pytest.mark.parametrize('groups', [1, 2, 3]) 50 | def test_convtranspose2d_case1(kernel_size, padding, stride, bias, dilation, groups): 51 | model = nn.Sequential(nn.ConvTranspose2d( 52 | groups * 3, groups, kernel_size=kernel_size, padding=padding, 53 | stride=stride, bias=bias, dilation=dilation, groups=groups 54 | ),) 55 | model.eval() 56 | 57 | input = torch.randn((1, groups * 3, 224, 224)) 58 | check_macs(model, input) 59 | 60 | 61 | @pytest.mark.parametrize('inputs', [1, 32, 64, 128, 256]) 62 | @pytest.mark.parametrize('outputs', [1, 32, 64, 128]) 63 | @pytest.mark.parametrize('bias', [True, False]) 64 | def test_linear_case1(inputs, outputs, bias): 65 | model = nn.Sequential(nn.Linear( 66 | inputs, outputs, bias=bias 67 | ),) 68 | model.eval() 69 | 70 | input = torch.randn((1, inputs)) 71 | check_macs(model, input) 72 | 73 | 74 | @pytest.mark.parametrize('inputs', [1, 32, 64, 128, 256]) 75 | @pytest.mark.parametrize('outputs', [1, 32, 64, 128]) 76 | @pytest.mark.parametrize('affine', [False]) 77 | def test_bn_case1(inputs, outputs, affine): 78 | model = nn.Sequential(nn.BatchNorm2d( 79 | inputs, outputs, affine=affine 80 | )) 81 | model.eval() 82 | 83 | input = torch.randn((1, inputs, 224, 224)) 84 | check_macs(model, input) 85 | 86 | 87 | @pytest.mark.parametrize('inputs', [1, 32, 64, 128, 256]) 88 | @pytest.mark.parametrize('scale_factor', [1, 2, 3, 5]) 89 | @pytest.mark.parametrize('mode', ['bilinear', 'nearest']) 90 | # @pytest.mark.parametrize('mode', ['linear', 'nearest']) 91 | def test_upsample_case1(inputs, scale_factor, mode): 92 | if mode == 'nearest': 93 | pytest.xfail() 94 | 95 | model = nn.Sequential(nn.Upsample( 96 | scale_factor=scale_factor, mode=mode 97 | ),) 98 | model.eval() 99 | 100 | input = torch.randn((1, inputs, 32, 32)) 101 | check_macs(model, input) 102 | # 103 | # model = nn.Sequential(nn.Upsample( 104 | # scale_factor=4, mode='bilinear' 105 | # ),) 106 | # model.eval() 107 | # 108 | # input = torch.randn((1, 32, 224, 224)) 109 | # check_macs(model, input) 110 | -------------------------------------------------------------------------------- /tests/test_calculate_params.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from thop import profile 4 | import pytest 5 | import tempfile 6 | import os 7 | from onnx_opcounter import calculate_params 8 | import onnx 9 | 10 | 11 | def check_params(model, input): 12 | macs, params = profile(model, inputs=(input,)) 13 | 14 | with tempfile.TemporaryDirectory() as tmp: 15 | torch.onnx.export(model, input, os.path.join(tmp, "_model.onnx"), 16 | verbose=True, input_names=['input'], output_names=['output']) 17 | onnx_model = onnx.load_model(os.path.join(tmp, "_model.onnx")) 18 | onnx_params = calculate_params(onnx_model) 19 | 20 | assert int(params) == int(onnx_params) 21 | 22 | 23 | @pytest.mark.parametrize('kernel_size', [1, 3, 5, 7]) 24 | @pytest.mark.parametrize('padding', [0, 1, 3, 5]) 25 | @pytest.mark.parametrize('stride', [1]) 26 | @pytest.mark.parametrize('bias', [True, False]) 27 | @pytest.mark.parametrize('dilation', [1, 2, 3]) 28 | @pytest.mark.parametrize('groups', [1, 2, 3]) 29 | def test_conv2d_case1(kernel_size, padding, stride, bias, dilation, groups): 30 | model = nn.Sequential(nn.Conv2d( 31 | groups * 3, groups, kernel_size=kernel_size, padding=padding, 32 | stride=stride, bias=bias, dilation=dilation, groups=groups 33 | ),) 34 | model.eval() 35 | 36 | input = torch.randn((1, groups * 3, 224, 224)) 37 | check_params(model, input) 38 | 39 | 40 | @pytest.mark.parametrize('kernel_size', [1, 3, 5, 7]) 41 | @pytest.mark.parametrize('padding', [0, 1, 3, 5]) 42 | @pytest.mark.parametrize('stride', [1]) 43 | @pytest.mark.parametrize('bias', [True, False]) 44 | @pytest.mark.parametrize('dilation', [1, 2, 3]) 45 | @pytest.mark.parametrize('groups', [1, 2, 3]) 46 | def test_convtranspose2d_case1(kernel_size, padding, stride, bias, dilation, groups): 47 | model = nn.Sequential(nn.ConvTranspose2d( 48 | groups * 3, groups, kernel_size=kernel_size, padding=padding, 49 | stride=stride, bias=bias, dilation=dilation, groups=groups 50 | ),) 51 | model.eval() 52 | 53 | input = torch.randn((1, groups * 3, 224, 224)) 54 | check_params(model, input) 55 | 56 | 57 | @pytest.mark.parametrize('inputs', [1, 32, 64, 128, 256]) 58 | @pytest.mark.parametrize('outputs', [1, 32, 64, 128]) 59 | @pytest.mark.parametrize('bias', [True, False]) 60 | def test_linear_case1(inputs, outputs, bias): 61 | model = nn.Sequential(nn.Linear( 62 | inputs, outputs, bias=bias 63 | ),) 64 | model.eval() 65 | 66 | input = torch.randn((1, inputs)) 67 | check_params(model, input) 68 | 69 | 70 | @pytest.mark.parametrize('planes', [1, 32, 64, 128, 256]) 71 | @pytest.mark.parametrize('size', [1, 32, 64, 128, 256]) 72 | @pytest.mark.parametrize('affine', [True, False]) 73 | def test_bn_case1(planes, size, affine): 74 | pytest.skip('PyTorch OpCounter produces wrong results') 75 | model = nn.Sequential(nn.BatchNorm1d( 76 | planes, affine=affine 77 | ),) 78 | model.eval() 79 | 80 | input = torch.randn((1, planes, size)) 81 | check_params(model, input) 82 | --------------------------------------------------------------------------------