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/utils/clip_grad.py
.py
import torch from timm.utils.agc import adaptive_clip_grad def dispatch_clip_grad(parameters, value: float, mode: str = 'norm', norm_type: float = 2.0): """ Dispatch to gradient clipping method Args: parameters (Iterable): model parameters to clip value (float): clipping value/factor/norm, m...
24
796
pytorch-image-models
timm/utils/random.py
.py
import random import numpy as np import torch def random_seed(seed=42, rank=0): torch.manual_seed(seed + rank) np.random.seed(seed + rank) random.seed(seed + rank)
10
178
pytorch-image-models
timm/utils/decay_batch.py
.py
""" Batch size decay and retry helpers. Copyright 2022 Ross Wightman """ import math def decay_batch_step(batch_size, num_intra_steps=2, no_odd=False): """ power of two batch-size decay with intra steps Decay by stepping between powers of 2: * determine power-of-2 floor of current batch size (base batch...
44
1,762
pytorch-image-models
timm/utils/agc.py
.py
""" Adaptive Gradient Clipping An impl of AGC, as per (https://arxiv.org/abs/2102.06171): @article{brock2021high, author={Andrew Brock and Soham De and Samuel L. Smith and Karen Simonyan}, title={High-Performance Large-Scale Image Recognition Without Normalization}, journal={arXiv preprint arXiv:}, year={2021...
43
1,624
pytorch-image-models
timm/utils/metrics.py
.py
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
33
922
pytorch-image-models
timm/utils/log.py
.py
""" Logging helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import logging.handlers class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): if record.levelno =...
29
1,015
pytorch-image-models
timm/utils/onnx.py
.py
from typing import Optional, Tuple, List import torch def onnx_forward(onnx_file, example_input): import onnxruntime sess_options = onnxruntime.SessionOptions() session = onnxruntime.InferenceSession(onnx_file, sess_options) input_name = session.get_inputs()[0].name output = session.run([], {inp...
105
3,710
pytorch-image-models
timm/utils/summary.py
.py
""" Summary utilities Hacked together by / Copyright 2020 Ross Wightman """ import csv import os from collections import OrderedDict try: import wandb except ImportError: pass def get_outdir(path, *paths, inc=False): outdir = os.path.join(path, *paths) if not os.path.exists(outdir): os.maked...
52
1,325
pytorch-image-models
timm/utils/cuda.py
.py
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call__( sel...
79
2,173
pytorch-image-models
timm/utils/checkpoint_saver.py
.py
""" Checkpoint Saver Track top-n training checkpoints and maintain recovery checkpoints on specified intervals. Hacked together by / Copyright 2020 Ross Wightman """ import glob import logging import operator import os import shutil import torch from .model import unwrap_model, get_state_dict _logger = logging.g...
188
7,197
pytorch-image-models
timm/task/distillation.py
.py
"""Knowledge distillation training tasks and components.""" import logging from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.models import create_model, group_parameters from timm.utils import unwrap_model from .task import TrainingTask _lo...
760
29,961
pytorch-image-models
timm/task/__init__.py
.py
"""Training task abstractions for timm. This module provides task-based abstractions for training loops where each task encapsulates both the forward pass and loss computation, returning a dictionary with loss components and outputs for logging. """ from .task import TrainingTask from ._helpers import resume_task_chec...
24
845
pytorch-image-models
timm/task/classification.py
.py
"""Classification training task.""" import logging from typing import Callable, Dict, Optional, Union import torch import torch.nn as nn from .task import TrainingTask _logger = logging.getLogger(__name__) class ClassificationTask(TrainingTask): """Standard supervised classification task. Simple task that...
103
3,244
pytorch-image-models
timm/task/_helpers.py
.py
"""Checkpoint helpers for task-based training.""" import argparse import logging import os from typing import Optional import torch from timm.models import clean_state_dict _logger = logging.getLogger(__name__) def _load_train_checkpoint(checkpoint_path, weights_only=True): use_safe_globals = weights_only and...
107
4,127
pytorch-image-models
timm/task/task.py
.py
"""Base training task abstraction. This module provides the base TrainingTask class that encapsulates a complete forward pass including loss computation. Tasks return a dictionary with loss components and outputs for logging. """ from contextlib import nullcontext from typing import Any, Dict, Optional import torch i...
248
8,999
pytorch-image-models
timm/task/token_distillation.py
.py
"""Token-based distillation training task for models with distillation heads.""" import logging from typing import Dict, Optional, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.models import create_model from timm.utils import unwrap_model from .task import TrainingTask _logger ...
369
15,230
pytorch-image-models
timm/data/naflex_loader.py
.py
"""NaFlex data loader for dynamic sequence length training. This module provides a specialized data loader for Vision Transformer models that supports: - Dynamic sequence length sampling during training for improved efficiency - Variable patch size training with probabilistic selection - Patch-level random erasing aug...
459
18,490
pytorch-image-models
timm/data/distributed_sampler.py
.py
import math import torch from torch.utils.data import Sampler import torch.distributed as dist class OrderedDistributedSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset. It is especially useful in conjunction with :class:`torch.nn.parallel.DistributedDataParallel`. In suc...
136
5,540
pytorch-image-models
timm/data/naflex_transforms.py
.py
""" NaFlex (NaViT + FlexiViT) Transforms and Collation Implements PyTorch versions of the transforms described in the NaViT and FlexiViT papers: - NaViT: https://arxiv.org/abs/2307.14995 - FlexiViT: https://arxiv.org/abs/2212.08013 Enables variable resolution/aspect ratio image handling with efficient patching. Hack...
850
33,926
pytorch-image-models
timm/data/naflex_dataset.py
.py
""" Dynamic Sequence Length Datasets for Variable Resolution Image Processing Implements two dataset wrappers: 1. NaFlexMapDatasetWrapper - Map-style dataset that returns batches with variable sequence lengths TODO: 2. NaFlexIterableDatasetWrapper - Iterable dataset that yields batches with variable sequence lengths ...
566
25,014
pytorch-image-models
timm/data/dataset_info.py
.py
from abc import ABC, abstractmethod from numbers import Integral from typing import Dict, List, NamedTuple, Optional, Tuple, Union LabelNames = Union[List[str], Tuple[str, ...], Dict[Union[int, str], str]] class DatasetInfo(ABC): def __init__(self): pass @abstractmethod def num_classes(self): ...
176
6,996
pytorch-image-models
timm/data/random_erasing.py
.py
""" Random Erasing (Cutout) Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0 Copyright Zhun Zhong & Liang Zheng Hacked together by / Copyright 2019, Ross Wightman """ import random import math import torch def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float3...
118
4,964
pytorch-image-models
timm/data/auto_augment.py
.py
""" AutoAugment, RandAugment, AugMix, and 3-Augment for PyTorch This code implements the searched ImageNet policies with various tweaks and improvements and does not include any of the search code. AA and RA Implementation adapted from: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/au...
1,001
35,599
pytorch-image-models
timm/data/naflex_random_erasing.py
.py
"""Patch-level random erasing augmentation for NaFlex Vision Transformers. This module implements random erasing specifically designed for patchified images, operating at the patch granularity rather than pixel level. It supports two modes: - 'patch': Randomly erases individual patches (speckle-like noise) - 'region':...
354
14,283
pytorch-image-models
timm/data/__init__.py
.py
from .auto_augment import RandAugment, AutoAugment, rand_augment_ops, auto_augment_policy,\ rand_augment_transform, auto_augment_transform from .config import resolve_data_config, resolve_model_data_config from .constants import * from .dataset import ImageDataset, IterableImageDataset, AugMixDataset from .dataset_...
29
1,367
pytorch-image-models
timm/data/constants.py
.py
DEFAULT_CROP_PCT = 0.875 DEFAULT_CROP_MODE = 'center' IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5) IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5) IMAGENET_DPN_MEAN = (124 / 255, 117 / 255, 104 / 255) IMAGENET_DPN_STD = tuple([1 / (.0167 *...
11
442
pytorch-image-models
timm/data/transforms.py
.py
import math import numbers import random import warnings from typing import List, Sequence, Tuple, Union import torch import torchvision.transforms as transforms import torchvision.transforms.functional as F try: from torchvision.transforms.functional import InterpolationMode has_interpolation_mode = True exce...
584
20,120
pytorch-image-models
timm/data/real_labels.py
.py
""" Real labels evaluator for ImageNet Paper: `Are we done with ImageNet?` - https://arxiv.org/abs/2006.07159 Based on Numpy example at https://github.com/google-research/reassessed-imagenet Hacked together by / Copyright 2020 Ross Wightman """ import os import json import numpy as np import pkgutil class RealLabels...
48
1,800
pytorch-image-models
timm/data/imagenet_info.py
.py
import csv import os import pkgutil import re from typing import Dict, List, Optional, Union from .dataset_info import DatasetInfo # NOTE no ambiguity wrt to mapping from # classes to ImageNet subset so far, but likely to change _NUM_CLASSES_TO_SUBSET = { 1000: 'imagenet-1k', 11221: 'imagenet-21k-miil', # m...
96
4,167
pytorch-image-models
timm/data/mixup.py
.py
""" Mixup and Cutmix Papers: mixup: Beyond Empirical Risk Minimization (https://arxiv.org/abs/1710.09412) CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features (https://arxiv.org/abs/1905.04899) Code Reference: CutMix: https://github.com/clovaai/CutMix-PyTorch Hacked together by / Co...
350
16,078
pytorch-image-models
timm/data/transforms_factory.py
.py
""" Transforms Factory Factory methods for building image transforms for use with TIMM (PyTorch Image Models) Hacked together by / Copyright 2019, Ross Wightman """ import math from typing import Optional, Tuple, Union import torch from torchvision import transforms from timm.data.constants import IMAGENET_DEFAULT_M...
535
22,478
pytorch-image-models
timm/data/dataset.py
.py
""" Quick n Simple Image Folder, Tarfile based DataSet Hacked together by / Copyright 2019, Ross Wightman """ import io import logging from typing import Optional import torch import torch.utils.data as data from PIL import Image from .readers import create_reader _logger = logging.getLogger(__name__) _ERROR_RETR...
208
6,527
pytorch-image-models
timm/data/tf_preprocessing.py
.py
""" Tensorflow Preprocessing Adapter Allows use of Tensorflow preprocessing pipeline in PyTorch Transform Copyright of original Tensorflow code below. Hacked together by / Copyright 2020 Ross Wightman """ # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2....
234
9,169
pytorch-image-models
timm/data/config.py
.py
import logging from .constants import * _logger = logging.getLogger(__name__) def resolve_data_config( args=None, pretrained_cfg=None, model=None, use_test_size=False, verbose=False ): assert model or args or pretrained_cfg, "At least one of model, args, or pretrained_cfg...
130
4,616
pytorch-image-models
timm/data/loader.py
.py
""" Loader Factory, Fast Collate, CUDA Prefetcher Prefetcher and Fast Collate inspired by NVIDIA APEX example at https://github.com/NVIDIA/apex/commit/d5e2bb4bdeedd27b1dfaf5bb2b24d6c000dee9be#diff-cf86c282ff7fba81fad27a559379d5bf Hacked together by / Copyright 2019, Ross Wightman """ import logging import random from...
505
21,065
pytorch-image-models
timm/data/scheduled_sampler.py
.py
"""Scheduled batch sampling and transform dispatch for map-style datasets.""" import math from itertools import islice from typing import Any, Callable, Iterator, List, Optional, Sequence, Tuple, Union import torch from torch.utils.data import Dataset, Sampler class ScheduledBatchSampler(Sampler[List[Tuple[Any, int...
332
15,383
pytorch-image-models
timm/data/dataset_factory.py
.py
""" Dataset Factory Hacked together by / Copyright 2021, Ross Wightman """ import os from typing import Optional from torchvision.datasets import CIFAR100, CIFAR10, MNIST, KMNIST, FashionMNIST, ImageFolder try: from torchvision.datasets import Places365 has_places365 = True except ImportError: has_places3...
231
8,627
pytorch-image-models
timm/data/naflex_mixup.py
.py
"""Variable‑size Mixup / CutMix utilities for NaFlex data loaders. This module provides: * `mix_batch_variable_size` – pixel‑level Mixup/CutMix that operates on a list of images whose spatial sizes differ, mixing only their central overlap so no resizing is required. * `pairwise_mixup_target` – builds soft‑label ...
251
9,001
pytorch-image-models
timm/data/readers/reader_image_tar.py
.py
""" A dataset reader that reads single tarfile based datasets This reader can read datasets consisting if a single tarfile containing images. I am planning to deprecated it in favour of ParerImageInTar. Hacked together by / Copyright 2020 Ross Wightman """ import os import tarfile from timm.utils.misc import natural...
75
2,644
pytorch-image-models
timm/data/readers/reader_factory.py
.py
import os from typing import Optional from .reader_image_folder import ReaderImageFolder from .reader_image_in_tar import ReaderImageInTar def create_reader( name: str, root: Optional[str] = None, split: str = 'train', **kwargs, ): kwargs = {k: v for k, v in kwargs.items() if v is...
49
1,918
pytorch-image-models
timm/data/readers/class_map.py
.py
import os import pickle class _ClassMapUnpickler(pickle.Unpickler): """Restricted unpickler for `.pkl` class map files. A class map is a plain ``{class_name: index}`` dict of built-in types, which never triggers ``find_class``. Disallowing all globals therefore blocks arbitrary code execution from a ...
38
1,570
pytorch-image-models
timm/data/readers/reader_tfds.py
.py
""" Dataset reader that wraps TFDS datasets Wraps many (most?) TFDS image-classification datasets from https://github.com/tensorflow/datasets https://www.tensorflow.org/datasets/catalog/overview#image_classification Hacked together by / Copyright 2020 Ross Wightman """ import math import os import sys from typing imp...
356
17,909
pytorch-image-models
timm/data/readers/img_extensions.py
.py
from copy import deepcopy __all__ = ['get_img_extensions', 'is_img_extension', 'set_img_extensions', 'add_img_extensions', 'del_img_extensions'] IMG_EXTENSIONS = ('.png', '.jpg', '.jpeg') # singleton, kept public for bwd compat use _IMG_EXTENSIONS_SET = set(IMG_EXTENSIONS) # set version, private, kept in sync de...
51
1,482
pytorch-image-models
timm/data/readers/reader_hfids.py
.py
""" Dataset reader for HF IterableDataset """ import math import os from itertools import repeat, chain from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets from datasets.distributed import split_dataset_by_node from datasets.splits import Sp...
220
8,409
pytorch-image-models
timm/data/readers/reader_hfds.py
.py
""" Dataset reader that wraps Hugging Face datasets Hacked together by / Copyright 2022 Ross Wightman """ import io import math from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets except ImportError as e: print("Please install Hugging Face data...
103
3,262
pytorch-image-models
timm/data/readers/reader_wds.py
.py
""" Dataset reader for webdataset Hacked together by / Copyright 2022 Ross Wightman """ import io import json import logging import math import os import random import sys from dataclasses import dataclass from functools import partial from itertools import islice from typing import Any, Callable, Dict, List, Optional...
467
16,976
pytorch-image-models
timm/data/readers/reader_image_in_tar.py
.py
""" A dataset reader that reads tarfile based datasets This reader can extract image samples from: * a single tar of image files * a folder of multiple tarfiles containing imagefiles * a tar of tars containing image files Labels are based on the combined folder and/or tar name structure. Hacked together by / Copyrig...
249
10,165
pytorch-image-models
timm/data/readers/reader_image_folder.py
.py
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
100
3,508
pytorch-image-models
timm/data/readers/shared_count.py
.py
from multiprocessing import Value class SharedCount: def __init__(self, epoch: int = 0): self.shared_epoch = Value('i', epoch) @property def value(self): return self.shared_epoch.value @value.setter def value(self, epoch): self.shared_epoch.value = epoch
15
303
pytorch-image-models
timm/data/readers/reader.py
.py
from abc import abstractmethod class Reader: def __init__(self): pass @abstractmethod def _filename(self, index, basename=False, absolute=False): pass def filename(self, index, basename=False, absolute=False): return self._filename(index, basename=basename, absolute=absolute)...
18
487
pytorch-image-models
timm/models/nfnet.py
.py
""" Normalization Free Nets. NFNet, NF-RegNet, NF-ResNet (pre-activation) Models Paper: `Characterizing signal propagation to close the performance gap in unnormalized ResNets` - https://arxiv.org/abs/2101.08692 Paper: `High-Performance Large-Scale Image Recognition Without Normalization` - https://arxiv.org/...
1,190
45,753
pytorch-image-models
timm/models/visformer.py
.py
""" Visformer Paper: Visformer: The Vision-friendly Transformer - https://arxiv.org/abs/2104.12533 From original at https://github.com/danczs/Visformer Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ from typing import Optional, Union, Type, Any import torch import torch....
592
20,709
pytorch-image-models
timm/models/davit.py
.py
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
954
32,770
pytorch-image-models
timm/models/vision_transformer_relpos.py
.py
""" Relative Position Vision Transformer (ViT) in PyTorch NOTE: these models are experimental / WIP, expect changes Hacked together by / Copyright 2022, Ross Wightman """ import logging import math from functools import partial from typing import List, Optional, Tuple, Type, Union try: from typing import Literal...
743
30,435
pytorch-image-models
timm/models/nasnet.py
.py
""" NasNet-A (Large) nasnetalarge implementation grabbed from Cadene's pretrained models https://github.com/Cadene/pretrained-models.pytorch """ from functools import partial from typing import Optional, Type import torch import torch.nn as nn from timm.layers import ConvNormAct, create_conv2d, create_pool2d, creat...
720
29,335
pytorch-image-models
timm/models/hgnet.py
.py
""" PP-HGNet (V1 & V2) Reference: https://github.com/PaddlePaddle/PaddleClas/blob/develop/docs/zh_CN/models/ImageNet1k/PP-HGNetV2.md The Paddle Implement of PP-HGNet (https://github.com/PaddlePaddle/PaddleClas/blob/release/2.5.1/docs/en/models/PP-HGNet_en.md) PP-HGNet: https://github.com/PaddlePaddle/PaddleClas/blob/r...
853
27,737
pytorch-image-models
timm/models/_manipulate.py
.py
import collections.abc import math import re from collections import defaultdict from itertools import chain from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, Union import torch import torch.utils.checkpoint from torch import nn as nn from torch import Tensor from timm.layers import use_r...
347
12,698
pytorch-image-models
timm/models/shvit.py
.py
"""SHViT SHViT: Single-Head Vision Transformer with Memory Efficient Macro Design Code: https://github.com/ysj9909/SHViT Paper: https://arxiv.org/abs/2401.16456 @inproceedings{yun2024shvit, author={Yun, Seokju and Ro, Youngmin}, title={SHViT: Single-Head Vision Transformer with Memory Efficient Macro Design}, bo...
567
20,059
pytorch-image-models
timm/models/nextvit.py
.py
""" Next-ViT As described in https://arxiv.org/abs/2207.05501 Next-ViT model defs and weights adapted from https://github.com/bytedance/Next-ViT, original copyright below """ # Copyright (c) ByteDance Inc. All rights reserved. from functools import partial from typing import List, Optional, Tuple, Union, Type import...
822
27,671
pytorch-image-models
timm/models/hub.py
.py
from ._hub import * import warnings warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.models", FutureWarning)
5
141
pytorch-image-models
timm/models/senet.py
.py
""" SEResNet implementation from Cadene's pretrained models https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py Additional credit to https://github.com/creafz Original model: https://github.com/hujie-frank/SENet ResNet code gently borrowed from https://github.com/pytorch/v...
543
20,138
pytorch-image-models
timm/models/xcit.py
.py
""" Cross-Covariance Image Transformer (XCiT) in PyTorch Paper: - https://arxiv.org/abs/2106.09681 Same as the official implementation, with some minor adaptations, original copyright below - https://github.com/facebookresearch/xcit/blob/master/xcit.py Modifications and additions for timm hacked together by ...
1,090
44,565
pytorch-image-models
timm/models/hieradet_sam2.py
.py
import math from copy import deepcopy from functools import partial from typing import Dict, List, Optional, Tuple, Type, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ( PatchEmbed, Mlp, Dr...
701
25,214
pytorch-image-models
timm/models/gcvit.py
.py
""" Global Context ViT From scratch implementation of GCViT in the style of timm swin_transformer_v2_cr.py Global Context Vision Transformers -https://arxiv.org/abs/2206.09959 @article{hatamizadeh2022global, title={Global Context Vision Transformers}, author={Hatamizadeh, Ali and Yin, Hongxu and Kautz, Jan and M...
687
24,868
pytorch-image-models
timm/models/byoanet.py
.py
""" Bring-Your-Own-Attention Network A flexible network w/ dataclass based config for stacking NN blocks including self-attention (or similar) layers. Currently used to implement experimental variants of: * Bottleneck Transformers * Lambda ResNets * HaloNets Consider all of the models definitions here as exper...
478
19,779
pytorch-image-models
timm/models/selecsls.py
.py
"""PyTorch SelecSLS Net example for ImageNet Classification License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/legalcode) Author: Dushyant Mehta (@mehtadushy) SelecSLS (core) Network Architecture as proposed in "XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera, Mehta et al."...
390
13,509
pytorch-image-models
timm/models/_builder.py
.py
import dataclasses import logging import os from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union from torch import nn as nn from torch.hub import load_state_dict_from_url from timm.models._features import FeatureListNet, FeatureDictNet,...
504
21,917
pytorch-image-models
timm/models/dpn.py
.py
""" PyTorch implementation of DualPathNetworks Based on original MXNet implementation https://github.com/cypw/DPNs with many ideas from another PyTorch implementation https://github.com/oyam/pytorch-DPNs. This implementation is compatible with the pretrained weights from cypw's MXNet implementation. Hacked together b...
388
14,067
pytorch-image-models
timm/models/_hub.py
.py
import hashlib import json import logging import os from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import Any, Dict, Iterable, List, Optional, Tuple, Union import torch from torch.hub import HASH_REGEX, download_url_to_file, urlparse try: from torch.hub ...
602
21,714
pytorch-image-models
timm/models/crossvit.py
.py
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
655
26,079
pytorch-image-models
timm/models/deit.py
.py
""" DeiT - Data-efficient Image Transformers DeiT model defs and weights from https://github.com/facebookresearch/deit, original copyright below paper: `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877 paper: `DeiT III: Revenge of the ViT` - https://arxiv.org/abs/2204.07118 Modifications ...
424
19,055
pytorch-image-models
timm/models/ghostnet.py
.py
""" An implementation of GhostNet & GhostNetV2 Models as defined in: GhostNet: More Features from Cheap Operations. https://arxiv.org/abs/1911.11907 GhostNetV2: Enhance Cheap Operation with Long-Range Attention. https://proceedings.neurips.cc/paper_files/paper/2022/file/40b60852a4abdaa696b5a1a78da34635-Paper-Conference...
1,016
36,846
pytorch-image-models
timm/models/focalnet.py
.py
""" FocalNet As described in `Focal Modulation Networks` - https://arxiv.org/abs/2203.11926 Significant modifications and refactoring from the original impl at https://github.com/microsoft/FocalNet This impl is/has: * fully convolutional, NCHW tensor layout throughout, seemed to have minimal performance impact but m...
741
27,245
pytorch-image-models
timm/models/resnetv2.py
.py
"""Pre-Activation ResNet v2 with GroupNorm and Weight Standardization. A PyTorch implementation of ResNetV2 adapted from the Google Big-Transfer (BiT) source code at https://github.com/google-research/big_transfer to match timm interfaces. The BiT weights have been included here as pretrained models from their origina...
1,193
45,851
pytorch-image-models
timm/models/repghost.py
.py
""" An implementation of RepGhostNet Model as defined in: RepGhost: A Hardware-Efficient Ghost Module via Re-parameterization. https://arxiv.org/abs/2211.06088 Original implementation: https://github.com/ChengpengChen/RepGhost """ import copy from functools import partial from typing import List, Optional, Tuple, Unio...
585
20,512
pytorch-image-models
timm/models/mambaout.py
.py
""" MambaOut models for image classification. Some implementations are modified from: timm (https://github.com/rwightman/pytorch-image-models), MetaFormer (https://github.com/sail-sg/metaformer), InceptionNeXt (https://github.com/sail-sg/inceptionnext) """ from collections import OrderedDict from typing import List, Op...
738
24,549
pytorch-image-models
timm/models/resnet.py
.py
"""PyTorch ResNet This started as a copy of https://github.com/pytorch/vision 'resnet.py' (BSD-3-Clause) with additional dropout and dynamic global avg/max pool. ResNeXt, SE-ResNeXt, SENet, and MXNet Gluon stem/downsample variants, tiered stems added by Ross Wightman Copyright 2019, Ross Wightman """ import math fro...
2,267
104,102
pytorch-image-models
timm/models/eva.py
.py
""" EVA EVA ViT from https://github.com/baaivision/EVA , paper: https://arxiv.org/abs/2211.07636 This file contains a number of ViT variants the utilise ROPE position embeddings, SwiGLU and other additions: * EVA & EVA02 model implementations that evolved from BEiT, additional models in vision_transformer.py. * `ti...
3,261
122,388
pytorch-image-models
timm/models/densenet.py
.py
"""Pytorch Densenet implementation w/ tweaks This file is a copy of https://github.com/pytorch/vision 'densenet.py' (BSD-3-Clause) with fixed kwargs passthrough and addition of dynamic global avg/max pool. """ import re from collections import OrderedDict from typing import Any, Dict, Optional, Tuple, Type, Union impo...
564
21,179
pytorch-image-models
timm/models/swin_transformer.py
.py
""" Swin Transformer A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030 Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below S3 (AutoFormerV2, https://arxiv.org/abs/2111.14725) Swin weig...
1,256
49,446
pytorch-image-models
timm/models/gemma4_vit.py
.py
"""Gemma4 Vision Transformer Vision encoder from Google's Gemma 4 multimodal model. Custom ViT with 2D RoPE, Gated MLP, QKV normalization, and 4-norm sandwich blocks. Paper: https://ai.google.dev/gemma/docs/core/model_card_4 Reference impl: https://github.com/huggingface/transformers (Gemma4VisionModel) Copyright 20...
1,486
60,250
pytorch-image-models
timm/models/_efficientnet_builder.py
.py
""" EfficientNet, MobileNetV3, etc Builder Assembles EfficieNet and related network feature blocks from string definitions. Handles stride, dilation calculations, and selects feature extraction points. Hacked together by / Copyright 2019, Ross Wightman """ from typing import Callable, Optional import logging import ...
582
24,025
pytorch-image-models
timm/models/naflexvit.py
.py
""" NaFlex Vision Transformer An improved version of the Vision Transformer with: 1. Encapsulated embedding and position encoding in a single module 2. Support for linear patch embedding on pre-patchified inputs 3. Support for NaFlex variable aspect, variable resolution 4. Support for FlexiViT variable patch size 5. S...
2,393
101,389
pytorch-image-models
timm/models/lcnetv2.py
.py
""" PP-LCNetV2 Reference: https://github.com/PaddlePaddle/PaddleClas/blob/release/2.6/docs/en/models/PP-LCNetV2_en.md The Paddle Implement of PP-LCNetV2 (https://github.com/PaddlePaddle/PaddleClas/blob/release/2.6/ppcls/arch/backbone/legendary_models/pp_lcnet_v2.py) PP-LCNetV2 is a CPU oriented network built on PP-LC...
483
18,308
pytorch-image-models
timm/models/convmixer.py
.py
""" ConvMixer """ from typing import Optional, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipula...
151
4,957
pytorch-image-models
timm/models/tiny_vit.py
.py
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import itertools from functools import partial from typing import Dict, List, ...
880
29,839
pytorch-image-models
timm/models/_pretrained.py
.py
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
95
3,525
pytorch-image-models
timm/models/convnext.py
.py
""" ConvNeXt Papers: * `A ConvNet for the 2020s` - https://arxiv.org/pdf/2201.03545.pdf @Article{liu2022convnet, author = {Zhuang Liu and Hanzi Mao and Chao-Yuan Wu and Christoph Feichtenhofer and Trevor Darrell and Saining Xie}, title = {A ConvNet for the 2020s}, journal = {Proceedings of the IEEE/CVF Confer...
1,438
61,592
pytorch-image-models
timm/models/hiera.py
.py
""" An PyTorch implementation of Hiera Adapted for timm from originals at https://github.com/facebookresearch/hiera """ # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. #...
1,050
38,528
pytorch-image-models
timm/models/__init__.py
.py
from .beit import * from .byoanet import * from .byobnet import * from .cait import * from .coat import * from .convit import * from .convmixer import * from .convnext import * from .cpubone import * from .crossvit import * from .csatv2 import * from .cspnet import * from .davit import * from .deit import * from .dense...
174
5,301
pytorch-image-models
timm/models/vision_transformer_sam.py
.py
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'Exploring Plain Vision Transformer Backbones for Object Detection' - https://arxiv.org/abs/2203.16527 'Segment Anything Model (SAM)' - https://github.com/facebookresearch/segment-anything/ """ import logging...
784
29,095
pytorch-image-models
timm/models/fastvit.py
.py
# FastViT for PyTorch # # Original implementation and weights from https://github.com/apple/ml-fastvit # # For licensing see accompanying LICENSE file at https://github.com/apple/ml-fastvit/tree/main # Original work is copyright (C) 2023 Apple Inc. All Rights Reserved. # import os from functools import partial from typ...
1,808
62,739
pytorch-image-models
timm/models/dla.py
.py
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
609
20,733
pytorch-image-models
timm/models/volo.py
.py
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
1,405
49,338
pytorch-image-models
timm/models/regnet.py
.py
"""RegNet X, Y, Z, and more Paper: `Designing Network Design Spaces` - https://arxiv.org/abs/2003.13678 Original Impl: https://github.com/facebookresearch/pycls/blob/master/pycls/models/regnet.py Paper: `Fast and Accurate Model Scaling` - https://arxiv.org/abs/2103.06877 Original Impl: None Based on original PyTorch...
1,491
56,256
pytorch-image-models
timm/models/rexnet.py
.py
""" ReXNet A PyTorch impl of `ReXNet: Diminishing Representational Bottleneck on Convolutional Neural Network` - https://arxiv.org/abs/2007.00992 Adapted from original impl at https://github.com/clovaai/rexnet Copyright (c) 2020-present NAVER Corp. MIT license Changes for timm, feature extraction, and rounded channe...
605
20,565
pytorch-image-models
timm/models/mvitv2.py
.py
""" Multi-Scale Vision Transformer v2 @inproceedings{li2021improved, title={MViTv2: Improved multiscale vision transformers for classification and detection}, author={Li, Yanghao and Wu, Chao-Yuan and Fan, Haoqi and Mangalam, Karttikeya and Xiong, Bo and Malik, Jitendra and Feichtenhofer, Christoph}, booktitle={...
1,157
41,367
pytorch-image-models
timm/models/_efficientnet_blocks.py
.py
""" EfficientNet, MobileNetV3, etc Blocks Hacked together by / Copyright 2019, Ross Wightman """ from typing import Callable, Dict, Optional, Type, Union import torch import torch.nn as nn from torch.nn import functional as F from timm.layers import ( create_conv2d, DropPath, make_divisible, create_a...
762
27,300
pytorch-image-models
timm/models/mobilenetv3.py
.py
""" MobileNet V3 A PyTorch impl of MobileNet-V3, compatible with TF weights from official impl. Paper: Searching for MobileNetV3 - https://arxiv.org/abs/1905.02244 Hacked together by / Copyright 2019, Ross Wightman """ from functools import partial from typing import Any, Dict, Callable, List, Optional, Tuple, Union...
1,527
61,760
pytorch-image-models
timm/models/_factory.py
.py
import re from pathlib import Path from typing import Any, Dict, Optional, Tuple, Union from torch import nn from timm.layers import set_layer_config from ._helpers import load_checkpoint from ._hub import load_model_config_from_hf, load_model_config_from_path from ._pretrained import PretrainedCfg from ._registry im...
187
8,438