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 | hubconf.py | .py | dependencies = ['torch']
import timm
globals().update(timm.models._registry._model_entrypoints)
| 4 | 96 |
pytorch-image-models | clean_checkpoint.py | .py | #!/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 SHA256
calculation for model zoo compatibility.
Hacked together by / Copyright 2020 Ross Wightman (https:... | 116 | 4,221 |
pytorch-image-models | validate.py | .py | #!/usr/bin/env python3
""" ImageNet Validation Script
This is intended to be a lean and easily modifiable ImageNet validation script for evaluating pretrained
models or training checkpoints against ImageNet or similarly organized image datasets. It prioritizes
canonical PyTorch, standard Python style, and good perform... | 572 | 24,959 |
pytorch-image-models | avg_checkpoints.py | .py | #!/usr/bin/env python3
""" Checkpoint Averaging Script
This script averages all model weights for checkpoints in specified path that match
the 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) tr... | 154 | 5,995 |
pytorch-image-models | legacy_train.py | .py | #!/usr/bin/env python3
""" ImageNet Training Script
This is intended to be a lean and easily modifiable ImageNet training script that reproduces ImageNet
training results with some of the latest networks and training techniques. It favours canonical PyTorch
and standard Python style over trying to be able to 'do it al... | 1,366 | 63,746 |
pytorch-image-models | onnx_validate.py | .py | """ ONNX-runtime validation script
This script was created to verify accuracy and performance of exported ONNX
models running with the onnxruntime. It utilizes the PyTorch dataloader/processing
pipeline for a fair comparison against the originals.
Copyright 2020 Ross Wightman
"""
import argparse
import numpy as np
im... | 111 | 4,544 |
pytorch-image-models | bulk_runner.py | .py | #!/usr/bin/env python3
""" Bulk Model Script Runner
Run validation or benchmark script in separate process for each model
Benchmark all 'vit*' models:
python bulk_runner.py --model-list 'vit*' --results-file vit_bench.csv benchmark.py --amp -b 512
Validate all models:
python bulk_runner.py --model-list all --resul... | 245 | 8,608 |
pytorch-image-models | onnx_export.py | .py | """ ONNX export script
Export PyTorch models as ONNX graphs.
This export script originally started as an adaptation of code snippets found at
https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html
The default parameters work with PyTorch 1.6 and ONNX 1.7 and produce an optimal ONNX graph
for h... | 113 | 5,151 |
pytorch-image-models | convert/convert_from_mxnet.py | .py | import argparse
import hashlib
import os
import mxnet as mx
import gluoncv
import torch
from timm import create_model
parser = argparse.ArgumentParser(description='Convert from MXNet')
parser.add_argument('--model', default='all', type=str, metavar='MODEL',
help='Name of model to train (default: "... | 108 | 4,033 |
pytorch-image-models | convert/convert_gemma4_vit.py | .py | #!/usr/bin/env python3
"""Extract Gemma4 Vision Encoder weights from a full Gemma4 multimodal model.
Uses safetensors lazy loading to avoid loading the full model into memory.
Converts HF Transformers weight keys to timm format.
Usage:
python convert/convert_gemma4_vit.py \
--source google/gemma-4-4b-it \... | 225 | 7,200 |
pytorch-image-models | convert/convert_lcnetv2_paddle.py | .py | """ Convert PP-LCNetV2 weights from PaddleClas to timm
Checkpoints: https://github.com/PaddlePaddle/PaddleClas/blob/release/2.6/docs/en/models/PP-LCNetV2_en.md
NOTE: `paddlepaddle` is required to unpickle the .pdparams files, it is not in requirements.txt
Usage:
python convert/convert_lcnetv2_paddle.py PPLCNetV2_... | 81 | 3,558 |
pytorch-image-models | convert/convert_nest_flax.py | .py | """
Convert weights from https://github.com/google-research/nested-transformer
NOTE: You'll need https://github.com/google/CommonLoopUtils, not included in requirements.txt
"""
import sys
import numpy as np
import torch
from clu import checkpoint
arch_depths = {
'nest_base': [2, 2, 20],
'nest_small': [2, 2... | 109 | 5,582 |
pytorch-image-models | timm/__init__.py | .py | from .version import __version__ as __version__
from .layers import (
is_scriptable as is_scriptable,
is_exportable as is_exportable,
set_scriptable as set_scriptable,
set_exportable as set_exportable,
)
from .models import (
create_model as create_model,
list_models as list_models,
list_pre... | 19 | 604 |
pytorch-image-models | timm/layers/grn.py | .py | """ Global Response Normalization Module
Based on the GRN layer presented in
`ConvNeXt-V2 - Co-designing and Scaling ConvNets with Masked Autoencoders` - https://arxiv.org/abs/2301.00808
This implementation
* works for both NCHW and NHWC tensor layouts
* uses affine param names matching existing torch norm layers
* s... | 48 | 1,505 |
pytorch-image-models | timm/layers/evo_norm.py | .py | """ EvoNorm in PyTorch
Based on `Evolving Normalization-Activation Layers` - https://arxiv.org/abs/2004.02967
@inproceedings{NEURIPS2020,
author = {Liu, Hanxiao and Brock, Andy and Simonyan, Karen and Le, Quoc},
booktitle = {Advances in Neural Information Processing Systems},
editor = {H. Larochelle and M. Ranzato ... | 471 | 16,284 |
pytorch-image-models | timm/layers/split_batchnorm.py | .py | """ Split BatchNorm
A PyTorch BatchNorm layer that splits input batch into N equal parts and passes each through
a separate BN layer. The first split is passed through the parent BN layers with weight/bias
keys the same as the original BN. All other splits pass through BN sub-layers under the '.aux_bn'
namespace.
Thi... | 88 | 3,639 |
pytorch-image-models | timm/layers/layer_scale.py | .py | import torch
from torch import nn
class LayerScale(nn.Module):
""" LayerScale on tensors with channels in last-dim.
"""
def __init__(
self,
dim: int,
init_values: float = 1e-5,
inplace: bool = False,
device=None,
dtype=None,
) -> ... | 55 | 1,483 |
pytorch-image-models | timm/layers/filter_response_norm.py | .py | """ Filter Response Norm in PyTorch
Based on `Filter Response Normalization Layer` - https://arxiv.org/abs/1911.09737
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional, Type
import torch
import torch.nn as nn
from .create_act import create_act_layer
from .trace_utils import _assert
... | 95 | 3,024 |
pytorch-image-models | timm/layers/ml_decoder.py | .py | from typing import Optional
import torch
from torch import nn
from torch import nn, Tensor
from torch.nn.modules.transformer import _get_activation_fn
def add_ml_decoder_head(model):
if hasattr(model, 'global_pool') and hasattr(model, 'fc'): # most CNN models, like Resnet50
model.global_pool = nn.Identi... | 147 | 6,650 |
pytorch-image-models | timm/layers/norm.py | .py | """ Normalization layers and wrappers
Norm layer definitions that support fast norm and consistent channel arg order (always first arg).
Hacked together by / Copyright 2022 Ross Wightman
"""
import numbers
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from .fast_norm im... | 576 | 19,960 |
pytorch-image-models | timm/layers/halo_attn.py | .py | """ Halo Self Attention
Paper: `Scaling Local Self-Attention for Parameter Efficient Visual Backbones`
- https://arxiv.org/abs/2103.12731
@misc{2103.12731,
Author = {Ashish Vaswani and Prajit Ramachandran and Aravind Srinivas and Niki Parmar and Blake Hechtman and
Jonathon Shlens},
Title = {Scaling Local Self... | 271 | 11,501 |
pytorch-image-models | timm/layers/conv2d_same.py | .py | """ Conv2d w/ Same Padding
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, Optional, Union
from ._fx import register_notrace_module
from .config import is_exportable, is_scriptable
from .padding import pad_same, pad_sam... | 143 | 4,043 |
pytorch-image-models | timm/layers/attention_pool2d.py | .py | """ Attention Pool 2D
Implementations of 2D spatial feature pooling using multi-head attention instead of average pool.
Based on idea in CLIP by OpenAI, licensed Apache 2.0
https://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca1657385717/clip/model.py
Hacked together by / Copyright 2021 Ross Wightman
"""... | 313 | 12,847 |
pytorch-image-models | timm/layers/patch_dropout.py | .py | from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
def patch_dropout_forward(
x: torch.Tensor,
prob: float,
num_prefix_tokens: int,
ordered: bool,
training: bool,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
"""
Common forward logic for p... | 108 | 3,031 |
pytorch-image-models | timm/layers/grid.py | .py | from typing import Tuple
import torch
def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]:
"""generate N-D grid in dimension order.
The ndgrid function is like meshgrid except that the order of the first two input arguments are switched.
That is, the statement
[X1,X2,X3] = ndgrid(x1,x2,x3)
produc... | 50 | 1,624 |
pytorch-image-models | timm/layers/classifier.py | .py | """ Classifier head and layer factory
Hacked together by / Copyright 2020 Ross Wightman
"""
from collections import OrderedDict
from functools import partial
from typing import Optional, Union, Callable
import torch
import torch.nn as nn
from torch.nn import functional as F
from .adaptive_avgmax_pool import SelectAd... | 301 | 11,017 |
pytorch-image-models | timm/layers/format.py | .py | from enum import Enum
from typing import Union
import torch
class Format(str, Enum):
NCHW = 'NCHW'
NHWC = 'NHWC'
NCL = 'NCL'
NLC = 'NLC'
FormatT = Union[str, Format]
def get_spatial_dim(fmt: FormatT):
"""Return spatial dimension indices for a given tensor format.
Args:
fmt: Tenso... | 93 | 1,880 |
pytorch-image-models | timm/layers/blur_pool.py | .py | """
BlurPool layer inspired by
- Kornia's Max_BlurPool2d
- Making Convolutional Networks Shift-Invariant Again :cite:`zhang2019shiftinvar`
Hacked together by Chris Ha and Ross Wightman
"""
from functools import partial
from math import comb # Python 3.8
from typing import Callable, Optional, Type, Union
import tor... | 156 | 5,731 |
pytorch-image-models | timm/layers/cbam.py | .py | """ CBAM (sort-of) Attention
Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521
WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on
some tasks, especially fine-grained it seems. I may end up removing this impl.
Hack... | 182 | 5,971 |
pytorch-image-models | timm/layers/create_norm_act.py | .py | """ NormAct (Normalization + Activation Layer) Factory
Create norm + act combo modules that attempt to be backwards compatible with separate norm + act
instances in models. Where these are used it will be possible to swap separate BN + act layers with
combined modules like IABN or EvoNorms.
Hacked together by / Copyr... | 146 | 4,668 |
pytorch-image-models | timm/layers/attention_pool.py | .py | from typing import Optional, Type
import torch
import torch.nn as nn
import torch.nn.functional as F
from .attention import maybe_add_mask
from .config import use_fused_attn
from .mlp import Mlp
from .weight_init import trunc_normal_tf_
class AttentionPoolLatent(nn.Module):
""" Attention pooling w/ latent query... | 203 | 7,439 |
pytorch-image-models | timm/layers/attention.py | .py | from typing import Final, Optional, Type
import torch
from torch import nn as nn
from torch.nn import functional as F
from ._fx import register_notrace_function
from .config import use_fused_attn
from .pos_embed_sincos import apply_rot_embed_cat
__all__ = ['Attention', 'AttentionRope', 'maybe_add_mask', 'resolve_se... | 294 | 12,083 |
pytorch-image-models | timm/layers/median_pool.py | .py | """ Median Pool
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch.nn as nn
import torch.nn.functional as F
from .helpers import to_2tuple, to_4tuple
class MedianPool2d(nn.Module):
""" Median pool (usable as median filter when stride=1) module.
Args:
kernel_size: size of pooling kern... | 50 | 1,719 |
pytorch-image-models | timm/layers/linear.py | .py | """ Linear layer (alternate definition)
"""
import torch
import torch.nn.functional as F
from torch import nn as nn
class Linear(nn.Linear):
r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
Wraps torch.nn.Linear to support AMP + torchscript usage by manually casting
weight &... | 20 | 743 |
pytorch-image-models | timm/layers/separable_conv.py | .py | """ Depthwise Separable Conv Modules
Basic DWS convs. Other variations of DWS exist with batch norm or activations between the
DW and PW convs such as the Depthwise modules in MobileNetV2 / EfficientNet and Xception.
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import Optional, Type, Union
from ... | 134 | 3,531 |
pytorch-image-models | timm/layers/other_pool.py | .py | """ Non-Local Attention Pooling Layers
A collection of global pooling layers that go beyond simple avg/max pooling.
LSEPool - LogSumExp pooling, a smooth approximation between avg and max pooling
SimPool - Attention-based pooling from 'Keep It SimPool' (ICCV 2023)
Based on implementations from:
* LSE Pooling: custom... | 287 | 10,543 |
pytorch-image-models | timm/layers/__init__.py | .py | from ._fx import (
create_feature_extractor,
get_graph_node_names,
register_notrace_function,
register_notrace_module,
is_notrace_module,
is_notrace_function,
get_notrace_modules,
get_notrace_functions,
)
from .activations import *
from .adaptive_avgmax_pool import (
adaptive_avgmax_... | 162 | 5,424 |
pytorch-image-models | timm/layers/norm_act.py | .py | """ Normalization + Activation Layers
Provides Norm+Act fns for standard PyTorch norm layers such as
* BatchNorm
* GroupNorm
* LayerNorm
This allows swapping with alternative layers that are natively both norm + act such as
* EvoNorm (evo_norm.py)
* FilterResponseNorm (filter_response_norm.py)
* InplaceABN (inplace_a... | 691 | 26,224 |
pytorch-image-models | timm/layers/patch_embed.py | .py | """ Image to Patch Embedding using Conv2d
A convolution based approach to patchifying a 2D image w/ embedding projection.
Based on code in:
* https://github.com/google-research/vision_transformer
* https://github.com/google-research/big_vision/tree/main/big_vision
Hacked together by / Copyright 2020 Ross Wightma... | 721 | 28,392 |
pytorch-image-models | timm/layers/hybrid_embed.py | .py | """ Image to Patch Hybird Embedding Layer
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
import math
from typing import List, Optional, Tuple, Union
import torch
from torch import nn as nn
import torch.nn.functional as F
from .format import Format, nchw_to
from .helpers import to_2tuple
from .p... | 268 | 10,460 |
pytorch-image-models | timm/layers/create_act.py | .py | """ Activation Factory
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import Callable, Optional, Type, Union
from .activations import *
from .activations_me import *
from .config import is_exportable, is_scriptable
from .typing import LayerType
# PyTorch has an optimized, native 'silu' (aka 'swish'... | 144 | 4,549 |
pytorch-image-models | timm/layers/coord_attn.py | .py | """ Coordinate Attention and Variants
Coordinate Attention decomposes channel attention into two 1D feature encoding processes
to capture long-range dependencies with precise positional information. This module includes
the original implementation along with simplified and other variants.
Papers / References:
- Coord... | 342 | 12,047 |
pytorch-image-models | timm/layers/selective_kernel.py | .py | """ Selective Kernel Convolution/Attention
Paper: Selective Kernel Networks (https://arxiv.org/abs/1903.06586)
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import List, Optional, Tuple, Type, Union
import torch
from torch import nn as nn
from .conv_bn_act import ConvNormAct
from .helpers import... | 150 | 6,022 |
pytorch-image-models | timm/layers/space_to_depth.py | .py | import torch
import torch.nn as nn
class SpaceToDepth(nn.Module):
"""Rearrange spatial dimensions into channel dimension.
Divides spatial dimensions by block_size and multiplies channels by block_size^2.
Used in TResNet as an efficient stem operation.
Args:
block_size: Spatial reduction fact... | 49 | 1,580 |
pytorch-image-models | timm/layers/pos_embed_sincos.py | .py | """ Sin-cos, fourier, rotary position embedding modules and functions
Hacked together by / Copyright 2022 Ross Wightman
"""
import math
from typing import List, Tuple, Optional, Union
import torch
from torch import nn as nn
from ._fx import register_notrace_function
from .grid import ndgrid
from .trace_utils import ... | 1,358 | 52,752 |
pytorch-image-models | timm/layers/bottleneck_attn.py | .py | """ Bottleneck Self Attention (Bottleneck Transformers)
Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605
@misc{2101.11605,
Author = {Aravind Srinivas and Tsung-Yi Lin and Niki Parmar and Jonathon Shlens and Pieter Abbeel and Ashish Vaswani},
Title = {Bottleneck Transformers f... | 186 | 7,626 |
pytorch-image-models | timm/layers/lambda_layer.py | .py | """ Lambda Layer
Paper: `LambdaNetworks: Modeling Long-Range Interactions Without Attention`
- https://arxiv.org/abs/2102.08602
@misc{2102.08602,
Author = {Irwan Bello},
Title = {LambdaNetworks: Modeling Long-Range Interactions Without Attention},
Year = {2021},
}
Status:
This impl is a WIP. Code snippets in the... | 176 | 7,158 |
pytorch-image-models | timm/layers/gather_excite.py | .py | """ Gather-Excite Attention Block
Paper: `Gather-Excite: Exploiting Feature Context in CNNs` - https://arxiv.org/abs/1810.12348
Official code here, but it's only partial impl in Caffe: https://github.com/hujie-frank/GENet
I've tried to support all of the extent both w/ and w/o params. I don't believe I've seen anoth... | 106 | 4,268 |
pytorch-image-models | timm/layers/std_conv.py | .py | """ Convolution with Weight Standardization (StdConv and ScaledStdConv)
StdConv:
@article{weightstandardization,
author = {Siyuan Qiao and Huiyu Wang and Chenxi Liu and Wei Shen and Alan Yuille},
title = {Weight Standardization},
journal = {arXiv preprint arXiv:1903.10520},
year = {2019},
}
Code:... | 233 | 8,672 |
pytorch-image-models | timm/layers/attention2d.py | .py | from typing import List, Optional, Type, Union
import torch
from torch import nn as nn
from torch.nn import functional as F
from .config import use_fused_attn
from .create_conv2d import create_conv2d
from .helpers import to_2tuple
from .pool2d_same import create_pool2d
class MultiQueryAttentionV2(nn.Module):
""... | 381 | 13,730 |
pytorch-image-models | timm/layers/squeeze_excite.py | .py | """ Squeeze-and-Excitation Channel Attention
An SE implementation originally based on PyTorch SE-Net impl.
Has since evolved with additional functionality / configuration.
Paper: `Squeeze-and-Excitation Networks` - https://arxiv.org/abs/1709.01507
Also included is Effective Squeeze-Excitation (ESE).
Paper: `CenterMa... | 135 | 5,208 |
pytorch-image-models | timm/layers/trace_utils.py | .py | try:
from torch import _assert
except ImportError:
def _assert(condition: bool, message: str):
assert condition, message
def _float_to_int(x: float) -> int:
"""
Symbolic tracing helper to substitute for inbuilt `int`.
Hint: Inbuilt `int` can't accept an argument of type `Proxy`
"""
... | 14 | 335 |
pytorch-image-models | timm/layers/pool2d_same.py | .py | """ AvgPool2d w/ Same Padding
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List, Tuple, Optional, Union
from ._fx import register_notrace_module
from .helpers import to_2tuple
from .padding import pad_same, get_padding_valu... | 102 | 3,613 |
pytorch-image-models | timm/layers/mlp.py | .py | """ MLP module w/ dropout and configurable activation layer
Hacked together by / Copyright 2020 Ross Wightman
"""
from functools import partial
from typing import Optional, Type, Union, Tuple
from torch import nn as nn
from .grn import GlobalResponseNorm
from .helpers import to_2tuple
class Mlp(nn.Module):
"""... | 291 | 10,659 |
pytorch-image-models | timm/layers/create_attn.py | .py | """ Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .coord_attn import CoordAttn, EfficientLocalAttn, StripAttn, SimpleCoordAttn
from .eca import EcaModule,... | 99 | 3,922 |
pytorch-image-models | timm/layers/pos_embed_rel.py | .py | """ Relative position embedding modules and functions
Hacked together by / Copyright 2022 Ross Wightman
"""
import math
import os
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from .grid import ndgrid
from .interpolate import RegularGridInterpolator
from .mlp i... | 588 | 22,813 |
pytorch-image-models | timm/layers/test_time_pool.py | .py | """ Test Time Pooling (Average-Max Pool)
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
from torch import nn
import torch.nn.functional as F
from .adaptive_avgmax_pool import adaptive_avgmax_pool2d
_logger = logging.getLogger(__name__)
class TestTimePoolHead(nn.Module):
def __init__(sel... | 53 | 1,974 |
pytorch-image-models | timm/layers/eca.py | .py | """
ECA module from ECAnet
paper: ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks
https://arxiv.org/abs/1910.03151
Original ECA model borrowed from https://github.com/BangguWu/ECANet
Modified circular ECA implementation and adaption for use in timm package
by Chris Ha https://github.com/V... | 171 | 7,065 |
pytorch-image-models | timm/layers/fast_norm.py | .py | """ 'Fast' Normalization Functions
For GroupNorm and LayerNorm these functions bypass typical AMP upcast to float32.
Additionally, for LayerNorm, the APEX fused LN is used if available (which also does not upcast)
Hacked together by / Copyright 2022 Ross Wightman
"""
from typing import List, Optional
import torch
f... | 260 | 8,454 |
pytorch-image-models | timm/layers/drop.py | .py | """ DropBlock, DropPath
PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers.
Papers:
DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890)
Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603.09382)
Code:
DropBlock impl ins... | 232 | 8,956 |
pytorch-image-models | timm/layers/padding.py | .py | """ Padding Helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
from typing import List, Tuple, Union
import torch
import torch.nn.functional as F
from .helpers import to_2tuple
# Calculate symmetric padding for a convolution
def get_padding(kernel_size: int, stride: int = 1, dilation: int = ... | 88 | 3,471 |
pytorch-image-models | timm/layers/adaptive_avgmax_pool.py | .py | """ PyTorch selectable adaptive pooling
Adaptive pooling with the ability to select the type of pooling from:
* 'avg' - Average pooling
* 'max' - Max pooling
* 'avgmax' - Sum of average and max pooling re-scaled by 0.5
* 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea... | 184 | 6,393 |
pytorch-image-models | timm/layers/weight_init.py | .py | import torch
import math
import warnings
from torch import nn
from torch.nn.init import _calculate_fan_in_and_fan_out
def is_meta_device(device) -> bool:
"""Check if targeting meta device (explicit arg or context manager)."""
if device is not None:
return str(device) == 'meta'
# Check context mana... | 179 | 6,619 |
pytorch-image-models | timm/layers/pool1d.py | .py | import torch
def global_pool_nlc(
x: torch.Tensor,
pool_type: str = 'token',
num_prefix_tokens: int = 1,
reduce_include_prefix: bool = False,
):
"""Apply global pooling to tensor in NLC format.
Args:
x: Input tensor in (batch, length, channels) format.
pool_typ... | 37 | 1,098 |
pytorch-image-models | timm/layers/cond_conv2d.py | .py | """ PyTorch Conditionally Parameterized Convolution (CondConv)
Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference
(https://arxiv.org/abs/1904.04971)
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
from functools import partial
from typing import Union, Tuple
import t... | 140 | 5,645 |
pytorch-image-models | timm/layers/global_context.py | .py | """ Global Context Attention Block
Paper: `GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond`
- https://arxiv.org/abs/1904.11492
Official code consulted as reference: https://github.com/xvjiarui/GCNet
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional, Tuple, Ty... | 85 | 2,832 |
pytorch-image-models | timm/layers/create_conv2d.py | .py | """ Create Conv2d Factory Method
Hacked together by / Copyright 2020 Ross Wightman
"""
from .mixed_conv2d import MixedConv2d
from .cond_conv2d import CondConv2d
from .conv2d_same import create_conv2d_pad
def create_conv2d(in_channels, out_channels, kernel_size, **kwargs):
""" Select a 2d convolution implementat... | 37 | 1,622 |
pytorch-image-models | timm/layers/create_norm.py | .py | """ Norm Layer Factory
Create norm modules by string (to mirror create_act and creat_norm-act fns)
Copyright 2022 Ross Wightman
"""
import functools
import types
from typing import Type
import torch.nn as nn
from .norm import (
GroupNorm,
GroupNorm1,
LayerNorm,
LayerNorm2d,
LayerNormFp32,
La... | 82 | 2,062 |
pytorch-image-models | timm/layers/typing.py | .py | from contextlib import nullcontext
from functools import wraps
from typing import Callable, Optional, Tuple, Type, TypeVar, Union, overload, ContextManager
import torch
__all__ = ["LayerType", "PadType", "nullwrap", "disable_compiler"]
LayerType = Union[str, Callable, Type[torch.nn.Module]]
PadType = Union[str, int... | 35 | 903 |
pytorch-image-models | timm/layers/helpers.py | .py | """ Layer/Module Helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
from itertools import repeat
import collections.abc
# From PyTorch internals
def _ntuple(n):
"""Return a function that converts input to an n-tuple.
Scalar values are repeated n times, while iterables are converted to tuples.
... | 80 | 2,116 |
pytorch-image-models | timm/layers/diff_attention.py | .py | """Differential Attention
Paper: 'Differential Transformer' - https://arxiv.org/abs/2410.05258
Reference impl: https://github.com/microsoft/unilm/tree/master/Diff-Transformer
Hacked together by / Copyright 2024, Ross Wightman
"""
import math
from typing import Optional, Type
import torch
import torch.nn as nn
impor... | 180 | 7,338 |
pytorch-image-models | timm/layers/config.py | .py | """ Model / Layer Config singleton state
"""
import os
import warnings
from typing import Any, Optional
import torch
__all__ = [
'is_exportable', 'is_scriptable', 'is_no_jit', 'use_fused_attn',
'set_exportable', 'set_scriptable', 'set_no_jit', 'set_layer_config', 'set_fused_attn',
'set_reentrant_ckpt', 'u... | 166 | 4,577 |
pytorch-image-models | timm/layers/interpolate.py | .py | """ Interpolation helpers for timm layers
RegularGridInterpolator from https://github.com/sbarratt/torch_interpolations
Copyright Shane Barratt, Apache 2.0 license
"""
import torch
from itertools import product
class RegularGridInterpolator:
""" Interpolate data defined on a rectilinear grid with even or uneven ... | 69 | 2,439 |
pytorch-image-models | timm/layers/inplace_abn.py | .py | import torch
from torch import nn as nn
try:
from inplace_abn.functions import inplace_abn, inplace_abn_sync
has_iabn = True
except ImportError:
has_iabn = False
def inplace_abn(x, weight, bias, running_mean, running_var,
training=True, momentum=0.1, eps=1e-05, activation="leaky_re... | 100 | 3,523 |
pytorch-image-models | timm/layers/activations.py | .py | """ Activations
A collection of activations fn and modules with a common interface so that they can
easily be swapped. All have an `inplace` arg even if not used.
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from torch import nn as nn
from torch.nn import functional as F
def swish(x, inplace:... | 174 | 4,740 |
pytorch-image-models | timm/layers/mixed_conv2d.py | .py | """ PyTorch Mixed Convolution
Paper: MixConv: Mixed Depthwise Convolutional Kernels (https://arxiv.org/abs/1907.09595)
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import List, Union
import torch
from torch import nn as nn
from .conv2d_same import create_conv2d_pad
def _split_channels(num_cha... | 69 | 2,156 |
pytorch-image-models | timm/layers/conv_bn_act.py | .py | """ Conv2d + BN + Act
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import Any, Dict, Optional, Type
from torch import nn as nn
from .typing import LayerType, PadType
from .blur_pool import create_aa
from .create_conv2d import create_conv2d
from .create_norm_act import get_norm_act_layer
class ... | 103 | 3,100 |
pytorch-image-models | timm/layers/non_local_attn.py | .py | """ Bilinear-Attention-Transform and Non-Local Attention
Paper: `Non-Local Neural Networks With Grouped Bilinear Attentional Transforms`
- https://openaccess.thecvf.com/content_CVPR_2020/html/Chi_Non-Local_Neural_Networks_With_Grouped_Bilinear_Attentional_Transforms_CVPR_2020_paper.html
Adapted from original code:... | 190 | 7,149 |
pytorch-image-models | timm/layers/activations_me.py | .py | """ Activations (memory-efficient w/ custom autograd)
A collection of activations fn and modules with a common interface so that they can
easily be swapped. All have an `inplace` arg even if not used.
These activations are not compatible with jit scripting or ONNX export of the model, please use
basic versions of the... | 209 | 5,427 |
pytorch-image-models | timm/layers/_fx.py | .py | from typing import Callable, Dict, List, Optional, Union, Tuple, Type
import torch
from torch import nn
try:
# NOTE we wrap torchvision fns to use timm leaf / no trace definitions
from torchvision.models.feature_extraction import create_feature_extractor as _create_feature_extractor
from torchvision.model... | 81 | 2,220 |
pytorch-image-models | timm/layers/pos_embed.py | .py | """ Position Embedding Utilities
Hacked together by / Copyright 2022 Ross Wightman
"""
import logging
import math
from typing import List, Tuple, Optional, Union
import torch
import torch.nn.functional as F
from ._fx import register_notrace_function
_logger = logging.getLogger(__name__)
@torch.fx.wrap
@register_n... | 87 | 2,835 |
pytorch-image-models | timm/layers/split_attn.py | .py | """ Split Attention Conv2d (for ResNeSt Models)
Paper: `ResNeSt: Split-Attention Networks` - /https://arxiv.org/abs/2004.08955
Adapted from original PyTorch impl at https://github.com/zhanghang1989/ResNeSt
Modified for torchscript compat, performance, and consistency with timm by Ross Wightman
"""
from typing import... | 113 | 3,688 |
pytorch-image-models | timm/loss/binary_cross_entropy.py | .py | """ Binary Cross Entropy w/ a few extras
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
class BinaryCrossEntropy(nn.Module):
""" BCE with optional one-hot from dense targets, label smoothing, thresholdin... | 66 | 2,483 |
pytorch-image-models | timm/loss/jsd.py | .py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .cross_entropy import LabelSmoothingCrossEntropy
class JsdCrossEntropy(nn.Module):
""" Jensen-Shannon Divergence + Cross-Entropy Loss
Based on impl here: https://github.com/google-research/augmix/blob/master/imagenet.py
From paper: ... | 40 | 1,595 |
pytorch-image-models | timm/loss/cross_entropy.py | .py | """ Cross Entropy w/ smoothing or soft targets
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class LabelSmoothingCrossEntropy(nn.Module):
""" NLL loss with label smoothing.
"""
def __init__(self, smoothing=0.1):
super(Lab... | 37 | 1,145 |
pytorch-image-models | timm/loss/asymmetric_loss.py | .py | import torch
import torch.nn as nn
class AsymmetricLossMultiLabel(nn.Module):
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-8, disable_torch_grad_focal_loss=False):
super(AsymmetricLossMultiLabel, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma_pos
... | 98 | 3,240 |
pytorch-image-models | timm/scheduler/scheduler.py | .py | import abc
from abc import ABC
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
class Scheduler(ABC):
""" Parameter Scheduler Base Class
A scheduler base class that can be used to schedule any optimizer parameter groups.
Unlike the builtin PyTorch schedulers, this is intended to b... | 128 | 5,631 |
pytorch-image-models | timm/scheduler/poly_lr.py | .py | """ Polynomial Scheduler
Polynomial LR schedule with warmup, noise.
Hacked together by / Copyright 2021 Ross Wightman
"""
import math
import logging
from typing import List, Tuple, Union
import torch
from .scheduler import Scheduler
_logger = logging.getLogger(__name__)
class PolyLRScheduler(Scheduler):
"""... | 114 | 3,910 |
pytorch-image-models | timm/scheduler/plateau_lr.py | .py | """ Plateau Scheduler
Adapts PyTorch plateau scheduler and allows application of noise, warmup.
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from typing import Any, Dict, List, Optional, Tuple, Union
from .scheduler import Scheduler
class PlateauLRScheduler(Scheduler):
"""Decay the LR by ... | 112 | 3,935 |
pytorch-image-models | timm/scheduler/cosine_lr.py | .py | """ Cosine Scheduler
Cosine LR schedule with warmup, cycle/restarts, noise, k-decay.
Hacked together by / Copyright 2021 Ross Wightman
"""
import logging
import math
import numpy as np
import torch
from typing import Tuple, List, Union
from .scheduler import Scheduler
_logger = logging.getLogger(__name__)
class ... | 118 | 4,080 |
pytorch-image-models | timm/scheduler/tanh_lr.py | .py | """ TanH Scheduler
TanH schedule with warmup, cycle/restarts, noise.
Hacked together by / Copyright 2021 Ross Wightman
"""
import logging
import math
import numpy as np
import torch
from typing import List, Tuple, Union
from .scheduler import Scheduler
_logger = logging.getLogger(__name__)
class TanhLRScheduler(... | 115 | 3,835 |
pytorch-image-models | timm/scheduler/step_lr.py | .py | """ Step Scheduler
Basic step LR schedule with warmup, noise.
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
import torch
from typing import List, Tuple, Union
from .scheduler import Scheduler
class StepLRScheduler(Scheduler):
"""
"""
def __init__(
self,
opt... | 64 | 1,905 |
pytorch-image-models | timm/scheduler/scheduler_factory.py | .py | """ Scheduler Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import List, Optional, Union
from torch.optim import Optimizer
from .cosine_lr import CosineLRScheduler
from .multistep_lr import MultiStepLRScheduler
from .plateau_lr import PlateauLRScheduler
from .poly_lr import PolyLRScheduler... | 211 | 6,934 |
pytorch-image-models | timm/scheduler/multistep_lr.py | .py | """ MultiStep LR Scheduler
Basic multi step LR schedule with warmup, noise.
"""
import torch
import bisect
from timm.scheduler.scheduler import Scheduler
from typing import List, Tuple, Union
class MultiStepLRScheduler(Scheduler):
"""
"""
def __init__(
self,
optimizer: torch.optim... | 64 | 2,078 |
pytorch-image-models | timm/utils/jit.py | .py | """ JIT scripting/tracing utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import os
import torch
def set_jit_legacy():
""" Set JIT executor to legacy w/ support for op fusion
This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes
in the JIT executor. These ... | 59 | 2,202 |
pytorch-image-models | timm/utils/misc.py | .py | """ Misc utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import argparse
import ast
import re
def natural_key(string_):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())]
def add_bool_arg(parser, nam... | 35 | 1,156 |
pytorch-image-models | timm/utils/model_ema.py | .py | """ Exponential Moving Average (EMA) of model updates
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
from collections import OrderedDict
from copy import deepcopy
from typing import Optional
import torch
import torch.nn as nn
_logger = logging.getLogger(__name__)
class ModelEma:
""" Model... | 262 | 11,395 |
pytorch-image-models | timm/utils/distributed.py | .py | """ Distributed training/validation utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
import os
from typing import Optional
import torch
from torch import distributed as dist
from .model import unwrap_model
_logger = logging.getLogger(__name__)
def reduce_tensor(tensor, n):
rt = tenso... | 183 | 5,918 |
pytorch-image-models | timm/utils/model.py | .py | """ Model / state_dict utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import fnmatch
from copy import deepcopy
import torch
from torchvision.ops.misc import FrozenBatchNorm2d
from timm.layers import BatchNormAct2d, SyncBatchNormAct, FrozenBatchNormAct2d,\
freeze_batch_norm_2d, unfreeze_batch_norm_2d... | 249 | 10,577 |
pytorch-image-models | timm/utils/attention_extract.py | .py | import fnmatch
import re
from collections import OrderedDict
from typing import Union, Optional, List
import torch
class AttentionExtract(torch.nn.Module):
# defaults should cover a significant number of timm models with attention maps.
default_node_names = ['*attn.softmax']
default_module_names = ['*att... | 86 | 3,226 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.