instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to improve code quality
from typing import List, Union import torch from torch import nn as nn from .conv2d_same import create_conv2d_pad def _split_channels(num_chan, num_groups): split = [num_chan // num_groups for _ in range(num_groups)] split[0] += num_chan - sum(split) return split class MixedConv2d(nn.ModuleDict): ...
--- +++ @@ -1,3 +1,9 @@+""" 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 @@ -13,6 +19,11 @@ class MixedConv2d(nn.ModuleDict): + """ Mi...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/mixed_conv2d.py
Add docstrings to incomplete code
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_same_arg, get_padding_value _USE_EXPORT_CONV = False def conv2d_same( x, ...
--- +++ @@ -1,3 +1,7 @@+""" Conv2d w/ Same Padding + +Hacked together by / Copyright 2020 Ross Wightman +""" import torch import torch.nn as nn import torch.nn.functional as F @@ -26,6 +30,8 @@ @register_notrace_module class Conv2dSame(nn.Conv2d): + """ Tensorflow like 'SAME' convolution wrapper for 2D convolu...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/conv2d_same.py
Create Google-style docstrings for my code
from typing import Any, Dict, List, Optional, Type, Union import torch from torch import nn as nn from torch.nn import functional as F from torchvision.ops.misc import FrozenBatchNorm2d from ._fx import register_notrace_module from .create_act import create_act_layer from .fast_norm import ( is_fast_norm, fas...
--- +++ @@ -1,3 +1,17 @@+""" 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_respons...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/norm_act.py
Add docstrings with type hints explained
from typing import Optional, Union, Tuple import torch import torch.nn as nn from .config import use_fused_attn from .helpers import to_2tuple from .pos_embed import resample_abs_pos_embed from .pos_embed_sincos import apply_rot_embed_cat, create_rope_embed from .weight_init import trunc_normal_ class RotAttentionP...
--- +++ @@ -1,3 +1,12 @@+""" 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 / ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/attention_pool2d.py
Write docstrings for utility functions
from typing import Optional, Tuple, Type, Union import torch from torch import nn as nn import torch.nn.functional as F from .conv_bn_act import ConvNormAct from .create_act import create_act_layer, get_act_layer from .helpers import make_divisible class ChannelAttn(nn.Module): def __init__( self, ...
--- +++ @@ -1,3 +1,12 @@+""" 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 en...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/cbam.py
Add clean documentation to messy code
from typing import Optional, Type, Union import torch import torch.nn as nn import torch.nn.functional as F from .config import use_fused_attn class LsePlus2d(nn.Module): def __init__( self, r: float = 10.0, r_learnable: bool = True, flatten: bool = True, ...
--- +++ @@ -1,3 +1,17 @@+""" 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 implementat...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/other_pool.py
Improve documentation using docstrings
import numbers from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from .fast_norm import ( is_fast_norm, fast_group_norm, fast_layer_norm, fast_rms_norm, rms_norm2d, fast_rms_norm2d, fast_simple_norm, simple_norm, ) try: from torch.nn.funct...
--- +++ @@ -1,3 +1,9 @@+""" 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 @@ -45,6 +51,9 @@ class GroupNorm1(nn.GroupNorm): ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/norm.py
Generate consistent docstrings
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 SplitInfo except ImportError as e: print("Pl...
--- +++ @@ -1,3 +1,5 @@+""" Dataset reader for HF IterableDataset +""" import math import os from itertools import repeat, chain @@ -122,6 +124,8 @@ self.global_num_workers = self.dist_num_replicas * self.num_workers def _lazy_init(self): + """ Lazily initialize worker (in worker processes)...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/readers/reader_hfids.py
Document this script properly
import random import math from typing import Optional, Union, Tuple import torch class PatchRandomErasing: def __init__( self, erase_prob: float = 0.5, patch_drop_prob: float = 0.0, min_count: int = 1, max_count: Optional[int] = None, min_...
--- +++ @@ -1,3 +1,15 @@+"""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 (sp...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/naflex_random_erasing.py
Generate helpful docstrings for debugging
import math from typing import Optional, Type import torch import torch.nn as nn import torch.nn.functional as F from .attention import maybe_add_mask, resolve_self_attn_mask from .config import use_fused_attn from .norm import RmsNorm class DiffAttention(nn.Module): fused_attn: torch.jit.Final[bool] def _...
--- +++ @@ -1,3 +1,11 @@+"""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 @@ -1...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/diff_attention.py
Add docstrings for utility scripts
from typing import Optional, Tuple, Type, Union import math from torch import nn as nn import torch.nn.functional as F from .create_act import create_act_layer, get_act_layer from .create_conv2d import create_conv2d from .helpers import make_divisible from .mlp import ConvMlp class GatherExcite(nn.Module): def ...
--- +++ @@ -1,3 +1,16 @@+""" 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. ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/gather_excite.py
Add inline docstrings for readability
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]]: if not training or prob == 0.: ...
--- +++ @@ -11,6 +11,19 @@ ordered: bool, training: bool, ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """ + Common forward logic for patch dropout. + + Args: + x: Input tensor of shape (B, L, D) + prob: Dropout probability + num_prefix_tokens: Number of prefix tok...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/patch_dropout.py
Insert docstrings into my code
import math from functools import partial from typing import Union, Tuple import torch from torch import nn as nn from torch.nn import functional as F from ._fx import register_notrace_module from .helpers import to_2tuple from .conv2d_same import conv2d_same from .padding import get_padding_value def get_condconv...
--- +++ @@ -1,3 +1,10 @@+""" 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 @@ -15,...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/cond_conv2d.py
Write docstrings for algorithm functions
from typing import Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from .format import get_spatial_dim, get_channel_dim _int_tuple_2_t = Union[int, Tuple[int, int]] def adaptive_pool_feat_mult(pool_type='avg'): if pool_type.endswith('catavgmax'): return 2 e...
--- +++ @@ -1,3 +1,14 @@+""" 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 ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/adaptive_avgmax_pool.py
Please document this code using docstrings
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...
--- +++ @@ -41,6 +41,13 @@ class Attention(nn.Module): + """Standard Multi-head Self Attention module with QKV projection. + + This module implements the standard multi-head attention mechanism used in transformers. + It supports both the fused attention implementation (scaled_dot_product_attention) for + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/attention.py
Write docstrings for backend logic
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 .patch_embed import resample_patch_embed _logger = logging.getLogger(__name__) class HybridEmbe...
--- +++ @@ -1,3 +1,7 @@+""" Image to Patch Hybird Embedding Layer + +Hacked together by / Copyright 2020 Ross Wightman +""" import logging import math from typing import List, Optional, Tuple, Union @@ -15,6 +19,9 @@ class HybridEmbed(nn.Module): + """ CNN Feature Map Embedding + Extract feature map from C...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/hybrid_embed.py
Generate helpful docstrings for debugging
import math from contextlib import suppress from functools import partial from typing import Callable, Dict, Iterator, List, Optional, Tuple, Union import torch from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from .loader import _worker_init, adapt_to_chs from .naflex_dataset import NaFlexMapData...
--- +++ @@ -1,3 +1,13 @@+"""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 +- ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/naflex_loader.py
Fill in missing docstrings in my code
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', 'use_reentrant_ckpt' ] # Set to True if prefer...
--- +++ @@ -1,3 +1,5 @@+""" Model / Layer Config singleton state +""" import os import warnings from typing import Any, Optional @@ -97,6 +99,9 @@ class set_layer_config: + """ Layer config context manager that allows setting all layer config flags at once. + If a flag arg is None, it will not change the c...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/config.py
Add structured docstrings to improve clarity
import torch import torch.nn.functional as F from torch import nn as nn class Linear(nn.Linear): def forward(self, input: torch.Tensor) -> torch.Tensor: if torch.jit.is_scripting(): bias = self.bias.to(dtype=input.dtype) if self.bias is not None else None return F.linear(input, sel...
--- +++ @@ -1,12 +1,19 @@+""" 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 us...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/linear.py
Provide clean and structured docstrings
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
--- +++ @@ -1,3 +1,11 @@+""" 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. # @@ -29,6 +37...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/tf_preprocessing.py
Turn comments into proper docstrings
import os import tarfile from timm.utils.misc import natural_key from .class_map import load_class_map from .img_extensions import get_img_extensions from .reader import Reader def extract_tarinfo(tarfile, class_to_idx=None, sort=True): extensions = get_img_extensions(as_set=True) files = [] labels = []...
--- +++ @@ -1,3 +1,10 @@+""" 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 @...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/data/readers/reader_image_tar.py
Write docstrings for algorithm functions
import torch.nn as nn import torch.nn.functional as F from .helpers import to_2tuple, to_4tuple class MedianPool2d(nn.Module): def __init__(self, kernel_size=3, stride=1, padding=0, same=False): super().__init__() self.k = to_2tuple(kernel_size) self.stride = to_2tuple(stride) self...
--- +++ @@ -1,9 +1,20 @@+""" 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: + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/median_pool.py
Add documentation for all methods
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): if isinstance(kernel_size, list): assert 'num_experts' not in kwargs # MixNet + CondConv combo not supported currently...
--- +++ @@ -1,3 +1,7 @@+""" Create Conv2d Factory Method + +Hacked together by / Copyright 2020 Ross Wightman +""" from .mixed_conv2d import MixedConv2d from .cond_conv2d import CondConv2d @@ -5,6 +9,11 @@ def create_conv2d(in_channels, out_channels, kernel_size, **kwargs): + """ Select a 2d convolution impl...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/create_conv2d.py
Document functions with clear intent
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') operator as of PyTorch 1.7. # Also hardsigmoid, hardswish, and soon mish. T...
--- +++ @@ -1,3 +1,6 @@+""" Activation Factory +Hacked together by / Copyright 2020 Ross Wightman +""" from typing import Callable, Optional, Type, Union from .activations import * @@ -87,6 +90,10 @@ def get_act_fn(name: Optional[LayerType] = 'relu'): + """ Activation Function Factory + Fetching activatio...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/create_act.py
Generate docstrings for each module
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_act_layer, create_aa, to_2tuple, LayerType, ConvNormAct, get_norm_act_layer, ...
--- +++ @@ -1,3 +1,7 @@+""" EfficientNet, MobileNetV3, etc Blocks + +Hacked together by / Copyright 2019, Ross Wightman +""" from typing import Callable, Dict, Optional, Type, Union import torch @@ -37,6 +41,16 @@ class SqueezeExcite(nn.Module): + """ Squeeze-and-Excitation w/ specific features for Efficient...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_efficientnet_blocks.py
Add professional docstrings to my codebase
from typing import Callable, Optional import logging import math import re from copy import deepcopy from functools import partial from typing import Any, Dict, List import torch.nn as nn from timm.layers import CondConv2d, get_condconv_initializer, get_act_layer, get_attn, make_divisible, LayerType from ._efficient...
--- +++ @@ -1,3 +1,10 @@+""" 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, ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_efficientnet_builder.py
Create docstrings for API functions
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_value def avg_pool2d_same( x: torch.Tensor, kernel_size: List[int], ...
--- +++ @@ -1,3 +1,7 @@+""" AvgPool2d w/ Same Padding + +Hacked together by / Copyright 2020 Ross Wightman +""" import torch import torch.nn as nn import torch.nn.functional as F @@ -23,6 +27,8 @@ @register_notrace_module class AvgPool2dSame(nn.AvgPool2d): + """ Tensorflow like 'SAME' wrapper for 2D average po...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/pool2d_same.py
Add docstrings for internal functions
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 ...
--- +++ @@ -52,6 +52,9 @@ def get_cache_dir(child_dir: str = ''): + """ + Returns the location of the directory where models are cached (and creates it if necessary). + """ # Issue warning to move data if old env is set if os.getenv('TORCH_MODEL_ZOO'): _logger.warning('TORCH_MODEL_ZOO is...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_hub.py
Add well-formatted docstrings
from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from timm.layers import ( create_feature_extractor, get_graph_node_names, register_notrace_module, register_notrace_function, is_notrace_module, is_notrace_function, get_notrace_function...
--- +++ @@ -1,3 +1,6 @@+""" PyTorch FX Based Feature Extraction Helpers +Using https://pytorch.org/vision/stable/feature_extraction.html +""" from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch @@ -33,6 +36,8 @@ class FeatureGraphNet(nn.Module): + """ A FX Graph based feature e...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_features_fx.py
Write docstrings for utility functions
import fnmatch import re import sys import warnings from collections import defaultdict, deque from copy import deepcopy from dataclasses import replace from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Sequence, Union, Tuple from ._pretrained import PretrainedCfg, DefaultCfg __all__ = [ 'sp...
--- +++ @@ -1,3 +1,6 @@+""" Model Registry +Hacked together by / Copyright 2020 Ross Wightman +""" import fnmatch import re @@ -166,10 +169,12 @@ def _natural_key(string_: str) -> List[Union[int, str]]: + """See https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/""" return [int(s) if s....
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_registry.py
Add docstrings following best practices
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 import Mlp from .weight_init import trunc_normal_ _USE_SCIPY = int(os.environ.get('TIMM_USE_SCIPY_INTERP', 0)...
--- +++ @@ -1,3 +1,7 @@+""" Relative position embedding modules and functions + +Hacked together by / Copyright 2022 Ross Wightman +""" import math import os from typing import Optional, Tuple @@ -123,6 +127,10 @@ interpolation: str = 'bicubic', antialias: bool = True, ): + """ + Resample rel...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/pos_embed_rel.py
Help me document legacy Python code
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 make_divisible from .trace_utils import _assert def _kernel_valid(k): if isinstance(k, (list, tuple)): for ki in k: return _kernel_valid(ki)...
--- +++ @@ -1,3 +1,9 @@+""" 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 @@ -26,6 +32,11 @@ device=None, ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/selective_kernel.py
Fully document this Python code with docstrings
import argparse import logging import os import pickle from typing import Any, Callable, Dict, Optional, Union import torch try: import safetensors.torch _has_safetensors = True except ImportError: _has_safetensors = False _logger = logging.getLogger(__name__) __all__ = [ 'clean_state_dict', 'l...
--- +++ @@ -1,3 +1,7 @@+""" Model creation / weight loading / state_dict helpers + +Hacked together by / Copyright 2020 Ross Wightman +""" import argparse import logging import os @@ -92,6 +96,17 @@ device: Union[str, torch.device] = 'cpu', weights_only: bool = True, ) -> Dict[str, Any]: + """Lo...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_helpers.py
Add minimal docstrings for each function
from typing import Optional, Type, Union import torch import torch.nn.functional as F from torch import nn from .helpers import make_divisible class RadixSoftmax(nn.Module): def __init__(self, radix: int, cardinality: int): super().__init__() self.radix = radix self.cardinality = cardina...
--- +++ @@ -1,3 +1,11 @@+""" 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 ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/split_attn.py
Add clean documentation to messy code
import torch import torch.nn as nn class SpaceToDepth(nn.Module): bs: torch.jit.Final[int] def __init__(self, block_size: int = 4): super().__init__() assert block_size == 4 self.bs = block_size def forward(self, x): N, C, H, W = x.size() x = x.view(N, C, H // sel...
--- +++ @@ -3,6 +3,14 @@ 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 facto...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/space_to_depth.py
Add docstrings explaining edge cases
# -------------------------------------------------------- # BEIT: BERT Pre-Training of Image Transformers (https://arxiv.org/abs/2106.08254) # Github source: https://github.com/microsoft/unilm/tree/master/beit # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # By Hangbo Bao # B...
--- +++ @@ -1,3 +1,31 @@+""" BEiT: BERT Pre-Training of Image Transformers (https://arxiv.org/abs/2106.08254) + +Model from official source: https://github.com/microsoft/unilm/tree/master/beit + +@inproceedings{beit, +title={{BEiT}: {BERT} Pre-Training of Image Transformers}, +author={Hangbo Bao and Li Dong and Songhao...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/beit.py
Improve my code by adding docstrings
from typing import Optional, Type, Union from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class SeparableConvNormAct(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size...
--- +++ @@ -1,3 +1,10 @@+""" 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 imp...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/separable_conv.py
Improve my code by adding docstrings
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 _assert def pixel_freq_bands( num_bands: int, max_freq: float = 224., linear_bands: bool = True, ...
--- +++ @@ -1,3 +1,7 @@+""" 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 @@ -41,6 +45,20 @@ device: Optional[torch.device] = None, dtype: torch.dtype = torch.fl...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/pos_embed_sincos.py
Add docstrings for internal functions
import torch import torch.nn as nn class SplitBatchNorm2d(torch.nn.BatchNorm2d): def __init__( self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, num_splits=2, device=None, ...
--- +++ @@ -1,3 +1,16 @@+""" 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 ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/split_batchnorm.py
Add docstrings including usage examples
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 ...
--- +++ @@ -13,6 +13,12 @@ self.eps = eps def forward(self, x, y): + """" + Parameters + ---------- + x: input logits + y: targets (multi-label binarized vector) + """ # Calculating Probabilities x_sigmoid = torch.sigmoid(x) @@ -56,6 +62,12 @@...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/loss/asymmetric_loss.py
Improve documentation using docstrings
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved. All Rights Reserved. import operator from collections import OrderedDict from dataclasses import dataclass from functools import partial, reduce from typing import Union, List, Tuple, Optional, Any, Type import torch from torch import nn from t...
--- +++ @@ -1,3 +1,17 @@+""" 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 Feichtenhof...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/mvitv2.py
Document functions with detailed explanations
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. from functools import partial from typing import List, Optional, Tuple, Union, Type, Any import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import PatchEmbed, Mlp, DropPath, trunc_nor...
--- +++ @@ -1,3 +1,11 @@+""" Class-Attention in Image Transformers (CaiT) + +Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 + +Original code and weights from https://github.com/facebookresearch/deit, copyright below + +Modifications and additions for timm hacked together by / Copyright...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/cait.py
Add docstrings that explain inputs and outputs
import re from collections import OrderedDict from typing import Any, Dict, Optional, Tuple, Type, Union import torch import torch.nn as nn import torch.nn.functional as F from torch.jit.annotations import List from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import BatchNormAct2d, g...
--- +++ @@ -1,3 +1,7 @@+"""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, Opti...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/densenet.py
Create documentation for each function signature
from functools import partial from typing import Any, Dict, Callable, List, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import SelectAdaptiv...
--- +++ @@ -1,3 +1,11 @@+""" 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, Call...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/mobilenetv3.py
Add docstrings to improve readability
import math from functools import partial from typing import Callable, List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ( DropPath, calculate_drop_path_rates, to_2tuple, to_ntuple, Mlp, ...
--- +++ @@ -1,3 +1,24 @@+""" 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...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/gcvit.py
Add detailed docstrings explaining each function
# Copyright IBM All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from functools import partial from typing import List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, calculate_drop_path_ra...
--- +++ @@ -1,3 +1,21 @@+""" 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 (ICC...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/crossvit.py
Write docstrings for algorithm functions
import os import pkgutil from copy import deepcopy from torch import nn as nn from timm.layers import Conv2dSame, BatchNormAct2d, Linear __all__ = ['extract_layer', 'set_layer', 'adapt_model_from_string', 'adapt_model_from_file'] def extract_layer(model, layer): layer = layer.split('.') module = model ...
--- +++ @@ -10,6 +10,15 @@ def extract_layer(model, layer): + """Extract a layer from a model using dot-separated path. + + Args: + model: PyTorch model. + layer: Dot-separated layer path (e.g., 'layer1.0.conv1'). + + Returns: + Extracted module. + """ layer = layer.split('.') ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_prune.py
Document helper functions with docstrings
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,...
--- +++ @@ -89,11 +89,13 @@ def set_pretrained_download_progress(enable: bool = True) -> None: + """ Set download progress for pretrained weights on/off (globally). """ global _DOWNLOAD_PROGRESS _DOWNLOAD_PROGRESS = enable def set_pretrained_check_hash(enable: bool = True) -> None: + """ Set ha...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_builder.py
Write docstrings describing each step
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...
--- +++ @@ -194,6 +194,11 @@ use_reentrant: Optional[bool] = None, **kwargs, ): + """ checkpoint wrapper fn + + A thin wrapper around torch.utils.checkpoint.checkpoint to default + use_reentrant to False + """ if use_reentrant is None: use_reentrant = use_reentrant_ckpt() @@ -213,6...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_manipulate.py
Document all endpoints with docstrings
from collections import OrderedDict from typing import List, Optional, Tuple, Type, Union import torch from torch import nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import trunc_normal_, DropPath, calculate_drop_path_rates, LayerNorm, LayerScale, ClNormMlpClassifierHead, get_...
--- +++ @@ -1,3 +1,10 @@+""" +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 Ordered...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/mambaout.py
Write docstrings for algorithm functions
from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import ( SelectAdaptivePool2d, Linear, LayerType...
--- +++ @@ -38,6 +38,16 @@ @register_notrace_module class MobileNetV5MultiScaleFusionAdapter(nn.Module): + """Multi-layer fusion token adapter. + + Args: + in_chs: List of input channel counts for each feature scale. + out_chs: The number of output channels. + output_resolution: The output resolution. + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/mobilenetv5.py
Add docstrings to my Python code
import logging from typing import Dict, List, Type, Optional, Tuple import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import create_classifier from ._builder import build_model_with_cfg, pretrained_cfg_for_features from ._features import FeatureInfo ...
--- +++ @@ -1,3 +1,13 @@+""" HRNet + +Copied from https://github.com/HRNet/HRNet-Image-Classification + +Original header: + Copyright (c) Microsoft + Licensed under the MIT License. + Written by Bin Xiao (Bin.Xiao@microsoft.com) + Modified by Ke Sun (sunk@mail.ustc.edu.cn) +""" import logging from typing import D...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/hrnet.py
Generate helpful docstrings for debugging
# Copyright (c) 2022 Mingyu Ding # All rights reserved. # This source code is licensed under the MIT license from functools import partial from typing import List, Optional, Tuple, Type, Union import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from timm.data import IMAGENET_DE...
--- +++ @@ -1,3 +1,13 @@+""" 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 ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/davit.py
Please document this code using docstrings
import math from collections import OrderedDict from dataclasses import dataclass, replace, field from functools import partial from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import torch from torch import nn from torch.jit import Final from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET...
--- +++ @@ -1,3 +1,38 @@+""" MaxVit and CoAtNet Vision Transformer - CNN Hybrids in PyTorch + +This is a from-scratch implementation of both CoAtNet and MaxVit in PyTorch. + +99% of the implementation was done from papers, however last minute some adjustments were made +based on the (as yet unfinished?) public code rel...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/maxxvit.py
Provide clean and structured docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from functools import partial from typing import Any, Dict, List, Optional, Set, 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.l...
--- +++ @@ -1,3 +1,17 @@+"""FasterNet +Run, Don't Walk: Chasing Higher FLOPS for Faster Neural Networks +- paper: https://arxiv.org/abs/2303.03667 +- code: https://github.com/JierunChen/FasterNet + +@article{chen2023run, + title={Run, Don't Walk: Chasing Higher FLOPS for Faster Neural Networks}, + author={Chen, Jieru...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/fasternet.py
Create docstrings for all classes and functions
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. from functools import partial from typing import Optional, Type import torch from torch import nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import resample_abs_pos_embed from timm.models.vision_transform...
--- +++ @@ -1,3 +1,13 @@+""" 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...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/deit.py
Create structured documentation for my script
from typing import List, Optional, Tuple, Union, Type, Any 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, DropPath, to_2tuple, trunc_normal_, _assert, LayerNorm from ._builder import build_mo...
--- +++ @@ -1,3 +1,12 @@+""" +CoaT architecture. + +Paper: Co-Scale Conv-Attentional Image Transformers - https://arxiv.org/abs/2104.06399 + +Official CoaT code at: https://github.com/mlpc-ucsd/CoaT + +Modified from timm/models/vision_transformer.py +""" from typing import List, Optional, Tuple, Union, Type, Any im...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/coat.py
Help me write clear docstrings
from typing import Optional, Tuple, Type, Union from torch import nn as nn from .create_act import create_act_layer from .helpers import make_divisible class SEModule(nn.Module): def __init__( self, channels: int, rd_ratio: float = 1. / 16, rd_channels: Optional[i...
--- +++ @@ -1,3 +1,15 @@+""" 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-Ex...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/squeeze_excite.py
Write proper docstrings for these functions
from functools import partial from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import trunc_normal_, DropPath, calculate_drop_path_rates, to_2tuple, get_padding, SelectAdaptivePool2d from ._buil...
--- +++ @@ -1,3 +1,7 @@+""" +InceptionNeXt paper: https://arxiv.org/abs/2303.16900 +Original implementation & weights from: https://github.com/sail-sg/inceptionnext +""" from functools import partial from typing import List, Optional, Tuple, Union, Type @@ -16,6 +20,8 @@ class InceptionDWConv2d(nn.Module): + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/inception_next.py
Add documentation for all methods
from collections import OrderedDict, defaultdict from copy import deepcopy from functools import partial from typing import Dict, List, Optional, Sequence, Tuple, Union import torch import torch.nn as nn from timm.layers import Format, _assert from ._manipulate import checkpoint __all__ = [ 'FeatureInfo', 'Featu...
--- +++ @@ -1,3 +1,13 @@+""" PyTorch Feature Extraction Helpers + +A collection of classes, functions, modules to help extract features from models +and provide a common interface for describing them. + +The return_layers, module re-writing idea inspired by torchvision IntermediateLayerGetter +https://github.com/pytorc...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_features.py
Add missing documentation to my Python functions
# 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...
--- +++ @@ -41,6 +41,14 @@ class MobileOneBlock(nn.Module): + """MobileOne building block. + + This block has a multi-branched architecture at train-time + and plain-CNN style architecture at inference time + For more details, please refer to our paper: + `An Improved One millisecond Mobile Backbone`...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/fastvit.py
Create docstrings for API functions
import math from functools import partial from typing import Dict, List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ( create_conv2d, create_norm_layer, get_act_layer, get_norm_layer, Conv...
--- +++ @@ -1,3 +1,19 @@+""" EfficientFormer-V2 + +@article{ + li2022rethinking, + title={Rethinking Vision Transformers for MobileNet Size and Speed}, + author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, + journal={a...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/efficientformer_v2.py
Document my Python code with docstrings
import torch import torch.nn as nn import torch.nn.functional as F class LabelSmoothingCrossEntropy(nn.Module): def __init__(self, smoothing=0.1): super(LabelSmoothingCrossEntropy, self).__init__() assert smoothing < 1.0 self.smoothing = smoothing self.confidence = 1. - smoothing ...
--- +++ @@ -1,3 +1,7 @@+""" Cross Entropy w/ smoothing or soft targets + +Hacked together by / Copyright 2021 Ross Wightman +""" import torch import torch.nn as nn @@ -5,6 +9,8 @@ class LabelSmoothingCrossEntropy(nn.Module): + """ NLL loss with label smoothing. + """ def __init__(self, smoothing=0.1)...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/loss/cross_entropy.py
Add concise docstrings to each method
# 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. # -------------------------------------------------------- # # Hiera: A Hierarchical Vision Transformer without the Bells-...
--- +++ @@ -1,3 +1,7 @@+""" 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. @@ -52,6 +56,10 @@ def conv_nd(n: int) -> Type[nn.Module]: + """ + Returns a conv ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/hiera.py
Replace inline comments with docstrings
from functools import partial from typing import Callable, Dict, List, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import create_conv2d, cre...
--- +++ @@ -1,3 +1,40 @@+""" The EfficientNet Family in PyTorch + +An implementation of EfficienNet that covers variety of related models with efficient architectures: + +* EfficientNet-V2 + - `EfficientNetV2: Smaller Models and Faster Training` - https://arxiv.org/abs/2104.00298 + +* EfficientNet (B0-B8, L2 + Tensorf...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/efficientnet.py
Add docstrings to improve readability
from functools import partial from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import create_classifier, ConvNormAct from ._builder import build_model_with_cfg from ._features import feature_...
--- +++ @@ -1,3 +1,7 @@+""" Pytorch Inception-V4 implementation +Sourced from https://github.com/Cadene/tensorflow-model-zoo.torch (MIT License) which is +based upon Google's Tensorflow implementation and pretrained weights (Apache 2.0 License) +""" from functools import partial from typing import List, Optional, Tup...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/inception_v4.py
Write docstrings for data processing functions
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the CC-by-NC license found in the # LICENSE file in the root directory of this source tree. # '''These modules are adapted from those of timm, see https://github.com/rwightman/pytorch-image-models/blob/master/timm...
--- +++ @@ -1,3 +1,17 @@+""" ConViT Model + +@article{d2021convit, + title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, + author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, + journal={arXiv preprint arXiv:2...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/convit.py
Add docstrings to improve readability
# Copyright 2022 Garena Online Private Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
--- +++ @@ -1,3 +1,16 @@+""" +Poolformer from MetaFormer is Actually What You Need for Vision https://arxiv.org/abs/2111.11418 + +IdentityFormer, RandFormer, PoolFormerV2, ConvFormer, and CAFormer +from MetaFormer Baselines for Vision https://arxiv.org/abs/2210.13452 + +All implemented models support feature extraction...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/metaformer.py
Add docstrings that explain inputs and outputs
__all__ = ['EfficientVitMsra'] import itertools from collections import OrderedDict from functools import partial from typing import Dict, List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SqueezeExcite, Sel...
--- +++ @@ -1,3 +1,10 @@+""" EfficientViT (by MSRA) + +Paper: `EfficientViT: Memory Efficient Vision Transformer with Cascaded Group Attention` + - https://arxiv.org/abs/2305.07027 + +Adapted from official impl at https://github.com/microsoft/Cream/tree/main/EfficientViT +""" __all__ = ['EfficientVitMsra'] impor...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/efficientvit_msra.py
Add detailed documentation for each class
from typing import Any, Dict, Optional from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs from .byobnet import ByoBlockCfg, ByoModelCfg, ByobNet, interleave_blocks __all__ = [] model_cfgs = dict( ...
--- +++ @@ -1,3 +1,17 @@+""" 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 t...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/byoanet.py
Add docstrings explaining edge cases
import os from pathlib import Path from typing import Any, Dict, Optional, Tuple, Union from urllib.parse import urlsplit 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 impor...
--- +++ @@ -16,6 +16,7 @@ def parse_model_name(model_name: str) -> Tuple[Optional[str], str]: + """Parse source and name from potentially prefixed model name.""" if model_name.startswith('hf_hub'): # NOTE for backwards compat, deprecate hf_hub use model_name = model_name.replace('hf_hub', ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/_factory.py
Create documentation for each function signature
import collections.abc import logging import math from functools import partial from typing import List, Optional, Tuple, Type, Union import torch import torch.nn.functional as F from torch import nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ( PatchEmbed, Mlp, ...
--- +++ @@ -1,3 +1,19 @@+""" Nested Transformer (NesT) in PyTorch + +A PyTorch implement of Aggregating Nested Transformers as described in: + +'Aggregating Nested Transformers' + - https://arxiv.org/abs/2105.12723 + +The official Jax code is released and available at https://github.com/google-research/nested-transf...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/nest.py
Add return value explanations in docstrings
import math from functools import partial from typing import Any, Dict, List, Set, Optional, Tuple, Union, Type 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 SelectAdaptivePool2d, Linear, make_divisible from...
--- +++ @@ -1,3 +1,14 @@+""" +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/40b60852a4abdaa696b5a...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/ghostnet.py
Generate docstrings with parameter types
import math from dataclasses import dataclass, field, replace from functools import partial from typing import Tuple, List, Dict, Optional, Union, Any, Callable, Sequence, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, OPENAI_CLIP_MEAN, OPENAI_CLIP_STD from ...
--- +++ @@ -1,3 +1,33 @@+""" Bring-Your-Own-Blocks Network + +A flexible network w/ dataclass based config for stacking those NN blocks. + +This model is currently used to implement the following networks: + +GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet aut...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/byobnet.py
Document my Python code with docstrings
from typing import Optional, Union import torch import torch.nn as nn import torch.nn.functional as F class BinaryCrossEntropy(nn.Module): def __init__( self, smoothing=0.1, target_threshold: Optional[float] = None, weight: Optional[torch.Tensor] = None, ...
--- +++ @@ -1,3 +1,7 @@+""" Binary Cross Entropy w/ a few extras + +Hacked together by / Copyright 2021 Ross Wightman +""" from typing import Optional, Union import torch @@ -6,6 +10,9 @@ class BinaryCrossEntropy(nn.Module): + """ BCE with optional one-hot from dense targets, label smoothing, thresholding + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/loss/binary_cross_entropy.py
Document functions with clear intent
# ConvNeXt # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the MIT license # ConvNeXt-V2 # 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 ...
--- +++ @@ -1,3 +1,30 @@+""" 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 = {Pr...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/convnext.py
Generate missing documentation strings
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 SelectAdaptivePool2d, DropPath, calculate_drop_path_rates, create_conv2d from ._builder import build_...
--- +++ @@ -1,3 +1,11 @@+""" 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/...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/hgnet.py
Write docstrings that follow conventions
# -------------------------------------------------------- # FocalNets -- Focal Modulation Networks # Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Jianwei Yang (jianwyan@microsoft.com) # -------------------------------------------------------- from functools impor...
--- +++ @@ -1,3 +1,16 @@+""" 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 ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/focalnet.py
Can you add docstrings to this Python file?
# Copyright (c) ByteDance Inc. All rights reserved. from functools import partial from typing import List, Optional, Tuple, Union, Type import torch import torch.nn.functional as F from torch import nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, calculate_drop_p...
--- +++ @@ -1,3 +1,9 @@+""" 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, Opti...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/nextvit.py
Add docstrings for better understanding
import math import warnings from functools import partial, reduce from typing import List, Optional, Tuple, Union import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from timm.layers import trunc_normal_, DropPath, Mlp, LayerNorm2d, Attention, NormMlpClassifierHead, LayerScale, Layer...
--- +++ @@ -1,3 +1,15 @@+"""CSATv2 + +A frequency-domain vision model using DCT transforms with spatial attention. + +Paper: TBD + +This model created by members of MLPA Lab. Welcome feedback and suggestion, questions. +gusdlf93@naver.com +juno.demie.oh@gmail.com + +Refined for timm by Ross Wightman +""" import math ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/csatv2.py
Add documentation for all methods
import logging import math from dataclasses import dataclass, fields, replace from functools import partial from typing import Callable, Dict, List, Optional, Set, Tuple, Type, Union, Any import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPT...
--- +++ @@ -1,3 +1,20 @@+""" 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 Fl...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/naflexvit.py
Add docstrings to existing functions
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...
--- +++ @@ -30,6 +30,15 @@ def window_partition(x, window_size: Tuple[int, int]): + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + Returns: + windows: windows after partit...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/hieradet_sam2.py
Add clean documentation to messy code
import math from functools import partial from typing import Any, Dict, List, Optional, Type, Union, Tuple import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import PatchEmbed, Mlp, GluMlp, GatedMlp, DropPath, lecun_normal_, to_2tuple from ._builder ...
--- +++ @@ -1,3 +1,43 @@+""" MLP-Mixer, ResMLP, and gMLP in PyTorch + +This impl originally based on MLP-Mixer paper. + +Official JAX impl: https://github.com/google-research/vision_transformer/blob/linen/vit_jax/models_mixer.py + +Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.0160...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/mlp_mixer.py
Include argument descriptions in docstrings
# EVA models Copyright (c) 2022 BAAI-Vision # EVA02 models Copyright (c) 2023 BAAI-Vision import math import os from functools import partial from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFA...
--- +++ @@ -1,3 +1,65 @@+""" 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...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/eva.py
Add concise docstrings to each method
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # Modified from # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # Copyright 2020 Ross Wightman, Apache-2.0 License from collections import OrderedDict from functools import partial from typing import ...
--- +++ @@ -1,3 +1,21 @@+""" LeViT + +Paper: `LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference` + - https://arxiv.org/abs/2104.01136 + +@article{graham2021levit, + title={LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference}, + author={Benjamin Graham and Alaaeldin El-Nouby ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/levit.py
Add return value explanations in docstrings
from dataclasses import dataclass, asdict, replace from functools import partial from typing import Any, Dict, List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ClassifierHead, ConvNormAct, DropPath, calculat...
--- +++ @@ -1,3 +1,17 @@+"""PyTorch CspNet + +A PyTorch implementation of Cross Stage Partial Networks including: +* CSPResNet50 +* CSPResNeXt50 +* CSPDarkNet53 +* and DarkNet53 for good measure + +Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 + +...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/cspnet.py
Document functions with detailed explanations
# # For licensing see accompanying LICENSE file. # Copyright (C) 2020 Apple Inc. All Rights Reserved. # import math from typing import Callable, Tuple, Optional, Type import torch import torch.nn.functional as F from torch import nn from timm.layers import to_2tuple, make_divisible, GroupNorm1, ConvMlp, DropPath, is_...
--- +++ @@ -1,3 +1,14 @@+""" MobileViT + +Paper: +V1: `MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer` - https://arxiv.org/abs/2110.02178 +V2: `Separable Self-attention for Mobile Vision Transformers` - https://arxiv.org/abs/2206.02680 + +MobileVitBlock and checkpoints adapted from htt...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/mobilevit.py
Document functions with clear intent
import math from functools import partial from typing import List, Optional, Tuple, Type, Union import torch import torch.nn.functional as F from torch import nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ( DropPath, calculate_drop_path_rates, LayerNorm2d, ...
--- +++ @@ -1,3 +1,12 @@+""" EdgeNeXt + +Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` + - https://arxiv.org/abs/2206.10589 + +Original code and weights from https://github.com/mmaaz60/EdgeNeXt + +Modifications and additions for timm by / Copyright 2022, Ross Wig...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/edgenext.py
Generate descriptive docstrings automatically
from typing import Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from ._fx import register_notrace_module from .padding import get_padding, get_padding_value, pad_same class StdConv2d(nn.Conv2d): def __init__( self, in_channel: int, ...
--- +++ @@ -1,3 +1,21 @@+""" 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}...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/std_conv.py
Provide clean and structured docstrings
from typing import Dict, List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ( DropPath, LayerScale, LayerScale2d, Mlp, calculate_drop_path_rates, trunc_normal_, to_2tuple, ndgri...
--- +++ @@ -1,3 +1,17 @@+""" EfficientFormer + +@article{li2022efficientformer, + title={EfficientFormer: Vision Transformers at MobileNet Speed}, + author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, + Sergey and Wang, Yanzhi and Ren, Jian}, + journal={arXiv preprin...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/efficientformer.py
Insert docstrings into my code
__all__ = ['EfficientVit', 'EfficientVitLarge'] from typing import List, Optional, Tuple, Type, Union from functools import partial 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 SelectAdaptivePool2d, create...
--- +++ @@ -1,3 +1,10 @@+""" EfficientViT (by MIT Song Han's Lab) + +Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` + - https://arxiv.org/abs/2205.14756 + +Adapted from official impl at https://github.com/mit-han-lab/efficientvit +""" __all__ = ['EfficientV...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/efficientvit_mit.py
Add docstrings for utility scripts
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: if device is not None: return str(device) == 'meta' # Check context manager (PyTorch 2.0+) if hasattr(torch, 'get_default_device'): defa...
--- +++ @@ -6,6 +6,7 @@ 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 manager (PyTorch 2.0+) @@ -52,12 +53,54 @@ def trunc_normal_(tensor, mean=0., std=1., a=-2...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/layers/weight_init.py
Add clean documentation to messy code
from typing import Any, Dict, List, Optional, Set, 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 GroupNorm1, SqueezeExcite, SelectAdaptivePool2d, LayerType, trunc_normal_ from ._builder im...
--- +++ @@ -1,3 +1,16 @@+"""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 Memo...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/shvit.py
Write documentation strings for class attributes
from typing import Any, Dict, List, Optional, Set, Tuple, Union, Type 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 DropPath, SelectAdaptivePool2d, Linear, LayerType, trunc_normal_, calculate_drop_path_rates...
--- +++ @@ -1,3 +1,14 @@+""" +Implementation of Prof-of-Concept Network: StarNet. + +We make StarNet as simple as possible [to show the key contribution of element-wise multiplication]: + - like NO layer-scale in network design, + - and NO EMA during training, + - which would improve the performance further. +...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/starnet.py
Create Google-style docstrings for my code
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, create_classifier from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs __all__ = ['NASNetALarge'] ...
--- +++ @@ -1,3 +1,7 @@+""" 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 @@ -489,6 +493,7 @@ class NASNetALarge(nn.Module): + """NASNetALarge (6...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/nasnet.py
Add standardized docstrings across the file
import math from typing import List, Optional, Tuple, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import create_classifier from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs __all__ = [...
--- +++ @@ -1,3 +1,10 @@+""" 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...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/dla.py
Generate docstrings for exported functions
from collections import OrderedDict from functools import partial from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SEModule, ConvNormAct, DropPath, calculate_drop_path_rates from ._builder import build_model_with...
--- +++ @@ -1,3 +1,10 @@+""" +TResNet: High Performance GPU-Dedicated Architecture +https://arxiv.org/pdf/2003.13630.pdf + +Original model: https://github.com/mrT23/TResNet + +""" from collections import OrderedDict from functools import partial from typing import List, Optional, Tuple, Union, Type @@ -268,6 +275,18...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/tresnet.py
Insert docstrings into my code
from functools import partial from typing import List, Optional, Tuple, Union, Callable, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, calculate_drop_path_rates, NormMlpClassifierHead, ClassifierHead, EffectiveSEModule, \ ...
--- +++ @@ -1,3 +1,8 @@+""" +RDNet +Copyright (c) 2024-present NAVER Cloud Corp. +Apache-2.0 +""" from functools import partial from typing import List, Optional, Tuple, Union, Callable, Type @@ -189,6 +194,29 @@ device=None, dtype=None, ): + """ + Args: + in_c...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/rdnet.py
Document this module using docstrings
import math from typing import Optional, Type from torch import nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectiveKernel, ConvNormAct, create_attn from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs from .res...
--- +++ @@ -1,3 +1,13 @@+""" Selective Kernel Networks (ResNet base) + +Paper: Selective Kernel Networks (https://arxiv.org/abs/1903.06586) + +This was inspired by reading 'Compounding the Performance Improvements...' (https://arxiv.org/abs/2001.06268) +and a streamlined impl at https://github.com/clovaai/assembled-cnn...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/sknet.py
Write clean docstrings for readability
# -------------------------------------------------------- # Twins # Copyright (c) 2021 Meituan # Licensed under The Apache 2.0 License [see LICENSE for details] # Written by Xinjie Li, Xiangxiang Chu # -------------------------------------------------------- import math from functools import partial from typing import...
--- +++ @@ -1,3 +1,10 @@+""" Twins +A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` + - https://arxiv.org/pdf/2104.13840.pdf + +Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below + +""" # -----------------------------------...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/twins.py