├── .coveragerc ├── .github └── dependabot.yml ├── .gitignore ├── .travis.yml ├── CHANGES.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── examples └── simple.py ├── requirements-dev.txt ├── setup.py ├── tests ├── conftest.py └── test_basic.py └── torch_inspect ├── __init__.py └── inspect.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = torch_inspect 4 | omit = site-packages, .tox 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "10:00" 8 | open-pull-requests-limit: 10 9 | ignore: 10 | - dependency-name: flake8 11 | versions: 12 | - 3.9.0 13 | - dependency-name: ipdb 14 | versions: 15 | - 0.13.5 16 | - 0.13.6 17 | - dependency-name: flake8-bugbear 18 | versions: 19 | - 21.3.1 20 | - 21.3.2 21 | - dependency-name: torchvision 22 | versions: 23 | - 0.8.2 24 | - 0.9.0 25 | - dependency-name: pyroma 26 | versions: 27 | - 2.6.1 28 | - 3.0.1 29 | - dependency-name: ipython 30 | versions: 31 | - 7.19.0 32 | - 7.20.0 33 | - 7.21.0 34 | - dependency-name: pytest 35 | versions: 36 | - 6.2.2 37 | - dependency-name: mypy 38 | versions: 39 | - "0.800" 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ># Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # PyInstaller 26 | # Usually these files are written by a python script from a template 27 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 28 | *.manifest 29 | *.spec 30 | 31 | # Installer logs 32 | pip-log.txt 33 | pip-delete-this-directory.txt 34 | 35 | # Unit test / coverage reports 36 | htmlcov/ 37 | .tox/ 38 | .coverage 39 | .cache 40 | nosetests.xml 41 | coverage.xml 42 | cover 43 | 44 | # Translations 45 | *.mo 46 | *.pot 47 | 48 | # Django stuff: 49 | *.log 50 | 51 | # Sphinx documentation 52 | docs/_build/ 53 | 54 | # PyBuilder 55 | target/ 56 | 57 | # PyCharm 58 | .idea 59 | 60 | .coverage.* 61 | coverage 62 | .mypy_cache/ 63 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | language: python 3 | sudo: required 4 | 5 | 6 | python: 7 | - '3.7' 8 | - '3.6' 9 | 10 | 11 | install: 12 | - pip install --upgrade setuptools 13 | - pip install codecov 14 | - pip install -r requirements-dev.txt 15 | 16 | script: 17 | make cov 18 | 19 | after_success: 20 | codecov 21 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | Changes 2 | ------- 3 | 4 | 0.0.3 (2019-10-13) 5 | ------------------ 6 | * Added LSTM support 7 | * Fixed multi input/output support 8 | * Added more network test cases 9 | * Batch size no longer -1 by default 10 | 11 | 12 | 0.0.2 (2019-09-22) 13 | ------------------ 14 | * Added batch norm support 15 | * Removed device parameter 16 | 17 | 18 | 0.0.1 (2019-09-1) 19 | ------------------ 20 | * Initial release. 21 | -------------------------------------------------------------------------------- /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 2019 Nikolay Novik (https://github.com/jettify) 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 | 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include CHANGES.rst 3 | include README.rst 4 | include Makefile 5 | graft torch_inspect 6 | graft tests 7 | global-exclude *.pyc 8 | prune docs/_build 9 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Some simple testing tasks (sorry, UNIX only). 2 | 3 | 4 | flake: 5 | flake8 torch_inspect tests examples setup.py 6 | 7 | test: flake 8 | pytest -sv 9 | 10 | vtest: 11 | pytest -sv -vv 12 | 13 | checkrst: 14 | python setup.py check --restructuredtext 15 | 16 | pyroma: 17 | pyroma -d . 18 | 19 | bandit: 20 | bandit -r ./torch_inspect 21 | 22 | mypy: 23 | mypy torch_inspect --ignore-missing-imports --strict 24 | 25 | cov cover coverage: flake checkrst pyroma bandit 26 | pytest -sv -vv --cov=torch_inspect --cov-report=term --cov-report=html ./tests 27 | @echo "open file://`pwd`/htmlcov/index.html" 28 | 29 | clean: 30 | rm -rf `find . -name __pycache__` 31 | rm -f `find . -type f -name '*.py[co]' ` 32 | rm -f `find . -type f -name '*~' ` 33 | rm -f `find . -type f -name '.*~' ` 34 | rm -f `find . -type f -name '@*' ` 35 | rm -f `find . -type f -name '#*#' ` 36 | rm -f `find . -type f -name '*.orig' ` 37 | rm -f `find . -type f -name '*.rej' ` 38 | rm -f .coverage 39 | rm -rf coverage 40 | rm -rf build 41 | rm -rf cover 42 | rm -rf dist 43 | 44 | doc: 45 | make -C docs html 46 | @echo "open file://`pwd`/docs/_build/html/index.html" 47 | 48 | black: 49 | black -S -l 79 setup.py torch_inspect/ tests/ examples/ 50 | 51 | .PHONY: all flake test vtest cov clean doc 52 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | torch-inspect 2 | ============= 3 | .. image:: https://travis-ci.com/jettify/pytorch-inspect.svg?branch=master 4 | :target: https://travis-ci.com/jettify/pytorch-inspect 5 | .. image:: https://codecov.io/gh/jettify/pytorch-inspect/branch/master/graph/badge.svg 6 | :target: https://codecov.io/gh/jettify/pytorch-inspect 7 | .. image:: https://img.shields.io/pypi/pyversions/torch-inspect.svg 8 | :target: https://pypi.org/project/torch-inspect 9 | .. image:: https://img.shields.io/pypi/v/torch-inspect.svg 10 | :target: https://pypi.python.org/pypi/torch-inspect 11 | 12 | **torch-inspect** -- collection of utility functions to inspect low level information of neural network for PyTorch_ 13 | 14 | Features 15 | ======== 16 | * Provides helper function ``summary`` that prints Keras style model summary. 17 | * Provides helper function ``inspect`` that returns object with network summary information for programmatic access. 18 | * RNN/LSTM support. 19 | * Library has tests and reasonable code coverage. 20 | 21 | 22 | Simple example 23 | -------------- 24 | 25 | .. code:: python 26 | 27 | import torch.nn as nn 28 | import torch.nn.functional as F 29 | import torch_inspect as ti 30 | 31 | class SimpleNet(nn.Module): 32 | def __init__(self): 33 | super(SimpleNet, self).__init__() 34 | self.conv1 = nn.Conv2d(1, 6, 3) 35 | self.conv2 = nn.Conv2d(6, 16, 3) 36 | self.fc1 = nn.Linear(16 * 6 * 6, 120) 37 | self.fc2 = nn.Linear(120, 84) 38 | self.fc3 = nn.Linear(84, 10) 39 | 40 | def forward(self, x): 41 | x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) 42 | x = F.max_pool2d(F.relu(self.conv2(x)), 2) 43 | x = x.view(-1, self.num_flat_features(x)) 44 | x = F.relu(self.fc1(x)) 45 | x = F.relu(self.fc2(x)) 46 | x = self.fc3(x) 47 | return x 48 | 49 | def num_flat_features(self, x): 50 | size = x.size()[1:] 51 | num_features = 1 52 | for s in size: 53 | num_features *= s 54 | return num_features 55 | 56 | 57 | net = SimpleNet() 58 | ti.summary(net, (1, 32, 32)) 59 | 60 | 61 | Will produce following output: 62 | 63 | .. code:: 64 | 65 | ---------------------------------------------------------------- 66 | Layer (type) Output Shape Param # 67 | ================================================================ 68 | Conv2d-1 [100, 6, 30, 30] 60 69 | Conv2d-2 [100, 16, 13, 13] 880 70 | Linear-3 [100, 120] 69,240 71 | Linear-4 [100, 84] 10,164 72 | Linear-5 [100, 10] 850 73 | ================================================================ 74 | Total params: 81,194 75 | Trainable params: 81,194 76 | Non-trainable params: 0 77 | ---------------------------------------------------------------- 78 | Input size (MB): 0.39 79 | Forward/backward pass size (MB): 6.35 80 | Params size (MB): 0.31 81 | Estimated Total Size (MB): 7.05 82 | ---------------------------------------------------------------- 83 | 84 | For programmatic access to network information there is ``inspect`` function: 85 | 86 | .. code:: python 87 | 88 | info = ti.inspect(net, (1, 32, 32)) 89 | print(info) 90 | 91 | 92 | .. code:: 93 | 94 | [LayerInfo(name='Conv2d-1', input_shape=[100, 1, 32, 32], output_shape=[100, 6, 30, 30], trainable_params=60, non_trainable_params=0), 95 | LayerInfo(name='Conv2d-2', input_shape=[100, 6, 15, 15], output_shape=[100, 16, 13, 13], trainable_params=880, non_trainable_params=0), 96 | LayerInfo(name='Linear-3', input_shape=[100, 576], output_shape=[100, 120], trainable_params=69240, non_trainable_params=0), 97 | LayerInfo(name='Linear-4', input_shape=[100, 120], output_shape=[100, 84], trainable_params=10164, non_trainable_params=0), 98 | LayerInfo(name='Linear-5', input_shape=[100, 84], output_shape=[100, 10], trainable_params=850, non_trainable_params=0)] 99 | 100 | 101 | Installation 102 | ------------ 103 | Installation process is simple, just:: 104 | 105 | $ pip install torch-inspect 106 | 107 | 108 | Requirements 109 | ------------ 110 | 111 | * Python_ 3.6+ 112 | * PyTorch_ 1.0+ 113 | 114 | 115 | References and Thanks 116 | --------------------- 117 | This package is based on pytorch-summary_ and PyTorch issue_ . Compared to 118 | pytorch-summary_, *pytorch-inspect* has support of RNN/LSTMs, also provides programmatic 119 | access to the network summary information. With a bit more modular structure and presence of tests 120 | it is easier to extend and support more features. 121 | 122 | 123 | .. _Python: https://www.python.org 124 | .. _PyTorch: https://github.com/pytorch/pytorch 125 | .. _pytorch-summary: https://github.com/sksq96/pytorch-summary 126 | .. _issue: https://github.com/pytorch/pytorch/issues/2001 127 | -------------------------------------------------------------------------------- /examples/simple.py: -------------------------------------------------------------------------------- 1 | import pprint 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import torch_inspect as ti 5 | 6 | 7 | class SimpleNet(nn.Module): 8 | def __init__(self): 9 | super(SimpleNet, self).__init__() 10 | self.conv1 = nn.Conv2d(1, 6, 3) 11 | self.conv2 = nn.Conv2d(6, 16, 3) 12 | self.fc1 = nn.Linear(16 * 6 * 6, 120) 13 | self.fc2 = nn.Linear(120, 84) 14 | self.fc3 = nn.Linear(84, 10) 15 | 16 | def forward(self, x): 17 | x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) 18 | x = F.max_pool2d(F.relu(self.conv2(x)), 2) 19 | x = x.view(-1, self.num_flat_features(x)) 20 | x = F.relu(self.fc1(x)) 21 | x = F.relu(self.fc2(x)) 22 | x = self.fc3(x) 23 | return x 24 | 25 | def num_flat_features(self, x): 26 | size = x.size()[1:] 27 | num_features = 1 28 | for s in size: 29 | num_features *= s 30 | return num_features 31 | 32 | 33 | def main(): 34 | net = SimpleNet() 35 | batch_size = 100 36 | ti.summary(net, (1, 32, 32), batch_size=batch_size) 37 | 38 | info = ti.inspect(net, (1, 32, 32), batch_size=batch_size) 39 | pprint.pprint(info) 40 | 41 | 42 | if __name__ == '__main__': 43 | main() 44 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | bandit==1.6.2 3 | black==20.8b1 4 | flake8-bugbear==20.11.1 5 | flake8-quotes==3.2.0 6 | flake8==3.8.4 7 | ipdb==0.13.4 8 | ipython==7.16.1 9 | mypy==0.790 10 | pyroma==2.6 11 | pytest-cov==2.10.1 12 | pytest==6.1.2 13 | torchvision==0.8.1 14 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import sys 4 | from setuptools import setup, find_packages 5 | 6 | 7 | install_requires = ['torch>=1.1.0'] 8 | 9 | PY36 = (3, 6, 0) 10 | PY37 = (3, 7, 0) 11 | 12 | 13 | if sys.version_info < PY36: 14 | raise RuntimeError('torch-inspect requires Python 3.6.0+') 15 | 16 | 17 | if sys.version_info < PY37: 18 | install_requires.append('dataclasses==0.6') 19 | 20 | 21 | def read(f): 22 | return open(os.path.join(os.path.dirname(__file__), f)).read().strip() 23 | 24 | 25 | def read_version(): 26 | regexp = re.compile(r"^__version__\W*=\W*'([\d.abrc]+)'") 27 | init_py = os.path.join( 28 | os.path.dirname(__file__), 'torch_inspect', '__init__.py' 29 | ) 30 | with open(init_py) as f: 31 | for line in f: 32 | match = regexp.match(line) 33 | if match is not None: 34 | return match.group(1) 35 | else: 36 | raise RuntimeError( 37 | 'Cannot find version in torch_inspect/__init__.py' 38 | ) 39 | 40 | 41 | classifiers = [ 42 | 'License :: OSI Approved :: Apache Software License', 43 | 'Intended Audience :: Developers', 44 | 'Programming Language :: Python :: 3', 45 | 'Programming Language :: Python :: 3.6', 46 | 'Programming Language :: Python :: 3.7', 47 | 'Operating System :: OS Independent', 48 | 'Development Status :: 3 - Alpha', 49 | ] 50 | 51 | 52 | setup( 53 | name='torch-inspect', 54 | version=read_version(), 55 | description=('Utility functions that prints a summary of a model.'), 56 | long_description='\n\n'.join((read('README.rst'), read('CHANGES.rst'))), 57 | classifiers=classifiers, 58 | platforms=['POSIX'], 59 | author='Nikolay Novik', 60 | author_email='nickolainovik@gmail.com', 61 | url='https://github.com/jettify/pytorch-inspect', 62 | download_url='https://pypi.org/project/torch-inspect/', 63 | license='Apache 2', 64 | packages=find_packages(), 65 | install_requires=install_requires, 66 | keywords=['torch-inspect', 'pytorch'], 67 | zip_safe=True, 68 | include_package_data=True, 69 | ) 70 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torchvision 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | 8 | class SimpleNet(nn.Module): 9 | def __init__(self): 10 | super(SimpleNet, self).__init__() 11 | self.conv1 = nn.Conv2d(1, 6, 3) 12 | self.conv2 = nn.Conv2d(6, 16, 3) 13 | self.fc1 = nn.Linear(16 * 6 * 6, 120) 14 | self.fc2 = nn.Linear(120, 84) 15 | self.fc3 = nn.Linear(84, 10) 16 | 17 | def forward(self, x): 18 | x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) 19 | x = F.max_pool2d(F.relu(self.conv2(x)), 2) 20 | x = x.view(-1, self.num_flat_features(x)) 21 | x = F.relu(self.fc1(x)) 22 | x = F.relu(self.fc2(x)) 23 | x = self.fc3(x) 24 | return x 25 | 26 | def num_flat_features(self, x): 27 | size = x.size()[1:] 28 | num_features = 1 29 | for s in size: 30 | num_features *= s 31 | return num_features 32 | 33 | 34 | class MultiInputNet(nn.Module): 35 | def __init__(self): 36 | super(MultiInputNet, self).__init__() 37 | self.features = nn.Sequential( 38 | nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1), nn.ReLU() 39 | ) 40 | 41 | def forward(self, x, y): 42 | x1 = self.features(x) 43 | x2 = self.features(y) 44 | return x1, x2 45 | 46 | 47 | class SimpleBatchNormModel(nn.Module): 48 | def __init__(self): 49 | super(SimpleBatchNormModel, self).__init__() 50 | hidden = 15 51 | input_size = 20 52 | self.main = nn.Sequential( 53 | nn.Linear(input_size, hidden, bias=False), 54 | nn.BatchNorm1d(hidden), 55 | nn.Linear(hidden, hidden, bias=False), 56 | nn.BatchNorm1d(hidden), 57 | nn.Linear(hidden, 1), 58 | ) 59 | 60 | def forward(self, input): 61 | output = self.main(input) 62 | return output 63 | 64 | 65 | class Generator(nn.Module): 66 | def __init__(self, ngpu=1): 67 | super(Generator, self).__init__() 68 | nz = 100 69 | ngf = 64 70 | nc = 3 71 | self.ngpu = ngpu 72 | self.main = nn.Sequential( 73 | nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False), 74 | nn.BatchNorm2d(ngf * 8), 75 | nn.ReLU(True), 76 | nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), 77 | nn.BatchNorm2d(ngf * 4), 78 | nn.ReLU(True), 79 | nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), 80 | nn.BatchNorm2d(ngf * 2), 81 | nn.ReLU(True), 82 | nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False), 83 | nn.BatchNorm2d(ngf), 84 | nn.ReLU(True), 85 | nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False), 86 | nn.Tanh(), 87 | ) 88 | 89 | def forward(self, input): 90 | if input.is_cuda and self.ngpu > 1: 91 | output = nn.parallel.data_parallel( 92 | self.main, input, range(self.ngpu) 93 | ) 94 | else: 95 | output = self.main(input) 96 | return output 97 | 98 | 99 | class LSTMTagger(nn.Module): 100 | def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size): 101 | super(LSTMTagger, self).__init__() 102 | self.hidden_dim = hidden_dim 103 | self.word_embeddings = nn.Embedding(vocab_size, embedding_dim) 104 | self.lstm = nn.LSTM(embedding_dim, hidden_dim) 105 | self.hidden2tag = nn.Linear(hidden_dim, tagset_size) 106 | 107 | def forward(self, sentence): 108 | embeds = self.word_embeddings(sentence) 109 | lstm_out, _ = self.lstm(embeds.view(len(sentence), 1, -1)) 110 | tag_space = self.hidden2tag(lstm_out.view(len(sentence), -1)) 111 | tag_scores = F.log_softmax(tag_space, dim=1) 112 | return tag_scores 113 | 114 | 115 | class SimpleConv(nn.Module): 116 | def __init__(self): 117 | super(SimpleConv, self).__init__() 118 | self.features = nn.Sequential( 119 | nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1), nn.ReLU() 120 | ) 121 | 122 | def forward(self, x, y): 123 | x1 = self.features(x) 124 | x2 = self.features(y) 125 | return x1, x2 126 | 127 | 128 | class Autoencoder(nn.Module): 129 | def __init__(self): 130 | super(Autoencoder, self).__init__() 131 | self.encoder = nn.Sequential( 132 | nn.Conv2d(3, 6, kernel_size=5), 133 | nn.ReLU(True), 134 | nn.Conv2d(6, 16, kernel_size=5), 135 | nn.ReLU(True), 136 | ) 137 | self.decoder = nn.Sequential( 138 | nn.ConvTranspose2d(16, 6, kernel_size=5), 139 | nn.ReLU(True), 140 | nn.ConvTranspose2d(6, 3, kernel_size=5), 141 | nn.ReLU(True), 142 | nn.Sigmoid(), 143 | ) 144 | 145 | def forward(self, x): 146 | x = self.encoder(x) 147 | x = self.decoder(x) 148 | return x 149 | 150 | 151 | @pytest.fixture(scope='session') 152 | def simple_model(): 153 | net = SimpleNet() 154 | return net 155 | 156 | 157 | @pytest.fixture(scope='session') 158 | def mobilenet(): 159 | model = torchvision.models.mobilenet_v2() 160 | return model 161 | 162 | 163 | @pytest.fixture(scope='session') 164 | def multi_input_net(): 165 | model = MultiInputNet() 166 | return model 167 | 168 | 169 | @pytest.fixture(scope='session') 170 | def lstm_tagger(): 171 | model = LSTMTagger(6, 6, 5, 3) 172 | return model 173 | 174 | 175 | @pytest.fixture(scope='session') 176 | def netgenerator(): 177 | model = Generator() 178 | return model 179 | 180 | 181 | @pytest.fixture(scope='session') 182 | def netbatchnorm(): 183 | model = SimpleBatchNormModel() 184 | return model 185 | 186 | 187 | @pytest.fixture(scope='session') 188 | def simpleconv(): 189 | model = SimpleConv() 190 | return model 191 | 192 | 193 | @pytest.fixture(scope='session') 194 | def autoencoder(): 195 | net = Autoencoder() 196 | return net 197 | 198 | 199 | class RNNModel(nn.Module): 200 | def __init__(self, input_size, output_size, hidden_dim, n_layers): 201 | super().__init__() 202 | self.hidden_dim = hidden_dim 203 | self.n_layers = n_layers 204 | self.rnn = nn.RNN(input_size, hidden_dim, n_layers, batch_first=True) 205 | self.fc = nn.Linear(hidden_dim, output_size) 206 | 207 | def forward(self, x): 208 | batch_size = x.size(0) 209 | hidden = self.init_hidden(batch_size) 210 | out, hidden = self.rnn(x, hidden) 211 | out = out.contiguous().view(-1, self.hidden_dim) 212 | out = self.fc(out) 213 | return out, hidden 214 | 215 | def init_hidden(self, batch_size): 216 | hidden = torch.zeros(self.n_layers, batch_size, self.hidden_dim) 217 | return hidden 218 | 219 | 220 | @pytest.fixture(scope='session') 221 | def rnn(): 222 | net = RNNModel(3, 1, 5, 3) 223 | return net 224 | 225 | 226 | class MultiInputNet2(nn.Module): 227 | def __init__(self): 228 | super(MultiInputNet2, self).__init__() 229 | self.pool = nn.MaxPool2d(2, 2) 230 | self.conv1 = nn.Conv2d(3, 64, 3, padding=1) 231 | self.conv2 = nn.Conv2d(64, 96, 3, padding=1) 232 | self.conv3 = nn.Conv2d(96, 128, 3, padding=1) 233 | self.conv4 = nn.Conv2d(128, 192, 3, padding=1) 234 | self.avg_pool = nn.AdaptiveAvgPool2d((1, 1)) 235 | self.linear1 = nn.Linear(192, 64) 236 | self.linear2 = nn.Linear(64, 4) 237 | 238 | def forward(self, image, unrefined_bounding_box): 239 | x = self.pool(F.relu(self.conv1(image))) 240 | x = self.pool(F.relu(self.conv2(x))) 241 | x = self.pool(F.relu(self.conv3(x))) 242 | x = F.relu(self.conv4(x)) 243 | 244 | x = self.avg_pool(x) 245 | x = x.view(x.size(0), -1) 246 | x = F.relu(self.linear1(x)) 247 | x = F.relu(self.linear2(x)) 248 | x = x + unrefined_bounding_box 249 | return x 250 | 251 | 252 | @pytest.fixture(scope='session') 253 | def multi_input_net2(): 254 | net = MultiInputNet2() 255 | return net 256 | 257 | 258 | class LSTMModel(nn.Module): 259 | # https://www.deeplearningwizard.com/deep_learning/practical_pytorch/ 260 | # pytorch_lstm_neuralnetwork/ 261 | def __init__(self, input_dim, hidden_dim, layer_dim, output_dim): 262 | super(LSTMModel, self).__init__() 263 | self.hidden_dim = hidden_dim 264 | self.layer_dim = layer_dim 265 | self.lstm = nn.LSTM(input_dim, hidden_dim, layer_dim, batch_first=True) 266 | self.fc = nn.Linear(hidden_dim, output_dim) 267 | 268 | def forward(self, x): 269 | h0 = torch.zeros( 270 | self.layer_dim, x.size(0), self.hidden_dim 271 | ).requires_grad_() 272 | c0 = torch.zeros( 273 | self.layer_dim, x.size(0), self.hidden_dim 274 | ).requires_grad_() 275 | out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach())) 276 | out = self.fc(out[:, -1, :]) 277 | return out 278 | 279 | 280 | @pytest.fixture(scope='session') 281 | def lstm_model(): 282 | input_dim = 28 283 | hidden_dim = 100 284 | layer_dim = 1 285 | output_dim = 10 286 | model = LSTMModel(input_dim, hidden_dim, layer_dim, output_dim) 287 | return model 288 | -------------------------------------------------------------------------------- /tests/test_basic.py: -------------------------------------------------------------------------------- 1 | import io 2 | import torch 3 | 4 | from torch_inspect import inspect, summary 5 | from torch_inspect.inspect import LayerInfo as L, NetworkInfo 6 | 7 | 8 | def test_inspect(simple_model): 9 | bs = 2 # default batch size 10 | r = inspect(simple_model, (1, 32, 32)) 11 | 12 | expected = [ 13 | L('Conv2d-1', [bs, 1, 32, 32], [bs, 6, 30, 30], 60, 0), 14 | L('Conv2d-2', [bs, 6, 15, 15], [bs, 16, 13, 13], 880, 0), 15 | L('Linear-3', [bs, 576], [bs, 120], 69240, 0), 16 | L('Linear-4', [bs, 120], [bs, 84], 10164, 0), 17 | L('Linear-5', [bs, 84], [bs, 10], 850, 0), 18 | ] 19 | 20 | assert r == expected 21 | 22 | bsize = 10 23 | r = inspect( 24 | simple_model, 25 | (1, 32, 32), 26 | input_dtype=torch.FloatTensor, 27 | input_initializer=torch.zeros, 28 | batch_size=bsize, 29 | ) 30 | expected = [ 31 | L('Conv2d-1', [bsize, 1, 32, 32], [bsize, 6, 30, 30], 60, 0), 32 | L('Conv2d-2', [bsize, 6, 15, 15], [bsize, 16, 13, 13], 880, 0), 33 | L('Linear-3', [bsize, 576], [bsize, 120], 69240, 0), 34 | L('Linear-4', [bsize, 120], [bsize, 84], 10164, 0), 35 | L('Linear-5', [bsize, 84], [bsize, 10], 850, 0), 36 | ] 37 | assert r == expected 38 | 39 | 40 | def test_inspect_multi_input(multi_input_net): 41 | bs = 10 42 | r = inspect(multi_input_net, [(1, 16, 16), (1, 28, 28)], batch_size=bs) 43 | expected = [ 44 | L('Conv2d-1', [bs, 1, 16, 16], [bs, 1, 16, 16], 10, 0), 45 | L('ReLU-2', [bs, 1, 16, 16], [bs, 1, 16, 16], 0, 0), 46 | L('Conv2d-3', [bs, 1, 28, 28], [bs, 1, 28, 28], 10, 0), 47 | L('ReLU-4', [bs, 1, 28, 28], [bs, 1, 28, 28], 0, 0), 48 | ] 49 | assert r == expected 50 | 51 | 52 | expected_summary = """ 53 | 54 | ---------------------------------------------------------------- 55 | Layer (type) Output Shape Param # 56 | ================================================================ 57 | Conv2d-1 [2, 6, 30, 30] 60 58 | Conv2d-2 [2, 16, 13, 13] 880 59 | Linear-3 [2, 120] 69,240 60 | Linear-4 [2, 84] 10,164 61 | Linear-5 [2, 10] 850 62 | ================================================================ 63 | Total params: 81,194 64 | Trainable params: 81,194 65 | Non-trainable params: 0 66 | ---------------------------------------------------------------- 67 | Input size (MB): 0.01 68 | Forward/backward pass size (MB): 0.13 69 | Params size (MB): 0.31 70 | Estimated Total Size (MB): 0.44 71 | ---------------------------------------------------------------- 72 | """ 73 | 74 | 75 | def test_summary(simple_model): 76 | with io.StringIO() as buf: 77 | summary( 78 | simple_model, 79 | [(1, 32, 32)], 80 | input_dtype=torch.FloatTensor, 81 | input_initializer=torch.zeros, 82 | file=buf, 83 | flush=True, 84 | ) 85 | r = buf.getvalue() 86 | assert r == expected_summary 87 | 88 | 89 | def test_inspect_net_with_batch_norm(netbatchnorm): 90 | bs = 10 91 | r = inspect(netbatchnorm, (20,), batch_size=bs) 92 | 93 | expected = [ 94 | L('Linear-1', [bs, 20], [bs, 15], 300, 0), 95 | L('BatchNorm1d-2', [bs, 15], [bs, 15], 30, 30), 96 | L('Linear-3', [bs, 15], [bs, 15], 225, 0), 97 | L('BatchNorm1d-4', [bs, 15], [bs, 15], 30, 30), 98 | L('Linear-5', [bs, 15], [bs, 1], 16, 0), 99 | ] 100 | assert r == expected 101 | with io.StringIO() as buf: 102 | network_info = summary(netbatchnorm, (20,), file=buf, batch_size=bs) 103 | expected_info = NetworkInfo(661, 601, 80 * bs, 488 * bs, 2644, 8324) 104 | assert expected_info == network_info 105 | 106 | 107 | def test_simpleconv(simpleconv): 108 | bs = 2 109 | r = inspect(simpleconv, [(1, 16, 16), (1, 28, 28)], batch_size=bs) 110 | expected = [ 111 | L('Conv2d-1', [bs, 1, 16, 16], [bs, 1, 16, 16], 10, 0), 112 | L('ReLU-2', [bs, 1, 16, 16], [bs, 1, 16, 16], 0, 0), 113 | L('Conv2d-3', [bs, 1, 28, 28], [bs, 1, 28, 28], 10, 0), 114 | L('ReLU-4', [bs, 1, 28, 28], [bs, 1, 28, 28], 0, 0), 115 | ] 116 | assert r == expected 117 | 118 | 119 | def test_autoencoder(autoencoder): 120 | bs = 10 121 | r = inspect(autoencoder, [(3, 32, 32)], batch_size=bs) 122 | expected = [ 123 | L('Conv2d-1', [bs, 3, 32, 32], [bs, 6, 28, 28], 456, 0), 124 | L('ReLU-2', [bs, 6, 28, 28], [bs, 6, 28, 28], 0, 0), 125 | L('Conv2d-3', [bs, 6, 28, 28], [bs, 16, 24, 24], 2416, 0), 126 | L('ReLU-4', [bs, 16, 24, 24], [bs, 16, 24, 24], 0, 0), 127 | L('ConvTranspose2d-5', [bs, 16, 24, 24], [bs, 6, 28, 28], 2406, 0), 128 | L('ReLU-6', [bs, 6, 28, 28], [bs, 6, 28, 28], 0, 0), 129 | L('ConvTranspose2d-7', [bs, 6, 28, 28], [bs, 3, 32, 32], 453, 0), 130 | L('ReLU-8', [bs, 3, 32, 32], [bs, 3, 32, 32], 0, 0), 131 | L('Sigmoid-9', [bs, 3, 32, 32], [bs, 3, 32, 32], 0, 0), 132 | ] 133 | assert r == expected 134 | 135 | 136 | def test_rnn(rnn): 137 | bs = 12 138 | r = inspect(rnn, [(6, 3)], batch_size=bs, input_initializer=torch.zeros) 139 | expected = [ 140 | L('RNN-1', [bs, 6, 3], [[bs, 6, 5], [3, bs, 5]], 170, 0), 141 | L('Linear-2', [6 * bs, 5], [6 * bs, 1], 6, 0), 142 | ] 143 | assert r == expected 144 | 145 | 146 | def test_multi_input_net2(multi_input_net2): 147 | bs = 10 148 | r = inspect(multi_input_net2, [(3, 128, 1024), (4,)], batch_size=bs) 149 | expected = [ 150 | L('Conv2d-1', [10, 3, 128, 1024], [10, 64, 128, 1024], 1792, 0), 151 | L('MaxPool2d-2', [10, 64, 128, 1024], [10, 64, 64, 512], 0, 0), 152 | L('Conv2d-3', [10, 64, 64, 512], [10, 96, 64, 512], 55392, 0), 153 | L('MaxPool2d-4', [10, 96, 64, 512], [10, 96, 32, 256], 0, 0), 154 | L('Conv2d-5', [10, 96, 32, 256], [10, 128, 32, 256], 110720, 0), 155 | L('MaxPool2d-6', [10, 128, 32, 256], [10, 128, 16, 128], 0, 0), 156 | L('Conv2d-7', [10, 128, 16, 128], [10, 192, 16, 128], 221376, 0), 157 | L('AdaptiveAvgPool2d-8', [10, 192, 16, 128], [10, 192, 1, 1], 0, 0), 158 | L('Linear-9', [10, 192], [10, 64], 12352, 0), 159 | L('Linear-10', [10, 64], [10, 4], 260, 0), 160 | ] 161 | assert r == expected 162 | 163 | expected_info = NetworkInfo( 164 | 401892, 401892, 62914560, 1289769280, 1607568, 1354291408 165 | ) 166 | with io.StringIO() as buf: 167 | net_info = summary( 168 | multi_input_net2, [(3, 128, 1024), (4,)], batch_size=bs, file=buf 169 | ) 170 | assert net_info == expected_info 171 | 172 | 173 | def test_lstm_model(lstm_model): 174 | bs = 10 175 | r = inspect( 176 | lstm_model, [(1, 28)], batch_size=bs, input_initializer=torch.zeros 177 | ) 178 | out = [[10, 1, 100], [[1, 10, 100], [1, 10, 100]]] 179 | expected = [ 180 | L('LSTM-1', [10, 1, 28], out, 52000, 0), 181 | L('Linear-2', [10, 100], [10, 10], 1010, 0), 182 | ] 183 | assert r == expected 184 | 185 | 186 | def test_lstm_tagger_with_embedding(lstm_tagger): 187 | bs = 10 188 | r = inspect( 189 | lstm_tagger, 190 | [(1, 1)], 191 | batch_size=bs, 192 | input_initializer=torch.zeros, 193 | input_dtype=torch.LongTensor, 194 | ) 195 | expected = [ 196 | L('Embedding-1', [bs, 1, 1], [bs, 1, 1, 6], 30, 0), 197 | L('LSTM-2', [bs, 1, 6], [[bs, 1, 6], [[1, 1, 6], [1, 1, 6]]], 336, 0), 198 | L('Linear-3', [bs, 6], [bs, 3], 21, 0), 199 | ] 200 | assert r == expected 201 | -------------------------------------------------------------------------------- /torch_inspect/__init__.py: -------------------------------------------------------------------------------- 1 | from .inspect import inspect, summary, LayerInfo, NetworkInfo 2 | 3 | 4 | __all__ = ('LayerInfo', 'NetworkInfo', 'inspect', 'summary') 5 | __version__ = '0.0.4a0' 6 | -------------------------------------------------------------------------------- /torch_inspect/inspect.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from dataclasses import dataclass 3 | from functools import partial 4 | from typing import List, IO, Union, Tuple, Type, Callable 5 | 6 | import numpy as np 7 | import torch 8 | import torch.nn as nn 9 | 10 | from torch.utils.hooks import RemovableHandle 11 | 12 | 13 | __all__ = ('LayerInfo', 'NetworkInfo', 'inspect', 'summary') 14 | 15 | 16 | InputShape = Tuple[int, ...] 17 | OutputShape = List[Union[int, List[int]]] 18 | 19 | 20 | @dataclass 21 | class LayerInfo: 22 | name: str 23 | input_shape: List[int] 24 | output_shape: OutputShape 25 | trainable_params: int 26 | non_trainable_params: int 27 | 28 | 29 | @dataclass 30 | class NetworkInfo: 31 | total_params: int 32 | trainable_params: int 33 | total_input_size: int 34 | total_output_size: int 35 | total_params_size: int 36 | total_size: int 37 | 38 | 39 | def make_network_info( 40 | info_list: List[LayerInfo], 41 | input_size: Union[InputShape, List[InputShape]], 42 | batch_size: int = 2, 43 | ) -> NetworkInfo: 44 | trainable_params = 0 45 | total_params = 0 46 | total_output = 0 47 | for layer in info_list: 48 | total_params += layer.trainable_params + layer.non_trainable_params 49 | total_output += abs(np.prod(layer.output_shape)) 50 | trainable_params += layer.trainable_params 51 | 52 | # multiple inputs to the network 53 | if isinstance(input_size, tuple): 54 | input_size = [input_size] 55 | 56 | # assume 4 bytes/number (float on cuda). 57 | total_input_size = np.prod(sum(input_size, ())) * abs(batch_size) * 4 58 | # x2 for gradients 59 | total_output_size = 2 * total_output * 4 60 | total_params_size = total_params * 4 61 | total_size = total_params_size + total_output_size + total_input_size 62 | ni = NetworkInfo( 63 | total_params, 64 | trainable_params, 65 | total_input_size, 66 | total_output_size, 67 | total_params_size, 68 | total_size, 69 | ) 70 | return ni 71 | 72 | 73 | def should_attach_hook(model: nn.Module, module: nn.Module) -> bool: 74 | v = ( 75 | not isinstance(module, nn.Sequential) 76 | and not isinstance(module, nn.ModuleList) 77 | and not (module is model) # exclude self 78 | ) 79 | return v 80 | 81 | 82 | def _has_running_mean(module: nn.Module) -> bool: 83 | return ( 84 | hasattr(module, 'running_mean') 85 | and hasattr(module.running_mean, 'size') 86 | and hasattr(module, 'track_running_stats') 87 | and module.track_running_stats 88 | ) 89 | 90 | 91 | def _has_running_var(module: nn.Module) -> bool: 92 | return ( 93 | hasattr(module, 'running_var') 94 | and hasattr(module.running_var, 'size') 95 | and hasattr(module, 'track_running_stats') 96 | and module.track_running_stats 97 | ) 98 | 99 | 100 | class _ModuleHook: 101 | def __init__(self, batch_size: int): 102 | self.batch_size = batch_size 103 | self.layer_list: List[LayerInfo] = [] 104 | 105 | def hook( 106 | self, 107 | module: nn.Module, 108 | input: torch.FloatTensor, 109 | output: torch.FloatTensor, 110 | ) -> None: 111 | 112 | # make layer name 113 | module_idx = len(self.layer_list) 114 | class_name = str(module.__class__).split('.')[-1].split("'")[0] 115 | name = f'{class_name}-{module_idx + 1}' 116 | 117 | # calculate input shape 118 | input_shape = list(input[0].size()) 119 | output_shape = infer_shape(output) 120 | 121 | # calculate number of params 122 | trainable_params = 0 123 | non_trainable_params = 0 124 | 125 | for _, param in module.named_parameters(): 126 | params = np.prod(param.size()) 127 | if param.requires_grad: 128 | trainable_params += params 129 | else: 130 | non_trainable_params += params 131 | 132 | if _has_running_mean(module): 133 | params = np.prod(module.running_mean.size()) 134 | non_trainable_params += params 135 | 136 | if _has_running_var(module): 137 | params = np.prod(module.running_var.size()) 138 | non_trainable_params += params 139 | 140 | # recored result 141 | layer = LayerInfo( 142 | name, 143 | input_shape, 144 | output_shape, 145 | int(trainable_params), 146 | int(non_trainable_params), 147 | ) 148 | self.layer_list.append(layer) 149 | 150 | 151 | Output = Union[Tuple[torch.Tensor, ...], torch.Tensor] 152 | 153 | 154 | def infer_shape(output: Output) -> OutputShape: 155 | shape: OutputShape = [] 156 | if isinstance(output, (list, tuple)): 157 | shape = [infer_shape(o) for o in output] # type: ignore 158 | else: 159 | shape = [int(s) for s in output.size()] 160 | return shape 161 | 162 | 163 | def inspect( 164 | model: nn.Module, 165 | input_size: Union[InputShape, List[InputShape]], 166 | input_dtype: Type[torch.Tensor] = torch.FloatTensor, 167 | input_initializer: Callable[..., torch.Tensor] = torch.rand, 168 | batch_size: int = 2, 169 | ) -> List[LayerInfo]: 170 | hook = _ModuleHook(batch_size) 171 | handles: List[RemovableHandle] = [] 172 | 173 | def register_hook(module: nn.Module) -> None: 174 | if should_attach_hook(model, module): 175 | h: RemovableHandle = module.register_forward_hook(hook.hook) 176 | handles.append(h) 177 | 178 | # multiple inputs to the network 179 | if isinstance(input_size, tuple): 180 | input_size = [input_size] 181 | 182 | # make fake input with batch_size of 2 for batchnorm 183 | x = [ 184 | input_initializer(batch_size, *in_size).type( 185 | input_dtype # type: ignore 186 | ) 187 | for in_size in input_size 188 | ] 189 | # attach hooks to each applicable layer 190 | model.apply(register_hook) 191 | 192 | # forward pass 193 | try: 194 | model(*x) 195 | finally: 196 | # cleanup all attached hooks, to move model to original state 197 | for h in handles: 198 | h.remove() # type: ignore 199 | 200 | return hook.layer_list 201 | 202 | 203 | def summary( 204 | model: nn.Module, 205 | input_size: Union[InputShape, List[InputShape]], 206 | input_dtype: Type[torch.Tensor] = torch.FloatTensor, 207 | input_initializer: Callable[..., torch.Tensor] = torch.rand, 208 | batch_size: int = 2, 209 | file: IO[str] = sys.stdout, 210 | flush: bool = False, 211 | ) -> NetworkInfo: 212 | summary = inspect( 213 | model, 214 | input_size, 215 | input_dtype=input_dtype, 216 | input_initializer=input_initializer, 217 | batch_size=batch_size, 218 | ) 219 | n = make_network_info(summary, input_size, batch_size) 220 | print_ = partial(print, file=file, flush=flush) 221 | print_('\n') 222 | print_('----------------------------------------------------------------') 223 | line_new = '{:>20} {:>25} {:>15}'.format( 224 | 'Layer (type)', 'Output Shape', 'Param #' 225 | ) 226 | print_(line_new) 227 | print_('================================================================') 228 | 229 | for layer in summary: 230 | total_params = layer.trainable_params + layer.non_trainable_params 231 | line_new = '{:>20} {:>25} {:>15}'.format( 232 | layer.name, str(layer.output_shape), '{0:,}'.format(total_params) 233 | ) 234 | print_(line_new) 235 | MB = 1024.0 ** 2 236 | print_('================================================================') 237 | print_(f'Total params: {n.total_params:,}') 238 | print_(f'Trainable params: {n.trainable_params:,}') 239 | print_(f'Non-trainable params: {n.total_params - n.trainable_params:,}') 240 | print_('----------------------------------------------------------------') 241 | print_(f'Input size (MB): {n.total_input_size / MB:0.2f}') 242 | print_(f'Forward/backward pass size (MB): {n.total_output_size / MB:0.2f}') 243 | print_(f'Params size (MB): {n.total_params_size / MB :0.2f}') 244 | print_(f'Estimated Total Size (MB): {n.total_size / MB:0.2f}') 245 | print_('----------------------------------------------------------------') 246 | return n 247 | --------------------------------------------------------------------------------