repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
pytorch-image-models
timm/models/rdnet.py
.py
""" RDNet Copyright (c) 2024-present NAVER Cloud Corp. Apache-2.0 """ from functools import partial from typing import List, Optional, Tuple, Union, Callable, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, calculate_drop_pat...
562
21,049
pytorch-image-models
timm/models/nest.py
.py
""" Nested Transformer (NesT) in PyTorch A PyTorch implement of Aggregating Nested Transformers as described in: 'Aggregating Nested Transformers' - https://arxiv.org/abs/2105.12723 The official Jax code is released and available at https://github.com/google-research/nested-transformer. The weights have been con...
699
25,818
pytorch-image-models
timm/models/registry.py
.py
from ._registry import * import warnings warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.models", FutureWarning)
5
146
pytorch-image-models
timm/models/levit.py
.py
""" LeViT Paper: `LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference` - https://arxiv.org/abs/2104.01136 @article{graham2021levit, title={LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference}, author={Benjamin Graham and Alaaeldin El-Nouby and Hugo Touvron and Pierre Stoc...
1,153
40,984
pytorch-image-models
timm/models/pit.py
.py
""" Pooling-based Vision Transformer (PiT) in PyTorch A PyTorch implement of Pooling-based Vision Transformers as described in 'Rethinking Spatial Dimensions of Vision Transformers' - https://arxiv.org/abs/2103.16302 This code was adapted from the original version at https://github.com/naver-ai/pit, original copyrigh...
556
18,607
pytorch-image-models
timm/models/hardcorenas.py
.py
from functools import partial import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from ._builder import build_model_with_cfg from ._builder import pretrained_cfg_for_features from ._efficientnet_blocks import SqueezeExcite from ._efficientnet_builder import decode_arch_def, resolve...
158
7,730
pytorch-image-models
timm/models/inception_resnet_v2.py
.py
""" Pytorch Inception-Resnet-V2 implementation Sourced from https://github.com/Cadene/tensorflow-model-zoo.torch (MIT License) which is based upon Google's Tensorflow implementation and pretrained weights (Apache 2.0 License) """ from functools import partial from typing import Type, Optional import torch import torch....
392
13,666
pytorch-image-models
timm/models/tresnet.py
.py
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn from timm.laye...
448
16,224
pytorch-image-models
timm/models/inception_v4.py
.py
""" Pytorch Inception-V4 implementation Sourced from https://github.com/Cadene/tensorflow-model-zoo.torch (MIT License) which is based upon Google's Tensorflow implementation and pretrained weights (Apache 2.0 License) """ from functools import partial from typing import List, Optional, Tuple, Union, Type import torch...
446
15,270
pytorch-image-models
timm/models/cspnet.py
.py
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
1,209
43,210
pytorch-image-models
timm/models/coat.py
.py
""" CoaT architecture. Paper: Co-Scale Conv-Attentional Image Transformers - https://arxiv.org/abs/2104.06399 Official CoaT code at: https://github.com/mlpc-ucsd/CoaT Modified from timm/models/vision_transformer.py """ from typing import List, Optional, Tuple, Union, Type, Any import torch import torch.nn as nn imp...
845
31,742
pytorch-image-models
timm/models/efficientformer_v2.py
.py
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
947
32,467
pytorch-image-models
timm/models/vision_transformer_hybrid.py
.py
""" Hybrid Vision Transformer (ViT) in PyTorch A PyTorch implement of the Hybrid Vision Transformers as described in: 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 `How to train your ViT? Data, Augmentation, and Regularization in Vision Transfor...
462
19,053
pytorch-image-models
timm/models/pvt_v2.py
.py
""" Pyramid Vision Transformer v2 @misc{wang2021pvtv2, title={PVTv2: Improved Baselines with Pyramid Vision Transformer}, author={Wenhai Wang and Enze Xie and Xiang Li and Deng-Ping Fan and Kaitao Song and Ding Liang and Tong Lu and Ping Luo and Ling Shao}, year={2021}, eprint={2106.137...
595
21,079
pytorch-image-models
timm/models/efficientvit_mit.py
.py
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit', 'EfficientVitLarge'] from ty...
1,282
41,978
pytorch-image-models
timm/models/cait.py
.py
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
633
23,170
pytorch-image-models
timm/models/_helpers.py
.py
""" Model creation / weight loading / state_dict helpers Hacked together by / Copyright 2020 Ross Wightman """ import argparse import logging import os import pickle from typing import Any, Callable, Dict, Optional, Union import torch try: import safetensors.torch _has_safetensors = True except ImportError:...
262
10,089
pytorch-image-models
timm/models/_features.py
.py
""" PyTorch Feature Extraction Helpers A collection of classes, functions, modules to help extract features from models and provide a common interface for describing them. The return_layers, module re-writing idea inspired by torchvision IntermediateLayerGetter https://github.com/pytorch/vision/blob/d88d8961ae51507d0...
484
19,758
pytorch-image-models
timm/models/beit.py
.py
""" BEiT: BERT Pre-Training of Image Transformers (https://arxiv.org/abs/2106.08254) Model from official source: https://github.com/microsoft/unilm/tree/master/beit @inproceedings{beit, title={{BEiT}: {BERT} Pre-Training of Image Transformers}, author={Hangbo Bao and Li Dong and Songhao Piao and Furu Wei}, booktitle=...
1,063
43,081
pytorch-image-models
timm/models/repvit.py
.py
""" RepViT Paper: `RepViT: Revisiting Mobile CNN From ViT Perspective` - https://arxiv.org/abs/2307.09283 @misc{wang2023repvit, title={RepViT: Revisiting Mobile CNN From ViT Perspective}, author={Ao Wang and Hui Chen and Zijia Lin and Hengjun Pu and Guiguang Ding}, year={2023}, eprint={230...
694
21,526
pytorch-image-models
timm/models/factory.py
.py
from ._factory import * import warnings warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.models", FutureWarning)
5
145
pytorch-image-models
timm/models/res2net.py
.py
""" Res2Net and Res2NeXt Adapted from Official Pytorch impl at: https://github.com/gasvn/Res2Net/ Paper: `Res2Net: A New Multi-scale Backbone Architecture` - https://arxiv.org/abs/1904.01169 """ import math from typing import Optional, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEA...
241
8,165
pytorch-image-models
timm/models/maxxvit.py
.py
""" MaxVit and CoAtNet Vision Transformer - CNN Hybrids in PyTorch This is a from-scratch implementation of both CoAtNet and MaxVit in PyTorch. 99% of the implementation was done from papers, however last minute some adjustments were made based on the (as yet unfinished?) public code release https://github.com/google...
2,712
101,089
pytorch-image-models
timm/models/byobnet.py
.py
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
3,181
116,445
pytorch-image-models
timm/models/efficientvit_msra.py
.py
""" EfficientViT (by MSRA) Paper: `EfficientViT: Memory Efficient Vision Transformer with Cascaded Group Attention` - https://arxiv.org/abs/2305.07027 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/EfficientViT """ __all__ = ['EfficientVitMsra'] import itertools from collections impor...
827
29,281
pytorch-image-models
timm/models/csatv2.py
.py
"""CSATv2 A frequency-domain vision model using DCT transforms with spatial attention. Paper: TBD This model created by members of MLPA Lab. Welcome feedback and suggestion, questions. gusdlf93@naver.com juno.demie.oh@gmail.com Refined for timm by Ross Wightman """ import math import warnings from functools import ...
871
33,967
pytorch-image-models
timm/models/mobilevit.py
.py
""" MobileViT Paper: V1: `MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer` - https://arxiv.org/abs/2110.02178 V2: `Separable Self-attention for Mobile Vision Transformers` - https://arxiv.org/abs/2206.02680 MobileVitBlock and checkpoints adapted from https://github.com/apple/ml-cvnets...
711
26,626
pytorch-image-models
timm/models/fasternet.py
.py
"""FasterNet Run, Don't Walk: Chasing Higher FLOPS for Faster Neural Networks - paper: https://arxiv.org/abs/2303.03667 - code: https://github.com/JierunChen/FasterNet @article{chen2023run, title={Run, Don't Walk: Chasing Higher FLOPS for Faster Neural Networks}, author={Chen, Jierun and Kao, Shiu-hong and He, Hao...
507
18,998
pytorch-image-models
timm/models/features.py
.py
from ._features import * import warnings warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.models", FutureWarning)
5
146
pytorch-image-models
timm/models/vision_transformer.py
.py
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 `How to train your ViT? Data, Augmentation, and Regularization in Vision Transformers` - https:...
4,923
211,911
pytorch-image-models
timm/models/starnet.py
.py
""" Implementation of Prof-of-Concept Network: StarNet. We make StarNet as simple as possible [to show the key contribution of element-wise multiplication]: - like NO layer-scale in network design, - and NO EMA during training, - which would improve the performance further. Created by: Xu Ma (Email: ma.xu...
363
13,637
pytorch-image-models
timm/models/metaformer.py
.py
""" Poolformer from MetaFormer is Actually What You Need for Vision https://arxiv.org/abs/2111.11418 IdentityFormer, RandFormer, PoolFormerV2, ConvFormer, and CAFormer from MetaFormer Baselines for Vision https://arxiv.org/abs/2210.13452 All implemented models support feature extraction and variable input resolution....
1,184
40,565
pytorch-image-models
timm/models/hrnet.py
.py
""" HRNet Copied from https://github.com/HRNet/HRNet-Image-Classification Original header: Copyright (c) Microsoft Licensed under the MIT License. Written by Bin Xiao (Bin.Xiao@microsoft.com) Modified by Ke Sun (sunk@mail.ustc.edu.cn) """ import logging from typing import Dict, List, Type, Optional, Tuple im...
1,005
34,373
pytorch-image-models
timm/models/swin_transformer_v2_cr.py
.py
""" Swin Transformer V2 A PyTorch impl of : `Swin Transformer V2: Scaling Up Capacity and Resolution` - https://arxiv.org/pdf/2111.09883 Code adapted from https://github.com/ChristophReich1996/Swin-Transformer-V2, original copyright/license info below This implementation is experimental and subject to change in ...
1,290
51,389
pytorch-image-models
timm/models/pnasnet.py
.py
""" pnasnet5large implementation grabbed from Cadene's pretrained models Additional credit to https://github.com/creafz https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/pnasnet.py """ from collections import OrderedDict from functools import partial from typing import Type i...
465
17,353
pytorch-image-models
timm/models/swin_transformer_v2.py
.py
""" Swin Transformer V2 A PyTorch impl of : `Swin Transformer V2: Scaling Up Capacity and Resolution` - https://arxiv.org/abs/2111.09883 Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below Modifications and additions for timm hacked together by / Copyright 2022, ...
1,320
53,039
pytorch-image-models
timm/models/convit.py
.py
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
459
16,683
pytorch-image-models
timm/models/mlp_mixer.py
.py
""" MLP-Mixer, ResMLP, and gMLP in PyTorch This impl originally based on MLP-Mixer paper. Official JAX impl: https://github.com/google-research/vision_transformer/blob/linen/vit_jax/models_mixer.py Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601 @article{tolstikhin2021, t...
881
33,749
pytorch-image-models
timm/models/vovnet.py
.py
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
560
18,826
pytorch-image-models
timm/models/resnest.py
.py
""" ResNeSt Models Paper: `ResNeSt: Split-Attention Networks` - https://arxiv.org/abs/2004.08955 Adapted from original PyTorch impl w/ weights at https://github.com/zhanghang1989/ResNeSt by Hang Zhang Modified for torchscript compat, and consistency with timm by Ross Wightman """ from typing import Optional, Type f...
279
10,479
pytorch-image-models
timm/models/fx_features.py
.py
from ._features_fx import * import warnings warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.models", FutureWarning)
5
149
pytorch-image-models
timm/models/twins.py
.py
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
631
23,769
pytorch-image-models
timm/models/sequencer.py
.py
""" Sequencer Paper: `Sequencer: Deep LSTM for Image Classification` - https://arxiv.org/pdf/2205.01972.pdf """ # Copyright (c) 2022. Yuki Tatsunami # Licensed under the Apache License, Version 2.0 (the "License"); import math from functools import partial from itertools import accumulate from typing import List, ...
573
18,907
pytorch-image-models
timm/models/xception_aligned.py
.py
"""Pytorch impl of Aligned Xception 41, 65, 71 This is a correct, from scratch impl of Aligned Xception (Deeplab) models compatible with TF weights at https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/model_zoo.md Hacked together by / Copyright 2020 Ross Wightman """ from functools import partia...
484
16,407
pytorch-image-models
timm/models/vitamin.py
.py
""" ViTamin Paper: Designing Scalable Vison Models in the Vision-Language Era A family of model weights on Huggingface: https://huggingface.co/collections/jienengchen/vitamin-family-661048126b72debdaca060bf @inproceedings{chen2024vitamin, title={ViTamin: Designing Scalable Vision Models in the Vision-language Era},...
627
21,490
pytorch-image-models
timm/models/inception_v3.py
.py
""" Inception-V3 Originally from torchvision Inception3 model Licensed BSD-Clause 3 https://github.com/pytorch/vision/blob/master/LICENSE """ from functools import partial from typing import Optional, Type import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_STD, ...
509
18,808
pytorch-image-models
timm/models/efficientformer.py
.py
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
687
23,607
pytorch-image-models
timm/models/inception_next.py
.py
""" InceptionNeXt paper: https://arxiv.org/abs/2303.16900 Original implementation & weights from: https://github.com/sail-sg/inceptionnext """ from functools import partial from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_D...
523
18,868
pytorch-image-models
timm/models/edgenext.py
.py
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from funct...
707
25,512
pytorch-image-models
timm/models/cpubone.py
.py
"""CPUBone CPUBone: Efficient Vision Backbone Design for Devices with Low Parallelization Capabilities Moritz Nottebaum, Matteo Dunnhofer, Christian Micheloni Conference on Computer Vision and Pattern Recognition (CVPR) Findings, 2026 Adapted from the original implementation at https://github.com/altair199797/CPUBone...
1,081
41,698
pytorch-image-models
timm/models/sknet.py
.py
""" Selective Kernel Networks (ResNet base) Paper: Selective Kernel Networks (https://arxiv.org/abs/1903.06586) This was inspired by reading 'Compounding the Performance Improvements...' (https://arxiv.org/abs/2001.06268) and a streamlined impl at https://github.com/clovaai/assembled-cnn but I ended up building somet...
270
9,771
pytorch-image-models
timm/models/tnt.py
.py
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT The official pytorch code is ...
596
22,766
pytorch-image-models
timm/models/swiftformer.py
.py
"""SwiftFormer SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications Code: https://github.com/Amshaker/SwiftFormer Paper: https://arxiv.org/pdf/2303.15446 @InProceedings{Shaker_2023_ICCV, author = {Shaker, Abdelrahman and Maaz, Muhammad and Rasheed, Hanoona and Kha...
650
24,050
pytorch-image-models
timm/models/_features_fx.py
.py
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from timm.layers import ( create_feature_extractor, get_graph_node_names, register_not...
101
3,279
pytorch-image-models
timm/models/_registry.py
.py
""" Model Registry Hacked together by / Copyright 2020 Ross Wightman """ import fnmatch import re import sys import warnings from collections import defaultdict, deque from copy import deepcopy from dataclasses import replace from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Sequence, Union, Tuple...
353
14,465
pytorch-image-models
timm/models/xception.py
.py
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Ke...
299
9,110
pytorch-image-models
timm/models/mobilenetv5.py
.py
from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import ( SelectAdaptivePool2d, Linear, LayerType...
881
33,419
pytorch-image-models
timm/models/vgg.py
.py
"""VGG Adapted from https://github.com/pytorch/vision 'vgg.py' (BSD-3-Clause) with a few changes for timm functionality. Copyright 2021 Ross Wightman """ from typing import Any, Dict, List, Optional, Type, Union, cast import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_...
427
14,626
pytorch-image-models
timm/models/efficientnet.py
.py
""" The EfficientNet Family in PyTorch An implementation of EfficienNet that covers variety of related models with efficient architectures: * EfficientNet-V2 - `EfficientNetV2: Smaller Models and Faster Training` - https://arxiv.org/abs/2104.00298 * EfficientNet (B0-B8, L2 + Tensorflow pretrained AutoAug/RandAug/A...
2,974
126,149
pytorch-image-models
timm/models/_prune.py
.py
import os import pkgutil from copy import deepcopy from torch import nn as nn from timm.layers import Conv2dSame, BatchNormAct2d, Linear __all__ = ['extract_layer', 'set_layer', 'adapt_model_from_string', 'adapt_model_from_file'] def extract_layer(model, layer): """Extract a layer from a model using dot-separa...
177
5,810
pytorch-image-models
timm/optim/nadam.py
.py
import math import torch from torch.optim.optimizer import Optimizer class NAdamLegacy(Optimizer): """Implements Nadam algorithm (a variant of Adam based on Nesterov momentum). NOTE: This impl has been deprecated in favour of torch.optim.NAdam and remains as a reference It has been proposed in `Incorpo...
107
4,114
pytorch-image-models
timm/optim/_param_groups.py
.py
import fnmatch import logging from itertools import islice from typing import Collection, Optional from torch import nn as nn from timm.models import group_parameters _logger = logging.getLogger(__name__) def _matches_pattern(name: str, patterns: Collection[str]) -> bool: """Check if parameter name matches an...
195
6,824
pytorch-image-models
timm/optim/adafactor.py
.py
""" Adafactor Optimizer Lifted from https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py Modified by Ross Wightman to fix some issues with factorization dims for non nn.Linear layers Original header/copyright below. """ # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is l...
230
9,969
pytorch-image-models
timm/optim/radam.py
.py
"""RAdam Optimizer. Implementation lifted from: https://github.com/LiyuanLucasLiu/RAdam Paper: `On the Variance of the Adaptive Learning Rate and Beyond` - https://arxiv.org/abs/1908.03265 NOTE: This impl has been deprecated in favour of torch.optim.RAdam and remains as a reference """ import math import torch from to...
106
3,843
pytorch-image-models
timm/optim/rmsprop_tf.py
.py
""" RMSProp modified to behave like Tensorflow impl Originally cut & paste from PyTorch RMSProp https://github.com/pytorch/pytorch/blob/063946d2b3f3f1e953a2a3b54e0b34f1393de295/torch/optim/rmsprop.py Licensed under BSD-Clause 3 (ish), https://github.com/pytorch/pytorch/blob/master/LICENSE References for added functio...
183
7,639
pytorch-image-models
timm/optim/sgdw.py
.py
""" SGD with decoupled weight-decay. References for added functionality: Cautious Optimizers: https://arxiv.org/abs/2411.16085 Why Gradients Rapidly Increase Near the End of Training: https://arxiv.org/abs/2506.02285 Hacked together by Ross Wightman """ from typing import List, Optional import torch from tor...
319
11,285
pytorch-image-models
timm/optim/sgdp.py
.py
""" SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP References for added functionality: Cautious Optimizers: ht...
98
2,971
pytorch-image-models
timm/optim/muon.py
.py
""" Muon Optimizer Improved Muon optimizer implementation with flexible handling of high-dimensional tensors. Combines PyTorch-style structure with options for: - Batched spatial processing for convolutions in addition to flatten - Optional spatial normalization - Selectable coefficient presets - Automatic fallback t...
1,057
41,665
pytorch-image-models
timm/optim/lamb.py
.py
""" PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb This optimizer code was adapted from the following (starting with latest) * https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py * https://github.com/NVIDIA/DeepLearningExample...
253
11,038
pytorch-image-models
timm/optim/nadamw.py
.py
""" NAdamW Optimizer Based on simplified algorithm in https://github.com/mlcommons/algorithmic-efficiency/tree/main/baselines/nadamw Added multi-tensor (foreach) path. References for added functionality: Cautious Optimizers: https://arxiv.org/abs/2411.16085 Why Gradients Rapidly Increase Near the End of Trai...
427
16,131
pytorch-image-models
timm/optim/lookahead.py
.py
""" Lookahead Optimizer Wrapper. Implementation modified from: https://github.com/alphadl/lookahead.pytorch Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610 Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from typing import Callable...
67
2,687
pytorch-image-models
timm/optim/adafactor_bv.py
.py
""" Adafactor (Big Vision variant) for PyTorch Adapted from the implementation in big vision: https://github.com/google-research/big_vision Described in 'Scaling Vision Transformers': https://arxiv.org/abs/2106.04560 References for added functionality: Cautious Optimizers: https://arxiv.org/abs/2411.16085 Wh...
341
13,102
pytorch-image-models
timm/optim/kron.py
.py
""" PyTorch Implementation of the Kron (PSGD) optimizer This is a PSGD optimizer using a Kronecker-factored preconditioner. This impl was adapted from https://github.com/evanatyourservice/kron_torch by Evan Walters, licensed CC-BY-4.0. Contributions to above also made by * Lucas Nestler, added to his https://github....
564
22,341
pytorch-image-models
timm/optim/nvnovograd.py
.py
""" Nvidia NovoGrad Optimizer. Original impl by Nvidia from Jasper example: - https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/SpeechRecognition/Jasper Paper: `Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks` - https://arxiv.org/abs/1905.11286 """ im...
133
4,953
pytorch-image-models
timm/optim/adamw.py
.py
""" AdamW Optimizer Impl copied from PyTorch master References for added functionality: Cautious Optimizers: https://arxiv.org/abs/2411.16085 Why Gradients Rapidly Increase Near the End of Training: https://arxiv.org/abs/2506.02285 NOTE: This impl has been deprecated in favour of torch.optim.AdamW and remains...
458
17,444
pytorch-image-models
timm/optim/adopt.py
.py
""" ADOPT PyTorch Optimizer ADOPT: Modified Adam Can Converge with Any β2 with the Optimal Rate: https://arxiv.org/abs/2411.02853 Modified for reduced dependencies on PyTorch internals from original at: https://github.com/iShohei220/adopt @inproceedings{taniguchi2024adopt, author={Taniguchi, Shohei and Harada, Keno...
527
19,706
pytorch-image-models
timm/optim/laprop.py
.py
""" PyTorch impl of LaProp optimizer Code simplified from https://github.com/Z-T-WANG/LaProp-Optimizer, MIT License Paper: LaProp: Separating Momentum and Adaptivity in Adam, https://arxiv.org/abs/2002.04839 @article{ziyin2020laprop, title={LaProp: a Better Way to Combine Momentum with Adaptive Gradient}, author...
160
6,418
pytorch-image-models
timm/optim/_helpers.py
.py
"""Small optimizer helpers shared by timm optimizer implementations.""" from typing import List, Optional, Sequence, Union import torch from torch import Tensor def _get_scalar_dtype() -> torch.dtype: return torch.float64 if torch.get_default_dtype() == torch.float64 else torch.float32 def _init_scalar( ...
91
3,241
pytorch-image-models
timm/optim/mars.py
.py
""" PyTorch MARS Optimizer Code simplified from https://github.com/AGI-Arena/MARS Paper: MARS: Unleashing the Power of Variance Reduction for Training Large Models - https://arxiv.org/abs/2411.10438 @article{yuan2024mars, title={MARS: Unleashing the Power of Variance Reduction for Training Large Models}, author=...
208
7,404
pytorch-image-models
timm/optim/lion.py
.py
""" Lion Optimizer Paper: `Symbolic Discovery of Optimization Algorithms` - https://arxiv.org/abs/2302.06675 Original Impl: https://github.com/google/automl/tree/master/lion References for added functionality: Cautious Optimizers: https://arxiv.org/abs/2411.16085 Why Gradients Rapidly Increase Near the End of ...
271
8,999
pytorch-image-models
timm/optim/lars.py
.py
""" PyTorch LARS / LARC Optimizer An implementation of LARS (SGD) + LARC in PyTorch Based on: * PyTorch SGD: https://github.com/pytorch/pytorch/blob/1.7/torch/optim/sgd.py#L100 * NVIDIA APEX LARC: https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py Additional cleanup and modifications to properly su...
133
5,166
pytorch-image-models
timm/optim/adamp.py
.py
""" AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP References for added functionality: Cautious Optimizers:...
152
5,156
pytorch-image-models
timm/optim/_types.py
.py
from typing import Any, Dict, Iterable, Union, Protocol, Type try: from typing import TypeAlias except ImportError: from typing_extensions import TypeAlias try: from typing import TypeVar except ImportError: from typing_extensions import TypeVar import torch import torch.optim try: from torch.opti...
29
735
pytorch-image-models
timm/optim/adan.py
.py
""" Adan Optimizer Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models[J]. arXiv preprint arXiv:2208.06677, 2022. https://arxiv.org/abs/2208.06677 Implementation adapted from https://github.com/sail-sg/Adan """ # Copyright 2022 Garena Online Private Limited # # Licensed under the Apache L...
328
11,757
pytorch-image-models
timm/optim/adabelief.py
.py
import math import torch from torch.optim.optimizer import Optimizer class AdaBelief(Optimizer): r"""Implements AdaBelief algorithm. Modified from Adam in PyTorch Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optiona...
219
10,034
pytorch-image-models
timm/optim/madgrad.py
.py
""" PyTorch MADGRAD optimizer MADGRAD: https://arxiv.org/abs/2101.11075 Code from: https://github.com/facebookresearch/madgrad """ # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import ma...
190
6,951
pytorch-image-models
timm/optim/adahessian.py
.py
""" AdaHessian Optimizer Lifted from https://github.com/davda54/ada-hessian/blob/master/ada_hessian.py Originally licensed MIT, Copyright 2020, David Samuel """ import torch class Adahessian(torch.optim.Optimizer): """ Implements the AdaHessian algorithm from "ADAHESSIAN: An Adaptive Second OrderOptimizer fo...
173
6,716
pytorch-image-models
timm/optim/_optim_factory.py
.py
""" Optimizer Factory w/ custom Weight Decay & Layer Decay support Hacked together by / Copyright 2021 Ross Wightman """ import logging from dataclasses import dataclass from functools import partial from typing import Any, Callable, Collection, Dict, List, Optional, Set, Tuple, Type, Union from fnmatch import fnmatch...
1,340
48,836
pytorch-image-models
results/generate_csv_results.py
.py
import numpy as np import pandas as pd results = { 'results-imagenet.csv': [ 'results-imagenet-real.csv', 'results-imagenetv2-matched-frequency.csv', 'results-sketch.csv' ], 'results-imagenet-a-clean.csv': [ 'results-imagenet-a.csv', ], 'results-imagenet-r-clean.csv...
80
2,769
pytorch-image-models
tests/test_factory.py
.py
import pytest from timm.models import parse_model_name, safe_model_name @pytest.mark.parametrize('model_name,expected', [ # plain timm model names ('resnet18', (None, 'resnet18')), ('resnet18.a1_in1k', (None, 'resnet18.a1_in1k')), # hf-hub, incl. deprecated hf_hub prefix and revision in path ('hf...
81
3,676
pytorch-image-models
tests/test_naflex_dataset.py
.py
import warnings from types import SimpleNamespace import torch from torch.utils.data import DataLoader, Dataset from timm.data import NaFlexMapDatasetWrapper class _TensorImageDataset(Dataset): def __init__(self, length=32): self.length = length def __getitem__(self, index): return torch.fu...
99
2,862
pytorch-image-models
tests/test_dataset_info.py
.py
import pytest from timm.data import CustomDatasetInfo, DatasetInfoLabelMapper, LabelMappingCoverage @pytest.mark.parametrize('label_names', [ ['cat', 'dog'], ('cat', 'dog'), ]) def test_custom_dataset_info_sequence_labels(label_names): info = CustomDatasetInfo( label_names, label_descript...
74
2,566
pytorch-image-models
tests/test_scheduler.py
.py
""" Scheduler Tests Tests for learning rate schedulers in timm.scheduler. """ import math import pytest import torch from torch.nn import Parameter from timm.scheduler import ( CosineLRScheduler, StepLRScheduler, MultiStepLRScheduler, PlateauLRScheduler, PolyLRScheduler, TanhLRScheduler, ) fro...
535
18,291
pytorch-image-models
tests/test_layers_drop.py
.py
"""Tests for timm.layers.drop module (DropBlock, DropPath).""" import torch import pytest from timm.layers.drop import drop_block_2d, DropBlock2d, drop_path, DropPath class TestDropBlock2d: """Test drop_block_2d function and DropBlock2d module.""" def test_drop_block_2d_output_shape(self): """Test t...
252
10,708
pytorch-image-models
tests/test_layers.py
.py
import pytest import torch import torch.nn as nn from timm.layers import ( Attention2d, MultiQueryAttentionV2, PatchEmbedInterpolator, create_act_layer, get_act_fn, get_act_layer, resample_abs_pos_embed, resample_patch_embed, set_layer_config, ) import importlib import os torch_ba...
342
10,817
pytorch-image-models
tests/test_hub.py
.py
import pytest import torch from timm.models._hub import load_state_dict_from_path try: import safetensors.torch _has_safetensors = True except ImportError: _has_safetensors = False def _write_ckpt(path, value): state_dict = {'weight': torch.full((2,), float(value))} if path.suffix == '.safetenso...
64
2,357
pytorch-image-models
tests/test_scheduled_sampler.py
.py
from collections import Counter import pytest import torch from PIL import Image from torch.utils.data import Dataset, DistributedSampler, SequentialSampler from timm.data import FastCollateMixup, ScheduledBatchSampler, ScheduledTransformDataset, create_loader class _ImageDataset(Dataset): def __init__(self, le...
481
16,555
pytorch-image-models
tests/test_models.py
.py
"""Run tests for all models Tests that run on CI should have a specific marker, e.g. @pytest.mark.base. This marker is used to parallelize the CI runs, with one runner for each marker. If new tests are added, ensure that they use one of the existing markers (documented in pyproject.toml > pytest > markers) or that a ...
1,039
46,130
pytorch-image-models
tests/test_task.py
.py
import pytest import torch import torch.nn as nn from timm.task import ClassificationTask, FeatureDistillationTask, load_task_ema_checkpoint, resume_task_checkpoint from timm.optim import create_optimizer_v2 from timm.utils import CheckpointSaver class TinyClassifier(nn.Module): def __init__(self, in_chans=3, nu...
211
7,881
pytorch-image-models
tests/test_optim.py
.py
""" Optimzier Tests These tests were adapted from PyTorch' optimizer tests. """ import functools import importlib import os from copy import deepcopy import pytest import torch from torch.nn import Parameter from torch.testing._internal.common_utils import TestCase from timm.optim import create_optimizer_v2, list_o...
764
25,686