Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- testbed/huggingface__datasets/.gitignoreAdded+67
- testbed/huggingface__datasets/setup.cfgAdded+10
- testbed/huggingface__huggingface_hub/.github/workflows/python-release.ymlAdded+33
- testbed/huggingface__huggingface_hub/MakefileAdded+18
- testbed/huggingface__pytorch-image-models/.gitattributesAdded+1
- testbed/huggingface__pytorch-image-models/.github/FUNDING.ymlAdded+2
- testbed/huggingface__pytorch-image-models/.github/ISSUE_TEMPLATE/bug_report.mdAdded+32
- testbed/huggingface__pytorch-image-models/.github/workflows/tests.ymlAdded+51
- testbed/huggingface__pytorch-image-models/.gitignoreAdded+108
- testbed/huggingface__pytorch-image-models/LICENSEAdded+201
- testbed/huggingface__pytorch-image-models/MANIFEST.inAdded+2
- testbed/huggingface__pytorch-image-models/README.mdAdded+423
- testbed/huggingface__pytorch-image-models/avg_checkpoints.pyAdded+117
- testbed/huggingface__pytorch-image-models/benchmark.pyAdded+481
- testbed/huggingface__pytorch-image-models/clean_checkpoint.pyAdded+82
- testbed/huggingface__pytorch-image-models/convert/convert_nest_flax.pyAdded+109
- testbed/huggingface__pytorch-image-models/distributed_train.shAdded+5
- testbed/huggingface__pytorch-image-models/docs/archived_changes.mdAdded+205
- testbed/huggingface__pytorch-image-models/docs/changes.mdAdded+130
- testbed/huggingface__pytorch-image-models/docs/feature_extraction.mdAdded+173
- testbed/huggingface__pytorch-image-models/docs/index.mdAdded+80
- testbed/huggingface__pytorch-image-models/docs/models.mdAdded+171
- testbed/huggingface__pytorch-image-models/docs/models/.templates/models/advprop.mdAdded+457
- testbed/huggingface__pytorch-image-models/docs/models/.templates/models/big-transfer.mdAdded+295
- testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-darknet.mdAdded+81
- testbed/huggingface__pytorch-image-models/docs/models/.templates/models/dpn.mdAdded+256
- testbed/huggingface__pytorch-image-models/docs/models/gloun-senet.mdAdded+124
- testbed/huggingface__pytorch-image-models/docs/models/gloun-seresnext.mdAdded+197
- testbed/huggingface__pytorch-image-models/docs/models/inception-resnet-v2.mdAdded+133
- testbed/huggingface__pytorch-image-models/docs/models/inception-v3.mdAdded+146
- testbed/huggingface__pytorch-image-models/docs/models/legacy-se-resnet.mdAdded+318
- testbed/huggingface__pytorch-image-models/docs/models/legacy-senet.mdAdded+135
- testbed/huggingface__pytorch-image-models/docs/models/mobilenet-v2.mdAdded+271
- testbed/huggingface__pytorch-image-models/docs/models/nasnet.mdAdded+131
- testbed/huggingface__pytorch-image-models/docs/models/noisy-student.mdAdded+571
- testbed/huggingface__pytorch-image-models/docs/models/pnasnet.mdAdded+132
- testbed/huggingface__pytorch-image-models/docs/models/res2net.mdAdded+321
- testbed/huggingface__pytorch-image-models/docs/models/resnest.mdAdded+469
- testbed/huggingface__pytorch-image-models/docs/models/resnet-d.mdAdded+324
- testbed/huggingface__pytorch-image-models/docs/models/resnet.mdAdded+439
- testbed/huggingface__pytorch-image-models/docs/models/resnext.mdAdded+244
- testbed/huggingface__pytorch-image-models/docs/models/rexnet.mdAdded+258
- testbed/huggingface__pytorch-image-models/docs/models/se-resnet.mdAdded+183
- testbed/huggingface__pytorch-image-models/docs/models/selecsls.mdAdded+197
- testbed/huggingface__pytorch-image-models/docs/models/seresnext.mdAdded+228
- testbed/huggingface__pytorch-image-models/docs/models/skresnet.mdAdded+173
- testbed/huggingface__pytorch-image-models/docs/models/skresnext.mdAdded+131
- testbed/huggingface__pytorch-image-models/docs/models/spnasnet.mdAdded+123
- testbed/huggingface__pytorch-image-models/docs/models/ssl-resnet.mdAdded+192
- testbed/huggingface__pytorch-image-models/docs/models/ssl-resnext.mdAdded+278
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Locked files*.lock!dvc.lock
# Extracted dummy datadatasets/**/dummy_data-zip-extracted/
# Compiled python modules.*.pyc
# Byte-compiled_pycache__/.cache/
# Python egg metadata, regenerated from source files by setuptools.*.egg-info.eggs/
# PyPI distribution artifacts.build/dist/
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# pyenv.python-version
# Tests.pytest_cache/
# Other*.DS_Store
# PyCharm/vscode.idea.vscode
# keep only the empty datasets and metrics directory with it's __init__.py file/src/*/datasets/*!/src/*/datasets/__init__.py
/src/*/metrics/*!/src/*/metrics/__init__.py
# Vim.*.swp
# playground/playground
# Sphinx documentationdocs/_build/docs/source/_build/
# Benchmark resultsreport.jsonreport.md
# Ruff.ruff_cache12345678910[metadata]license_files = LICENSE
[tool:pytest]# Test fails if a FutureWarning is thrown by `huggingface_hub`filterwarnings = error::FutureWarning:huggingface_hub*markers = unit: unit test integration: integration test123456789101112131415161718192021222324252627282930313233name: Python release
on: push: tags: - v*
env: PYPI_TOKEN: ${{ secrets.PYPI_TOKEN_DIST }}
jobs: python_release: runs-on: ubuntu-latest
steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | pip install --upgrade pip pip install setuptools wheel
- run: python setup.py sdist bdist_wheel
- run: | pip install twine
- name: Upload to PyPi run: | twine upload dist/* -u __token__ -p "$PYPI_TOKEN"123456789101112131415161718.PHONY: quality style test
check_dirs := tests src
quality: black --check $(check_dirs) isort --check-only $(check_dirs) flake8 $(check_dirs)
style: black $(check_dirs) isort $(check_dirs)
test: HUGGINGFACE_CO_STAGING=1 pytest -sv ./tests/
1*.ipynb linguist-documentation12# These are supported funding model platformsgithub: rwightman1234567891011121314151617181920212223242526272829303132---name: Bug reportabout: Create a bug report to help us improve. Issues are for reporting bugs or requesting features, the discussion forum is available for asking questions or seeking help from the community.title: "[BUG] Issue title..."labels: bugassignees: rwightman
---
**Describe the bug**A clear and concise description of what the bug is.
**To Reproduce**Steps to reproduce the behavior:1.2.
**Expected behavior**A clear and concise description of what you expected to happen.
**Screenshots**If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):** - OS: [e.g. Windows 10, Ubuntu 18.04] - This repository version [e.g. pip 0.3.1 or commit ref] - PyTorch version w/ CUDA/cuDNN [e.g. from `conda list`, 1.7.0 py3.8_cuda11.0.221_cudnn8.0.3_0]
**Additional context**Add any other context about the problem here.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051name: Python tests
on: push: branches: [ master ] pull_request: branches: [ master ]
env: OMP_NUM_THREADS: 2 MKL_NUM_THREADS: 2
jobs: test: name: Run tests on ${{ matrix.os }} with Python ${{ matrix.python }} strategy: matrix: os: [ubuntu-latest, macOS-latest] python: ['3.8'] torch: ['1.9.0'] torchvision: ['0.10.0'] runs-on: ${{ matrix.os }}
steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python }} - name: Install testing dependencies run: | python -m pip install --upgrade pip pip install pytest pytest-timeout - name: Install torch on mac if: startsWith(matrix.os, 'macOS') run: pip install --no-cache-dir torch==${{ matrix.torch }} torchvision==${{ matrix.torchvision }} - name: Install torch on ubuntu if: startsWith(matrix.os, 'ubuntu') run: | pip install --no-cache-dir torch==${{ matrix.torch }}+cpu torchvision==${{ matrix.torchvision }}+cpu -f https://download.pytorch.org/whl/torch_stable.html sudo apt update sudo apt install -y google-perftools - name: Install requirements run: | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi pip install --no-cache-dir git+https://github.com/mapillary/inplace_abn.git@v1.1.0 - name: Run tests env: LD_PRELOAD: /usr/lib/x86_64-linux-gnu/libtcmalloc.so.4 run: | pytest -vv --durations=0 ./tests123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover.hypothesis/.pytest_cache/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuildertarget/
# Jupyter Notebook.ipynb_checkpoints
# pyenv.python-version
# celery beat schedule filecelerybeat-schedule
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# PyCharm.idea
# PyTorch weights*.tar*.pth*.gzUntitled.ipynbTesting notebook.ipynb123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2019 Ross Wightman
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12include timm/models/pruned/*.txt
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423# PyTorch Image Models- [Sponsors](#sponsors)- [What's New](#whats-new)- [Introduction](#introduction)- [Models](#models)- [Features](#features)- [Results](#results)- [Getting Started (Documentation)](#getting-started-documentation)- [Train, Validation, Inference Scripts](#train-validation-inference-scripts)- [Awesome PyTorch Resources](#awesome-pytorch-resources)- [Licenses](#licenses)- [Citing](#citing)
## Sponsors
A big thank you to my [GitHub Sponsors](https://github.com/sponsors/rwightman) for their support!
In addition to the sponsors at the link above, I've received hardware and/or cloud resources from* Nvidia (https://www.nvidia.com/en-us/)* TFRC (https://www.tensorflow.org/tfrc)
I'm fortunate to be able to dedicate significant time and money of my own supporting this and other open source projects. However, as the projects increase in scope, outside support is needed to continue with the current trajectory of hardware, infrastructure, and electricty costs.
## What's New
### Aug 18, 2021* Optimizer bonanza! * Add LAMB and LARS optimizers, incl trust ratio clipping options. Tweaked to work properly in PyTorch XLA (tested on TPUs w/ `timm bits` [branch](https://github.com/rwightman/pytorch-image-models/tree/bits_and_tpu/timm/bits)) * Add MADGRAD from FB research w/ a few tweaks (decoupled decay option, step handling that works with PyTorch XLA) * Some cleanup on all optimizers and factory. No more `.data`, a bit more consistency, unit tests for all! * SGDP and AdamP still won't work with PyTorch XLA but others should (have yet to test Adabelief, Adafactor, Adahessian myself).* EfficientNet-V2 XL TF ported weights added, but they don't validate well in PyTorch (L is better). The pre-processing for the V2 TF training is a bit diff and the fine-tuned 21k -> 1k weights are very sensitive and less robust than the 1k weights.* Added PyTorch trained EfficientNet-V2 'Tiny' w/ GlobalContext attn weights. Only .1-.2 top-1 better than the SE so more of a curiosity for those interested. ### July 12, 2021* Add XCiT models from [official facebook impl](https://github.com/facebookresearch/xcit). Contributed by [Alexander Soare](https://github.com/alexander-soare)
### July 5-9, 2021* Add `efficientnetv2_rw_t` weights, a custom 'tiny' 13.6M param variant that is a bit better than (non NoisyStudent) B3 models. Both faster and better accuracy (at same or lower res) * top-1 82.34 @ 288x288 and 82.54 @ 320x320* Add [SAM pretrained](https://arxiv.org/abs/2106.01548) in1k weight for ViT B/16 (`vit_base_patch16_sam_224`) and B/32 (`vit_base_patch32_sam_224`) models.* Add 'Aggregating Nested Transformer' (NesT) w/ weights converted from official [Flax impl](https://github.com/google-research/nested-transformer). Contributed by [Alexander Soare](https://github.com/alexander-soare). * `jx_nest_base` - 83.534, `jx_nest_small` - 83.120, `jx_nest_tiny` - 81.426
### June 23, 2021* Reproduce gMLP model training, `gmlp_s16_224` trained to 79.6 top-1, matching [paper](https://arxiv.org/abs/2105.08050). Hparams for this and other recent MLP training [here](https://gist.github.com/rwightman/d6c264a9001f9167e06c209f630b2cc6)
### June 20, 2021* Release Vision Transformer 'AugReg' weights from [How to train your ViT? Data, Augmentation, and Regularization in Vision Transformers](https://arxiv.org/abs/2106.10270) * .npz weight loading support added, can load any of the 50K+ weights from the [AugReg series](https://console.cloud.google.com/storage/browser/vit_models/augreg) * See [example notebook](https://colab.research.google.com/github/google-research/vision_transformer/blob/master/vit_jax_augreg.ipynb) from [official impl](https://github.com/google-research/vision_transformer/) for navigating the augreg weights * Replaced all default weights w/ best AugReg variant (if possible). All AugReg 21k classifiers work. * Highlights: `vit_large_patch16_384` (87.1 top-1), `vit_large_r50_s32_384` (86.2 top-1), `vit_base_patch16_384` (86.0 top-1) * `vit_deit_*` renamed to just `deit_*` * Remove my old small model, replace with DeiT compatible small w/ AugReg weights* Add 1st training of my `gmixer_24_224` MLP /w GLU, 78.1 top-1 w/ 25M params.* Add weights from official ResMLP release (https://github.com/facebookresearch/deit)* Add `eca_nfnet_l2` weights from my 'lightweight' series. 84.7 top-1 at 384x384.* Add distilled BiT 50x1 student and 152x2 Teacher weights from [Knowledge distillation: A good teacher is patient and consistent](https://arxiv.org/abs/2106.05237)* NFNets and ResNetV2-BiT models work w/ Pytorch XLA now * weight standardization uses F.batch_norm instead of std_mean (std_mean wasn't lowered) * eps values adjusted, will be slight differences but should be quite close* Improve test coverage and classifier interface of non-conv (vision transformer and mlp) models* Cleanup a few classifier / flatten details for models w/ conv classifiers or early global pool* Please report any regressions, this PR touched quite a few models.
### June 8, 2021* Add first ResMLP weights, trained in PyTorch XLA on TPU-VM w/ my XLA branch. 24 block variant, 79.2 top-1.* Add ResNet51-Q model w/ pretrained weights at 82.36 top-1. * NFNet inspired block layout with quad layer stem and no maxpool * Same param count (35.7M) and throughput as ResNetRS-50 but +1.5 top-1 @ 224x224 and +2.5 top-1 at 288x288
### May 25, 2021* Add LeViT, Visformer, ConViT (PR by Aman Arora), Twins (PR by paper authors) transformer models* Add ResMLP and gMLP MLP vision models to the existing MLP Mixer impl* Fix a number of torchscript issues with various vision transformer models* Cleanup input_size/img_size override handling and improve testing / test coverage for all vision transformer and MLP models* More flexible pos embedding resize (non-square) for ViT and TnT. Thanks [Alexander Soare](https://github.com/alexander-soare)* Add `efficientnetv2_rw_m` model and weights (started training before official code). 84.8 top-1, 53M params.
### May 14, 2021* Add EfficientNet-V2 official model defs w/ ported weights from official [Tensorflow/Keras](https://github.com/google/automl/tree/master/efficientnetv2) impl. * 1k trained variants: `tf_efficientnetv2_s/m/l` * 21k trained variants: `tf_efficientnetv2_s/m/l_in21k` * 21k pretrained -> 1k fine-tuned: `tf_efficientnetv2_s/m/l_in21ft1k` * v2 models w/ v1 scaling: `tf_efficientnetv2_b0` through `b3` * Rename my prev V2 guess `efficientnet_v2s` -> `efficientnetv2_rw_s` * Some blank `efficientnetv2_*` models in-place for future native PyTorch training
### May 5, 2021* Add MLP-Mixer models and port pretrained weights from [Google JAX impl](https://github.com/google-research/vision_transformer/tree/linen)* Add CaiT models and pretrained weights from [FB](https://github.com/facebookresearch/deit)* Add ResNet-RS models and weights from [TF](https://github.com/tensorflow/tpu/tree/master/models/official/resnet/resnet_rs). Thanks [Aman Arora](https://github.com/amaarora)* Add CoaT models and weights. Thanks [Mohammed Rizin](https://github.com/morizin)* Add new ImageNet-21k weights & finetuned weights for TResNet, MobileNet-V3, ViT models. Thanks [mrT](https://github.com/mrT23)* Add GhostNet models and weights. Thanks [Kai Han](https://github.com/iamhankai)* Update ByoaNet attention modules * Improve SA module inits * Hack together experimental stand-alone Swin based attn module and `swinnet` * Consistent '26t' model defs for experiments.* Add improved Efficientnet-V2S (prelim model def) weights. 83.8 top-1.* WandB logging support
### April 13, 2021* Add Swin Transformer models and weights from https://github.com/microsoft/Swin-Transformer
### April 12, 2021* Add ECA-NFNet-L1 (slimmed down F1 w/ SiLU, 41M params) trained with this code. 84% top-1 @ 320x320. Trained at 256x256.* Add EfficientNet-V2S model (unverified model definition) weights. 83.3 top-1 @ 288x288. Only trained single res 224. Working on progressive training.* Add ByoaNet model definition (Bring-your-own-attention) w/ SelfAttention block and corresponding SA/SA-like modules and model defs * Lambda Networks - https://arxiv.org/abs/2102.08602 * Bottleneck Transformers - https://arxiv.org/abs/2101.11605 * Halo Nets - https://arxiv.org/abs/2103.12731* Adabelief optimizer contributed by Juntang Zhuang
### April 1, 2021* Add snazzy `benchmark.py` script for bulk `timm` model benchmarking of train and/or inference* Add Pooling-based Vision Transformer (PiT) models (from https://github.com/naver-ai/pit) * Merged distilled variant into main for torchscript compatibility * Some `timm` cleanup/style tweaks and weights have hub download support* Cleanup Vision Transformer (ViT) models * Merge distilled (DeiT) model into main so that torchscript can work * Support updated weight init (defaults to old still) that closer matches original JAX impl (possibly better training from scratch) * Separate hybrid model defs into different file and add several new model defs to fiddle with, support patch_size != 1 for hybrids * Fix fine-tuning num_class changes (PiT and ViT) and pos_embed resizing (Vit) with distilled variants * nn.Sequential for block stack (does not break downstream compat)* TnT (Transformer-in-Transformer) models contributed by author (from https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT)* Add RegNetY-160 weights from DeiT teacher model* Add new NFNet-L0 w/ SE attn (rename `nfnet_l0b`->`nfnet_l0`) weights 82.75 top-1 @ 288x288* Some fixes/improvements for TFDS dataset wrapper
### March 17, 2021* Add new ECA-NFNet-L0 (rename `nfnet_l0c`->`eca_nfnet_l0`) weights trained by myself. * 82.6 top-1 @ 288x288, 82.8 @ 320x320, trained at 224x224 * Uses SiLU activation, approx 2x faster than `dm_nfnet_f0` and 50% faster than `nfnet_f0s` w/ 1/3 param count* Integrate [Hugging Face model hub](https://huggingface.co/models) into timm create_model and default_cfg handling for pretrained weight and config sharing (more on this soon!)* Merge HardCoRe NAS models contributed by https://github.com/yoniaflalo* Merge PyTorch trained EfficientNet-EL and pruned ES/EL variants contributed by [DeGirum](https://github.com/DeGirum)
### March 7, 2021* First 0.4.x PyPi release w/ NFNets (& related), ByoB (GPU-Efficient, RepVGG, etc).* Change feature extraction for pre-activation nets (NFNets, ResNetV2) to return features before activation.* Tested with PyTorch 1.8 release. Updated CI to use 1.8.* Benchmarked several arch on RTX 3090, Titan RTX, and V100 across 1.7.1, 1.8, NGC 20.12, and 21.02. Some interesting performance variations to take note of https://gist.github.com/rwightman/bb59f9e245162cee0e38bd66bd8cd77f
### Feb 18, 2021* Add pretrained weights and model variants for NFNet-F* models from [DeepMind Haiku impl](https://github.com/deepmind/deepmind-research/tree/master/nfnets). * Models are prefixed with `dm_`. They require SAME padding conv, skipinit enabled, and activation gains applied in act fn. * These models are big, expect to run out of GPU memory. With the GELU activiation + other options, they are roughly 1/2 the inference speed of my SiLU PyTorch optimized `s` variants. * Original model results are based on pre-processing that is not the same as all other models so you'll see different results in the results csv (once updated). * Matching the original pre-processing as closely as possible I get these results: * `dm_nfnet_f6` - 86.352 * `dm_nfnet_f5` - 86.100 * `dm_nfnet_f4` - 85.834 * `dm_nfnet_f3` - 85.676 * `dm_nfnet_f2` - 85.178 * `dm_nfnet_f1` - 84.696 * `dm_nfnet_f0` - 83.464
### Feb 16, 2021* Add Adaptive Gradient Clipping (AGC) as per https://arxiv.org/abs/2102.06171. Integrated w/ PyTorch gradient clipping via mode arg that defaults to prev 'norm' mode. For backward arg compat, clip-grad arg must be specified to enable when using train.py. * AGC w/ default clipping factor `--clip-grad .01 --clip-mode agc` * PyTorch global norm of 1.0 (old behaviour, always norm), `--clip-grad 1.0` * PyTorch value clipping of 10, `--clip-grad 10. --clip-mode value` * AGC performance is definitely sensitive to the clipping factor. More experimentation needed to determine good values for smaller batch sizes and optimizers besides those in paper. So far I've found .001-.005 is necessary for stable RMSProp training w/ NFNet/NF-ResNet.
### Feb 12, 2021* Update Normalization-Free nets to include new NFNet-F (https://arxiv.org/abs/2102.06171) model defs
### Feb 10, 2021* First Normalization-Free model training experiments done, * nf_resnet50 - 80.68 top-1 @ 288x288, 80.31 @ 256x256 * nf_regnet_b1 - 79.30 @ 288x288, 78.75 @ 256x256* More model archs, incl a flexible ByobNet backbone ('Bring-your-own-blocks') * GPU-Efficient-Networks (https://github.com/idstcv/GPU-Efficient-Networks), impl in `byobnet.py` * RepVGG (https://github.com/DingXiaoH/RepVGG), impl in `byobnet.py` * classic VGG (from torchvision, impl in `vgg.py`)* Refinements to normalizer layer arg handling and normalizer+act layer handling in some models* Default AMP mode changed to native PyTorch AMP instead of APEX. Issues not being fixed with APEX. Native works with `--channels-last` and `--torchscript` model training, APEX does not.* Fix a few bugs introduced since last pypi release
### Feb 8, 2021* Add several ResNet weights with ECA attention. 26t & 50t trained @ 256, test @ 320. 269d train @ 256, fine-tune @320, test @ 352. * `ecaresnet26t` - 79.88 top-1 @ 320x320, 79.08 @ 256x256 * `ecaresnet50t` - 82.35 top-1 @ 320x320, 81.52 @ 256x256 * `ecaresnet269d` - 84.93 top-1 @ 352x352, 84.87 @ 320x320* Remove separate tiered (`t`) vs tiered_narrow (`tn`) ResNet model defs, all `tn` changed to `t` and `t` models removed (`seresnext26t_32x4d` only model w/ weights that was removed).* Support model default_cfgs with separate train vs test resolution `test_input_size` and remove extra `_320` suffix ResNet model defs that were just for test.
### Jan 30, 2021* Add initial "Normalization Free" NF-RegNet-B* and NF-ResNet model definitions based on [paper](https://arxiv.org/abs/2101.08692)
### Jan 25, 2021* Add ResNetV2 Big Transfer (BiT) models w/ ImageNet-1k and 21k weights from https://github.com/google-research/big_transfer* Add official R50+ViT-B/16 hybrid models + weights from https://github.com/google-research/vision_transformer* ImageNet-21k ViT weights are added w/ model defs and representation layer (pre logits) support * NOTE: ImageNet-21k classifier heads were zero'd in original weights, they are only useful for transfer learning* Add model defs and weights for DeiT Vision Transformer models from https://github.com/facebookresearch/deit* Refactor dataset classes into ImageDataset/IterableImageDataset + dataset specific parser classes* Add Tensorflow-Datasets (TFDS) wrapper to allow use of TFDS image classification sets with train script * Ex: `train.py /data/tfds --dataset tfds/oxford_iiit_pet --val-split test --model resnet50 -b 256 --amp --num-classes 37 --opt adamw --lr 3e-4 --weight-decay .001 --pretrained -j 2`* Add improved .tar dataset parser that reads images from .tar, folder of .tar files, or .tar within .tar * Run validation on full ImageNet-21k directly from tar w/ BiT model: `validate.py /data/fall11_whole.tar --model resnetv2_50x1_bitm_in21k --amp`* Models in this update should be stable w/ possible exception of ViT/BiT, possibility of some regressions with train/val scripts and dataset handling
### Jan 3, 2021* Add SE-ResNet-152D weights * 256x256 val, 0.94 crop top-1 - 83.75 * 320x320 val, 1.0 crop - 84.36* Update [results files](results/)
## Introduction
Py**T**orch **Im**age **M**odels (`timm`) is a collection of image models, layers, utilities, optimizers, schedulers, data-loaders / augmentations, and reference training / validation scripts that aim to pull together a wide variety of SOTA models with ability to reproduce ImageNet training results.
The work of many others is present here. I've tried to make sure all source material is acknowledged via links to github, arxiv papers, etc in the README, documentation, and code docstrings. Please let me know if I missed anything.
## Models
All model architecture families include variants with pretrained weights. There are specific model variants without any weights, it is NOT a bug. Help training new or better weights is always appreciated. Here are some example [training hparams](https://rwightman.github.io/pytorch-image-models/training_hparam_examples) to get you started.
A full version of the list below with source links can be found in the [documentation](https://rwightman.github.io/pytorch-image-models/models/).
* Aggregating Nested Transformers - https://arxiv.org/abs/2105.12723* Big Transfer ResNetV2 (BiT) - https://arxiv.org/abs/1912.11370* Bottleneck Transformers - https://arxiv.org/abs/2101.11605* CaiT (Class-Attention in Image Transformers) - https://arxiv.org/abs/2103.17239* CoaT (Co-Scale Conv-Attentional Image Transformers) - https://arxiv.org/abs/2104.06399* ConViT (Soft Convolutional Inductive Biases Vision Transformers)- https://arxiv.org/abs/2103.10697* CspNet (Cross-Stage Partial Networks) - https://arxiv.org/abs/1911.11929* DeiT (Vision Transformer) - https://arxiv.org/abs/2012.12877* DenseNet - https://arxiv.org/abs/1608.06993* DLA - https://arxiv.org/abs/1707.06484* DPN (Dual-Path Network) - https://arxiv.org/abs/1707.01629* EfficientNet (MBConvNet Family) * EfficientNet NoisyStudent (B0-B7, L2) - https://arxiv.org/abs/1911.04252 * EfficientNet AdvProp (B0-B8) - https://arxiv.org/abs/1911.09665 * EfficientNet (B0-B7) - https://arxiv.org/abs/1905.11946 * EfficientNet-EdgeTPU (S, M, L) - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html * EfficientNet V2 - https://arxiv.org/abs/2104.00298 * FBNet-C - https://arxiv.org/abs/1812.03443 * MixNet - https://arxiv.org/abs/1907.09595 * MNASNet B1, A1 (Squeeze-Excite), and Small - https://arxiv.org/abs/1807.11626 * MobileNet-V2 - https://arxiv.org/abs/1801.04381 * Single-Path NAS - https://arxiv.org/abs/1904.02877* GhostNet - https://arxiv.org/abs/1911.11907* gMLP - https://arxiv.org/abs/2105.08050* GPU-Efficient Networks - https://arxiv.org/abs/2006.14090* Halo Nets - https://arxiv.org/abs/2103.12731* HardCoRe-NAS - https://arxiv.org/abs/2102.11646* HRNet - https://arxiv.org/abs/1908.07919* Inception-V3 - https://arxiv.org/abs/1512.00567* Inception-ResNet-V2 and Inception-V4 - https://arxiv.org/abs/1602.07261* Lambda Networks - https://arxiv.org/abs/2102.08602* LeViT (Vision Transformer in ConvNet's Clothing) - https://arxiv.org/abs/2104.01136* MLP-Mixer - https://arxiv.org/abs/2105.01601* MobileNet-V3 (MBConvNet w/ Efficient Head) - https://arxiv.org/abs/1905.02244* NASNet-A - https://arxiv.org/abs/1707.07012* NFNet-F - https://arxiv.org/abs/2102.06171* NF-RegNet / NF-ResNet - https://arxiv.org/abs/2101.08692* PNasNet - https://arxiv.org/abs/1712.00559* Pooling-based Vision Transformer (PiT) - https://arxiv.org/abs/2103.16302* RegNet - https://arxiv.org/abs/2003.13678* RepVGG - https://arxiv.org/abs/2101.03697* ResMLP - https://arxiv.org/abs/2105.03404* ResNet/ResNeXt * ResNet (v1b/v1.5) - https://arxiv.org/abs/1512.03385 * ResNeXt - https://arxiv.org/abs/1611.05431 * 'Bag of Tricks' / Gluon C, D, E, S variations - https://arxiv.org/abs/1812.01187 * Weakly-supervised (WSL) Instagram pretrained / ImageNet tuned ResNeXt101 - https://arxiv.org/abs/1805.00932 * Semi-supervised (SSL) / Semi-weakly Supervised (SWSL) ResNet/ResNeXts - https://arxiv.org/abs/1905.00546 * ECA-Net (ECAResNet) - https://arxiv.org/abs/1910.03151v4 * Squeeze-and-Excitation Networks (SEResNet) - https://arxiv.org/abs/1709.01507 * ResNet-RS - https://arxiv.org/abs/2103.07579* Res2Net - https://arxiv.org/abs/1904.01169* ResNeSt - https://arxiv.org/abs/2004.08955* ReXNet - https://arxiv.org/abs/2007.00992* SelecSLS - https://arxiv.org/abs/1907.00837* Selective Kernel Networks - https://arxiv.org/abs/1903.06586* Swin Transformer - https://arxiv.org/abs/2103.14030* Transformer-iN-Transformer (TNT) - https://arxiv.org/abs/2103.00112* TResNet - https://arxiv.org/abs/2003.13630* Twins (Spatial Attention in Vision Transformers) - https://arxiv.org/pdf/2104.13840.pdf* Vision Transformer - https://arxiv.org/abs/2010.11929* VovNet V2 and V1 - https://arxiv.org/abs/1911.06667* Xception - https://arxiv.org/abs/1610.02357* Xception (Modified Aligned, Gluon) - https://arxiv.org/abs/1802.02611* Xception (Modified Aligned, TF) - https://arxiv.org/abs/1802.02611* XCiT (Cross-Covariance Image Transformers) - https://arxiv.org/abs/2106.09681
## Features
Several (less common) features that I often utilize in my projects are included. Many of their additions are the reason why I maintain my own set of models, instead of using others' via PIP:
* All models have a common default configuration interface and API for * accessing/changing the classifier - `get_classifier` and `reset_classifier` * doing a forward pass on just the features - `forward_features` (see [documentation](https://rwightman.github.io/pytorch-image-models/feature_extraction/)) * these makes it easy to write consistent network wrappers that work with any of the models* All models support multi-scale feature map extraction (feature pyramids) via create_model (see [documentation](https://rwightman.github.io/pytorch-image-models/feature_extraction/)) * `create_model(name, features_only=True, out_indices=..., output_stride=...)` * `out_indices` creation arg specifies which feature maps to return, these indices are 0 based and generally correspond to the `C(i + 1)` feature level. * `output_stride` creation arg controls output stride of the network by using dilated convolutions. Most networks are stride 32 by default. Not all networks support this. * feature map channel counts, reduction level (stride) can be queried AFTER model creation via the `.feature_info` member* All models have a consistent pretrained weight loader that adapts last linear if necessary, and from 3 to 1 channel input if desired* High performance [reference training, validation, and inference scripts](https://rwightman.github.io/pytorch-image-models/scripts/) that work in several process/GPU modes: * NVIDIA DDP w/ a single GPU per process, multiple processes with APEX present (AMP mixed-precision optional) * PyTorch DistributedDataParallel w/ multi-gpu, single process (AMP disabled as it crashes when enabled) * PyTorch w/ single GPU single process (AMP optional)* A dynamic global pool implementation that allows selecting from average pooling, max pooling, average + max, or concat([average, max]) at model creation. All global pooling is adaptive average by default and compatible with pretrained weights.* A 'Test Time Pool' wrapper that can wrap any of the included models and usually provides improved performance doing inference with input images larger than the training size. Idea adapted from original DPN implementation when I ported (https://github.com/cypw/DPNs)* Learning rate schedulers * Ideas adopted from * [AllenNLP schedulers](https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers) * [FAIRseq lr_scheduler](https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler) * SGDR: Stochastic Gradient Descent with Warm Restarts (https://arxiv.org/abs/1608.03983) * Schedulers include `step`, `cosine` w/ restarts, `tanh` w/ restarts, `plateau`* Optimizers: * `rmsprop_tf` adapted from PyTorch RMSProp by myself. Reproduces much improved Tensorflow RMSProp behaviour. * `radam` by [Liyuan Liu](https://github.com/LiyuanLucasLiu/RAdam) (https://arxiv.org/abs/1908.03265) * `novograd` by [Masashi Kimura](https://github.com/convergence-lab/novograd) (https://arxiv.org/abs/1905.11286) * `lookahead` adapted from impl by [Liam](https://github.com/alphadl/lookahead.pytorch) (https://arxiv.org/abs/1907.08610) * `fused<name>` optimizers by name with [NVIDIA Apex](https://github.com/NVIDIA/apex/tree/master/apex/optimizers) installed * `adamp` and `sgdp` by [Naver ClovAI](https://github.com/clovaai) (https://arxiv.org/abs/2006.08217) * `adafactor` adapted from [FAIRSeq impl](https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py) (https://arxiv.org/abs/1804.04235) * `adahessian` by [David Samuel](https://github.com/davda54/ada-hessian) (https://arxiv.org/abs/2006.00719)* Random Erasing from [Zhun Zhong](https://github.com/zhunzhong07/Random-Erasing/blob/master/transforms.py) (https://arxiv.org/abs/1708.04896)* Mixup (https://arxiv.org/abs/1710.09412)* CutMix (https://arxiv.org/abs/1905.04899)* AutoAugment (https://arxiv.org/abs/1805.09501) and RandAugment (https://arxiv.org/abs/1909.13719) ImageNet configurations modeled after impl for EfficientNet training (https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py)* AugMix w/ JSD loss (https://arxiv.org/abs/1912.02781), JSD w/ clean + augmented mixing support works with AutoAugment and RandAugment as well* SplitBachNorm - allows splitting batch norm layers between clean and augmented (auxiliary batch norm) data* DropPath aka "Stochastic Depth" (https://arxiv.org/abs/1603.09382) * DropBlock (https://arxiv.org/abs/1810.12890)* Blur Pooling (https://arxiv.org/abs/1904.11486)* Space-to-Depth by [mrT23](https://github.com/mrT23/TResNet/blob/master/src/models/tresnet/layers/space_to_depth.py) (https://arxiv.org/abs/1801.04590) -- original paper?* Adaptive Gradient Clipping (https://arxiv.org/abs/2102.06171, https://github.com/deepmind/deepmind-research/tree/master/nfnets)* An extensive selection of channel and/or spatial attention modules: * Bottleneck Transformer - https://arxiv.org/abs/2101.11605 * CBAM - https://arxiv.org/abs/1807.06521 * Effective Squeeze-Excitation (ESE) - https://arxiv.org/abs/1911.06667 * Efficient Channel Attention (ECA) - https://arxiv.org/abs/1910.03151 * Gather-Excite (GE) - https://arxiv.org/abs/1810.12348 * Global Context (GC) - https://arxiv.org/abs/1904.11492 * Halo - https://arxiv.org/abs/2103.12731 * Involution - https://arxiv.org/abs/2103.06255 * Lambda Layer - https://arxiv.org/abs/2102.08602 * Non-Local (NL) - https://arxiv.org/abs/1711.07971 * Squeeze-and-Excitation (SE) - https://arxiv.org/abs/1709.01507 * Selective Kernel (SK) - (https://arxiv.org/abs/1903.06586 * Split (SPLAT) - https://arxiv.org/abs/2004.08955 * Shifted Window (SWIN) - https://arxiv.org/abs/2103.14030
## Results
Model validation results can be found in the [documentation](https://rwightman.github.io/pytorch-image-models/results/) and in the [results tables](results/README.md)
## Getting Started (Documentation)
My current [documentation](https://rwightman.github.io/pytorch-image-models/) for `timm` covers the basics.
[timmdocs](https://fastai.github.io/timmdocs/) is quickly becoming a much more comprehensive set of documentation for `timm`. A big thanks to [Aman Arora](https://github.com/amaarora) for his efforts creating timmdocs.
[paperswithcode](https://paperswithcode.com/lib/timm) is a good resource for browsing the models within `timm`.
## Train, Validation, Inference Scripts
The root folder of the repository contains reference train, validation, and inference scripts that work with the included models and other features of this repository. They are adaptable for other datasets and use cases with a little hacking. See [documentation](https://rwightman.github.io/pytorch-image-models/scripts/) for some basics and [training hparams](https://rwightman.github.io/pytorch-image-models/training_hparam_examples) for some train examples that produce SOTA ImageNet results.
## Awesome PyTorch Resources
One of the greatest assets of PyTorch is the community and their contributions. A few of my favourite resources that pair well with the models and components here are listed below.
### Object Detection, Instance and Semantic Segmentation* Detectron2 - https://github.com/facebookresearch/detectron2* Segmentation Models (Semantic) - https://github.com/qubvel/segmentation_models.pytorch* EfficientDet (Obj Det, Semantic soon) - https://github.com/rwightman/efficientdet-pytorch
### Computer Vision / Image Augmentation* Albumentations - https://github.com/albumentations-team/albumentations* Kornia - https://github.com/kornia/kornia
### Knowledge Distillation* RepDistiller - https://github.com/HobbitLong/RepDistiller* torchdistill - https://github.com/yoshitomo-matsubara/torchdistill
### Metric Learning* PyTorch Metric Learning - https://github.com/KevinMusgrave/pytorch-metric-learning
### Training / Frameworks* fastai - https://github.com/fastai/fastai
## Licenses
### CodeThe code here is licensed Apache 2.0. I've taken care to make sure any third party code included or adapted has compatible (permissive) licenses such as MIT, BSD, etc. I've made an effort to avoid any GPL / LGPL conflicts. That said, it is your responsibility to ensure you comply with licenses here and conditions of any dependent licenses. Where applicable, I've linked the sources/references for various components in docstrings. If you think I've missed anything please create an issue.
### Pretrained WeightsSo far all of the pretrained weights available here are pretrained on ImageNet with a select few that have some additional pretraining (see extra note below). ImageNet was released for non-commercial research purposes only (https://image-net.org/download). It's not clear what the implications of that are for the use of pretrained weights from that dataset. Any models I have trained with ImageNet are done for research purposes and one should assume that the original dataset license applies to the weights. It's best to seek legal advice if you intend to use the pretrained weights in a commercial product.
#### Pretrained on more than ImageNetSeveral weights included or references here were pretrained with proprietary datasets that I do not have access to. These include the Facebook WSL, SSL, SWSL ResNe(Xt) and the Google Noisy Student EfficientNet models. The Facebook models have an explicit non-commercial license (CC-BY-NC 4.0, https://github.com/facebookresearch/semi-supervised-ImageNet1K-models, https://github.com/facebookresearch/WSL-Images). The Google models do not appear to have any restriction beyond the Apache 2.0 license (and ImageNet concerns). In either case, you should contact Facebook or Google with any questions.
## Citing
### BibTeX
```bibtex@misc{rw2019timm, author = {Ross Wightman}, title = {PyTorch Image Models}, year = {2019}, publisher = {GitHub}, journal = {GitHub repository}, doi = {10.5281/zenodo.4414861}, howpublished = {\url{https://github.com/rwightman/pytorch-image-models}}}```
### Latest DOI
[](https://zenodo.org/badge/latestdoi/168799526)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117#!/usr/bin/env python3""" Checkpoint Averaging Script
This script averages all model weights for checkpoints in specified path that matchthe specified filter wildcard. All checkpoints must be from the exact same model.
For any hope of decent results, the checkpoints should be from the same or child(via resumes) training session. This can be viewed as similar to maintaining runningEMA (exponential moving average) of the model weights or performing SWA (stochasticweight averaging), but post-training.
Hacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman)"""import torchimport argparseimport osimport globimport hashlibfrom timm.models.helpers import load_state_dict
parser = argparse.ArgumentParser(description='PyTorch Checkpoint Averager')parser.add_argument('--input', default='', type=str, metavar='PATH', help='path to base input folder containing checkpoints')parser.add_argument('--filter', default='*.pth.tar', type=str, metavar='WILDCARD', help='checkpoint filter (path wildcard)')parser.add_argument('--output', default='./averaged.pth', type=str, metavar='PATH', help='output filename')parser.add_argument('--no-use-ema', dest='no_use_ema', action='store_true', help='Force not using ema version of weights (if present)')parser.add_argument('--no-sort', dest='no_sort', action='store_true', help='Do not sort and select by checkpoint metric, also makes "n" argument irrelevant')parser.add_argument('-n', type=int, default=10, metavar='N', help='Number of checkpoints to average')
def checkpoint_metric(checkpoint_path): if not checkpoint_path or not os.path.isfile(checkpoint_path): return {} print("=> Extracting metric from checkpoint '{}'".format(checkpoint_path)) checkpoint = torch.load(checkpoint_path, map_location='cpu') metric = None if 'metric' in checkpoint: metric = checkpoint['metric'] return metric
def main(): args = parser.parse_args() # by default use the EMA weights (if present) args.use_ema = not args.no_use_ema # by default sort by checkpoint metric (if present) and avg top n checkpoints args.sort = not args.no_sort
if os.path.exists(args.output): print("Error: Output filename ({}) already exists.".format(args.output)) exit(1)
pattern = args.input if not args.input.endswith(os.path.sep) and not args.filter.startswith(os.path.sep): pattern += os.path.sep pattern += args.filter checkpoints = glob.glob(pattern, recursive=True)
if args.sort: checkpoint_metrics = [] for c in checkpoints: metric = checkpoint_metric(c) if metric is not None: checkpoint_metrics.append((metric, c)) checkpoint_metrics = list(sorted(checkpoint_metrics)) checkpoint_metrics = checkpoint_metrics[-args.n:] print("Selected checkpoints:") [print(m, c) for m, c in checkpoint_metrics] avg_checkpoints = [c for m, c in checkpoint_metrics] else: avg_checkpoints = checkpoints print("Selected checkpoints:") [print(c) for c in checkpoints]
avg_state_dict = {} avg_counts = {} for c in avg_checkpoints: new_state_dict = load_state_dict(c, args.use_ema) if not new_state_dict: print("Error: Checkpoint ({}) doesn't exist".format(args.checkpoint)) continue
for k, v in new_state_dict.items(): if k not in avg_state_dict: avg_state_dict[k] = v.clone().to(dtype=torch.float64) avg_counts[k] = 1 else: avg_state_dict[k] += v.to(dtype=torch.float64) avg_counts[k] += 1
for k, v in avg_state_dict.items(): v.div_(avg_counts[k])
# float32 overflow seems unlikely based on weights seen to date, but who knows float32_info = torch.finfo(torch.float32) final_state_dict = {} for k, v in avg_state_dict.items(): v = v.clamp(float32_info.min, float32_info.max) final_state_dict[k] = v.to(dtype=torch.float32)
try: torch.save(final_state_dict, args.output, _use_new_zipfile_serialization=False) except: torch.save(final_state_dict, args.output)
with open(args.output, 'rb') as f: sha_hash = hashlib.sha256(f.read()).hexdigest() print("=> Saved state_dict to '{}, SHA256: {}'".format(args.output, sha_hash))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481#!/usr/bin/env python3""" Model Benchmark Script
An inference and train step benchmark script for timm models.
Hacked together by Ross Wightman (https://github.com/rwightman)"""import argparseimport osimport csvimport jsonimport timeimport loggingimport torchimport torch.nn as nnimport torch.nn.parallelfrom collections import OrderedDictfrom contextlib import suppressfrom functools import partial
from timm.models import create_model, is_model, list_modelsfrom timm.optim import create_optimizer_v2from timm.data import resolve_data_configfrom timm.utils import AverageMeter, setup_default_logging
has_apex = Falsetry: from apex import amp has_apex = Trueexcept ImportError: pass
has_native_amp = Falsetry: if getattr(torch.cuda.amp, 'autocast') is not None: has_native_amp = Trueexcept AttributeError: pass
torch.backends.cudnn.benchmark = True_logger = logging.getLogger('validate')
parser = argparse.ArgumentParser(description='PyTorch Benchmark')
# benchmark specific argsparser.add_argument('--model-list', metavar='NAME', default='', help='txt file based list of model names to benchmark')parser.add_argument('--bench', default='both', type=str, help="Benchmark mode. One of 'inference', 'train', 'both'. Defaults to 'both'")parser.add_argument('--detail', action='store_true', default=False, help='Provide train fwd/bwd/opt breakdown detail if True. Defaults to False')parser.add_argument('--results-file', default='', type=str, metavar='FILENAME', help='Output csv file for validation results (summary)')parser.add_argument('--num-warm-iter', default=10, type=int, metavar='N', help='Number of warmup iterations (default: 10)')parser.add_argument('--num-bench-iter', default=40, type=int, metavar='N', help='Number of benchmark iterations (default: 40)')
# common inference / train argsparser.add_argument('--model', '-m', metavar='NAME', default='resnet50', help='model architecture (default: resnet50)')parser.add_argument('-b', '--batch-size', default=256, type=int, metavar='N', help='mini-batch size (default: 256)')parser.add_argument('--img-size', default=None, type=int, metavar='N', help='Input image dimension, uses model default if empty')parser.add_argument('--input-size', default=None, nargs=3, type=int, metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty')parser.add_argument('--num-classes', type=int, default=None, help='Number classes in dataset')parser.add_argument('--gp', default=None, type=str, metavar='POOL', help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.')parser.add_argument('--channels-last', action='store_true', default=False, help='Use channels_last memory layout')parser.add_argument('--amp', action='store_true', default=False, help='use PyTorch Native AMP for mixed precision training. Overrides --precision arg.')parser.add_argument('--precision', default='float32', type=str, help='Numeric precision. One of (amp, float32, float16, bfloat16, tf32)')parser.add_argument('--torchscript', dest='torchscript', action='store_true', help='convert model torchscript for inference')
# train optimizer parametersparser.add_argument('--opt', default='sgd', type=str, metavar='OPTIMIZER', help='Optimizer (default: "sgd"')parser.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: None, use opt default)')parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)')parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='Optimizer momentum (default: 0.9)')parser.add_argument('--weight-decay', type=float, default=0.0001, help='weight decay (default: 0.0001)')parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)')parser.add_argument('--clip-mode', type=str, default='norm', help='Gradient clipping mode. One of ("norm", "value", "agc")')
# model regularization / loss params that impact model or loss fnparser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)')parser.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.)')parser.add_argument('--drop-path', type=float, default=None, metavar='PCT', help='Drop path rate (default: None)')parser.add_argument('--drop-block', type=float, default=None, metavar='PCT', help='Drop block rate (default: None)')
def timestamp(sync=False): return time.perf_counter()
def cuda_timestamp(sync=False, device=None): if sync: torch.cuda.synchronize(device=device) return time.perf_counter()
def count_params(model: nn.Module): return sum([m.numel() for m in model.parameters()])
def resolve_precision(precision: str): assert precision in ('amp', 'float16', 'bfloat16', 'float32') use_amp = False model_dtype = torch.float32 data_dtype = torch.float32 if precision == 'amp': use_amp = True elif precision == 'float16': model_dtype = torch.float16 data_dtype = torch.float16 elif precision == 'bfloat16': model_dtype = torch.bfloat16 data_dtype = torch.bfloat16 return use_amp, model_dtype, data_dtype
class BenchmarkRunner: def __init__( self, model_name, detail=False, device='cuda', torchscript=False, precision='float32', num_warm_iter=10, num_bench_iter=50, **kwargs): self.model_name = model_name self.detail = detail self.device = device self.use_amp, self.model_dtype, self.data_dtype = resolve_precision(precision) self.channels_last = kwargs.pop('channels_last', False) self.amp_autocast = torch.cuda.amp.autocast if self.use_amp else suppress
self.model = create_model( model_name, num_classes=kwargs.pop('num_classes', None), in_chans=3, global_pool=kwargs.pop('gp', 'fast'), scriptable=torchscript) self.model.to( device=self.device, dtype=self.model_dtype, memory_format=torch.channels_last if self.channels_last else None) self.num_classes = self.model.num_classes self.param_count = count_params(self.model) _logger.info('Model %s created, param count: %d' % (model_name, self.param_count)) if torchscript: self.model = torch.jit.script(self.model)
data_config = resolve_data_config(kwargs, model=self.model, use_test_size=True) self.input_size = data_config['input_size'] self.batch_size = kwargs.pop('batch_size', 256)
self.example_inputs = None self.num_warm_iter = num_warm_iter self.num_bench_iter = num_bench_iter self.log_freq = num_bench_iter // 5 if 'cuda' in self.device: self.time_fn = partial(cuda_timestamp, device=self.device) else: self.time_fn = timestamp
def _init_input(self): self.example_inputs = torch.randn( (self.batch_size,) + self.input_size, device=self.device, dtype=self.data_dtype) if self.channels_last: self.example_inputs = self.example_inputs.contiguous(memory_format=torch.channels_last)
class InferenceBenchmarkRunner(BenchmarkRunner):
def __init__(self, model_name, device='cuda', torchscript=False, **kwargs): super().__init__(model_name=model_name, device=device, torchscript=torchscript, **kwargs) self.model.eval()
def run(self): def _step(): t_step_start = self.time_fn() with self.amp_autocast(): output = self.model(self.example_inputs) t_step_end = self.time_fn(True) return t_step_end - t_step_start
_logger.info( f'Running inference benchmark on {self.model_name} for {self.num_bench_iter} steps w/ ' f'input size {self.input_size} and batch size {self.batch_size}.')
with torch.no_grad(): self._init_input()
for _ in range(self.num_warm_iter): _step()
total_step = 0. num_samples = 0 t_run_start = self.time_fn() for i in range(self.num_bench_iter): delta_fwd = _step() total_step += delta_fwd num_samples += self.batch_size num_steps = i + 1 if num_steps % self.log_freq == 0: _logger.info( f"Infer [{num_steps}/{self.num_bench_iter}]." f" {num_samples / total_step:0.2f} samples/sec." f" {1000 * total_step / num_steps:0.3f} ms/step.") t_run_end = self.time_fn(True) t_run_elapsed = t_run_end - t_run_start
results = dict( samples_per_sec=round(num_samples / t_run_elapsed, 2), step_time=round(1000 * total_step / self.num_bench_iter, 3), batch_size=self.batch_size, img_size=self.input_size[-1], param_count=round(self.param_count / 1e6, 2), )
_logger.info( f"Inference benchmark of {self.model_name} done. " f"{results['samples_per_sec']:.2f} samples/sec, {results['step_time']:.2f} ms/step")
return results
class TrainBenchmarkRunner(BenchmarkRunner):
def __init__(self, model_name, device='cuda', torchscript=False, **kwargs): super().__init__(model_name=model_name, device=device, torchscript=torchscript, **kwargs) self.model.train()
if kwargs.pop('smoothing', 0) > 0: self.loss = nn.CrossEntropyLoss().to(self.device) else: self.loss = nn.CrossEntropyLoss().to(self.device) self.target_shape = tuple()
self.optimizer = create_optimizer_v2( self.model, opt=kwargs.pop('opt', 'sgd'), lr=kwargs.pop('lr', 1e-4))
def _gen_target(self, batch_size): return torch.empty( (batch_size,) + self.target_shape, device=self.device, dtype=torch.long).random_(self.num_classes)
def run(self): def _step(detail=False): self.optimizer.zero_grad() # can this be ignored? t_start = self.time_fn() t_fwd_end = t_start t_bwd_end = t_start with self.amp_autocast(): output = self.model(self.example_inputs) if isinstance(output, tuple): output = output[0] if detail: t_fwd_end = self.time_fn(True) target = self._gen_target(output.shape[0]) self.loss(output, target).backward() if detail: t_bwd_end = self.time_fn(True) self.optimizer.step() t_end = self.time_fn(True) if detail: delta_fwd = t_fwd_end - t_start delta_bwd = t_bwd_end - t_fwd_end delta_opt = t_end - t_bwd_end return delta_fwd, delta_bwd, delta_opt else: delta_step = t_end - t_start return delta_step
_logger.info( f'Running train benchmark on {self.model_name} for {self.num_bench_iter} steps w/ ' f'input size {self.input_size} and batch size {self.batch_size}.')
self._init_input()
for _ in range(self.num_warm_iter): _step()
t_run_start = self.time_fn() if self.detail: total_fwd = 0. total_bwd = 0. total_opt = 0. num_samples = 0 for i in range(self.num_bench_iter): delta_fwd, delta_bwd, delta_opt = _step(True) num_samples += self.batch_size total_fwd += delta_fwd total_bwd += delta_bwd total_opt += delta_opt num_steps = (i + 1) if num_steps % self.log_freq == 0: total_step = total_fwd + total_bwd + total_opt _logger.info( f"Train [{num_steps}/{self.num_bench_iter}]." f" {num_samples / total_step:0.2f} samples/sec." f" {1000 * total_fwd / num_steps:0.3f} ms/step fwd," f" {1000 * total_bwd / num_steps:0.3f} ms/step bwd," f" {1000 * total_opt / num_steps:0.3f} ms/step opt." ) total_step = total_fwd + total_bwd + total_opt t_run_elapsed = self.time_fn() - t_run_start results = dict( samples_per_sec=round(num_samples / t_run_elapsed, 2), step_time=round(1000 * total_step / self.num_bench_iter, 3), fwd_time=round(1000 * total_fwd / self.num_bench_iter, 3), bwd_time=round(1000 * total_bwd / self.num_bench_iter, 3), opt_time=round(1000 * total_opt / self.num_bench_iter, 3), batch_size=self.batch_size, img_size=self.input_size[-1], param_count=round(self.param_count / 1e6, 2), ) else: total_step = 0. num_samples = 0 for i in range(self.num_bench_iter): delta_step = _step(False) num_samples += self.batch_size total_step += delta_step num_steps = (i + 1) if num_steps % self.log_freq == 0: _logger.info( f"Train [{num_steps}/{self.num_bench_iter}]." f" {num_samples / total_step:0.2f} samples/sec." f" {1000 * total_step / num_steps:0.3f} ms/step.") t_run_elapsed = self.time_fn() - t_run_start results = dict( samples_per_sec=round(num_samples / t_run_elapsed, 2), step_time=round(1000 * total_step / self.num_bench_iter, 3), batch_size=self.batch_size, img_size=self.input_size[-1], param_count=round(self.param_count / 1e6, 2), )
_logger.info( f"Train benchmark of {self.model_name} done. " f"{results['samples_per_sec']:.2f} samples/sec, {results['step_time']:.2f} ms/sample")
return results
def decay_batch_exp(batch_size, factor=0.5, divisor=16): out_batch_size = batch_size * factor if out_batch_size > divisor: out_batch_size = (out_batch_size + 1) // divisor * divisor else: out_batch_size = batch_size - 1 return max(0, int(out_batch_size))
def _try_run(model_name, bench_fn, initial_batch_size, bench_kwargs): batch_size = initial_batch_size results = dict() while batch_size >= 1: torch.cuda.empty_cache() try: bench = bench_fn(model_name=model_name, batch_size=batch_size, **bench_kwargs) results = bench.run() return results except RuntimeError as e: print(f'Error: {str(e)} while running benchmark. Reducing batch size to {batch_size} for retry.') batch_size = decay_batch_exp(batch_size) return results
def benchmark(args): if args.amp: _logger.warning("Overriding precision to 'amp' since --amp flag set.") args.precision = 'amp' _logger.info(f'Benchmarking in {args.precision} precision. ' f'{"NHWC" if args.channels_last else "NCHW"} layout. ' f'torchscript {"enabled" if args.torchscript else "disabled"}')
bench_kwargs = vars(args).copy() bench_kwargs.pop('amp') model = bench_kwargs.pop('model') batch_size = bench_kwargs.pop('batch_size')
bench_fns = (InferenceBenchmarkRunner,) prefixes = ('infer',) if args.bench == 'both': bench_fns = ( InferenceBenchmarkRunner, TrainBenchmarkRunner ) prefixes = ('infer', 'train') elif args.bench == 'train': bench_fns = TrainBenchmarkRunner, prefixes = 'train',
model_results = OrderedDict(model=model) for prefix, bench_fn in zip(prefixes, bench_fns): run_results = _try_run(model, bench_fn, initial_batch_size=batch_size, bench_kwargs=bench_kwargs) if prefix: run_results = {'_'.join([prefix, k]): v for k, v in run_results.items()} model_results.update(run_results) param_count = model_results.pop('infer_param_count', model_results.pop('train_param_count', 0)) model_results.setdefault('param_count', param_count) model_results.pop('train_param_count', 0) return model_results
def main(): setup_default_logging() args = parser.parse_args() model_cfgs = [] model_names = []
if args.model_list: args.model = '' with open(args.model_list) as f: model_names = [line.rstrip() for line in f] model_cfgs = [(n, None) for n in model_names] elif args.model == 'all': # validate all models in a list of names with pretrained checkpoints args.pretrained = True model_names = list_models(pretrained=True, exclude_filters=['*in21k']) model_cfgs = [(n, None) for n in model_names] elif not is_model(args.model): # model name doesn't exist, try as wildcard filter model_names = list_models(args.model) model_cfgs = [(n, None) for n in model_names]
if len(model_cfgs): results_file = args.results_file or './benchmark.csv' _logger.info('Running bulk validation on these pretrained models: {}'.format(', '.join(model_names))) results = [] try: for m, _ in model_cfgs: if not m: continue args.model = m r = benchmark(args) results.append(r) except KeyboardInterrupt as e: pass sort_key = 'train_samples_per_sec' if 'train' in args.bench else 'infer_samples_per_sec' results = sorted(results, key=lambda x: x[sort_key], reverse=True) if len(results): write_results(results_file, results)
import json json_str = json.dumps(results, indent=4) print(json_str) else: benchmark(args)
def write_results(results_file, results): with open(results_file, mode='w') as cf: dw = csv.DictWriter(cf, fieldnames=results[0].keys()) dw.writeheader() for r in results: dw.writerow(r) cf.flush()
if __name__ == '__main__': main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182#!/usr/bin/env python3""" Checkpoint Cleaning Script
Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc.and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256calculation for model zoo compatibility.
Hacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman)"""import torchimport argparseimport osimport hashlibimport shutilfrom collections import OrderedDict
parser = argparse.ArgumentParser(description='PyTorch Checkpoint Cleaner')parser.add_argument('--checkpoint', default='', type=str, metavar='PATH', help='path to latest checkpoint (default: none)')parser.add_argument('--output', default='', type=str, metavar='PATH', help='output path')parser.add_argument('--use-ema', dest='use_ema', action='store_true', help='use ema version of weights if present')parser.add_argument('--clean-aux-bn', dest='clean_aux_bn', action='store_true', help='remove auxiliary batch norm layers (from SplitBN training) from checkpoint')
_TEMP_NAME = './_checkpoint.pth'
def main(): args = parser.parse_args()
if os.path.exists(args.output): print("Error: Output filename ({}) already exists.".format(args.output)) exit(1)
# Load an existing checkpoint to CPU, strip everything but the state_dict and re-save if args.checkpoint and os.path.isfile(args.checkpoint): print("=> Loading checkpoint '{}'".format(args.checkpoint)) checkpoint = torch.load(args.checkpoint, map_location='cpu')
new_state_dict = OrderedDict() if isinstance(checkpoint, dict): state_dict_key = 'state_dict_ema' if args.use_ema else 'state_dict' if state_dict_key in checkpoint: state_dict = checkpoint[state_dict_key] else: state_dict = checkpoint else: assert False for k, v in state_dict.items(): if args.clean_aux_bn and 'aux_bn' in k: # If all aux_bn keys are removed, the SplitBN layers will end up as normal and # load with the unmodified model using BatchNorm2d. continue name = k[7:] if k.startswith('module') else k new_state_dict[name] = v print("=> Loaded state_dict from '{}'".format(args.checkpoint))
try: torch.save(new_state_dict, _TEMP_NAME, _use_new_zipfile_serialization=False) except: torch.save(new_state_dict, _TEMP_NAME)
with open(_TEMP_NAME, 'rb') as f: sha_hash = hashlib.sha256(f.read()).hexdigest()
if args.output: checkpoint_root, checkpoint_base = os.path.split(args.output) checkpoint_base = os.path.splitext(checkpoint_base)[0] else: checkpoint_root = '' checkpoint_base = os.path.splitext(args.checkpoint)[0] final_filename = '-'.join([checkpoint_base, sha_hash[:8]]) + '.pth' shutil.move(_TEMP_NAME, os.path.join(checkpoint_root, final_filename)) print("=> Saved state_dict to '{}, SHA256: {}'".format(final_filename, sha_hash)) else: print("Error: Checkpoint ({}) doesn't exist".format(args.checkpoint))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Convert weights from https://github.com/google-research/nested-transformerNOTE: You'll need https://github.com/google/CommonLoopUtils, not included in requirements.txt"""
import sys
import numpy as npimport torch
from clu import checkpoint
arch_depths = { 'nest_base': [2, 2, 20], 'nest_small': [2, 2, 20], 'nest_tiny': [2, 2, 8],}
def convert_nest(checkpoint_path, arch): """ Expects path to checkpoint which is a dir containing 4 files like in each of these folders - https://console.cloud.google.com/storage/browser/gresearch/nest-checkpoints `arch` is needed to Returns a state dict that can be used with `torch.nn.Module.load_state_dict` Hint: Follow timm.models.nest.Nest.__init__ and https://github.com/google-research/nested-transformer/blob/main/models/nest_net.py """ assert arch in ['nest_base', 'nest_small', 'nest_tiny'], "Your `arch` is not supported"
flax_dict = checkpoint.load_state_dict(checkpoint_path)['optimizer']['target'] state_dict = {}
# Patch embedding state_dict['patch_embed.proj.weight'] = torch.tensor( flax_dict['PatchEmbedding_0']['Conv_0']['kernel']).permute(3, 2, 0, 1) state_dict['patch_embed.proj.bias'] = torch.tensor(flax_dict['PatchEmbedding_0']['Conv_0']['bias']) # Positional embeddings posemb_keys = [k for k in flax_dict.keys() if k.startswith('PositionEmbedding')] for i, k in enumerate(posemb_keys): state_dict[f'levels.{i}.pos_embed'] = torch.tensor(flax_dict[k]['pos_embedding']) # Transformer encoders depths = arch_depths[arch] for level in range(len(depths)): for layer in range(depths[level]): global_layer_ix = sum(depths[:level]) + layer # Norms for i in range(2): state_dict[f'levels.{level}.transformer_encoder.{layer}.norm{i+1}.weight'] = torch.tensor( flax_dict[f'EncoderNDBlock_{global_layer_ix}'][f'LayerNorm_{i}']['scale']) state_dict[f'levels.{level}.transformer_encoder.{layer}.norm{i+1}.bias'] = torch.tensor( flax_dict[f'EncoderNDBlock_{global_layer_ix}'][f'LayerNorm_{i}']['bias']) # Attention qkv w_q = flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MultiHeadAttention_0']['DenseGeneral_0']['kernel'] w_kv = flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MultiHeadAttention_0']['DenseGeneral_1']['kernel'] # Pay attention to dims here (maybe get pen and paper) w_kv = np.concatenate(np.split(w_kv, 2, -1), 1) w_qkv = np.concatenate([w_q, w_kv], 1) state_dict[f'levels.{level}.transformer_encoder.{layer}.attn.qkv.weight'] = torch.tensor(w_qkv).flatten(1).permute(1,0) b_q = flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MultiHeadAttention_0']['DenseGeneral_0']['bias'] b_kv = flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MultiHeadAttention_0']['DenseGeneral_1']['bias'] # Pay attention to dims here (maybe get pen and paper) b_kv = np.concatenate(np.split(b_kv, 2, -1), 0) b_qkv = np.concatenate([b_q, b_kv], 0) state_dict[f'levels.{level}.transformer_encoder.{layer}.attn.qkv.bias'] = torch.tensor(b_qkv).reshape(-1) # Attention proj w_proj = flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MultiHeadAttention_0']['proj_kernel'] w_proj = torch.tensor(w_proj).permute(2, 1, 0).flatten(1) state_dict[f'levels.{level}.transformer_encoder.{layer}.attn.proj.weight'] = w_proj state_dict[f'levels.{level}.transformer_encoder.{layer}.attn.proj.bias'] = torch.tensor( flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MultiHeadAttention_0']['bias']) # MLP for i in range(2): state_dict[f'levels.{level}.transformer_encoder.{layer}.mlp.fc{i+1}.weight'] = torch.tensor( flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MlpBlock_0'][f'Dense_{i}']['kernel']).permute(1, 0) state_dict[f'levels.{level}.transformer_encoder.{layer}.mlp.fc{i+1}.bias'] = torch.tensor( flax_dict[f'EncoderNDBlock_{global_layer_ix}']['MlpBlock_0'][f'Dense_{i}']['bias'])
# Block aggregations (ConvPool) for level in range(1, len(depths)): # Convs state_dict[f'levels.{level}.pool.conv.weight'] = torch.tensor( flax_dict[f'ConvPool_{level-1}']['Conv_0']['kernel']).permute(3, 2, 0, 1) state_dict[f'levels.{level}.pool.conv.bias'] = torch.tensor( flax_dict[f'ConvPool_{level-1}']['Conv_0']['bias']) # Norms state_dict[f'levels.{level}.pool.norm.weight'] = torch.tensor( flax_dict[f'ConvPool_{level-1}']['LayerNorm_0']['scale']) state_dict[f'levels.{level}.pool.norm.bias'] = torch.tensor( flax_dict[f'ConvPool_{level-1}']['LayerNorm_0']['bias'])
# Final norm state_dict[f'norm.weight'] = torch.tensor(flax_dict['LayerNorm_0']['scale']) state_dict[f'norm.bias'] = torch.tensor(flax_dict['LayerNorm_0']['bias'])
# Classifier state_dict['head.weight'] = torch.tensor(flax_dict['Dense_0']['kernel']).permute(1, 0) state_dict['head.bias'] = torch.tensor(flax_dict['Dense_0']['bias'])
return state_dict
if __name__ == '__main__': variant = sys.argv[1] # base, small, or tiny state_dict = convert_nest(f'./nest-{variant[0]}_imagenet', f'nest_{variant}') torch.save(state_dict, f'./jx_nest_{variant}.pth')12345#!/bin/bashNUM_PROC=$1shiftpython3 -m torch.distributed.launch --nproc_per_node=$NUM_PROC train.py "$@"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# Archived Changes
### Dec 18, 2020* Add ResNet-101D, ResNet-152D, and ResNet-200D weights trained @ 256x256 * 256x256 val, 0.94 crop (top-1) - 101D (82.33), 152D (83.08), 200D (83.25) * 288x288 val, 1.0 crop - 101D (82.64), 152D (83.48), 200D (83.76) * 320x320 val, 1.0 crop - 101D (83.00), 152D (83.66), 200D (84.01)
### Dec 7, 2020* Simplify EMA module (ModelEmaV2), compatible with fully torchscripted models* Misc fixes for SiLU ONNX export, default_cfg missing from Feature extraction models, Linear layer w/ AMP + torchscript* PyPi release @ 0.3.2 (needed by EfficientDet)
### Oct 30, 2020* Test with PyTorch 1.7 and fix a small top-n metric view vs reshape issue.* Convert newly added 224x224 Vision Transformer weights from official JAX repo. 81.8 top-1 for B/16, 83.1 L/16.* Support PyTorch 1.7 optimized, native SiLU (aka Swish) activation. Add mapping to 'silu' name, custom swish will eventually be deprecated.* Fix regression for loading pretrained classifier via direct model entrypoint functions. Didn't impact create_model() factory usage.* PyPi release @ 0.3.0 version!
### Oct 26, 2020* Update Vision Transformer models to be compatible with official code release at https://github.com/google-research/vision_transformer* Add Vision Transformer weights (ImageNet-21k pretrain) for 384x384 base and large models converted from official jax impl * ViT-B/16 - 84.2 * ViT-B/32 - 81.7 * ViT-L/16 - 85.2 * ViT-L/32 - 81.5
### Oct 21, 2020* Weights added for Vision Transformer (ViT) models. 77.86 top-1 for 'small' and 79.35 for 'base'. Thanks to [Christof](https://www.kaggle.com/christofhenkel) for training the base model w/ lots of GPUs.
### Oct 13, 2020* Initial impl of Vision Transformer models. Both patch and hybrid (CNN backbone) variants. Currently trying to train...* Adafactor and AdaHessian (FP32 only, no AMP) optimizers* EdgeTPU-M (`efficientnet_em`) model trained in PyTorch, 79.3 top-1* Pip release, doc updates pending a few more changes...
### Sept 18, 2020* New ResNet 'D' weights. 72.7 (top-1) ResNet-18-D, 77.1 ResNet-34-D, 80.5 ResNet-50-D* Added a few untrained defs for other ResNet models (66D, 101D, 152D, 200/200D)
### Sept 3, 2020* New weights * Wide-ResNet50 - 81.5 top-1 (vs 78.5 torchvision) * SEResNeXt50-32x4d - 81.3 top-1 (vs 79.1 cadene)* Support for native Torch AMP and channels_last memory format added to train/validate scripts (`--channels-last`, `--native-amp` vs `--apex-amp`)* Models tested with channels_last on latest NGC 20.08 container. AdaptiveAvgPool in attn layers changed to mean((2,3)) to work around bug with NHWC kernel.
### Aug 12, 2020* New/updated weights from training experiments * EfficientNet-B3 - 82.1 top-1 (vs 81.6 for official with AA and 81.9 for AdvProp) * RegNetY-3.2GF - 82.0 top-1 (78.9 from official ver) * CSPResNet50 - 79.6 top-1 (76.6 from official ver)* Add CutMix integrated w/ Mixup. See [pull request](https://github.com/rwightman/pytorch-image-models/pull/218) for some usage examples* Some fixes for using pretrained weights with `in_chans` != 3 on several models.
### Aug 5, 2020Universal feature extraction, new models, new weights, new test sets.* All models support the `features_only=True` argument for `create_model` call to return a network that extracts feature maps from the deepest layer at each stride.* New models * CSPResNet, CSPResNeXt, CSPDarkNet, DarkNet * ReXNet * (Modified Aligned) Xception41/65/71 (a proper port of TF models)* New trained weights * SEResNet50 - 80.3 top-1 * CSPDarkNet53 - 80.1 top-1 * CSPResNeXt50 - 80.0 top-1 * DPN68b - 79.2 top-1 * EfficientNet-Lite0 (non-TF ver) - 75.5 (submitted by [@hal-314](https://github.com/hal-314))* Add 'real' labels for ImageNet and ImageNet-Renditions test set, see [`results/README.md`](results/README.md)* Test set ranking/top-n diff script by [@KushajveerSingh](https://github.com/KushajveerSingh)* Train script and loader/transform tweaks to punch through more aug arguments* README and documentation overhaul. See initial (WIP) documentation at https://rwightman.github.io/pytorch-image-models/* adamp and sgdp optimizers added by [@hellbell](https://github.com/hellbell)
### June 11, 2020Bunch of changes:* DenseNet models updated with memory efficient addition from torchvision (fixed a bug), blur pooling and deep stem additions* VoVNet V1 and V2 models added, 39 V2 variant (ese_vovnet_39b) trained to 79.3 top-1* Activation factory added along with new activations: * select act at model creation time for more flexibility in using activations compatible with scripting or tracing (ONNX export) * hard_mish (experimental) added with memory-efficient grad, along with ME hard_swish * context mgr for setting exportable/scriptable/no_jit states* Norm + Activation combo layers added with initial trial support in DenseNet and VoVNet along with impl of EvoNorm and InplaceAbn wrapper that fit the interface* Torchscript works for all but two of the model types as long as using Pytorch 1.5+, tests added for this* Some import cleanup and classifier reset changes, all models will have classifier reset to nn.Identity on reset_classifer(0) call* Prep for 0.1.28 pip release
### May 12, 2020* Add ResNeSt models (code adapted from https://github.com/zhanghang1989/ResNeSt, paper https://arxiv.org/abs/2004.08955))
### May 3, 2020* Pruned EfficientNet B1, B2, and B3 (https://arxiv.org/abs/2002.08258) contributed by [Yonathan Aflalo](https://github.com/yoniaflalo)
### May 1, 2020* Merged a number of execellent contributions in the ResNet model family over the past month * BlurPool2D and resnetblur models initiated by [Chris Ha](https://github.com/VRandme), I trained resnetblur50 to 79.3. * TResNet models and SpaceToDepth, AntiAliasDownsampleLayer layers by [mrT23](https://github.com/mrT23) * ecaresnet (50d, 101d, light) models and two pruned variants using pruning as per (https://arxiv.org/abs/2002.08258) by [Yonathan Aflalo](https://github.com/yoniaflalo)* 200 pretrained models in total now with updated results csv in results folder
### April 5, 2020* Add some newly trained MobileNet-V2 models trained with latest h-params, rand augment. They compare quite favourably to EfficientNet-Lite * 3.5M param MobileNet-V2 100 @ 73% * 4.5M param MobileNet-V2 110d @ 75% * 6.1M param MobileNet-V2 140 @ 76.5% * 5.8M param MobileNet-V2 120d @ 77.3%
### March 18, 2020* Add EfficientNet-Lite models w/ weights ported from [Tensorflow TPU](https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet/lite)* Add RandAugment trained ResNeXt-50 32x4d weights with 79.8 top-1. Trained by [Andrew Lavin](https://github.com/andravin) (see Training section for hparams)
### April 5, 2020* Add some newly trained MobileNet-V2 models trained with latest h-params, rand augment. They compare quite favourably to EfficientNet-Lite * 3.5M param MobileNet-V2 100 @ 73% * 4.5M param MobileNet-V2 110d @ 75% * 6.1M param MobileNet-V2 140 @ 76.5% * 5.8M param MobileNet-V2 120d @ 77.3%
### March 18, 2020* Add EfficientNet-Lite models w/ weights ported from [Tensorflow TPU](https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet/lite)* Add RandAugment trained ResNeXt-50 32x4d weights with 79.8 top-1. Trained by [Andrew Lavin](https://github.com/andravin) (see Training section for hparams)
### Feb 29, 2020* New MobileNet-V3 Large weights trained from stratch with this code to 75.77% top-1* IMPORTANT CHANGE - default weight init changed for all MobilenetV3 / EfficientNet / related models * overall results similar to a bit better training from scratch on a few smaller models tried * performance early in training seems consistently improved but less difference by end * set `fix_group_fanout=False` in `_init_weight_goog` fn if you need to reproducte past behaviour* Experimental LR noise feature added applies a random perturbation to LR each epoch in specified range of training
### Feb 18, 2020* Big refactor of model layers and addition of several attention mechanisms. Several additions motivated by 'Compounding the Performance Improvements...' (https://arxiv.org/abs/2001.06268): * Move layer/module impl into `layers` subfolder/module of `models` and organize in a more granular fashion * ResNet downsample paths now properly support dilation (output stride != 32) for avg_pool ('D' variant) and 3x3 (SENets) networks * Add Selective Kernel Nets on top of ResNet base, pretrained weights * skresnet18 - 73% top-1 * skresnet34 - 76.9% top-1 * skresnext50_32x4d (equiv to SKNet50) - 80.2% top-1 * ECA and CECA (circular padding) attention layer contributed by [Chris Ha](https://github.com/VRandme) * CBAM attention experiment (not the best results so far, may remove) * Attention factory to allow dynamically selecting one of SE, ECA, CBAM in the `.se` position for all ResNets * Add DropBlock and DropPath (formerly DropConnect for EfficientNet/MobileNetv3) support to all ResNet variants* Full dataset results updated that incl NoisyStudent weights and 2 of the 3 SK weights
### Feb 12, 2020* Add EfficientNet-L2 and B0-B7 NoisyStudent weights ported from [Tensorflow TPU](https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet)
### Feb 6, 2020* Add RandAugment trained EfficientNet-ES (EdgeTPU-Small) weights with 78.1 top-1. Trained by [Andrew Lavin](https://github.com/andravin) (see Training section for hparams)
### Feb 1/2, 2020* Port new EfficientNet-B8 (RandAugment) weights, these are different than the B8 AdvProp, different input normalization.* Update results csv files on all models for ImageNet validation and three other test sets* Push PyPi package update
### Jan 31, 2020* Update ResNet50 weights with a new 79.038 result from further JSD / AugMix experiments. Full command line for reproduction in training section below.
### Jan 11/12, 2020* Master may be a bit unstable wrt to training, these changes have been tested but not all combos* Implementations of AugMix added to existing RA and AA. Including numerous supporting pieces like JSD loss (Jensen-Shannon divergence + CE), and AugMixDataset* SplitBatchNorm adaptation layer added for implementing Auxiliary BN as per AdvProp paper* ResNet-50 AugMix trained model w/ 79% top-1 added* `seresnext26tn_32x4d` - 77.99 top-1, 93.75 top-5 added to tiered experiment, higher img/s than 't' and 'd'
### Jan 3, 2020* Add RandAugment trained EfficientNet-B0 weight with 77.7 top-1. Trained by [Michael Klachko](https://github.com/michaelklachko) with this code and recent hparams (see Training section)* Add `avg_checkpoints.py` script for post training weight averaging and update all scripts with header docstrings and shebangs.
### Dec 30, 2019* Merge [Dushyant Mehta's](https://github.com/mehtadushy) PR for SelecSLS (Selective Short and Long Range Skip Connections) networks. Good GPU memory consumption and throughput. Original: https://github.com/mehtadushy/SelecSLS-Pytorch
### Dec 28, 2019* Add new model weights and training hparams (see Training Hparams section) * `efficientnet_b3` - 81.5 top-1, 95.7 top-5 at default res/crop, 81.9, 95.8 at 320x320 1.0 crop-pct * trained with RandAugment, ended up with an interesting but less than perfect result (see training section) * `seresnext26d_32x4d`- 77.6 top-1, 93.6 top-5 * deep stem (32, 32, 64), avgpool downsample * stem/dowsample from bag-of-tricks paper * `seresnext26t_32x4d`- 78.0 top-1, 93.7 top-5 * deep tiered stem (24, 48, 64), avgpool downsample (a modified 'D' variant) * stem sizing mods from Jeremy Howard and fastai devs discussing ResNet architecture experiments
### Dec 23, 2019* Add RandAugment trained MixNet-XL weights with 80.48 top-1.* `--dist-bn` argument added to train.py, will distribute BN stats between nodes after each train epoch, before eval
### Dec 4, 2019* Added weights from the first training from scratch of an EfficientNet (B2) with my new RandAugment implementation. Much better than my previous B2 and very close to the official AdvProp ones (80.4 top-1, 95.08 top-5).
### Nov 29, 2019* Brought EfficientNet and MobileNetV3 up to date with my https://github.com/rwightman/gen-efficientnet-pytorch code. Torchscript and ONNX export compat excluded. * AdvProp weights added * Official TF MobileNetv3 weights added* EfficientNet and MobileNetV3 hook based 'feature extraction' classes added. Will serve as basis for using models as backbones in obj detection/segmentation tasks. Lots more to be done here...* HRNet classification models and weights added from https://github.com/HRNet/HRNet-Image-Classification* Consistency in global pooling, `reset_classifer`, and `forward_features` across models * `forward_features` always returns unpooled feature maps now* Reasonable chance I broke something... let me know
### Nov 22, 2019* Add ImageNet training RandAugment implementation alongside AutoAugment. PyTorch Transform compatible format, using PIL. Currently training two EfficientNet models from scratch with promising results... will update.* `drop-connect` cmd line arg finally added to `train.py`, no need to hack model fns. Works for efficientnet/mobilenetv3 based models, ignored otherwise.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Recent Changes
### June 8, 2021* Add first ResMLP weights, trained in PyTorch XLA on TPU-VM w/ my XLA branch. 24 block variant, 79.2 top-1.* Add ResNet51-Q model w/ pretrained weights at 82.36 top-1. * NFNet inspired block layout with quad layer stem and no maxpool * Same param count (35.7M) and throughput as ResNetRS-50 but +1.5 top-1 @ 224x224 and +2.5 top-1 at 288x288
### May 25, 2021* Add LeViT, Visformer, Convit (PR by Aman Arora), Twins (PR by paper authors) transformer models* Cleanup input_size/img_size override handling and testing for all vision transformer models* Add `efficientnetv2_rw_m` model and weights (started training before official code). 84.8 top-1, 53M params.
### May 14, 2021* Add EfficientNet-V2 official model defs w/ ported weights from official [Tensorflow/Keras](https://github.com/google/automl/tree/master/efficientnetv2) impl. * 1k trained variants: `tf_efficientnetv2_s/m/l` * 21k trained variants: `tf_efficientnetv2_s/m/l_in21k` * 21k pretrained -> 1k fine-tuned: `tf_efficientnetv2_s/m/l_in21ft1k` * v2 models w/ v1 scaling: `tf_efficientnetv2_b0` through `b3` * Rename my prev V2 guess `efficientnet_v2s` -> `efficientnetv2_rw_s` * Some blank `efficientnetv2_*` models in-place for future native PyTorch training
### May 5, 2021* Add MLP-Mixer models and port pretrained weights from [Google JAX impl](https://github.com/google-research/vision_transformer/tree/linen)* Add CaiT models and pretrained weights from [FB](https://github.com/facebookresearch/deit)* Add ResNet-RS models and weights from [TF](https://github.com/tensorflow/tpu/tree/master/models/official/resnet/resnet_rs). Thanks [Aman Arora](https://github.com/amaarora)* Add CoaT models and weights. Thanks [Mohammed Rizin](https://github.com/morizin)* Add new ImageNet-21k weights & finetuned weights for TResNet, MobileNet-V3, ViT models. Thanks [mrT](https://github.com/mrT23)* Add GhostNet models and weights. Thanks [Kai Han](https://github.com/iamhankai)* Update ByoaNet attention modles * Improve SA module inits * Hack together experimental stand-alone Swin based attn module and `swinnet` * Consistent '26t' model defs for experiments.* Add improved Efficientnet-V2S (prelim model def) weights. 83.8 top-1.* WandB logging support
### April 13, 2021* Add Swin Transformer models and weights from https://github.com/microsoft/Swin-Transformer
### April 12, 2021* Add ECA-NFNet-L1 (slimmed down F1 w/ SiLU, 41M params) trained with this code. 84% top-1 @ 320x320. Trained at 256x256.* Add EfficientNet-V2S model (unverified model definition) weights. 83.3 top-1 @ 288x288. Only trained single res 224. Working on progressive training.* Add ByoaNet model definition (Bring-your-own-attention) w/ SelfAttention block and corresponding SA/SA-like modules and model defs * Lambda Networks - https://arxiv.org/abs/2102.08602 * Bottleneck Transformers - https://arxiv.org/abs/2101.11605 * Halo Nets - https://arxiv.org/abs/2103.12731* Adabelief optimizer contributed by Juntang Zhuang
### April 1, 2021* Add snazzy `benchmark.py` script for bulk `timm` model benchmarking of train and/or inference* Add Pooling-based Vision Transformer (PiT) models (from https://github.com/naver-ai/pit) * Merged distilled variant into main for torchscript compatibility * Some `timm` cleanup/style tweaks and weights have hub download support* Cleanup Vision Transformer (ViT) models * Merge distilled (DeiT) model into main so that torchscript can work * Support updated weight init (defaults to old still) that closer matches original JAX impl (possibly better training from scratch) * Separate hybrid model defs into different file and add several new model defs to fiddle with, support patch_size != 1 for hybrids * Fix fine-tuning num_class changes (PiT and ViT) and pos_embed resizing (Vit) with distilled variants * nn.Sequential for block stack (does not break downstream compat)* TnT (Transformer-in-Transformer) models contributed by author (from https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT)* Add RegNetY-160 weights from DeiT teacher model* Add new NFNet-L0 w/ SE attn (rename `nfnet_l0b`->`nfnet_l0`) weights 82.75 top-1 @ 288x288* Some fixes/improvements for TFDS dataset wrapper
### March 7, 2021* First 0.4.x PyPi release w/ NFNets (& related), ByoB (GPU-Efficient, RepVGG, etc).* Change feature extraction for pre-activation nets (NFNets, ResNetV2) to return features before activation.
### Feb 18, 2021* Add pretrained weights and model variants for NFNet-F* models from [DeepMind Haiku impl](https://github.com/deepmind/deepmind-research/tree/master/nfnets). * Models are prefixed with `dm_`. They require SAME padding conv, skipinit enabled, and activation gains applied in act fn. * These models are big, expect to run out of GPU memory. With the GELU activiation + other options, they are roughly 1/2 the inference speed of my SiLU PyTorch optimized `s` variants. * Original model results are based on pre-processing that is not the same as all other models so you'll see different results in the results csv (once updated). * Matching the original pre-processing as closely as possible I get these results: * `dm_nfnet_f6` - 86.352 * `dm_nfnet_f5` - 86.100 * `dm_nfnet_f4` - 85.834 * `dm_nfnet_f3` - 85.676 * `dm_nfnet_f2` - 85.178 * `dm_nfnet_f1` - 84.696 * `dm_nfnet_f0` - 83.464
### Feb 16, 2021* Add Adaptive Gradient Clipping (AGC) as per https://arxiv.org/abs/2102.06171. Integrated w/ PyTorch gradient clipping via mode arg that defaults to prev 'norm' mode. For backward arg compat, clip-grad arg must be specified to enable when using train.py. * AGC w/ default clipping factor `--clip-grad .01 --clip-mode agc` * PyTorch global norm of 1.0 (old behaviour, always norm), `--clip-grad 1.0` * PyTorch value clipping of 10, `--clip-grad 10. --clip-mode value` * AGC performance is definitely sensitive to the clipping factor. More experimentation needed to determine good values for smaller batch sizes and optimizers besides those in paper. So far I've found .001-.005 is necessary for stable RMSProp training w/ NFNet/NF-ResNet.
### Feb 12, 2021* Update Normalization-Free nets to include new NFNet-F (https://arxiv.org/abs/2102.06171) model defs
### Feb 10, 2021* More model archs, incl a flexible ByobNet backbone ('Bring-your-own-blocks') * GPU-Efficient-Networks (https://github.com/idstcv/GPU-Efficient-Networks), impl in `byobnet.py` * RepVGG (https://github.com/DingXiaoH/RepVGG), impl in `byobnet.py` * classic VGG (from torchvision, impl in `vgg`)* Refinements to normalizer layer arg handling and normalizer+act layer handling in some models* Default AMP mode changed to native PyTorch AMP instead of APEX. Issues not being fixed with APEX. Native works with `--channels-last` and `--torchscript` model training, APEX does not.* Fix a few bugs introduced since last pypi release
### Feb 8, 2021* Add several ResNet weights with ECA attention. 26t & 50t trained @ 256, test @ 320. 269d train @ 256, fine-tune @320, test @ 352. * `ecaresnet26t` - 79.88 top-1 @ 320x320, 79.08 @ 256x256 * `ecaresnet50t` - 82.35 top-1 @ 320x320, 81.52 @ 256x256 * `ecaresnet269d` - 84.93 top-1 @ 352x352, 84.87 @ 320x320* Remove separate tiered (`t`) vs tiered_narrow (`tn`) ResNet model defs, all `tn` changed to `t` and `t` models removed (`seresnext26t_32x4d` only model w/ weights that was removed).* Support model default_cfgs with separate train vs test resolution `test_input_size` and remove extra `_320` suffix ResNet model defs that were just for test.
### Jan 30, 2021* Add initial "Normalization Free" NF-RegNet-B* and NF-ResNet model definitions based on [paper](https://arxiv.org/abs/2101.08692)
### Jan 25, 2021* Add ResNetV2 Big Transfer (BiT) models w/ ImageNet-1k and 21k weights from https://github.com/google-research/big_transfer* Add official R50+ViT-B/16 hybrid models + weights from https://github.com/google-research/vision_transformer* ImageNet-21k ViT weights are added w/ model defs and representation layer (pre logits) support * NOTE: ImageNet-21k classifier heads were zero'd in original weights, they are only useful for transfer learning* Add model defs and weights for DeiT Vision Transformer models from https://github.com/facebookresearch/deit* Refactor dataset classes into ImageDataset/IterableImageDataset + dataset specific parser classes* Add Tensorflow-Datasets (TFDS) wrapper to allow use of TFDS image classification sets with train script * Ex: `train.py /data/tfds --dataset tfds/oxford_iiit_pet --val-split test --model resnet50 -b 256 --amp --num-classes 37 --opt adamw --lr 3e-4 --weight-decay .001 --pretrained -j 2`* Add improved .tar dataset parser that reads images from .tar, folder of .tar files, or .tar within .tar * Run validation on full ImageNet-21k directly from tar w/ BiT model: `validate.py /data/fall11_whole.tar --model resnetv2_50x1_bitm_in21k --amp`* Models in this update should be stable w/ possible exception of ViT/BiT, possibility of some regressions with train/val scripts and dataset handling
### Jan 3, 2021* Add SE-ResNet-152D weights * 256x256 val, 0.94 crop top-1 - 83.75 * 320x320 val, 1.0 crop - 84.36* Update results files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173# Feature Extraction
All of the models in `timm` have consistent mechanisms for obtaining various types of features from the model for tasks besides classification.
## Penultimate Layer Features (Pre-Classifier Features)
The features from the penultimate model layer can be obtained in several ways without requiring model surgery (although feel free to do surgery). One must first decide if they want pooled or un-pooled features.
### Unpooled
There are three ways to obtain unpooled features.
Without modifying the network, one can call `model.forward_features(input)` on any model instead of the usual `model(input)`. This will bypass the head classifier and global pooling for networks.
If one wants to explicitly modify the network to return unpooled features, they can either create the model without a classifier and pooling, or remove it later. Both paths remove the parameters associated with the classifier from the network.
#### forward_features()```python hl_lines="3 6"import torchimport timmm = timm.create_model('xception41', pretrained=True)o = m(torch.randn(2, 3, 299, 299))print(f'Original shape: {o.shape}')o = m.forward_features(torch.randn(2, 3, 299, 299))print(f'Unpooled shape: {o.shape}')```Output:```textOriginal shape: torch.Size([2, 1000])Unpooled shape: torch.Size([2, 2048, 10, 10])```
#### Create with no classifier and pooling```python hl_lines="3"import torchimport timmm = timm.create_model('resnet50', pretrained=True, num_classes=0, global_pool='')o = m(torch.randn(2, 3, 224, 224))print(f'Unpooled shape: {o.shape}')```Output:```textUnpooled shape: torch.Size([2, 2048, 7, 7])```
#### Remove it later```python hl_lines="3 6"import torchimport timmm = timm.create_model('densenet121', pretrained=True)o = m(torch.randn(2, 3, 224, 224))print(f'Original shape: {o.shape}')m.reset_classifier(0, '')o = m(torch.randn(2, 3, 224, 224))print(f'Unpooled shape: {o.shape}')```Output:```textOriginal shape: torch.Size([2, 1000])Unpooled shape: torch.Size([2, 1024, 7, 7])```
### Pooled
To modify the network to return pooled features, one can use `forward_features()` and pool/flatten the result themselves, or modify the network like above but keep pooling intact.
#### Create with no classifier```python hl_lines="3"import torchimport timmm = timm.create_model('resnet50', pretrained=True, num_classes=0)o = m(torch.randn(2, 3, 224, 224))print(f'Pooled shape: {o.shape}')```Output:```textPooled shape: torch.Size([2, 2048])```
#### Remove it later```python hl_lines="3 6"import torchimport timmm = timm.create_model('ese_vovnet19b_dw', pretrained=True)o = m(torch.randn(2, 3, 224, 224))print(f'Original shape: {o.shape}')m.reset_classifier(0)o = m(torch.randn(2, 3, 224, 224))print(f'Pooled shape: {o.shape}')```Output:```textPooled shape: torch.Size([2, 1024])```
## Multi-scale Feature Maps (Feature Pyramid)
Object detection, segmentation, keypoint, and a variety of dense pixel tasks require access to feature maps from the backbone network at multiple scales. This is often done by modifying the original classification network. Since each network varies quite a bit in structure, it's not uncommon to see only a few backbones supported in any given obj detection or segmentation library.
`timm` allows a consistent interface for creating any of the included models as feature backbones that output feature maps for selected levels.
A feature backbone can be created by adding the argument `features_only=True` to any `create_model` call. By default 5 strides will be output from most models (not all have that many), with the first starting at 2 (some start at 1 or 4).
### Create a feature map extraction model```python hl_lines="3"import torchimport timmm = timm.create_model('resnest26d', features_only=True, pretrained=True)o = m(torch.randn(2, 3, 224, 224))for x in o: print(x.shape)```Output:```texttorch.Size([2, 64, 112, 112])torch.Size([2, 256, 56, 56])torch.Size([2, 512, 28, 28])torch.Size([2, 1024, 14, 14])torch.Size([2, 2048, 7, 7])```
### Query the feature information
After a feature backbone has been created, it can be queried to provide channel or resolution reduction information to the downstream heads without requiring static config or hardcoded constants. The `.feature_info` attribute is a class encapsulating the information about the feature extraction points.
```python hl_lines="3 4"import torchimport timmm = timm.create_model('regnety_032', features_only=True, pretrained=True)print(f'Feature channels: {m.feature_info.channels()}')o = m(torch.randn(2, 3, 224, 224))for x in o: print(x.shape)```Output:```textFeature channels: [32, 72, 216, 576, 1512]torch.Size([2, 32, 112, 112])torch.Size([2, 72, 56, 56])torch.Size([2, 216, 28, 28])torch.Size([2, 576, 14, 14])torch.Size([2, 1512, 7, 7])```
### Select specific feature levels or limit the stride
There are to additional creation arguments impacting the output features.
* `out_indices` selects which indices to output* `output_stride` limits the feature output stride of the network (also works in classification mode BTW)
`out_indices` is supported by all models, but not all models have the same index to feature stride mapping. Look at the code or check feature_info to compare. The out indices generally correspond to the `C(i+1)th` feature level (a `2^(i+1)` reduction). For most models, index 0 is the stride 2 features, and index 4 is stride 32.
`output_stride` is achieved by converting layers to use dilated convolutions. Doing so is not always straightforward, some networks only support `output_stride=32`.
```python hl_lines="3 4 5"import torchimport timmm = timm.create_model('ecaresnet101d', features_only=True, output_stride=8, out_indices=(2, 4), pretrained=True)print(f'Feature channels: {m.feature_info.channels()}')print(f'Feature reduction: {m.feature_info.reduction()}')o = m(torch.randn(2, 3, 320, 320))for x in o: print(x.shape)```Output:```textFeature channels: [512, 2048]Feature reduction: [8, 8]torch.Size([2, 512, 40, 40])torch.Size([2, 2048, 40, 40])```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Getting Started
## Welcome
Welcome to the `timm` documentation, a lean set of docs that covers the basics of `timm`.
For a more comprehensive set of docs (currently under development), please visit [timmdocs](https://fastai.github.io/timmdocs/) by [Aman Arora](https://github.com/amaarora).
## Install
The library can be installed with pip:
```pip install timm```
I update the PyPi (pip) packages when I'm confident there are no significant model regressions from previous releases. If you want to pip install the bleeding edge from GitHub, use:```pip install git+https://github.com/rwightman/pytorch-image-models.git```
!!! info "Conda Environment" All development and testing has been done in Conda Python 3 environments on Linux x86-64 systems, specifically Python 3.6.x, 3.7.x., 3.8.x., 3.9 Little to no care has been taken to be Python 2.x friendly and will not support it. If you run into any challenges running on Windows, or other OS, I'm definitely open to looking into those issues so long as it's in a reproducible (read Conda) environment. PyTorch versions 1.4, 1.5.x, 1.6, 1.7.x, and 1.8 have been tested with this code. I've tried to keep the dependencies minimal, the setup is as per the PyTorch default install instructions for Conda: ``` conda create -n torch-env conda activate torch-env conda install pytorch torchvision cudatoolkit=11.1 -c pytorch -c conda-forge conda install pyyaml ```
## Load a Pretrained Model
Pretrained models can be loaded using `timm.create_model`
```pythonimport timm
m = timm.create_model('mobilenetv3_large_100', pretrained=True)m.eval()```
## List Models with Pretrained Weights```pythonimport timmfrom pprint import pprintmodel_names = timm.list_models(pretrained=True)pprint(model_names)>>> ['adv_inception_v3', 'cspdarknet53', 'cspresnext50', 'densenet121', 'densenet161', 'densenet169', 'densenet201', 'densenetblur121d', 'dla34', 'dla46_c',...]```
## List Model Architectures by Wildcard```pythonimport timmfrom pprint import pprintmodel_names = timm.list_models('*resne*t*')pprint(model_names)>>> ['cspresnet50', 'cspresnet50d', 'cspresnet50w', 'cspresnext50',...]```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171# Model Summaries
The model architectures included come from a wide variety of sources. Sources, including papers, original impl ("reference code") that I rewrote / adapted, and PyTorch impl that I leveraged directly ("code") are listed below.
Most included models have pretrained weights. The weights are either:
1. from their original sources2. ported by myself from their original impl in a different framework (e.g. Tensorflow models)3. trained from scratch using the included training script
The validation results for the pretrained weights are [here](results.md)
A more exciting view (with pretty pictures) of the models within `timm` can be found at [paperswithcode](https://paperswithcode.com/lib/timm).
## Big Transfer ResNetV2 (BiT) [[resnetv2.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/resnetv2.py)]* Paper: `Big Transfer (BiT): General Visual Representation Learning` - https://arxiv.org/abs/1912.11370* Reference code: https://github.com/google-research/big_transfer
## Cross-Stage Partial Networks [[cspnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/cspnet.py)]* Paper: `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929* Reference impl: https://github.com/WongKinYiu/CrossStagePartialNetworks
## DenseNet [[densenet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/densenet.py)]* Paper: `Densely Connected Convolutional Networks` - https://arxiv.org/abs/1608.06993* Code: https://github.com/pytorch/vision/tree/master/torchvision/models
## DLA [[dla.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/dla.py)]* Paper: https://arxiv.org/abs/1707.06484* Code: https://github.com/ucbdrive/dla
## Dual-Path Networks [[dpn.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/dpn.py)]* Paper: `Dual Path Networks` - https://arxiv.org/abs/1707.01629* My PyTorch code: https://github.com/rwightman/pytorch-dpn-pretrained* Reference code: https://github.com/cypw/DPNs
## GPU-Efficient Networks [[byobnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/byobnet.py)]* Paper: `Neural Architecture Design for GPU-Efficient Networks` - https://arxiv.org/abs/2006.14090* Reference code: https://github.com/idstcv/GPU-Efficient-Networks
## HRNet [[hrnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/hrnet.py)]* Paper: `Deep High-Resolution Representation Learning for Visual Recognition` - https://arxiv.org/abs/1908.07919* Code: https://github.com/HRNet/HRNet-Image-Classification
## Inception-V3 [[inception_v3.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/inception_v3.py)]* Paper: `Rethinking the Inception Architecture for Computer Vision` - https://arxiv.org/abs/1512.00567* Code: https://github.com/pytorch/vision/tree/master/torchvision/models
## Inception-V4 [[inception_v4.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/inception_v4.py)]* Paper: `Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning` - https://arxiv.org/abs/1602.07261* Code: https://github.com/Cadene/pretrained-models.pytorch* Reference code: https://github.com/tensorflow/models/tree/master/research/slim/nets
## Inception-ResNet-V2 [[inception_resnet_v2.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/inception_resnet_v2.py)]* Paper: `Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning` - https://arxiv.org/abs/1602.07261* Code: https://github.com/Cadene/pretrained-models.pytorch* Reference code: https://github.com/tensorflow/models/tree/master/research/slim/nets
## NASNet-A [[nasnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/nasnet.py)]* Papers: `Learning Transferable Architectures for Scalable Image Recognition` - https://arxiv.org/abs/1707.07012* Code: https://github.com/Cadene/pretrained-models.pytorch* Reference code: https://github.com/tensorflow/models/tree/master/research/slim/nets/nasnet
## PNasNet-5 [[pnasnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/pnasnet.py)]* Papers: `Progressive Neural Architecture Search` - https://arxiv.org/abs/1712.00559* Code: https://github.com/Cadene/pretrained-models.pytorch* Reference code: https://github.com/tensorflow/models/tree/master/research/slim/nets/nasnet
## EfficientNet [[efficientnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/efficientnet.py)]
* Papers: * EfficientNet NoisyStudent (B0-B7, L2) - https://arxiv.org/abs/1911.04252 * EfficientNet AdvProp (B0-B8) - https://arxiv.org/abs/1911.09665 * EfficientNet (B0-B7) - https://arxiv.org/abs/1905.11946 * EfficientNet-EdgeTPU (S, M, L) - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html * MixNet - https://arxiv.org/abs/1907.09595 * MNASNet B1, A1 (Squeeze-Excite), and Small - https://arxiv.org/abs/1807.11626 * MobileNet-V2 - https://arxiv.org/abs/1801.04381 * FBNet-C - https://arxiv.org/abs/1812.03443 * Single-Path NAS - https://arxiv.org/abs/1904.02877* My PyTorch code: https://github.com/rwightman/gen-efficientnet-pytorch* Reference code: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet
## MobileNet-V3 [[mobilenetv3.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/mobilenetv3.py)]* Paper: `Searching for MobileNetV3` - https://arxiv.org/abs/1905.02244* Reference code: https://github.com/tensorflow/models/tree/master/research/slim/nets/mobilenet
## RegNet [[regnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/regnet.py)]* Paper: `Designing Network Design Spaces` - https://arxiv.org/abs/2003.13678* Reference code: https://github.com/facebookresearch/pycls/blob/master/pycls/models/regnet.py
## RepVGG [[byobnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/byobnet.py)]* Paper: `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697* Reference code: https://github.com/DingXiaoH/RepVGG
## ResNet, ResNeXt [[resnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/resnet.py)]
* ResNet (V1B) * Paper: `Deep Residual Learning for Image Recognition` - https://arxiv.org/abs/1512.03385 * Code: https://github.com/pytorch/vision/tree/master/torchvision/models* ResNeXt * Paper: `Aggregated Residual Transformations for Deep Neural Networks` - https://arxiv.org/abs/1611.05431 * Code: https://github.com/pytorch/vision/tree/master/torchvision/models* 'Bag of Tricks' / Gluon C, D, E, S ResNet variants * Paper: `Bag of Tricks for Image Classification with CNNs` - https://arxiv.org/abs/1812.01187 * Code: https://github.com/dmlc/gluon-cv/blob/master/gluoncv/model_zoo/resnetv1b.py* Instagram pretrained / ImageNet tuned ResNeXt101 * Paper: `Exploring the Limits of Weakly Supervised Pretraining` - https://arxiv.org/abs/1805.00932 * Weights: https://pytorch.org/hub/facebookresearch_WSL-Images_resnext (NOTE: CC BY-NC 4.0 License, NOT commercial friendly)* Semi-supervised (SSL) / Semi-weakly Supervised (SWSL) ResNet and ResNeXts * Paper: `Billion-scale semi-supervised learning for image classification` - https://arxiv.org/abs/1905.00546 * Weights: https://github.com/facebookresearch/semi-supervised-ImageNet1K-models (NOTE: CC BY-NC 4.0 License, NOT commercial friendly)* Squeeze-and-Excitation Networks * Paper: `Squeeze-and-Excitation Networks` - https://arxiv.org/abs/1709.01507 * Code: Added to ResNet base, this is current version going forward, old `senet.py` is being deprecated* ECAResNet (ECA-Net) * Paper: `ECA-Net: Efficient Channel Attention for Deep CNN` - https://arxiv.org/abs/1910.03151v4 * Code: Added to ResNet base, ECA module contributed by @VRandme, reference https://github.com/BangguWu/ECANet
## Res2Net [[res2net.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/res2net.py)]* Paper: `Res2Net: A New Multi-scale Backbone Architecture` - https://arxiv.org/abs/1904.01169* Code: https://github.com/gasvn/Res2Net
## ResNeSt [[resnest.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/resnest.py)]* Paper: `ResNeSt: Split-Attention Networks` - https://arxiv.org/abs/2004.08955* Code: https://github.com/zhanghang1989/ResNeSt
## ReXNet [[rexnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/rexnet.py)]* Paper: `ReXNet: Diminishing Representational Bottleneck on CNN` - https://arxiv.org/abs/2007.00992* Code: https://github.com/clovaai/rexnet
## Selective-Kernel Networks [[sknet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/sknet.py)]* Paper: `Selective-Kernel Networks` - https://arxiv.org/abs/1903.06586* Code: https://github.com/implus/SKNet, https://github.com/clovaai/assembled-cnn
## SelecSLS [[selecsls.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/selecsls.py)]* Paper: `XNect: Real-time Multi-Person 3D Motion Capture with a Single RGB Camera` - https://arxiv.org/abs/1907.00837* Code: https://github.com/mehtadushy/SelecSLS-Pytorch
## Squeeze-and-Excitation Networks [[senet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/senet.py)]NOTE: I am deprecating this version of the networks, the new ones are part of `resnet.py`
* Paper: `Squeeze-and-Excitation Networks` - https://arxiv.org/abs/1709.01507* Code: https://github.com/Cadene/pretrained-models.pytorch
## TResNet [[tresnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/tresnet.py)]* Paper: `TResNet: High Performance GPU-Dedicated Architecture` - https://arxiv.org/abs/2003.13630* Code: https://github.com/mrT23/TResNet
## VGG [[vgg.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vgg.py)]* Paper: `Very Deep Convolutional Networks For Large-Scale Image Recognition` - https://arxiv.org/pdf/1409.1556.pdf* Reference code: https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py
## Vision Transformer [[vision_transformer.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py)]* Paper: `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` - https://arxiv.org/abs/2010.11929* Reference code and pretrained weights: https://github.com/google-research/vision_transformer
## VovNet V2 and V1 [[vovnet.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vovnet.py)]* Paper: `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667* Reference code: https://github.com/youngwanLEE/vovnet-detectron2
## Xception [[xception.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/xception.py)]* Paper: `Xception: Deep Learning with Depthwise Separable Convolutions` - https://arxiv.org/abs/1610.02357* Code: https://github.com/Cadene/pretrained-models.pytorch
## Xception (Modified Aligned, Gluon) [[gluon_xception.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/gluon_xception.py)]* Paper: `Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation` - https://arxiv.org/abs/1802.02611* Reference code: https://github.com/dmlc/gluon-cv/tree/master/gluoncv/model_zoo, https://github.com/jfzhang95/pytorch-deeplab-xception/
## Xception (Modified Aligned, TF) [[aligned_xception.py](https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/aligned_xception.py)]* Paper: `Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation` - https://arxiv.org/abs/1802.02611* Reference code: https://github.com/tensorflow/models/tree/master/research/deeplab123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457# AdvProp (EfficientNet)
**AdvProp** is an adversarial training scheme which treats adversarial examples as additional examples, to prevent overfitting. Key to the method is the usage of a separate auxiliary batch norm for adversarial examples, as they have different underlying distributions to normal examples.
The weights from this model were ported from [Tensorflow/TPU](https://github.com/tensorflow/tpu).
{% include 'code_snippets.md' %}
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{xie2020adversarial, title={Adversarial Examples Improve Image Recognition}, author={Cihang Xie and Mingxing Tan and Boqing Gong and Jiang Wang and Alan Yuille and Quoc V. Le}, year={2020}, eprint={1911.09665}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: AdvProp Paper: Title: Adversarial Examples Improve Image Recognition URL: https://paperswithcode.com/paper/adversarial-examples-improve-imageModels:- Name: tf_efficientnet_b0_ap In Collection: AdvProp Metadata: FLOPs: 488688572 Parameters: 5290000 File Size: 21385973 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b0_ap LR: 0.256 Epochs: 350 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 2048 Image Size: '224' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1334 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b0_ap-f262efe1.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.1% Top 5 Accuracy: 93.26%- Name: tf_efficientnet_b1_ap In Collection: AdvProp Metadata: FLOPs: 883633200 Parameters: 7790000 File Size: 31515350 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b1_ap LR: 0.256 Epochs: 350 Crop Pct: '0.882' Momentum: 0.9 Batch Size: 2048 Image Size: '240' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1344 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b1_ap-44ef0a3d.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.28% Top 5 Accuracy: 94.3%- Name: tf_efficientnet_b2_ap In Collection: AdvProp Metadata: FLOPs: 1234321170 Parameters: 9110000 File Size: 36800745 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b2_ap LR: 0.256 Epochs: 350 Crop Pct: '0.89' Momentum: 0.9 Batch Size: 2048 Image Size: '260' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1354 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b2_ap-2f8e7636.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.3% Top 5 Accuracy: 95.03%- Name: tf_efficientnet_b3_ap In Collection: AdvProp Metadata: FLOPs: 2275247568 Parameters: 12230000 File Size: 49384538 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b3_ap LR: 0.256 Epochs: 350 Crop Pct: '0.904' Momentum: 0.9 Batch Size: 2048 Image Size: '300' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1364 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b3_ap-aad25bdd.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.82% Top 5 Accuracy: 95.62%- Name: tf_efficientnet_b4_ap In Collection: AdvProp Metadata: FLOPs: 5749638672 Parameters: 19340000 File Size: 77993585 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b4_ap LR: 0.256 Epochs: 350 Crop Pct: '0.922' Momentum: 0.9 Batch Size: 2048 Image Size: '380' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1374 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b4_ap-dedb23e6.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 83.26% Top 5 Accuracy: 96.39%- Name: tf_efficientnet_b5_ap In Collection: AdvProp Metadata: FLOPs: 13176501888 Parameters: 30390000 File Size: 122403150 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b5_ap LR: 0.256 Epochs: 350 Crop Pct: '0.934' Momentum: 0.9 Batch Size: 2048 Image Size: '456' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1384 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b5_ap-9e82fae8.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 84.25% Top 5 Accuracy: 96.97%- Name: tf_efficientnet_b6_ap In Collection: AdvProp Metadata: FLOPs: 24180518488 Parameters: 43040000 File Size: 173237466 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b6_ap LR: 0.256 Epochs: 350 Crop Pct: '0.942' Momentum: 0.9 Batch Size: 2048 Image Size: '528' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1394 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b6_ap-4ffb161f.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 84.79% Top 5 Accuracy: 97.14%- Name: tf_efficientnet_b7_ap In Collection: AdvProp Metadata: FLOPs: 48205304880 Parameters: 66349999 File Size: 266850607 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b7_ap LR: 0.256 Epochs: 350 Crop Pct: '0.949' Momentum: 0.9 Batch Size: 2048 Image Size: '600' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1405 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b7_ap-ddb28fec.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 85.12% Top 5 Accuracy: 97.25%- Name: tf_efficientnet_b8_ap In Collection: AdvProp Metadata: FLOPs: 80962956270 Parameters: 87410000 File Size: 351412563 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AdvProp - AutoAugment - Label Smoothing - RMSProp - Stochastic Depth - Weight Decay Training Data: - ImageNet ID: tf_efficientnet_b8_ap LR: 0.128 Epochs: 350 Crop Pct: '0.954' Momentum: 0.9 Batch Size: 2048 Image Size: '672' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1416 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b8_ap-00e169fa.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 85.37% Top 5 Accuracy: 97.3%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295# Big Transfer (BiT)
**Big Transfer (BiT)** is a type of pretraining recipe that pre-trains on a large supervised source dataset, and fine-tunes the weights on the target task. Models are trained on the JFT-300M dataset. The finetuned models contained in this collection are finetuned on ImageNet.
{% include 'code_snippets.md' %}
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{kolesnikov2020big, title={Big Transfer (BiT): General Visual Representation Learning}, author={Alexander Kolesnikov and Lucas Beyer and Xiaohua Zhai and Joan Puigcerver and Jessica Yung and Sylvain Gelly and Neil Houlsby}, year={2020}, eprint={1912.11370}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: Big Transfer Paper: Title: 'Big Transfer (BiT): General Visual Representation Learning' URL: https://paperswithcode.com/paper/large-scale-learning-of-general-visualModels:- Name: resnetv2_101x1_bitm In Collection: Big Transfer Metadata: FLOPs: 5330896 Parameters: 44540000 File Size: 178256468 Architecture: - 1x1 Convolution - Bottleneck Residual Block - Convolution - Global Average Pooling - Group Normalization - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Weight Standardization Tasks: - Image Classification Training Techniques: - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPUv3-512 ID: resnetv2_101x1_bitm LR: 0.03 Epochs: 90 Layers: 101 Crop Pct: '1.0' Momentum: 0.9 Batch Size: 4096 Image Size: '480' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnetv2.py#L444 Weights: https://storage.googleapis.com/bit_models/BiT-M-R101x1-ILSVRC2012.npz Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 82.21% Top 5 Accuracy: 96.47%- Name: resnetv2_101x3_bitm In Collection: Big Transfer Metadata: FLOPs: 15988688 Parameters: 387930000 File Size: 1551830100 Architecture: - 1x1 Convolution - Bottleneck Residual Block - Convolution - Global Average Pooling - Group Normalization - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Weight Standardization Tasks: - Image Classification Training Techniques: - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPUv3-512 ID: resnetv2_101x3_bitm LR: 0.03 Epochs: 90 Layers: 101 Crop Pct: '1.0' Momentum: 0.9 Batch Size: 4096 Image Size: '480' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnetv2.py#L451 Weights: https://storage.googleapis.com/bit_models/BiT-M-R101x3-ILSVRC2012.npz Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 84.38% Top 5 Accuracy: 97.37%- Name: resnetv2_152x2_bitm In Collection: Big Transfer Metadata: FLOPs: 10659792 Parameters: 236340000 File Size: 945476668 Architecture: - 1x1 Convolution - Bottleneck Residual Block - Convolution - Global Average Pooling - Group Normalization - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Weight Standardization Tasks: - Image Classification Training Techniques: - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet - JFT-300M ID: resnetv2_152x2_bitm Crop Pct: '1.0' Image Size: '480' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnetv2.py#L458 Weights: https://storage.googleapis.com/bit_models/BiT-M-R152x2-ILSVRC2012.npz Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 84.4% Top 5 Accuracy: 97.43%- Name: resnetv2_152x4_bitm In Collection: Big Transfer Metadata: FLOPs: 21317584 Parameters: 936530000 File Size: 3746270104 Architecture: - 1x1 Convolution - Bottleneck Residual Block - Convolution - Global Average Pooling - Group Normalization - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Weight Standardization Tasks: - Image Classification Training Techniques: - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPUv3-512 ID: resnetv2_152x4_bitm Crop Pct: '1.0' Image Size: '480' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnetv2.py#L465 Weights: https://storage.googleapis.com/bit_models/BiT-M-R152x4-ILSVRC2012.npz Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 84.95% Top 5 Accuracy: 97.45%- Name: resnetv2_50x1_bitm In Collection: Big Transfer Metadata: FLOPs: 5330896 Parameters: 25550000 File Size: 102242668 Architecture: - 1x1 Convolution - Bottleneck Residual Block - Convolution - Global Average Pooling - Group Normalization - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Weight Standardization Tasks: - Image Classification Training Techniques: - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPUv3-512 ID: resnetv2_50x1_bitm LR: 0.03 Epochs: 90 Layers: 50 Crop Pct: '1.0' Momentum: 0.9 Batch Size: 4096 Image Size: '480' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnetv2.py#L430 Weights: https://storage.googleapis.com/bit_models/BiT-M-R50x1-ILSVRC2012.npz Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.19% Top 5 Accuracy: 95.63%- Name: resnetv2_50x3_bitm In Collection: Big Transfer Metadata: FLOPs: 15988688 Parameters: 217320000 File Size: 869321580 Architecture: - 1x1 Convolution - Bottleneck Residual Block - Convolution - Global Average Pooling - Group Normalization - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Weight Standardization Tasks: - Image Classification Training Techniques: - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPUv3-512 ID: resnetv2_50x3_bitm LR: 0.03 Epochs: 90 Layers: 50 Crop Pct: '1.0' Momentum: 0.9 Batch Size: 4096 Image Size: '480' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnetv2.py#L437 Weights: https://storage.googleapis.com/bit_models/BiT-M-R50x3-ILSVRC2012.npz Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 83.75% Top 5 Accuracy: 97.12%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# CSP-DarkNet
**CSPDarknet53** is a convolutional neural network and backbone for object detection that uses [DarkNet-53](https://paperswithcode.com/method/darknet-53). It employs a CSPNet strategy to partition the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a split and merge strategy allows for more gradient flow through the network.
This CNN is used as the backbone for [YOLOv4](https://paperswithcode.com/method/yolov4).
{% include 'code_snippets.md' %}
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{bochkovskiy2020yolov4, title={YOLOv4: Optimal Speed and Accuracy of Object Detection}, author={Alexey Bochkovskiy and Chien-Yao Wang and Hong-Yuan Mark Liao}, year={2020}, eprint={2004.10934}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: CSP DarkNet Paper: Title: 'YOLOv4: Optimal Speed and Accuracy of Object Detection' URL: https://paperswithcode.com/paper/yolov4-optimal-speed-and-accuracy-of-objectModels:- Name: cspdarknet53 In Collection: CSP DarkNet Metadata: FLOPs: 8545018880 Parameters: 27640000 File Size: 110775135 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Mish - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - CutMix - Label Smoothing - Mosaic - Polynomial Learning Rate Decay - SGD with Momentum - Self-Adversarial Training - Weight Decay Training Data: - ImageNet Training Resources: 1x NVIDIA RTX 2070 GPU ID: cspdarknet53 LR: 0.1 Layers: 53 Crop Pct: '0.887' Momentum: 0.9 Batch Size: 128 Image Size: '256' Warmup Steps: 1000 Weight Decay: 0.0005 Interpolation: bilinear Training Steps: 8000000 FPS (GPU RTX 2070): 66 Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/cspnet.py#L441 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/cspdarknet53_ra_256-d05c7c21.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.05% Top 5 Accuracy: 95.09%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256# Dual Path Network (DPN)
A **Dual Path Network (DPN)** is a convolutional neural network which presents a new topology of connection paths internally. The intuition is that [ResNets](https://paperswithcode.com/method/resnet) enables feature re-usage while DenseNet enables new feature exploration, and both are important for learning good representations. To enjoy the benefits from both path topologies, Dual Path Networks share common features while maintaining the flexibility to explore new features through dual path architectures.
The principal building block is an [DPN Block](https://paperswithcode.com/method/dpn-block).
{% include 'code_snippets.md' %}
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{chen2017dual, title={Dual Path Networks}, author={Yunpeng Chen and Jianan Li and Huaxin Xiao and Xiaojie Jin and Shuicheng Yan and Jiashi Feng}, year={2017}, eprint={1707.01629}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: DPN Paper: Title: Dual Path Networks URL: https://paperswithcode.com/paper/dual-path-networksModels:- Name: dpn107 In Collection: DPN Metadata: FLOPs: 23524280296 Parameters: 86920000 File Size: 348612331 Architecture: - Batch Normalization - Convolution - DPN Block - Dense Connections - Global Average Pooling - Max Pooling - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 40x K80 GPUs ID: dpn107 LR: 0.316 Layers: 107 Crop Pct: '0.875' Batch Size: 1280 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/dpn.py#L310 Weights: https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn107_extra-1ac7121e2.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.16% Top 5 Accuracy: 94.91%- Name: dpn131 In Collection: DPN Metadata: FLOPs: 20586274792 Parameters: 79250000 File Size: 318016207 Architecture: - Batch Normalization - Convolution - DPN Block - Dense Connections - Global Average Pooling - Max Pooling - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 40x K80 GPUs ID: dpn131 LR: 0.316 Layers: 131 Crop Pct: '0.875' Batch Size: 960 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/dpn.py#L302 Weights: https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn131-71dfe43e0.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.83% Top 5 Accuracy: 94.71%- Name: dpn68 In Collection: DPN Metadata: FLOPs: 2990567880 Parameters: 12610000 File Size: 50761994 Architecture: - Batch Normalization - Convolution - DPN Block - Dense Connections - Global Average Pooling - Max Pooling - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 40x K80 GPUs ID: dpn68 LR: 0.316 Layers: 68 Crop Pct: '0.875' Batch Size: 1280 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/dpn.py#L270 Weights: https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn68-66bebafa7.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 76.31% Top 5 Accuracy: 92.97%- Name: dpn68b In Collection: DPN Metadata: FLOPs: 2990567880 Parameters: 12610000 File Size: 50781025 Architecture: - Batch Normalization - Convolution - DPN Block - Dense Connections - Global Average Pooling - Max Pooling - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 40x K80 GPUs ID: dpn68b LR: 0.316 Layers: 68 Crop Pct: '0.875' Batch Size: 1280 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/dpn.py#L278 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/dpn68b_ra-a31ca160.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.21% Top 5 Accuracy: 94.42%- Name: dpn92 In Collection: DPN Metadata: FLOPs: 8357659624 Parameters: 37670000 File Size: 151248422 Architecture: - Batch Normalization - Convolution - DPN Block - Dense Connections - Global Average Pooling - Max Pooling - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 40x K80 GPUs ID: dpn92 LR: 0.316 Layers: 92 Crop Pct: '0.875' Batch Size: 1280 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/dpn.py#L286 Weights: https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn92_extra-b040e4a9b.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.99% Top 5 Accuracy: 94.84%- Name: dpn98 In Collection: DPN Metadata: FLOPs: 15003675112 Parameters: 61570000 File Size: 247021307 Architecture: - Batch Normalization - Convolution - DPN Block - Dense Connections - Global Average Pooling - Max Pooling - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 40x K80 GPUs ID: dpn98 LR: 0.4 Layers: 98 Crop Pct: '0.875' Batch Size: 1280 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/dpn.py#L294 Weights: https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn98-5b90dec4d.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.65% Top 5 Accuracy: 94.61%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124# (Gluon) SENet
A **SENet** is a convolutional neural network architecture that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html).
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('gluon_senet154', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `gluon_senet154`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('gluon_senet154', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{hu2019squeezeandexcitation, title={Squeeze-and-Excitation Networks}, author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, year={2019}, eprint={1709.01507}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: Gloun SENet Paper: Title: Squeeze-and-Excitation Networks URL: https://paperswithcode.com/paper/squeeze-and-excitation-networksModels:- Name: gluon_senet154 In Collection: Gloun SENet Metadata: FLOPs: 26681705136 Parameters: 115090000 File Size: 461546622 Architecture: - Convolution - Dense Connections - Global Average Pooling - Max Pooling - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Data: - ImageNet ID: gluon_senet154 Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/gluon_resnet.py#L239 Weights: https://github.com/rwightman/pytorch-pretrained-gluonresnet/releases/download/v0.1/gluon_senet154-70a1a3c0.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.23% Top 5 Accuracy: 95.35%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# (Gluon) SE-ResNeXt
**SE ResNeXt** is a variant of a [ResNext](https://www.paperswithcode.com/method/resnext) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html).
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('gluon_seresnext101_32x4d', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `gluon_seresnext101_32x4d`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('gluon_seresnext101_32x4d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{hu2019squeezeandexcitation, title={Squeeze-and-Excitation Networks}, author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, year={2019}, eprint={1709.01507}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: Gloun SEResNeXt Paper: Title: Squeeze-and-Excitation Networks URL: https://paperswithcode.com/paper/squeeze-and-excitation-networksModels:- Name: gluon_seresnext101_32x4d In Collection: Gloun SEResNeXt Metadata: FLOPs: 10302923504 Parameters: 48960000 File Size: 196505510 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Data: - ImageNet ID: gluon_seresnext101_32x4d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/gluon_resnet.py#L219 Weights: https://github.com/rwightman/pytorch-pretrained-gluonresnet/releases/download/v0.1/gluon_seresnext101_32x4d-cf52900d.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.87% Top 5 Accuracy: 95.29%- Name: gluon_seresnext101_64x4d In Collection: Gloun SEResNeXt Metadata: FLOPs: 19958950640 Parameters: 88230000 File Size: 353875948 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Data: - ImageNet ID: gluon_seresnext101_64x4d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/gluon_resnet.py#L229 Weights: https://github.com/rwightman/pytorch-pretrained-gluonresnet/releases/download/v0.1/gluon_seresnext101_64x4d-f9926f93.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.88% Top 5 Accuracy: 95.31%- Name: gluon_seresnext50_32x4d In Collection: Gloun SEResNeXt Metadata: FLOPs: 5475179184 Parameters: 27560000 File Size: 110578827 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Data: - ImageNet ID: gluon_seresnext50_32x4d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/gluon_resnet.py#L209 Weights: https://github.com/rwightman/pytorch-pretrained-gluonresnet/releases/download/v0.1/gluon_seresnext50_32x4d-90cf2d6e.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.92% Top 5 Accuracy: 94.82%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# Inception ResNet v2
**Inception-ResNet-v2** is a convolutional neural architecture that builds on the Inception family of architectures but incorporates [residual connections](https://paperswithcode.com/method/residual-connection) (replacing the filter concatenation stage of the Inception architecture).
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('inception_resnet_v2', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `inception_resnet_v2`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('inception_resnet_v2', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{szegedy2016inceptionv4, title={Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning}, author={Christian Szegedy and Sergey Ioffe and Vincent Vanhoucke and Alex Alemi}, year={2016}, eprint={1602.07261}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: Inception ResNet v2 Paper: Title: Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning URL: https://paperswithcode.com/paper/inception-v4-inception-resnet-and-the-impactModels:- Name: inception_resnet_v2 In Collection: Inception ResNet v2 Metadata: FLOPs: 16959133120 Parameters: 55850000 File Size: 223774238 Architecture: - Average Pooling - Dropout - Inception-ResNet-v2 Reduction-B - Inception-ResNet-v2-A - Inception-ResNet-v2-B - Inception-ResNet-v2-C - Reduction-A - Softmax Tasks: - Image Classification Training Techniques: - Label Smoothing - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 20x NVIDIA Kepler GPUs ID: inception_resnet_v2 LR: 0.045 Dropout: 0.2 Crop Pct: '0.897' Momentum: 0.9 Image Size: '299' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/inception_resnet_v2.py#L343 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/inception_resnet_v2-940b1cd6.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 0.95% Top 5 Accuracy: 17.29%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# Inception v3
**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://paperswithcode.com/method/auxiliary-classifier) to propagate label information lower down the network (along with the use of batch normalization for layers in the sidehead). The key building block is an [Inception Module](https://paperswithcode.com/method/inception-v3-module).
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('inception_v3', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `inception_v3`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('inception_v3', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{DBLP:journals/corr/SzegedyVISW15, author = {Christian Szegedy and Vincent Vanhoucke and Sergey Ioffe and Jonathon Shlens and Zbigniew Wojna}, title = {Rethinking the Inception Architecture for Computer Vision}, journal = {CoRR}, volume = {abs/1512.00567}, year = {2015}, url = {http://arxiv.org/abs/1512.00567}, archivePrefix = {arXiv}, eprint = {1512.00567}, timestamp = {Mon, 13 Aug 2018 16:49:07 +0200}, biburl = {https://dblp.org/rec/journals/corr/SzegedyVISW15.bib}, bibsource = {dblp computer science bibliography, https://dblp.org}}```
<!--Type: model-indexCollections:- Name: Inception v3 Paper: Title: Rethinking the Inception Architecture for Computer Vision URL: https://paperswithcode.com/paper/rethinking-the-inception-architecture-forModels:- Name: inception_v3 In Collection: Inception v3 Metadata: FLOPs: 7352418880 Parameters: 23830000 File Size: 108857766 Architecture: - 1x1 Convolution - Auxiliary Classifier - Average Pooling - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inception-v3 Module - Max Pooling - ReLU - Softmax Tasks: - Image Classification Training Techniques: - Gradient Clipping - Label Smoothing - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 50x NVIDIA Kepler GPUs ID: inception_v3 LR: 0.045 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Image Size: '299' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/inception_v3.py#L442 Weights: https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.46% Top 5 Accuracy: 93.48%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318# (Legacy) SE-ResNet
**SE ResNet** is a variant of a [ResNet](https://www.paperswithcode.com/method/resnet) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('legacy_seresnet101', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `legacy_seresnet101`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('legacy_seresnet101', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{hu2019squeezeandexcitation, title={Squeeze-and-Excitation Networks}, author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, year={2019}, eprint={1709.01507}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: Legacy SE ResNet Paper: Title: Squeeze-and-Excitation Networks URL: https://paperswithcode.com/paper/squeeze-and-excitation-networksModels:- Name: legacy_seresnet101 In Collection: Legacy SE ResNet Metadata: FLOPs: 9762614000 Parameters: 49330000 File Size: 197822624 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: legacy_seresnet101 LR: 0.6 Epochs: 100 Layers: 101 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/senet.py#L426 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet101-7e38fcc6.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.38% Top 5 Accuracy: 94.26%- Name: legacy_seresnet152 In Collection: Legacy SE ResNet Metadata: FLOPs: 14553578160 Parameters: 66819999 File Size: 268033864 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: legacy_seresnet152 LR: 0.6 Epochs: 100 Layers: 152 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/senet.py#L433 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet152-d17c99b7.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.67% Top 5 Accuracy: 94.38%- Name: legacy_seresnet18 In Collection: Legacy SE ResNet Metadata: FLOPs: 2328876024 Parameters: 11780000 File Size: 47175663 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: legacy_seresnet18 LR: 0.6 Epochs: 100 Layers: 18 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/senet.py#L405 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet18-4bb0ce65.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 71.74% Top 5 Accuracy: 90.34%- Name: legacy_seresnet34 In Collection: Legacy SE ResNet Metadata: FLOPs: 4706201004 Parameters: 21960000 File Size: 87958697 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: legacy_seresnet34 LR: 0.6 Epochs: 100 Layers: 34 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/senet.py#L412 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet34-a4004e63.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 74.79% Top 5 Accuracy: 92.13%- Name: legacy_seresnet50 In Collection: Legacy SE ResNet Metadata: FLOPs: 4974351024 Parameters: 28090000 File Size: 112611220 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: legacy_seresnet50 LR: 0.6 Epochs: 100 Layers: 50 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Image Size: '224' Interpolation: bilinear Minibatch Size: 1024 Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/senet.py#L419 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/se_resnet50-ce0d4300.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.64% Top 5 Accuracy: 93.74%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135# (Legacy) SENet
A **SENet** is a convolutional neural network architecture that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
The weights from this model were ported from Gluon.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('legacy_senet154', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `legacy_senet154`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('legacy_senet154', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{hu2019squeezeandexcitation, title={Squeeze-and-Excitation Networks}, author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, year={2019}, eprint={1709.01507}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: Legacy SENet Paper: Title: Squeeze-and-Excitation Networks URL: https://paperswithcode.com/paper/squeeze-and-excitation-networksModels:- Name: legacy_senet154 In Collection: Legacy SENet Metadata: FLOPs: 26659556016 Parameters: 115090000 File Size: 461488402 Architecture: - Convolution - Dense Connections - Global Average Pooling - Max Pooling - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: legacy_senet154 LR: 0.6 Epochs: 100 Layers: 154 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/senet.py#L440 Weights: http://data.lip6.fr/cadene/pretrainedmodels/senet154-c7b49a05.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.33% Top 5 Accuracy: 95.51%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271# MobileNet v2
**MobileNetV2** is a convolutional neural network architecture that seeks to perform well on mobile devices. It is based on an [inverted residual structure](https://paperswithcode.com/method/inverted-residual-block) where the residual connections are between the bottleneck layers. The intermediate expansion layer uses lightweight depthwise convolutions to filter features as a source of non-linearity. As a whole, the architecture of MobileNetV2 contains the initial fully convolution layer with 32 filters, followed by 19 residual bottleneck layers.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('mobilenetv2_100', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `mobilenetv2_100`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('mobilenetv2_100', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{DBLP:journals/corr/abs-1801-04381, author = {Mark Sandler and Andrew G. Howard and Menglong Zhu and Andrey Zhmoginov and Liang{-}Chieh Chen}, title = {Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation}, journal = {CoRR}, volume = {abs/1801.04381}, year = {2018}, url = {http://arxiv.org/abs/1801.04381}, archivePrefix = {arXiv}, eprint = {1801.04381}, timestamp = {Tue, 12 Jan 2021 15:30:06 +0100}, biburl = {https://dblp.org/rec/journals/corr/abs-1801-04381.bib}, bibsource = {dblp computer science bibliography, https://dblp.org}}```
<!--Type: model-indexCollections:- Name: MobileNet V2 Paper: Title: 'MobileNetV2: Inverted Residuals and Linear Bottlenecks' URL: https://paperswithcode.com/paper/mobilenetv2-inverted-residuals-and-linearModels:- Name: mobilenetv2_100 In Collection: MobileNet V2 Metadata: FLOPs: 401920448 Parameters: 3500000 File Size: 14202571 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Depthwise Separable Convolution - Dropout - Inverted Residual Block - Max Pooling - ReLU6 - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 16x GPUs ID: mobilenetv2_100 LR: 0.045 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1536 Image Size: '224' Weight Decay: 4.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L955 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_100_ra-b33bc2c4.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 72.95% Top 5 Accuracy: 91.0%- Name: mobilenetv2_110d In Collection: MobileNet V2 Metadata: FLOPs: 573958832 Parameters: 4520000 File Size: 18316431 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Depthwise Separable Convolution - Dropout - Inverted Residual Block - Max Pooling - ReLU6 - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 16x GPUs ID: mobilenetv2_110d LR: 0.045 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1536 Image Size: '224' Weight Decay: 4.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L969 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_110d_ra-77090ade.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 75.05% Top 5 Accuracy: 92.19%- Name: mobilenetv2_120d In Collection: MobileNet V2 Metadata: FLOPs: 888510048 Parameters: 5830000 File Size: 23651121 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Depthwise Separable Convolution - Dropout - Inverted Residual Block - Max Pooling - ReLU6 - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 16x GPUs ID: mobilenetv2_120d LR: 0.045 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1536 Image Size: '224' Weight Decay: 4.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L977 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_120d_ra-5987e2ed.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.28% Top 5 Accuracy: 93.51%- Name: mobilenetv2_140 In Collection: MobileNet V2 Metadata: FLOPs: 770196784 Parameters: 6110000 File Size: 24673555 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Depthwise Separable Convolution - Dropout - Inverted Residual Block - Max Pooling - ReLU6 - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 16x GPUs ID: mobilenetv2_140 LR: 0.045 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1536 Image Size: '224' Weight Decay: 4.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L962 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_140_ra-21a4e913.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 76.51% Top 5 Accuracy: 93.0%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# NASNet
**NASNet** is a type of convolutional neural network discovered through neural architecture search. The building blocks consist of normal and reduction cells.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('nasnetalarge', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `nasnetalarge`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('nasnetalarge', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{zoph2018learning, title={Learning Transferable Architectures for Scalable Image Recognition}, author={Barret Zoph and Vijay Vasudevan and Jonathon Shlens and Quoc V. Le}, year={2018}, eprint={1707.07012}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: NASNet Paper: Title: Learning Transferable Architectures for Scalable Image Recognition URL: https://paperswithcode.com/paper/learning-transferable-architectures-forModels:- Name: nasnetalarge In Collection: NASNet Metadata: FLOPs: 30242402862 Parameters: 88750000 File Size: 356056626 Architecture: - Average Pooling - Batch Normalization - Convolution - Depthwise Separable Convolution - Dropout - ReLU Tasks: - Image Classification Training Techniques: - Label Smoothing - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 50x Tesla K40 GPUs ID: nasnetalarge Dropout: 0.5 Crop Pct: '0.911' Momentum: 0.9 Image Size: '331' Interpolation: bicubic Label Smoothing: 0.1 RMSProp $\epsilon$: 1.0 Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/nasnet.py#L562 Weights: http://data.lip6.fr/cadene/pretrainedmodels/nasnetalarge-a1897284.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 82.63% Top 5 Accuracy: 96.05%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571# Noisy Student (EfficientNet)
**Noisy Student Training** is a semi-supervised learning approach. It extends the idea of self-trainingand distillation with the use of equal-or-larger student models and noise added to the student during learning. It has three main steps:
1. train a teacher model on labeled images2. use the teacher to generate pseudo labels on unlabeled images3. train a student model on the combination of labeled images and pseudo labeled images.
The algorithm is iterated a few times by treating the student as a teacher to relabel the unlabeled data and training a new student.
Noisy Student Training seeks to improve on self-training and distillation in two ways. First, it makes the student larger than, or at least equal to, the teacher so the student can better learn from a larger dataset. Second, it adds noise to the student so the noised student is forced to learn harder from the pseudo labels. To noise the student, it uses input noise such as RandAugment data augmentation, and model noise such as dropout and stochastic depth during training.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('tf_efficientnet_b0_ns', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `tf_efficientnet_b0_ns`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('tf_efficientnet_b0_ns', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{xie2020selftraining, title={Self-training with Noisy Student improves ImageNet classification}, author={Qizhe Xie and Minh-Thang Luong and Eduard Hovy and Quoc V. Le}, year={2020}, eprint={1911.04252}, archivePrefix={arXiv}, primaryClass={cs.LG}}```
<!--Type: model-indexCollections:- Name: Noisy Student Paper: Title: Self-training with Noisy Student improves ImageNet classification URL: https://paperswithcode.com/paper/self-training-with-noisy-student-improvesModels:- Name: tf_efficientnet_b0_ns In Collection: Noisy Student Metadata: FLOPs: 488688572 Parameters: 5290000 File Size: 21386709 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b0_ns LR: 0.128 Epochs: 700 Dropout: 0.5 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 2048 Image Size: '224' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1427 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b0_ns-c0e6a31c.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.66% Top 5 Accuracy: 94.37%- Name: tf_efficientnet_b1_ns In Collection: Noisy Student Metadata: FLOPs: 883633200 Parameters: 7790000 File Size: 31516408 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b1_ns LR: 0.128 Epochs: 700 Dropout: 0.5 Crop Pct: '0.882' Momentum: 0.9 Batch Size: 2048 Image Size: '240' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1437 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b1_ns-99dd0c41.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.39% Top 5 Accuracy: 95.74%- Name: tf_efficientnet_b2_ns In Collection: Noisy Student Metadata: FLOPs: 1234321170 Parameters: 9110000 File Size: 36801803 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b2_ns LR: 0.128 Epochs: 700 Dropout: 0.5 Crop Pct: '0.89' Momentum: 0.9 Batch Size: 2048 Image Size: '260' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1447 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b2_ns-00306e48.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 82.39% Top 5 Accuracy: 96.24%- Name: tf_efficientnet_b3_ns In Collection: Noisy Student Metadata: FLOPs: 2275247568 Parameters: 12230000 File Size: 49385734 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b3_ns LR: 0.128 Epochs: 700 Dropout: 0.5 Crop Pct: '0.904' Momentum: 0.9 Batch Size: 2048 Image Size: '300' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1457 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b3_ns-9d44bf68.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 84.04% Top 5 Accuracy: 96.91%- Name: tf_efficientnet_b4_ns In Collection: Noisy Student Metadata: FLOPs: 5749638672 Parameters: 19340000 File Size: 77995057 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b4_ns LR: 0.128 Epochs: 700 Dropout: 0.5 Crop Pct: '0.922' Momentum: 0.9 Batch Size: 2048 Image Size: '380' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1467 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b4_ns-d6313a46.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 85.15% Top 5 Accuracy: 97.47%- Name: tf_efficientnet_b5_ns In Collection: Noisy Student Metadata: FLOPs: 13176501888 Parameters: 30390000 File Size: 122404944 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b5_ns LR: 0.128 Epochs: 350 Dropout: 0.5 Crop Pct: '0.934' Momentum: 0.9 Batch Size: 2048 Image Size: '456' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1477 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b5_ns-6f26d0cf.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 86.08% Top 5 Accuracy: 97.75%- Name: tf_efficientnet_b6_ns In Collection: Noisy Student Metadata: FLOPs: 24180518488 Parameters: 43040000 File Size: 173239537 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b6_ns LR: 0.128 Epochs: 350 Dropout: 0.5 Crop Pct: '0.942' Momentum: 0.9 Batch Size: 2048 Image Size: '528' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1487 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b6_ns-51548356.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 86.45% Top 5 Accuracy: 97.88%- Name: tf_efficientnet_b7_ns In Collection: Noisy Student Metadata: FLOPs: 48205304880 Parameters: 66349999 File Size: 266853140 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod ID: tf_efficientnet_b7_ns LR: 0.128 Epochs: 350 Dropout: 0.5 Crop Pct: '0.949' Momentum: 0.9 Batch Size: 2048 Image Size: '600' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1498 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b7_ns-1dbc32de.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 86.83% Top 5 Accuracy: 98.08%- Name: tf_efficientnet_l2_ns In Collection: Noisy Student Metadata: FLOPs: 611646113804 Parameters: 480310000 File Size: 1925950424 Architecture: - 1x1 Convolution - Average Pooling - Batch Normalization - Convolution - Dense Connections - Dropout - Inverted Residual Block - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - AutoAugment - FixRes - Label Smoothing - Noisy Student - RMSProp - RandAugment - Weight Decay Training Data: - ImageNet - JFT-300M Training Resources: Cloud TPU v3 Pod Training Time: 6 days ID: tf_efficientnet_l2_ns LR: 0.128 Epochs: 350 Dropout: 0.5 Crop Pct: '0.96' Momentum: 0.9 Batch Size: 2048 Image Size: '800' Weight Decay: 1.0e-05 Interpolation: bicubic RMSProp Decay: 0.9 Label Smoothing: 0.1 BatchNorm Momentum: 0.99 Stochastic Depth Survival: 0.8 Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1520 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_l2_ns-df73bb44.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 88.35% Top 5 Accuracy: 98.66%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# PNASNet
**Progressive Neural Architecture Search**, or **PNAS**, is a method for learning the structure of convolutional neural networks (CNNs). It uses a sequential model-based optimization (SMBO) strategy, where we search the space of cell structures, starting with simple (shallow) models and progressing to complex ones, pruning out unpromising structures as we go.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('pnasnet5large', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `pnasnet5large`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('pnasnet5large', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{liu2018progressive, title={Progressive Neural Architecture Search}, author={Chenxi Liu and Barret Zoph and Maxim Neumann and Jonathon Shlens and Wei Hua and Li-Jia Li and Li Fei-Fei and Alan Yuille and Jonathan Huang and Kevin Murphy}, year={2018}, eprint={1712.00559}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: PNASNet Paper: Title: Progressive Neural Architecture Search URL: https://paperswithcode.com/paper/progressive-neural-architecture-searchModels:- Name: pnasnet5large In Collection: PNASNet Metadata: FLOPs: 31458865950 Parameters: 86060000 File Size: 345153926 Architecture: - Average Pooling - Batch Normalization - Convolution - Depthwise Separable Convolution - Dropout - ReLU Tasks: - Image Classification Training Techniques: - Label Smoothing - RMSProp - Weight Decay Training Data: - ImageNet Training Resources: 100x NVIDIA P100 GPUs ID: pnasnet5large LR: 0.015 Dropout: 0.5 Crop Pct: '0.911' Momentum: 0.9 Batch Size: 1600 Image Size: '331' Interpolation: bicubic Label Smoothing: 0.1 Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/pnasnet.py#L343 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-cadene/pnasnet5large-bf079911.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 0.98% Top 5 Accuracy: 18.58%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321# Res2Net
**Res2Net** is an image model that employs a variation on bottleneck residual blocks, [Res2Net Blocks](https://paperswithcode.com/method/res2net-block). The motivation is to be able to represent features at multiple scales. This is achieved through a novel building block for CNNs that constructs hierarchical residual-like connections within one single residual block. This represents multi-scale features at a granular level and increases the range of receptive fields for each network layer.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('res2net101_26w_4s', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `res2net101_26w_4s`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('res2net101_26w_4s', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{Gao_2021, title={Res2Net: A New Multi-Scale Backbone Architecture}, volume={43}, ISSN={1939-3539}, url={http://dx.doi.org/10.1109/TPAMI.2019.2938758}, DOI={10.1109/tpami.2019.2938758}, number={2}, journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, publisher={Institute of Electrical and Electronics Engineers (IEEE)}, author={Gao, Shang-Hua and Cheng, Ming-Ming and Zhao, Kai and Zhang, Xin-Yu and Yang, Ming-Hsuan and Torr, Philip}, year={2021}, month={Feb}, pages={652–662}}```
<!--Type: model-indexCollections:- Name: Res2Net Paper: Title: 'Res2Net: A New Multi-scale Backbone Architecture' URL: https://paperswithcode.com/paper/res2net-a-new-multi-scale-backboneModels:- Name: res2net101_26w_4s In Collection: Res2Net Metadata: FLOPs: 10415881200 Parameters: 45210000 File Size: 181456059 Architecture: - Batch Normalization - Convolution - Global Average Pooling - ReLU - Res2Net Block Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 4x Titan Xp GPUs ID: res2net101_26w_4s LR: 0.1 Epochs: 100 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/res2net.py#L152 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-res2net/res2net101_26w_4s-02a759a1.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.19% Top 5 Accuracy: 94.43%- Name: res2net50_14w_8s In Collection: Res2Net Metadata: FLOPs: 5403546768 Parameters: 25060000 File Size: 100638543 Architecture: - Batch Normalization - Convolution - Global Average Pooling - ReLU - Res2Net Block Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 4x Titan Xp GPUs ID: res2net50_14w_8s LR: 0.1 Epochs: 100 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/res2net.py#L196 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-res2net/res2net50_14w_8s-6527dddc.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.14% Top 5 Accuracy: 93.86%- Name: res2net50_26w_4s In Collection: Res2Net Metadata: FLOPs: 5499974064 Parameters: 25700000 File Size: 103110087 Architecture: - Batch Normalization - Convolution - Global Average Pooling - ReLU - Res2Net Block Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 4x Titan Xp GPUs ID: res2net50_26w_4s LR: 0.1 Epochs: 100 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/res2net.py#L141 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-res2net/res2net50_26w_4s-06e79181.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.99% Top 5 Accuracy: 93.85%- Name: res2net50_26w_6s In Collection: Res2Net Metadata: FLOPs: 8130156528 Parameters: 37050000 File Size: 148603239 Architecture: - Batch Normalization - Convolution - Global Average Pooling - ReLU - Res2Net Block Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 4x Titan Xp GPUs ID: res2net50_26w_6s LR: 0.1 Epochs: 100 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/res2net.py#L163 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-res2net/res2net50_26w_6s-19041792.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.57% Top 5 Accuracy: 94.12%- Name: res2net50_26w_8s In Collection: Res2Net Metadata: FLOPs: 10760338992 Parameters: 48400000 File Size: 194085165 Architecture: - Batch Normalization - Convolution - Global Average Pooling - ReLU - Res2Net Block Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 4x Titan Xp GPUs ID: res2net50_26w_8s LR: 0.1 Epochs: 100 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/res2net.py#L174 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-res2net/res2net50_26w_8s-2c7c9f12.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.19% Top 5 Accuracy: 94.37%- Name: res2net50_48w_2s In Collection: Res2Net Metadata: FLOPs: 5375291520 Parameters: 25290000 File Size: 101421406 Architecture: - Batch Normalization - Convolution - Global Average Pooling - ReLU - Res2Net Block Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 4x Titan Xp GPUs ID: res2net50_48w_2s LR: 0.1 Epochs: 100 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/res2net.py#L185 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-res2net/res2net50_48w_2s-afed724a.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.53% Top 5 Accuracy: 93.56%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469# ResNeSt
A **ResNeSt** is a variant on a [ResNet](https://paperswithcode.com/method/resnet), which instead stacks [Split-Attention blocks](https://paperswithcode.com/method/split-attention). The cardinal group representations are then concatenated along the channel dimension: $V = \text{Concat}${$V^{1},V^{2},\cdots{V}^{K}$}. As in standard residual blocks, the final output $Y$ of otheur Split-Attention block is produced using a shortcut connection: $Y=V+X$, if the input and output feature-map share the same shape. For blocks with a stride, an appropriate transformation $\mathcal{T}$ is applied to the shortcut connection to align the output shapes: $Y=V+\mathcal{T}(X)$. For example, $\mathcal{T}$ can be strided convolution or combined convolution-with-pooling.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('resnest101e', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `resnest101e`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('resnest101e', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{zhang2020resnest, title={ResNeSt: Split-Attention Networks}, author={Hang Zhang and Chongruo Wu and Zhongyue Zhang and Yi Zhu and Haibin Lin and Zhi Zhang and Yue Sun and Tong He and Jonas Mueller and R. Manmatha and Mu Li and Alexander Smola}, year={2020}, eprint={2004.08955}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: ResNeSt Paper: Title: 'ResNeSt: Split-Attention Networks' URL: https://paperswithcode.com/paper/resnest-split-attention-networksModels:- Name: resnest101e In Collection: ResNeSt Metadata: FLOPs: 17423183648 Parameters: 48280000 File Size: 193782911 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest101e LR: 0.1 Epochs: 270 Layers: 101 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 4096 Image Size: '256' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L182 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-resnest/resnest101-22405ba7.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 82.88% Top 5 Accuracy: 96.31%- Name: resnest14d In Collection: ResNeSt Metadata: FLOPs: 3548594464 Parameters: 10610000 File Size: 42562639 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest14d LR: 0.1 Epochs: 270 Layers: 14 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 8192 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L148 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/gluon_resnest14-9c8fe254.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 75.51% Top 5 Accuracy: 92.52%- Name: resnest200e In Collection: ResNeSt Metadata: FLOPs: 45954387872 Parameters: 70200000 File Size: 193782911 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest200e LR: 0.1 Epochs: 270 Layers: 200 Dropout: 0.2 Crop Pct: '0.909' Momentum: 0.9 Batch Size: 2048 Image Size: '320' Weight Decay: 0.0001 Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L194 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-resnest/resnest101-22405ba7.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 83.85% Top 5 Accuracy: 96.89%- Name: resnest269e In Collection: ResNeSt Metadata: FLOPs: 100830307104 Parameters: 110930000 File Size: 445402691 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest269e LR: 0.1 Epochs: 270 Layers: 269 Dropout: 0.2 Crop Pct: '0.928' Momentum: 0.9 Batch Size: 2048 Image Size: '416' Weight Decay: 0.0001 Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L206 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-resnest/resnest269-0cc87c48.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 84.53% Top 5 Accuracy: 96.99%- Name: resnest26d In Collection: ResNeSt Metadata: FLOPs: 4678918720 Parameters: 17070000 File Size: 68470242 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest26d LR: 0.1 Epochs: 270 Layers: 26 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 8192 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L159 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/gluon_resnest26-50eb607c.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.48% Top 5 Accuracy: 94.3%- Name: resnest50d In Collection: ResNeSt Metadata: FLOPs: 6937106336 Parameters: 27480000 File Size: 110273258 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest50d LR: 0.1 Epochs: 270 Layers: 50 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 8192 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L170 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-resnest/resnest50-528c19ca.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.96% Top 5 Accuracy: 95.38%- Name: resnest50d_1s4x24d In Collection: ResNeSt Metadata: FLOPs: 5686764544 Parameters: 25680000 File Size: 103045531 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest50d_1s4x24d LR: 0.1 Epochs: 270 Layers: 50 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 8192 Image Size: '224' Weight Decay: 0.0001 Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L229 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-resnest/resnest50_fast_1s4x24d-d4a4f76f.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.0% Top 5 Accuracy: 95.33%- Name: resnest50d_4s2x40d In Collection: ResNeSt Metadata: FLOPs: 5657064720 Parameters: 30420000 File Size: 122133282 Architecture: - 1x1 Convolution - Convolution - Dense Connections - Global Average Pooling - Max Pooling - ReLU - Residual Connection - Softmax - Split Attention Tasks: - Image Classification Training Techniques: - AutoAugment - DropBlock - Label Smoothing - Mixup - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 64x NVIDIA V100 GPUs ID: resnest50d_4s2x40d LR: 0.1 Epochs: 270 Layers: 50 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 8192 Image Size: '224' Weight Decay: 0.0001 Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnest.py#L218 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-resnest/resnest50_fast_4s2x40d-41d14ed0.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.11% Top 5 Accuracy: 95.55%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324# ResNet-D
**ResNet-D** is a modification on the [ResNet](https://paperswithcode.com/method/resnet) architecture that utilises an [average pooling](https://paperswithcode.com/method/average-pooling) tweak for downsampling. The motivation is that in the unmodified ResNet, the [1×1 convolution](https://paperswithcode.com/method/1x1-convolution) for the downsampling block ignores 3/4 of input feature maps, so this is modified so no information will be ignored
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('resnet101d', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `resnet101d`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('resnet101d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{he2018bag, title={Bag of Tricks for Image Classification with Convolutional Neural Networks}, author={Tong He and Zhi Zhang and Hang Zhang and Zhongyue Zhang and Junyuan Xie and Mu Li}, year={2018}, eprint={1812.01187}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: ResNet-D Paper: Title: Bag of Tricks for Image Classification with Convolutional Neural Networks URL: https://paperswithcode.com/paper/bag-of-tricks-for-image-classification-withModels:- Name: resnet101d In Collection: ResNet-D Metadata: FLOPs: 13805639680 Parameters: 44570000 File Size: 178791263 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet101d Crop Pct: '0.94' Image Size: '256' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L716 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet101d_ra2-2803ffab.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 82.31% Top 5 Accuracy: 96.06%- Name: resnet152d In Collection: ResNet-D Metadata: FLOPs: 20155275264 Parameters: 60210000 File Size: 241596837 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet152d Crop Pct: '0.94' Image Size: '256' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L724 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet152d_ra2-5cac0439.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 83.13% Top 5 Accuracy: 96.35%- Name: resnet18d In Collection: ResNet-D Metadata: FLOPs: 2645205760 Parameters: 11710000 File Size: 46893231 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet18d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L649 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet18d_ra2-48a79e06.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 72.27% Top 5 Accuracy: 90.69%- Name: resnet200d In Collection: ResNet-D Metadata: FLOPs: 26034378752 Parameters: 64690000 File Size: 259662933 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet200d Crop Pct: '0.94' Image Size: '256' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L749 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet200d_ra2-bdba9bf9.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 83.24% Top 5 Accuracy: 96.49%- Name: resnet26d In Collection: ResNet-D Metadata: FLOPs: 3335276032 Parameters: 16010000 File Size: 64209122 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet26d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L683 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet26d-69e92c46.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 76.69% Top 5 Accuracy: 93.15%- Name: resnet34d In Collection: ResNet-D Metadata: FLOPs: 5026601728 Parameters: 21820000 File Size: 87369807 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet34d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L666 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet34d_ra2-f8dcfcaf.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.11% Top 5 Accuracy: 93.38%- Name: resnet50d In Collection: ResNet-D Metadata: FLOPs: 5591002624 Parameters: 25580000 File Size: 102567109 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet50d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L699 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet50d_ra2-464e36ba.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.55% Top 5 Accuracy: 95.16%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439# ResNet
**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual blocks](https://paperswithcode.com/method/residual-block) ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('resnet18', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `resnet18`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('resnet18', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{DBLP:journals/corr/HeZRS15, author = {Kaiming He and Xiangyu Zhang and Shaoqing Ren and Jian Sun}, title = {Deep Residual Learning for Image Recognition}, journal = {CoRR}, volume = {abs/1512.03385}, year = {2015}, url = {http://arxiv.org/abs/1512.03385}, archivePrefix = {arXiv}, eprint = {1512.03385}, timestamp = {Wed, 17 Apr 2019 17:23:45 +0200}, biburl = {https://dblp.org/rec/journals/corr/HeZRS15.bib}, bibsource = {dblp computer science bibliography, https://dblp.org}}```
<!--Type: model-indexCollections:- Name: ResNet Paper: Title: Deep Residual Learning for Image Recognition URL: https://paperswithcode.com/paper/deep-residual-learning-for-image-recognitionModels:- Name: resnet18 In Collection: ResNet Metadata: FLOPs: 2337073152 Parameters: 11690000 File Size: 46827520 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet18 Crop Pct: '0.875' Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L641 Weights: https://download.pytorch.org/models/resnet18-5c106cde.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 69.74% Top 5 Accuracy: 89.09%- Name: resnet26 In Collection: ResNet Metadata: FLOPs: 3026804736 Parameters: 16000000 File Size: 64129972 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet26 Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L675 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet26-9aa10e23.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 75.29% Top 5 Accuracy: 92.57%- Name: resnet34 In Collection: ResNet Metadata: FLOPs: 4718469120 Parameters: 21800000 File Size: 87290831 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet34 Crop Pct: '0.875' Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L658 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet34-43635321.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 75.11% Top 5 Accuracy: 92.28%- Name: resnet50 In Collection: ResNet Metadata: FLOPs: 5282531328 Parameters: 25560000 File Size: 102488165 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnet50 Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L691 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet50_ram-a26f946b.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.04% Top 5 Accuracy: 94.39%- Name: resnetblur50 In Collection: ResNet Metadata: FLOPs: 6621606912 Parameters: 25560000 File Size: 102488165 Architecture: - 1x1 Convolution - Batch Normalization - Blur Pooling - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnetblur50 Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/resnet.py#L1160 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnetblur50-84f4748f.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.29% Top 5 Accuracy: 94.64%- Name: tv_resnet101 In Collection: ResNet Metadata: FLOPs: 10068547584 Parameters: 44550000 File Size: 178728960 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet ID: tv_resnet101 LR: 0.1 Epochs: 90 Crop Pct: '0.875' LR Gamma: 0.1 Momentum: 0.9 Batch Size: 32 Image Size: '224' LR Step Size: 30 Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L761 Weights: https://download.pytorch.org/models/resnet101-5d3b4d8f.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.37% Top 5 Accuracy: 93.56%- Name: tv_resnet152 In Collection: ResNet Metadata: FLOPs: 14857660416 Parameters: 60190000 File Size: 241530880 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet ID: tv_resnet152 LR: 0.1 Epochs: 90 Crop Pct: '0.875' LR Gamma: 0.1 Momentum: 0.9 Batch Size: 32 Image Size: '224' LR Step Size: 30 Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L769 Weights: https://download.pytorch.org/models/resnet152-b121ed2d.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.32% Top 5 Accuracy: 94.05%- Name: tv_resnet34 In Collection: ResNet Metadata: FLOPs: 4718469120 Parameters: 21800000 File Size: 87306240 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet ID: tv_resnet34 LR: 0.1 Epochs: 90 Crop Pct: '0.875' LR Gamma: 0.1 Momentum: 0.9 Batch Size: 32 Image Size: '224' LR Step Size: 30 Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L745 Weights: https://download.pytorch.org/models/resnet34-333f7ec4.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 73.3% Top 5 Accuracy: 91.42%- Name: tv_resnet50 In Collection: ResNet Metadata: FLOPs: 5282531328 Parameters: 25560000 File Size: 102502400 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet ID: tv_resnet50 LR: 0.1 Epochs: 90 Crop Pct: '0.875' LR Gamma: 0.1 Momentum: 0.9 Batch Size: 32 Image Size: '224' LR Step Size: 30 Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L753 Weights: https://download.pytorch.org/models/resnet50-19c8e357.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 76.16% Top 5 Accuracy: 92.88%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244# ResNeXt
A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('resnext101_32x8d', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `resnext101_32x8d`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('resnext101_32x8d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{DBLP:journals/corr/XieGDTH16, author = {Saining Xie and Ross B. Girshick and Piotr Doll{\'{a}}r and Zhuowen Tu and Kaiming He}, title = {Aggregated Residual Transformations for Deep Neural Networks}, journal = {CoRR}, volume = {abs/1611.05431}, year = {2016}, url = {http://arxiv.org/abs/1611.05431}, archivePrefix = {arXiv}, eprint = {1611.05431}, timestamp = {Mon, 13 Aug 2018 16:45:58 +0200}, biburl = {https://dblp.org/rec/journals/corr/XieGDTH16.bib}, bibsource = {dblp computer science bibliography, https://dblp.org}}```
<!--Type: model-indexCollections:- Name: ResNeXt Paper: Title: Aggregated Residual Transformations for Deep Neural Networks URL: https://paperswithcode.com/paper/aggregated-residual-transformations-for-deepModels:- Name: resnext101_32x8d In Collection: ResNeXt Metadata: FLOPs: 21180417024 Parameters: 88790000 File Size: 356082095 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnext101_32x8d Crop Pct: '0.875' Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnet.py#L877 Weights: https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.3% Top 5 Accuracy: 94.53%- Name: resnext50_32x4d In Collection: ResNeXt Metadata: FLOPs: 5472648192 Parameters: 25030000 File Size: 100435887 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnext50_32x4d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnet.py#L851 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnext50_32x4d_ra-d733960d.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.79% Top 5 Accuracy: 94.61%- Name: resnext50d_32x4d In Collection: ResNeXt Metadata: FLOPs: 5781119488 Parameters: 25050000 File Size: 100515304 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Data: - ImageNet ID: resnext50d_32x4d Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/resnet.py#L869 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnext50d_32x4d-103e99f8.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.67% Top 5 Accuracy: 94.87%- Name: tv_resnext50_32x4d In Collection: ResNeXt Metadata: FLOPs: 5472648192 Parameters: 25030000 File Size: 100441675 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet ID: tv_resnext50_32x4d LR: 0.1 Epochs: 90 Crop Pct: '0.875' LR Gamma: 0.1 Momentum: 0.9 Batch Size: 32 Image Size: '224' LR Step Size: 30 Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L842 Weights: https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.61% Top 5 Accuracy: 93.68%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258# RexNet
**Rank Expansion Networks** (ReXNets) follow a set of new design principles for designing bottlenecks in image classification models. Authors refine each layer by 1) expanding the input channel size of the convolution layer and 2) replacing the [ReLU6s](https://www.paperswithcode.com/method/relu6).
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('rexnet_100', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `rexnet_100`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('rexnet_100', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{han2020rexnet, title={ReXNet: Diminishing Representational Bottleneck on Convolutional Neural Network}, author={Dongyoon Han and Sangdoo Yun and Byeongho Heo and YoungJoon Yoo}, year={2020}, eprint={2007.00992}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: RexNet Paper: Title: 'ReXNet: Diminishing Representational Bottleneck on Convolutional Neural Network' URL: https://paperswithcode.com/paper/rexnet-diminishing-representationalModels:- Name: rexnet_100 In Collection: RexNet Metadata: FLOPs: 509989377 Parameters: 4800000 File Size: 19417552 Architecture: - Batch Normalization - Convolution - Dropout - ReLU6 - Residual Connection Tasks: - Image Classification Training Techniques: - Label Smoothing - Linear Warmup With Cosine Annealing - Nesterov Accelerated Gradient - Weight Decay Training Data: - ImageNet Training Resources: 4x NVIDIA V100 GPUs ID: rexnet_100 LR: 0.5 Epochs: 400 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 512 Image Size: '224' Weight Decay: 1.0e-05 Interpolation: bicubic Label Smoothing: 0.1 Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/rexnet.py#L212 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-rexnet/rexnetv1_100-1b4dddf4.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.86% Top 5 Accuracy: 93.88%- Name: rexnet_130 In Collection: RexNet Metadata: FLOPs: 848364461 Parameters: 7560000 File Size: 30508197 Architecture: - Batch Normalization - Convolution - Dropout - ReLU6 - Residual Connection Tasks: - Image Classification Training Techniques: - Label Smoothing - Linear Warmup With Cosine Annealing - Nesterov Accelerated Gradient - Weight Decay Training Data: - ImageNet Training Resources: 4x NVIDIA V100 GPUs ID: rexnet_130 LR: 0.5 Epochs: 400 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 512 Image Size: '224' Weight Decay: 1.0e-05 Interpolation: bicubic Label Smoothing: 0.1 Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/rexnet.py#L218 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-rexnet/rexnetv1_130-590d768e.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.49% Top 5 Accuracy: 94.67%- Name: rexnet_150 In Collection: RexNet Metadata: FLOPs: 1122374469 Parameters: 9730000 File Size: 39227315 Architecture: - Batch Normalization - Convolution - Dropout - ReLU6 - Residual Connection Tasks: - Image Classification Training Techniques: - Label Smoothing - Linear Warmup With Cosine Annealing - Nesterov Accelerated Gradient - Weight Decay Training Data: - ImageNet Training Resources: 4x NVIDIA V100 GPUs ID: rexnet_150 LR: 0.5 Epochs: 400 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 512 Image Size: '224' Weight Decay: 1.0e-05 Interpolation: bicubic Label Smoothing: 0.1 Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/rexnet.py#L224 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-rexnet/rexnetv1_150-bd1a6aa8.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.31% Top 5 Accuracy: 95.16%- Name: rexnet_200 In Collection: RexNet Metadata: FLOPs: 1960224938 Parameters: 16370000 File Size: 65862221 Architecture: - Batch Normalization - Convolution - Dropout - ReLU6 - Residual Connection Tasks: - Image Classification Training Techniques: - Label Smoothing - Linear Warmup With Cosine Annealing - Nesterov Accelerated Gradient - Weight Decay Training Data: - ImageNet Training Resources: 4x NVIDIA V100 GPUs ID: rexnet_200 LR: 0.5 Epochs: 400 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 512 Image Size: '224' Weight Decay: 1.0e-05 Interpolation: bicubic Label Smoothing: 0.1 Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/rexnet.py#L230 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-rexnet/rexnetv1_200-8c0b7f2d.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.63% Top 5 Accuracy: 95.67%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183# SE-ResNet
**SE ResNet** is a variant of a [ResNet](https://www.paperswithcode.com/method/resnet) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('seresnet152d', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `seresnet152d`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('seresnet152d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{hu2019squeezeandexcitation, title={Squeeze-and-Excitation Networks}, author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, year={2019}, eprint={1709.01507}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: SE ResNet Paper: Title: Squeeze-and-Excitation Networks URL: https://paperswithcode.com/paper/squeeze-and-excitation-networksModels:- Name: seresnet152d In Collection: SE ResNet Metadata: FLOPs: 20161904304 Parameters: 66840000 File Size: 268144497 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: seresnet152d LR: 0.6 Epochs: 100 Layers: 152 Dropout: 0.2 Crop Pct: '0.94' Momentum: 0.9 Batch Size: 1024 Image Size: '256' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/resnet.py#L1206 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet152d_ra2-04464dd2.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 83.74% Top 5 Accuracy: 96.77%- Name: seresnet50 In Collection: SE ResNet Metadata: FLOPs: 5285062320 Parameters: 28090000 File Size: 112621903 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: seresnet50 LR: 0.6 Epochs: 100 Layers: 50 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/resnet.py#L1180 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnet50_ra_224-8efdb4bb.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.26% Top 5 Accuracy: 95.07%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# SelecSLS
**SelecSLS** uses novel selective long and short range skip connections to improve the information flow allowing for a drastically faster network without compromising accuracy.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('selecsls42b', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `selecsls42b`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('selecsls42b', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{Mehta_2020, title={XNect}, volume={39}, ISSN={1557-7368}, url={http://dx.doi.org/10.1145/3386569.3392410}, DOI={10.1145/3386569.3392410}, number={4}, journal={ACM Transactions on Graphics}, publisher={Association for Computing Machinery (ACM)}, author={Mehta, Dushyant and Sotnychenko, Oleksandr and Mueller, Franziska and Xu, Weipeng and Elgharib, Mohamed and Fua, Pascal and Seidel, Hans-Peter and Rhodin, Helge and Pons-Moll, Gerard and Theobalt, Christian}, year={2020}, month={Jul}}```
<!--Type: model-indexCollections:- Name: SelecSLS Paper: Title: 'XNect: Real-time Multi-Person 3D Motion Capture with a Single RGB Camera' URL: https://paperswithcode.com/paper/xnect-real-time-multi-person-3d-human-poseModels:- Name: selecsls42b In Collection: SelecSLS Metadata: FLOPs: 3824022528 Parameters: 32460000 File Size: 129948954 Architecture: - Batch Normalization - Convolution - Dense Connections - Dropout - Global Average Pooling - ReLU - SelecSLS Block Tasks: - Image Classification Training Techniques: - Cosine Annealing - Random Erasing Training Data: - ImageNet ID: selecsls42b Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/selecsls.py#L335 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-selecsls/selecsls42b-8af30141.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.18% Top 5 Accuracy: 93.39%- Name: selecsls60 In Collection: SelecSLS Metadata: FLOPs: 4610472600 Parameters: 30670000 File Size: 122839714 Architecture: - Batch Normalization - Convolution - Dense Connections - Dropout - Global Average Pooling - ReLU - SelecSLS Block Tasks: - Image Classification Training Techniques: - Cosine Annealing - Random Erasing Training Data: - ImageNet ID: selecsls60 Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/selecsls.py#L342 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-selecsls/selecsls60-bbf87526.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.99% Top 5 Accuracy: 93.83%- Name: selecsls60b In Collection: SelecSLS Metadata: FLOPs: 4657653144 Parameters: 32770000 File Size: 131252898 Architecture: - Batch Normalization - Convolution - Dense Connections - Dropout - Global Average Pooling - ReLU - SelecSLS Block Tasks: - Image Classification Training Techniques: - Cosine Annealing - Random Erasing Training Data: - ImageNet ID: selecsls60b Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/b9843f954b0457af2db4f9dea41a8538f51f5d78/timm/models/selecsls.py#L349 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-selecsls/selecsls60b-94e619b5.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.41% Top 5 Accuracy: 94.18%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228# SE-ResNeXt
**SE ResNeXt** is a variant of a [ResNext](https://www.paperswithcode.com/method/resneXt) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('seresnext26d_32x4d', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `seresnext26d_32x4d`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('seresnext26d_32x4d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{hu2019squeezeandexcitation, title={Squeeze-and-Excitation Networks}, author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, year={2019}, eprint={1709.01507}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: SEResNeXt Paper: Title: Squeeze-and-Excitation Networks URL: https://paperswithcode.com/paper/squeeze-and-excitation-networksModels:- Name: seresnext26d_32x4d In Collection: SEResNeXt Metadata: FLOPs: 3507053024 Parameters: 16810000 File Size: 67425193 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: seresnext26d_32x4d LR: 0.6 Epochs: 100 Layers: 26 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/resnet.py#L1234 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnext26d_32x4d-80fa48a3.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.59% Top 5 Accuracy: 93.61%- Name: seresnext26t_32x4d In Collection: SEResNeXt Metadata: FLOPs: 3466436448 Parameters: 16820000 File Size: 67414838 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: seresnext26t_32x4d LR: 0.6 Epochs: 100 Layers: 26 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/resnet.py#L1246 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnext26tn_32x4d-569cb627.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.99% Top 5 Accuracy: 93.73%- Name: seresnext50_32x4d In Collection: SEResNeXt Metadata: FLOPs: 5475179184 Parameters: 27560000 File Size: 110569859 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax - Squeeze-and-Excitation Block Tasks: - Image Classification Training Techniques: - Label Smoothing - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x NVIDIA Titan X GPUs ID: seresnext50_32x4d LR: 0.6 Epochs: 100 Layers: 50 Dropout: 0.2 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 1024 Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/resnet.py#L1267 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/seresnext50_32x4d_racm-a304a460.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.27% Top 5 Accuracy: 95.62%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173# SK-ResNet
**SK ResNet** is a variant of a [ResNet](https://www.paperswithcode.com/method/resnet) that employs a [Selective Kernel](https://paperswithcode.com/method/selective-kernel) unit. In general, all the large kernel convolutions in the original bottleneck blocks in ResNet are replaced by the proposed [SK convolutions](https://paperswithcode.com/method/selective-kernel-convolution), enabling the network to choose appropriate receptive field sizes in an adaptive manner.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('skresnet18', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `skresnet18`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('skresnet18', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{li2019selective, title={Selective Kernel Networks}, author={Xiang Li and Wenhai Wang and Xiaolin Hu and Jian Yang}, year={2019}, eprint={1903.06586}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: SKResNet Paper: Title: Selective Kernel Networks URL: https://paperswithcode.com/paper/selective-kernel-networksModels:- Name: skresnet18 In Collection: SKResNet Metadata: FLOPs: 2333467136 Parameters: 11960000 File Size: 47923238 Architecture: - Convolution - Dense Connections - Global Average Pooling - Max Pooling - Residual Connection - Selective Kernel - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x GPUs ID: skresnet18 LR: 0.1 Epochs: 100 Layers: 18 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 4.0e-05 Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/sknet.py#L148 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/skresnet18_ra-4eec2804.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 73.03% Top 5 Accuracy: 91.17%- Name: skresnet34 In Collection: SKResNet Metadata: FLOPs: 4711849952 Parameters: 22280000 File Size: 89299314 Architecture: - Convolution - Dense Connections - Global Average Pooling - Max Pooling - Residual Connection - Selective Kernel - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet Training Resources: 8x GPUs ID: skresnet34 LR: 0.1 Epochs: 100 Layers: 34 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 4.0e-05 Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/sknet.py#L165 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/skresnet34_ra-bdc0ccde.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 76.93% Top 5 Accuracy: 93.32%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# SK-ResNeXt
**SK ResNeXt** is a variant of a [ResNeXt](https://www.paperswithcode.com/method/resnext) that employs a [Selective Kernel](https://paperswithcode.com/method/selective-kernel) unit. In general, all the large kernel convolutions in the original bottleneck blocks in ResNext are replaced by the proposed [SK convolutions](https://paperswithcode.com/method/selective-kernel-convolution), enabling the network to choose appropriate receptive field sizes in an adaptive manner.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('skresnext50_32x4d', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `skresnext50_32x4d`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('skresnext50_32x4d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{li2019selective, title={Selective Kernel Networks}, author={Xiang Li and Wenhai Wang and Xiaolin Hu and Jian Yang}, year={2019}, eprint={1903.06586}, archivePrefix={arXiv}, primaryClass={cs.CV}}```
<!--Type: model-indexCollections:- Name: SKResNeXt Paper: Title: Selective Kernel Networks URL: https://paperswithcode.com/paper/selective-kernel-networksModels:- Name: skresnext50_32x4d In Collection: SKResNeXt Metadata: FLOPs: 5739845824 Parameters: 27480000 File Size: 110340975 Architecture: - Convolution - Dense Connections - Global Average Pooling - Grouped Convolution - Max Pooling - Residual Connection - Selective Kernel - Softmax Tasks: - Image Classification Training Data: - ImageNet Training Resources: 8x GPUs ID: skresnext50_32x4d LR: 0.1 Epochs: 100 Layers: 50 Crop Pct: '0.875' Momentum: 0.9 Batch Size: 256 Image Size: '224' Weight Decay: 0.0001 Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/a7f95818e44b281137503bcf4b3e3e94d8ffa52f/timm/models/sknet.py#L210 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/skresnext50_ra-f40e40bf.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.15% Top 5 Accuracy: 94.64%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# SPNASNet
**Single-Path NAS** is a novel differentiable NAS method for designing hardware-efficient ConvNets in less than 4 hours.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('spnasnet_100', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `spnasnet_100`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('spnasnet_100', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@misc{stamoulis2019singlepath, title={Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours}, author={Dimitrios Stamoulis and Ruizhou Ding and Di Wang and Dimitrios Lymberopoulos and Bodhi Priyantha and Jie Liu and Diana Marculescu}, year={2019}, eprint={1904.02877}, archivePrefix={arXiv}, primaryClass={cs.LG}}```
<!--Type: model-indexCollections:- Name: SPNASNet Paper: Title: 'Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours' URL: https://paperswithcode.com/paper/single-path-nas-designing-hardware-efficientModels:- Name: spnasnet_100 In Collection: SPNASNet Metadata: FLOPs: 442385600 Parameters: 4420000 File Size: 17902337 Architecture: - Average Pooling - Batch Normalization - Convolution - Depthwise Separable Convolution - Dropout - ReLU Tasks: - Image Classification Training Data: - ImageNet ID: spnasnet_100 Crop Pct: '0.875' Image Size: '224' Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L995 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/spnasnet_100-048bc3f4.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 74.08% Top 5 Accuracy: 91.82%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192# SSL ResNet
**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual blocks](https://paperswithcode.com/method/residual-block) ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks.
The model in this collection utilises semi-supervised learning to improve the performance of the model. The approach brings important gains to standard architectures for image, video and fine-grained classification.
Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('ssl_resnet18', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `ssl_resnet18`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('ssl_resnet18', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{DBLP:journals/corr/abs-1905-00546, author = {I. Zeki Yalniz and Herv{\'{e}} J{\'{e}}gou and Kan Chen and Manohar Paluri and Dhruv Mahajan}, title = {Billion-scale semi-supervised learning for image classification}, journal = {CoRR}, volume = {abs/1905.00546}, year = {2019}, url = {http://arxiv.org/abs/1905.00546}, archivePrefix = {arXiv}, eprint = {1905.00546}, timestamp = {Mon, 28 Sep 2020 08:19:37 +0200}, biburl = {https://dblp.org/rec/journals/corr/abs-1905-00546.bib}, bibsource = {dblp computer science bibliography, https://dblp.org}}```
<!--Type: model-indexCollections:- Name: SSL ResNet Paper: Title: Billion-scale semi-supervised learning for image classification URL: https://paperswithcode.com/paper/billion-scale-semi-supervised-learning-forModels:- Name: ssl_resnet18 In Collection: SSL ResNet Metadata: FLOPs: 2337073152 Parameters: 11690000 File Size: 46811375 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet - YFCC-100M Training Resources: 64x GPUs ID: ssl_resnet18 LR: 0.0015 Epochs: 30 Layers: 18 Crop Pct: '0.875' Batch Size: 1536 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L894 Weights: https://dl.fbaipublicfiles.com/semiweaksupervision/model_files/semi_supervised_resnet18-d92f0530.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 72.62% Top 5 Accuracy: 91.42%- Name: ssl_resnet50 In Collection: SSL ResNet Metadata: FLOPs: 5282531328 Parameters: 25560000 File Size: 102480594 Architecture: - 1x1 Convolution - Batch Normalization - Bottleneck Residual Block - Convolution - Global Average Pooling - Max Pooling - ReLU - Residual Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet - YFCC-100M Training Resources: 64x GPUs ID: ssl_resnet50 LR: 0.0015 Epochs: 30 Layers: 50 Crop Pct: '0.875' Batch Size: 1536 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L904 Weights: https://dl.fbaipublicfiles.com/semiweaksupervision/model_files/semi_supervised_resnet50-08389792.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.24% Top 5 Accuracy: 94.83%-->123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278# SSL ResNeXT
A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width.
The model in this collection utilises semi-supervised learning to improve the performance of the model. The approach brings important gains to standard architectures for image, video and fine-grained classification.
Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only.
## How do I use this model on an image?To load a pretrained model:
```pythonimport timmmodel = timm.create_model('ssl_resnext101_32x16d', pretrained=True)model.eval()```
To load and preprocess the image:```python import urllibfrom PIL import Imagefrom timm.data import resolve_data_configfrom timm.data.transforms_factory import create_transform
config = resolve_data_config({}, model=model)transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")urllib.request.urlretrieve(url, filename)img = Image.open(filename).convert('RGB')tensor = transform(img).unsqueeze(0) # transform and add batch dimension```
To get the model predictions:```pythonimport torchwith torch.no_grad(): out = model(tensor)probabilities = torch.nn.functional.softmax(out[0], dim=0)print(probabilities.shape)# prints: torch.Size([1000])```
To get the top-5 predictions class names:```python# Get imagenet class mappingsurl, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")urllib.request.urlretrieve(url, filename) with open("imagenet_classes.txt", "r") as f: categories = [s.strip() for s in f.readlines()]
# Print top categories per imagetop5_prob, top5_catid = torch.topk(probabilities, 5)for i in range(top5_prob.size(0)): print(categories[top5_catid[i]], top5_prob[i].item())# prints class names and probabilities like:# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)]```
Replace the model name with the variant you want to use, e.g. `ssl_resnext101_32x16d`. You can find the IDs in the model summaries at the top of this page.
To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use.
## How do I finetune this model?You can finetune any of the pre-trained models just by changing the classifier (the last layer).```pythonmodel = timm.create_model('ssl_resnext101_32x16d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)```To finetune on your own dataset, you have to write a training loop or adapt [timm's trainingscript](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset.
## How do I train this model?
You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh.
## Citation
```BibTeX@article{DBLP:journals/corr/abs-1905-00546, author = {I. Zeki Yalniz and Herv{\'{e}} J{\'{e}}gou and Kan Chen and Manohar Paluri and Dhruv Mahajan}, title = {Billion-scale semi-supervised learning for image classification}, journal = {CoRR}, volume = {abs/1905.00546}, year = {2019}, url = {http://arxiv.org/abs/1905.00546}, archivePrefix = {arXiv}, eprint = {1905.00546}, timestamp = {Mon, 28 Sep 2020 08:19:37 +0200}, biburl = {https://dblp.org/rec/journals/corr/abs-1905-00546.bib}, bibsource = {dblp computer science bibliography, https://dblp.org}}```
<!--Type: model-indexCollections:- Name: SSL ResNext Paper: Title: Billion-scale semi-supervised learning for image classification URL: https://paperswithcode.com/paper/billion-scale-semi-supervised-learning-forModels:- Name: ssl_resnext101_32x16d In Collection: SSL ResNext Metadata: FLOPs: 46623691776 Parameters: 194030000 File Size: 777518664 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet - YFCC-100M Training Resources: 64x GPUs ID: ssl_resnext101_32x16d LR: 0.0015 Epochs: 30 Layers: 101 Crop Pct: '0.875' Batch Size: 1536 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L944 Weights: https://dl.fbaipublicfiles.com/semiweaksupervision/model_files/semi_supervised_resnext101_32x16-15fffa57.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.84% Top 5 Accuracy: 96.09%- Name: ssl_resnext101_32x4d In Collection: SSL ResNext Metadata: FLOPs: 10298145792 Parameters: 44180000 File Size: 177341913 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet - YFCC-100M Training Resources: 64x GPUs ID: ssl_resnext101_32x4d LR: 0.0015 Epochs: 30 Layers: 101 Crop Pct: '0.875' Batch Size: 1536 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L924 Weights: https://dl.fbaipublicfiles.com/semiweaksupervision/model_files/semi_supervised_resnext101_32x4-dc43570a.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.91% Top 5 Accuracy: 95.73%- Name: ssl_resnext101_32x8d In Collection: SSL ResNext Metadata: FLOPs: 21180417024 Parameters: 88790000 File Size: 356056638 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet - YFCC-100M Training Resources: 64x GPUs ID: ssl_resnext101_32x8d LR: 0.0015 Epochs: 30 Layers: 101 Crop Pct: '0.875' Batch Size: 1536 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L934 Weights: https://dl.fbaipublicfiles.com/semiweaksupervision/model_files/semi_supervised_resnext101_32x8-2cfe2f8b.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 81.61% Top 5 Accuracy: 96.04%- Name: ssl_resnext50_32x4d In Collection: SSL ResNext Metadata: FLOPs: 5472648192 Parameters: 25030000 File Size: 100428550 Architecture: - 1x1 Convolution - Batch Normalization - Convolution - Global Average Pooling - Grouped Convolution - Max Pooling - ReLU - ResNeXt Block - Residual Connection - Softmax Tasks: - Image Classification Training Techniques: - SGD with Momentum - Weight Decay Training Data: - ImageNet - YFCC-100M Training Resources: 64x GPUs ID: ssl_resnext50_32x4d LR: 0.0015 Epochs: 30 Layers: 50 Crop Pct: '0.875' Batch Size: 1536 Image Size: '224' Weight Decay: 0.0001 Interpolation: bilinear Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/resnet.py#L914 Weights: https://dl.fbaipublicfiles.com/semiweaksupervision/model_files/semi_supervised_resnext50_32x4-ddb3e555.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.3% Top 5 Accuracy: 95.41%-->testbed/huggingface__datasets/.gitignoreAdded+67
testbed/huggingface__datasets/setup.cfgAdded+10
testbed/huggingface__huggingface_hub/.github/workflows/python-release.ymlAdded+33
testbed/huggingface__huggingface_hub/MakefileAdded+18
testbed/huggingface__pytorch-image-models/.gitattributesAdded+1
testbed/huggingface__pytorch-image-models/.github/FUNDING.ymlAdded+2
testbed/huggingface__pytorch-image-models/.github/ISSUE_TEMPLATE/bug_report.mdAdded+32
testbed/huggingface__pytorch-image-models/.github/workflows/tests.ymlAdded+51
testbed/huggingface__pytorch-image-models/.gitignoreAdded+108
testbed/huggingface__pytorch-image-models/LICENSEAdded+201
testbed/huggingface__pytorch-image-models/MANIFEST.inAdded+2
testbed/huggingface__pytorch-image-models/README.mdAdded+423
testbed/huggingface__pytorch-image-models/avg_checkpoints.pyAdded+117
testbed/huggingface__pytorch-image-models/benchmark.pyAdded+481
testbed/huggingface__pytorch-image-models/clean_checkpoint.pyAdded+82
testbed/huggingface__pytorch-image-models/convert/convert_nest_flax.pyAdded+109
testbed/huggingface__pytorch-image-models/distributed_train.shAdded+5
testbed/huggingface__pytorch-image-models/docs/archived_changes.mdAdded+205
testbed/huggingface__pytorch-image-models/docs/changes.mdAdded+130
testbed/huggingface__pytorch-image-models/docs/feature_extraction.mdAdded+173
testbed/huggingface__pytorch-image-models/docs/index.mdAdded+80
testbed/huggingface__pytorch-image-models/docs/models.mdAdded+171
testbed/huggingface__pytorch-image-models/docs/models/.templates/models/advprop.mdAdded+457
testbed/huggingface__pytorch-image-models/docs/models/.templates/models/big-transfer.mdAdded+295
testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-darknet.mdAdded+81
testbed/huggingface__pytorch-image-models/docs/models/.templates/models/dpn.mdAdded+256
testbed/huggingface__pytorch-image-models/docs/models/gloun-senet.mdAdded+124
testbed/huggingface__pytorch-image-models/docs/models/gloun-seresnext.mdAdded+197
testbed/huggingface__pytorch-image-models/docs/models/inception-resnet-v2.mdAdded+133
testbed/huggingface__pytorch-image-models/docs/models/inception-v3.mdAdded+146
testbed/huggingface__pytorch-image-models/docs/models/legacy-se-resnet.mdAdded+318
testbed/huggingface__pytorch-image-models/docs/models/legacy-senet.mdAdded+135
testbed/huggingface__pytorch-image-models/docs/models/mobilenet-v2.mdAdded+271
testbed/huggingface__pytorch-image-models/docs/models/nasnet.mdAdded+131
testbed/huggingface__pytorch-image-models/docs/models/noisy-student.mdAdded+571
testbed/huggingface__pytorch-image-models/docs/models/pnasnet.mdAdded+132
testbed/huggingface__pytorch-image-models/docs/models/res2net.mdAdded+321
testbed/huggingface__pytorch-image-models/docs/models/resnest.mdAdded+469
testbed/huggingface__pytorch-image-models/docs/models/resnet-d.mdAdded+324
testbed/huggingface__pytorch-image-models/docs/models/resnet.mdAdded+439
testbed/huggingface__pytorch-image-models/docs/models/resnext.mdAdded+244
testbed/huggingface__pytorch-image-models/docs/models/rexnet.mdAdded+258
testbed/huggingface__pytorch-image-models/docs/models/se-resnet.mdAdded+183
testbed/huggingface__pytorch-image-models/docs/models/selecsls.mdAdded+197
testbed/huggingface__pytorch-image-models/docs/models/seresnext.mdAdded+228
testbed/huggingface__pytorch-image-models/docs/models/skresnet.mdAdded+173
testbed/huggingface__pytorch-image-models/docs/models/skresnext.mdAdded+131
testbed/huggingface__pytorch-image-models/docs/models/spnasnet.mdAdded+123
testbed/huggingface__pytorch-image-models/docs/models/ssl-resnet.mdAdded+192
testbed/huggingface__pytorch-image-models/docs/models/ssl-resnext.mdAdded+278