repo_id stringlengths 15 89 | file_path stringlengths 27 180 | content stringlengths 1 2.23M | __index_level_0__ int64 0 0 |
|---|---|---|---|
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/pool2d_same.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
from .helpers import to_2tuple
from .padding import pad_same, get_padding_value
def avg_pool2d_same(x, kernel_size: List[int... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/activations.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:... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/activations_me.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 either
the JIT or bas... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/attention_pool2d.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
"""... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/typing.py | from typing import Callable, Tuple, Type, Union
import torch
LayerType = Union[str, Callable, Type[torch.nn.Module]]
PadType = Union[str, int, Tuple[int, int]]
| 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/config.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 to True if prefer to... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/create_attn.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 .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Gl... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/conv_bn_act.py | """ Conv2d + BN + Act
Hacked together by / Copyright 2020 Ross Wightman
"""
import functools
from torch import nn as nn
from .create_conv2d import create_conv2d
from .create_norm_act import get_norm_act_layer
class ConvNormAct(nn.Module):
def __init__(
self,
in_channels,
out_... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/grn.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/split_batchnorm.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/test_time_pool.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/lambda_layer.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/activations_jit.py | """ Activations
A collection of jit-scripted activations fn and modules with a common interface so that they can
easily be swapped. All have an `inplace` arg even if not used.
All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not
currently work across in-place op bou... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/mlp.py | """ MLP module w/ dropout and configurable activation layer
Hacked together by / Copyright 2020 Ross Wightman
"""
from functools import partial
from torch import nn as nn
from .grn import GlobalResponseNorm
from .helpers import to_2tuple
class Mlp(nn.Module):
""" MLP as used in Vision Transformer, MLP-Mixer an... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/create_conv2d.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/pos_embed.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 .helpers import to_2tuple
_logger = logging.getLogger(__name__)
def resample_abs_pos_embed(
po... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/create_act.py | """ Activation Factory
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import Union, Callable, Type
from .activations import *
from .activations_jit import *
from .activations_me import *
from .config import is_exportable, is_scriptable, is_no_jit
# PyTorch has an optimized, native 'silu' (aka 'swis... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/halo_attn.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/adaptive_avgmax_pool.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/classifier.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/__init__.py | from .activations import *
from .adaptive_avgmax_pool import \
adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d
from .attention_pool import AttentionPoolLatent
from .attention_pool2d import AttentionPool2d, RotAttentionPool2d, RotaryEmbedding
from .blur_pool import BlurPool... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/interpolate.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 ... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/ml_decoder.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/non_local_attn.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:... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/evo_norm.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 ... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/conv2d_same.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
from .config import is_exportable, is_scriptable
from .padding import pad_same, pad_same_arg, get_padding_value
_USE_EXPORT_CONV = Fa... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/patch_dropout.py | from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
class PatchDropout(nn.Module):
"""
https://arxiv.org/abs/2212.00794
"""
return_indices: torch.jit.Final[bool]
def __init__(
self,
prob: float = 0.5,
num_prefix_tokens: int = 1,
... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/gather_excite.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/linear.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 &... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/norm.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/trace_utils.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`
"""
... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/create_norm_act.py | """ NormAct (Normalizaiton + Activation Layer) Factory
Create norm + act combo modules that attempt to be backwards compatible with separate norm + act
isntances 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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/pos_embed_sincos.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 .trace_utils import _assert
def pixel_freq_bands(
num_bands: int,
max_... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/bottleneck_attn.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/split_attn.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
"""
import torch
impor... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/squeeze_excite.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/cond_conv2d.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
import numpy as np
import torch
from torc... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/cbam.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/mixed_conv2d.py | """ PyTorch Mixed Convolution
Paper: MixConv: Mixed Depthwise Convolutional Kernels (https://arxiv.org/abs/1907.09595)
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from torch import nn as nn
from .conv2d_same import create_conv2d_pad
def _split_channels(num_chan, num_groups):
split = [nu... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/format.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):
fmt = Format(fmt)
if fmt is Format.NLC:
dim = (1,)
elif fmt is Format.NCL:
... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/separable_conv.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 torch import nn as nn
from .create_conv2d... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/fast_norm.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/selective_kernel.py | """ Selective Kernel Convolution/Attention
Paper: Selective Kernel Networks (https://arxiv.org/abs/1903.06586)
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from torch import nn as nn
from .conv_bn_act import ConvNormActAa
from .helpers import make_divisible
from .trace_utils import _assert
de... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/patch_embed.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/create_norm.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, RmsNorm
from torchvision.ops.misc import Fr... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/padding.py | """ Padding Helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
from typing import List, Tuple
import torch
import torch.nn.functional as F
# Calculate symmetric padding for a convolution
def get_padding(kernel_size: int, stride: int = 1, dilation: int = 1, **_) -> int:
padding = ((stride ... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/global_context.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 torch import nn as nn
import torc... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/norm_act.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/attention_pool.py | from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
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
"""
fused_attn: torch.jit.Final[boo... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/layers/pos_embed_rel.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 .interpolate import RegularGridInterpolator
from .mlp import Mlp
from .weight_in... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/loss/asymmetric_loss.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
... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/loss/jsd.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: ... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/loss/__init__.py | from .asymmetric_loss import AsymmetricLossMultiLabel, AsymmetricLossSingleLabel
from .binary_cross_entropy import BinaryCrossEntropy
from .cross_entropy import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from .jsd import JsdCrossEntropy
| 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/loss/cross_entropy.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... | 0 |
hf_public_repos/pytorch-image-models/timm | hf_public_repos/pytorch-image-models/timm/loss/binary_cross_entropy.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... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/convert/convert_nest_flax.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... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/convert/convert_from_mxnet.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: "... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/tests/test_models.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 ... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/tests/test_optim.py | """ Optimzier Tests
These tests were adapted from PyTorch' optimizer tests.
"""
import math
import pytest
import functools
from copy import deepcopy
import torch
from torch.testing._internal.common_utils import TestCase
from torch.nn import Parameter
from timm.scheduler import PlateauLRScheduler
from timm.optim imp... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/tests/test_layers.py | import torch
import torch.nn as nn
from timm.layers import create_act_layer, set_layer_config
import importlib
import os
torch_backend = os.environ.get('TORCH_BACKEND')
if torch_backend is not None:
importlib.import_module(torch_backend)
torch_device = os.environ.get('TORCH_DEVICE', 'cpu')
class MLP(nn.Module):... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/tests/test_utils.py | from torch.nn.modules.batchnorm import BatchNorm2d
from torchvision.ops.misc import FrozenBatchNorm2d
import timm
from timm.utils.model import freeze, unfreeze
def test_freeze_unfreeze():
model = timm.create_model('resnet18')
# Freeze all
freeze(model)
# Check top level module
assert model.fc.we... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/archived_changes.md | # Archived Changes
### Nov 22, 2021
* A number of updated weights anew new model defs
* `eca_halonext26ts` - 79.5 @ 256
* `resnet50_gn` (new) - 80.1 @ 224, 81.3 @ 288
* `resnet50` - 80.7 @ 224, 80.9 @ 288 (trained at 176, not replacing current a1 weights as default since these don't scale as well to higher res, ... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/results.md | # Results
CSV files containing an ImageNet-1K and out-of-distribution (OOD) test set validation results for all models with pretrained weights is located in the repository [results folder](https://github.com/rwightman/pytorch-image-models/tree/master/results).
## Self-trained Weights
The table below includes ImageNe... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/scripts.md | # Scripts
A train, validation, inference, and checkpoint cleaning script included in the github root folder. Scripts are not currently packaged in the pip release.
The training and validation scripts evolved from early versions of the [PyTorch Imagenet Examples](https://github.com/pytorch/examples). I have added signi... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/index.md | # Getting Started
## Welcome
Welcome to the `timm` documentation, a lean set of docs that covers the basics of `timm`.
For a more comprehensive set of docs (currently under development), please visit [timmdocs](http://timm.fast.ai) by [Aman Arora](https://github.com/amaarora).
## Install
The library can be install... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/training_hparam_examples.md | # Training Examples
## EfficientNet-B2 with RandAugment - 80.4 top-1, 95.1 top-5
These params are for dual Titan RTX cards with NVIDIA Apex installed:
`./distributed_train.sh 2 /imagenet/ --model efficientnet_b2 -b 128 --sched step --epochs 450 --decay-epochs 2.4 --decay-rate .97 --opt rmsproptf --opt-eps .001 -j 8 -... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/changes.md | # Recent Changes
### Aug 29, 2022
* MaxVit window size scales with img_size by default. Add new RelPosMlp MaxViT weight that leverages this:
* `maxvit_rmlp_nano_rw_256` - 83.0 @ 256, 83.6 @ 320 (T)
### Aug 26, 2022
* CoAtNet (https://arxiv.org/abs/2106.04803) and MaxVit (https://arxiv.org/abs/2204.01697) `timm` or... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/feature_extraction.md | # Feature Extraction
All of the models in `timm` have consistent mechanisms for obtaining various types of features from the model for tasks besides classification.
## Penultimate Layer Features (Pre-Classifier Features)
The features from the penultimate model layer can be obtained in several ways without requiring ... | 0 |
hf_public_repos/pytorch-image-models | hf_public_repos/pytorch-image-models/docs/models.md | # Model Summaries
The model architectures included come from a wide variety of sources. Sources, including papers, original impl ("reference code") that I rewrote / adapted, and PyTorch impl that I leveraged directly ("code") are listed below.
Most included models have pretrained weights. The weights are either:
1. ... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/csp-resnet.md | # CSP-ResNet
**CSPResNet** is a convolutional neural network where we apply the Cross Stage Partial Network (CSPNet) approach to [ResNet](https://paperswithcode.com/method/resnet). The CSPNet partitions the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a ... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/tf-efficientnet-lite.md | # (Tensorflow) EfficientNet Lite
**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/res2next.md | # Res2NeXt
**Res2NeXt** is an image model that employs a variation on [ResNeXt](https://paperswithcode.com/method/resnext) bottleneck residual blocks. The motivation is to be able to represent features at multiple scales. This is achieved through a novel building block for CNNs that constructs hierarchical residual-li... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/legacy-se-resnext.md | # (Legacy) SE-ResNeXt
**SE ResNeXt** is a variant of a [ResNeXt](https://www.paperswithcode.com/method/resnext) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
## How do I use this... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/xception.md | # Xception
**Xception** is a convolutional neural network architecture that relies solely on [depthwise separable convolution layers](https://paperswithcode.com/method/depthwise-separable-convolution).
The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models).
## How do I... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/gloun-seresnext.md | # (Gluon) SE-ResNeXt
**SE ResNeXt** is a variant of a [ResNext](https://www.paperswithcode.com/method/resnext) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
The weights from this... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/dla.md | # Deep Layer Aggregation
Extending “shallow” skip connections, **Dense Layer Aggregation (DLA)** incorporates more depth and sharing. The authors introduce two structures for deep layer aggregation (DLA): iterative deep aggregation (IDA) and hierarchical deep aggregation (HDA). These structures are expressed through ... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/skresnext.md | # SK-ResNeXt
**SK ResNeXt** is a variant of a [ResNeXt](https://www.paperswithcode.com/method/resnext) that employs a [Selective Kernel](https://paperswithcode.com/method/selective-kernel) unit. In general, all the large kernel convolutions in the original bottleneck blocks in ResNext are replaced by the proposed [SK ... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/mixnet.md | # MixNet
**MixNet** is a type of convolutional neural network discovered via AutoML that utilises [MixConvs](https://paperswithcode.com/method/mixconv) instead of regular [depthwise convolutions](https://paperswithcode.com/method/depthwise-convolution).
## How do I use this model on an image?
To load a pretrained mod... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/vision-transformer.md | # Vision Transformer (ViT)
The **Vision Transformer** is a model for image classification that employs a Transformer-like architecture over patches of the image. This includes the use of [Multi-Head Attention](https://paperswithcode.com/method/multi-head-attention), [Scaled Dot-Product Attention](https://paperswithcod... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/regnetx.md | # RegNetX
**RegNetX** is a convolutional network design space with simple, regular models with parameters: depth $d$, initial width $w\_{0} > 0$, and slope $w\_{a} > 0$, and generates a different block width $u\_{j}$ for each block $j < d$. The key restriction for the RegNet types of model is that there is a linear pa... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/csp-darknet.md | # CSP-DarkNet
**CSPDarknet53** is a convolutional neural network and backbone for object detection that uses [DarkNet-53](https://paperswithcode.com/method/darknet-53). It employs a CSPNet strategy to partition the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The u... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/tf-efficientnet.md | # (Tensorflow) EfficientNet
**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scal... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/hrnet.md | # HRNet
**HRNet**, or **High-Resolution Net**, is a general purpose convolutional neural network for tasks like semantic segmentation, object detection and image classification. It is able to maintain high resolution representations through the whole process. We start from a high-resolution convolution stream, gradual... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/gloun-xception.md | # (Gluon) Xception
**Xception** is a convolutional neural network architecture that relies solely on [depthwise separable convolution](https://paperswithcode.com/method/depthwise-separable-convolution) layers.
The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html).
##... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/tf-mobilenet-v3.md | # (Tensorflow) MobileNet v3
**MobileNetV3** is a convolutional neural network that is designed for mobile phone CPUs. The network design includes the use of a [hard swish activation](https://paperswithcode.com/method/hard-swish) and [squeeze-and-excitation](https://paperswithcode.com/method/squeeze-and-excitation-bloc... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/ssl-resnext.md | # SSL ResNeXT
A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) ... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/swsl-resnet.md | # SWSL ResNet
**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual ... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/densenet.md | # DenseNet
**DenseNet** is a type of convolutional neural network that utilises dense connections between layers, through [Dense Blocks](http://www.paperswithcode.com/method/dense-block), where we connect *all layers* (with matching feature-map sizes) directly with each other. To preserve the feed-forward nature, each... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/legacy-senet.md | # (Legacy) SENet
A **SENet** is a convolutional neural network architecture that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
The weights from this model were ported from Gluon.
## ... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/mobilenet-v3.md | # MobileNet v3
**MobileNetV3** is a convolutional neural network that is designed for mobile phone CPUs. The network design includes the use of a [hard swish activation](https://paperswithcode.com/method/hard-swish) and [squeeze-and-excitation](https://paperswithcode.com/method/squeeze-and-excitation-block) modules in... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/efficientnet.md | # EfficientNet
**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network wi... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/tresnet.md | # TResNet
A **TResNet** is a variant on a [ResNet](https://paperswithcode.com/method/resnet) that aim to boost accuracy while maintaining GPU training and inference efficiency. They contain several design tricks including a SpaceToDepth stem, [Anti-Alias downsampling](https://paperswithcode.com/method/anti-alias-down... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/tf-mixnet.md | # (Tensorflow) MixNet
**MixNet** is a type of convolutional neural network discovered via AutoML that utilises [MixConvs](https://paperswithcode.com/method/mixconv) instead of regular [depthwise convolutions](https://paperswithcode.com/method/depthwise-convolution).
The weights from this model were ported from [Tenso... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/gloun-resnext.md | # (Gluon) ResNeXt
A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformatio... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/seresnext.md | # SE-ResNeXt
**SE ResNeXt** is a variant of a [ResNext](https://www.paperswithcode.com/method/resneXt) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
## How do I use this model on... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/swsl-resnext.md | # SWSL ResNeXt
A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations)... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/nasnet.md | # NASNet
**NASNet** is a type of convolutional neural network discovered through neural architecture search. The building blocks consist of normal and reduction cells.
## How do I use this model on an image?
To load a pretrained model:
```python
import timm
model = timm.create_model('nasnetalarge', pretrained=True)
... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/selecsls.md | # SelecSLS
**SelecSLS** uses novel selective long and short range skip connections to improve the information flow allowing for a drastically faster network without compromising accuracy.
## How do I use this model on an image?
To load a pretrained model:
```python
import timm
model = timm.create_model('selecsls42b'... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/tf-inception-v3.md | # (Tensorflow) Inception v3
**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://pape... | 0 |
hf_public_repos/pytorch-image-models/docs | hf_public_repos/pytorch-image-models/docs/models/legacy-se-resnet.md | # (Legacy) SE-ResNet
**SE ResNet** is a variant of a [ResNet](https://www.paperswithcode.com/method/resnet) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration.
## How do I use this mod... | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.