index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
17,507
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_features.py
342,343
313,346
forward
FeatureListNet
343,346
343,346
class FeatureListNet(FeatureDictNet): """ Feature extractor with list return A specialization of FeatureDictNet that always returns features as a list (values() of dict). """ def __init__( self, model: nn.Module, out_indices: OutIndicesT = (0, 1, 2, 3, 4), ...
class FeatureListNet(FeatureDictNet): """ Feature extractor with list return A specialization of FeatureDictNet that always returns features as a list (values() of dict). """ def __init__( self, model: nn.Module, out_indices: OutIndicesT = (0, 1, 2, 3, 4), ...
return list(self._collect(x).values())
return list(self._collect(x).values())
2
330
18
348
""" PyTorch Feature Extraction Helpers A collection of classes, functions, modules to help extract features from models and provide a common interface for describing them. The return_layers, module re-writing idea inspired by torchvision IntermediateLayerGetter https://github.com/pytorch/vision/blob/d88d8961ae51507d0...
""" PyTorch Feature Extraction Helpers A collection of classes, functions, modules to help extract features from models and provide a common interface for describing them. The return_layers, module re-writing idea inspired by torchvision IntermediateLayerGetter https://github.com/pytorch/vision/blob/d88d8961ae51507d0...
17,508
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_features_fx.py
95,96
1,154
create_feature_extractor
96,103
96,103
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
assert has_fx_feature_extraction, 'Please update to PyTorch 1.10+, torchvision 0.11+ for FX feature extraction' return _create_feature_extractor( model, return_nodes, tracer_kwargs={'leaf_modules': list(_leaf_modules), 'autowrap_functions': list(_autowrap_functions)} )
assert has_fx_feature_extraction, 'Please update to PyTorch 1.10+, torchvision 0.11+ for FX feature extraction' return _create_feature_extractor( model, return_nodes, tracer_kwargs={'leaf_modules': list(_leaf_modules), 'autowrap_functions': list(_autowrap_functions)} )
22
1,575
105
1,680
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
17,509
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_features_fx.py
122,123
103,126
forward
FeatureGraphNet
123,126
123,126
class FeatureGraphNet(nn.Module): """ A FX Graph based feature extractor that works with the model feature_info metadata """ def __init__( self, model: nn.Module, out_indices: Tuple[int, ...], out_map: Optional[Dict] = None, output_fmt: str = 'NCHW...
class FeatureGraphNet(nn.Module): """ A FX Graph based feature extractor that works with the model feature_info metadata """ def __init__( self, model: nn.Module, out_indices: Tuple[int, ...], out_map: Optional[Dict] = None, output_fmt: str = 'NCHW...
return list(self.graph_module(x).values())
return list(self.graph_module(x).values())
2
276
20
296
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
17,510
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_features_fx.py
149,150
126,154
forward
GraphExtractNet
150,154
150,154
class GraphExtractNet(nn.Module): """ A standalone feature extraction wrapper that maps dict -> list or single tensor NOTE: * one can use feature_extractor directly if dictionary output is desired * unlike FeatureGraphNet, this is intended to be used standalone and not with model feature_info ...
class GraphExtractNet(nn.Module): """ A standalone feature extraction wrapper that maps dict -> list or single tensor NOTE: * one can use feature_extractor directly if dictionary output is desired * unlike FeatureGraphNet, this is intended to be used standalone and not with model feature_info ...
out = list(self.graph_module(x).values()) if self.squeeze_out and len(out) == 1: return out[0] return out
out = list(self.graph_module(x).values()) if self.squeeze_out and len(out) == 1: return out[0] return out
13
293
49
342
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
""" PyTorch FX Based Feature Extraction Helpers Using https://pytorch.org/vision/stable/feature_extraction.html """ from typing import Callable, Dict, List, Optional, Union, Tuple, Type import torch from torch import nn from ._features import _get_feature_info, _get_return_layers try: from torchvision.models.fea...
17,511
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_helpers.py
88,93
1,151
remap_state_dict
96,108
93,108
""" Model creation / weight loading / state_dict helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from collections import OrderedDict from typing import Any, Callable, Dict, Optional, Union import torch try: import safetensors.torch _has_safetensors = True except ImportEr...
""" Model creation / weight loading / state_dict helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from collections import OrderedDict from typing import Any, Callable, Dict, Optional, Union import torch try: import safetensors.torch _has_safetensors = True except ImportEr...
out_dict = {} for (ka, va), (kb, vb) in zip(model.state_dict().items(), state_dict.items()): assert va.numel() == vb.numel(), f'Tensor size mismatch {ka}: {va.shape} vs {kb}: {vb.shape}. Remap failed.' if va.shape != vb.shape: if allow_reshape: vb = vb.reshape(va.shap...
""" remap checkpoint by iterating over state dicts in order (ignoring original keys). This assumes models (and originating state dict) were created with params registered in same order. """ out_dict = {} for (ka, va), (kb, vb) in zip(model.state_dict().items(), state_dict.items()): assert va...
52
1,636
189
1,825
""" Model creation / weight loading / state_dict helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from collections import OrderedDict from typing import Any, Callable, Dict, Optional, Union import torch try: import safetensors.torch _has_safetensors = True except ImportEr...
""" Model creation / weight loading / state_dict helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from collections import OrderedDict from typing import Any, Callable, Dict, Optional, Union import torch try: import safetensors.torch _has_safetensors = True except ImportEr...
17,513
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_pretrained.py
69,70
1,95
filter_pretrained_cfg
70,81
70,81
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
filtered_cfg = {} keep_null = {'pool_size', 'first_conv', 'classifier'} # always keep these keys, even if none for k, v in cfg.items(): if remove_source and k in {'url', 'file', 'hf_hub_id', 'hf_hub_id', 'hf_hub_filename', 'source'}: continue if remove_null and v is None and k n...
filtered_cfg = {} keep_null = {'pool_size', 'first_conv', 'classifier'} # always keep these keys, even if none for k, v in cfg.items(): if remove_source and k in {'url', 'file', 'hf_hub_id', 'hf_hub_id', 'hf_hub_filename', 'source'}: continue if remove_null and v is None and k n...
50
1,055
148
1,203
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
17,514
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_pretrained.py
91,93
81,95
default_with_tag
DefaultCfg
93,95
93,95
@dataclass class DefaultCfg: tags: Deque[str] = field(default_factory=deque) # priority queue of tags (first is default) cfgs: Dict[str, PretrainedCfg] = field(default_factory=dict) # pretrained cfgs by tag is_pretrained: bool = False # at least one of the configs has a pretrained source set @proper...
@dataclass class DefaultCfg: tags: Deque[str] = field(default_factory=deque) # priority queue of tags (first is default) cfgs: Dict[str, PretrainedCfg] = field(default_factory=dict) # pretrained cfgs by tag is_pretrained: bool = False # at least one of the configs has a pretrained source set @proper...
tag = self.tags[0] return tag, self.cfgs[tag]
tag = self.tags[0] return tag, self.cfgs[tag]
6
152
24
176
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
17,515
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_pretrained.py
57,59
10,69
has_weights
PretrainedCfg
59,61
59,61
@dataclass class PretrainedCfg: """ """ # weight source locations url: Optional[Union[str, Tuple[str, str]]] = None # remote URL file: Optional[str] = None # local / shared filesystem path state_dict: Optional[Dict[str, Any]] = None # in-memory state dict hf_hub_id: Optional[str] = None ...
@dataclass class PretrainedCfg: """ """ # weight source locations url: Optional[Union[str, Tuple[str, str]]] = None # remote URL file: Optional[str] = None # local / shared filesystem path state_dict: Optional[Dict[str, Any]] = None # in-memory state dict hf_hub_id: Optional[str] = None ...
return self.url or self.file or self.hf_hub_id
return self.url or self.file or self.hf_hub_id
6
770
23
793
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
import copy from collections import deque, defaultdict from dataclasses import dataclass, field, replace, asdict from typing import Any, Deque, Dict, Tuple, Optional, Union __all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg'] @dataclass class PretrainedCfg: """ """ # weight source location...
17,516
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/_prune.py
12,13
1,114
extract_layer
13,30
13,30
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): FILL_FUNC_BODYdef set_layer(model, layer, val): ...
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): FILL_FUNC_BODYdef set_layer(model, layer, val): ...
layer = layer.split('.') module = model if hasattr(model, 'module') and layer[0] != 'module': module = model.module if not hasattr(model, 'module') and layer[0] == 'module': layer = layer[1:] for l in layer: if hasattr(module, l): if not l.isdigit(): ...
layer = layer.split('.') module = model if hasattr(model, 'module') and layer[0] != 'module': module = model.module if not hasattr(model, 'module') and layer[0] == 'module': layer = layer[1:] for l in layer: if hasattr(module, l): if not l.isdigit(): ...
50
1,214
154
1,368
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): FILL_FUNC_BODYdef set_layer(model, layer, val): ...
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): FILL_FUNC_BODYdef set_layer(model, layer, val): ...
17,520
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/byobnet.py
253,254
213,271
init_weights
BasicBlock
254,260
254,260
class BasicBlock(nn.Module): """ ResNet Basic Block - kxk + kxk """ def __init__( self, in_chs: int, out_chs: int, kernel_size: int = 3, stride: int = 1, dilation: Tuple[int, int] = (1, 1), group_size: Optional[int] = None,...
class BasicBlock(nn.Module): """ ResNet Basic Block - kxk + kxk """ def __init__( self, in_chs: int, out_chs: int, kernel_size: int = 3, stride: int = 1, dilation: Tuple[int, int] = (1, 1), group_size: Optional[int] = None,...
if zero_init_last and self.shortcut is not None and getattr(self.conv2_kxk.bn, 'weight', None) is not None: nn.init.zeros_(self.conv2_kxk.bn.weight) for attn in (self.attn, self.attn_last): if hasattr(attn, 'reset_parameters'): attn.reset_parameters()
if zero_init_last and self.shortcut is not None and getattr(self.conv2_kxk.bn, 'weight', None) is not None: nn.init.zeros_(self.conv2_kxk.bn.weight) for attn in (self.attn, self.attn_last): if hasattr(attn, 'reset_parameters'): attn.reset_parameters()
24
682
113
795
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
17,521
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/byobnet.py
319,320
271,340
init_weights
BottleneckBlock
320,326
320,326
class BottleneckBlock(nn.Module): """ ResNet-like Bottleneck Block - 1x1 - kxk - 1x1 """ def __init__( self, in_chs: int, out_chs: int, kernel_size: int = 3, stride: int = 1, dilation: Tuple[int, int] = (1, 1), bottle_ratio...
class BottleneckBlock(nn.Module): """ ResNet-like Bottleneck Block - 1x1 - kxk - 1x1 """ def __init__( self, in_chs: int, out_chs: int, kernel_size: int = 3, stride: int = 1, dilation: Tuple[int, int] = (1, 1), bottle_ratio...
if zero_init_last and self.shortcut is not None and getattr(self.conv3_1x1.bn, 'weight', None) is not None: nn.init.zeros_(self.conv3_1x1.bn.weight) for attn in (self.attn, self.attn_last): if hasattr(attn, 'reset_parameters'): attn.reset_parameters()
if zero_init_last and self.shortcut is not None and getattr(self.conv3_1x1.bn, 'weight', None) is not None: nn.init.zeros_(self.conv3_1x1.bn.weight) for attn in (self.attn, self.attn_last): if hasattr(attn, 'reset_parameters'): attn.reset_parameters()
24
873
113
986
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
17,522
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/byobnet.py
1222,1224
1141,1262
group_matcher
ByobNet
1224,1233
1224,1233
class ByobNet(nn.Module): """ 'Bring-your-own-blocks' Net A flexible network backbone that allows building model stem + blocks via dataclass cfg definition w/ factory functions for module instantiation. Current assumption is that both stem and blocks are in conv-bn-act order (w/ block ending in act). ...
class ByobNet(nn.Module): """ 'Bring-your-own-blocks' Net A flexible network backbone that allows building model stem + blocks via dataclass cfg definition w/ factory functions for module instantiation. Current assumption is that both stem and blocks are in conv-bn-act order (w/ block ending in act). ...
matcher = dict( stem=r'^stem', blocks=[ (r'^stages\.(\d+)' if coarse else r'^stages\.(\d+)\.(\d+)', None), (r'^final_conv', (99999,)) ] ) return matcher
matcher = dict( stem=r'^stem', blocks=[ (r'^stages\.(\d+)' if coarse else r'^stages\.(\d+)\.(\d+)', None), (r'^final_conv', (99999,)) ] ) return matcher
17
1,333
97
1,430
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
17,523
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/byobnet.py
394,395
340,406
forward
DarkBlock
395,406
395,406
class DarkBlock(nn.Module): """ DarkNet-like (1x1 + 3x3 w/ stride) block The GE-Net impl included a 1x1 + 3x3 block in their search space. It was not used in the feature models. This block is pretty much a DarkNet block (also DenseNet) hence the name. Neither DarkNet or DenseNet uses strides within the...
class DarkBlock(nn.Module): """ DarkNet-like (1x1 + 3x3 w/ stride) block The GE-Net impl included a 1x1 + 3x3 block in their search space. It was not used in the feature models. This block is pretty much a DarkNet block (also DenseNet) hence the name. Neither DarkNet or DenseNet uses strides within the...
shortcut = x x = self.conv1_1x1(x) x = self.attn(x) x = self.conv2_kxk(x) x = self.attn_last(x) x = self.drop_path(x) if self.shortcut is not None: x = x + self.shortcut(shortcut) return self.act(x)
shortcut = x x = self.conv1_1x1(x) x = self.attn(x) x = self.conv2_kxk(x) x = self.attn_last(x) x = self.drop_path(x) if self.shortcut is not None: x = x + self.shortcut(shortcut) return self.act(x)
30
831
118
949
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
17,524
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/byobnet.py
188,189
167,192
forward
DownsampleAvg
189,192
189,192
class DownsampleAvg(nn.Module): def __init__( self, in_chs: int, out_chs: int, stride: int = 1, dilation: int = 1, apply_act: bool = False, layers: LayerFn = None, ): """ AvgPool Downsampling as in 'D' ResNet variants.""...
class DownsampleAvg(nn.Module): def __init__( self, in_chs: int, out_chs: int, stride: int = 1, dilation: int = 1, apply_act: bool = False, layers: LayerFn = None, ): """ AvgPool Downsampling as in 'D' ResNet variants.""...
return self.conv(self.pool(x))
return self.conv(self.pool(x))
2
298
18
316
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
17,525
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/byobnet.py
459,460
406,471
forward
EdgeBlock
460,471
460,471
class EdgeBlock(nn.Module): """ EdgeResidual-like (3x3 + 1x1) block A two layer block like DarkBlock, but with the order of the 3x3 and 1x1 convs reversed. Very similar to the EfficientNet Edge-Residual block but this block it ends with activations, is intended to be used with either expansion or bottl...
class EdgeBlock(nn.Module): """ EdgeResidual-like (3x3 + 1x1) block A two layer block like DarkBlock, but with the order of the 3x3 and 1x1 convs reversed. Very similar to the EfficientNet Edge-Residual block but this block it ends with activations, is intended to be used with either expansion or bottl...
shortcut = x x = self.conv1_kxk(x) x = self.attn(x) x = self.conv2_1x1(x) x = self.attn_last(x) x = self.drop_path(x) if self.shortcut is not None: x = x + self.shortcut(shortcut) return self.act(x)
shortcut = x x = self.conv1_kxk(x) x = self.attn(x) x = self.conv2_1x1(x) x = self.attn_last(x) x = self.drop_path(x) if self.shortcut is not None: x = x + self.shortcut(shortcut) return self.act(x)
30
802
118
920
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
17,528
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/byobnet.py
879,880
823,892
forward
SelfAttnBlock
880,892
880,892
class SelfAttnBlock(nn.Module): """ ResNet-like Bottleneck Block - 1x1 - optional kxk - self attn - 1x1 """ def __init__( self, in_chs: int, out_chs: int, kernel_size: int = 3, stride: int = 1, dilation: Tuple[int, int] = (1, 1), ...
class SelfAttnBlock(nn.Module): """ ResNet-like Bottleneck Block - 1x1 - optional kxk - self attn - 1x1 """ def __init__( self, in_chs: int, out_chs: int, kernel_size: int = 3, stride: int = 1, dilation: Tuple[int, int] = (1, 1), ...
shortcut = x x = self.conv1_1x1(x) x = self.conv2_kxk(x) x = self.self_attn(x) x = self.post_attn(x) x = self.conv3_1x1(x) x = self.drop_path(x) if self.shortcut is not None: x = x + self.shortcut(shortcut) return self.act(x)
shortcut = x x = self.conv1_1x1(x) x = self.conv2_kxk(x) x = self.self_attn(x) x = self.post_attn(x) x = self.conv3_1x1(x) x = self.drop_path(x) if self.shortcut is not None: x = x + self.shortcut(shortcut) return self.act(x)
33
857
136
993
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Architect...
17,531
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cait.py
46,47
27,71
forward
ClassAttn
47,71
47,71
class ClassAttn(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to do CA fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super...
class ClassAttn(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to do CA fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super...
B, N, C = x.shape q = self.q(x[:, 0]).unsqueeze(1).reshape(B, 1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) k = self.k(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1,...
B, N, C = x.shape q = self.q(x[:, 0]).unsqueeze(1).reshape(B, 1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) k = self.k(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1,...
90
328
400
728
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
17,532
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cait.py
198,199
159,204
forward
LayerScaleBlock
199,204
199,204
class LayerScaleBlock(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to add layerScale def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=...
class LayerScaleBlock(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to add layerScale def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=...
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x))) x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) return x
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x))) x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) return x
16
460
71
531
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
17,533
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cait.py
110,111
71,117
forward
LayerScaleBlockClassAttn
111,117
111,117
class LayerScaleBlockClassAttn(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to add CA and LayerScale def __init__( self, dim, num_heads, mlp_ratio=4., ...
class LayerScaleBlockClassAttn(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to add CA and LayerScale def __init__( self, dim, num_heads, mlp_ratio=4., ...
u = torch.cat((x_cls, x), dim=1) x_cls = x_cls + self.drop_path(self.gamma_1 * self.attn(self.norm1(u))) x_cls = x_cls + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x_cls))) return x_cls
u = torch.cat((x_cls, x), dim=1) x_cls = x_cls + self.drop_path(self.gamma_1 * self.attn(self.norm1(u))) x_cls = x_cls + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x_cls))) return x_cls
21
467
103
570
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
17,534
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cait.py
139,140
117,159
forward
TalkingHeadAttn
140,159
140,159
class TalkingHeadAttn(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to add Talking Heads Attention (https://arxiv.org/pdf/2003.02436v1.pdf) def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0....
class TalkingHeadAttn(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py # with slight modifications to add Talking Heads Attention (https://arxiv.org/pdf/2003.02436v1.pdf) def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0....
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] attn = q @ k.transpose(-2, -1) attn = self.proj_l(attn.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) attn = attn.so...
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] attn = q @ k.transpose(-2, -1) attn = self.proj_l(attn.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) attn = attn.so...
73
333
315
648
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
""" Class-Attention in Image Transformers (CaiT) Paper: 'Going deeper with Image Transformers' - https://arxiv.org/abs/2103.17239 Original code and weights from https://github.com/facebookresearch/deit, copyright below Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ # Copy...
17,537
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/coat.py
149,150
141,168
forward
ConvPosEnc
150,168
150,168
class ConvPosEnc(nn.Module): """ Convolutional Position Encoding. Note: This module is similar to the conditional position encoding in CPVT. """ def __init__(self, dim, k=3): super(ConvPosEnc, self).__init__() self.proj = nn.Conv2d(dim, dim, k, 1, k//2, groups=dim) def for...
class ConvPosEnc(nn.Module): """ Convolutional Position Encoding. Note: This module is similar to the conditional position encoding in CPVT. """ def __init__(self, dim, k=3): super(ConvPosEnc, self).__init__() self.proj = nn.Conv2d(dim, dim, k, 1, k//2, groups=dim) def for...
B, N, C = x.shape H, W = size _assert(N == 1 + H * W, '') # Extract CLS token and image tokens. cls_token, img_tokens = x[:, :1], x[:, 1:] # [B, 1, C], [B, H*W, C] # Depthwise convolution. feat = img_tokens.transpose(1, 2).view(B, C, H, W) x = s...
B, N, C = x.shape H, W = size _assert(N == 1 + H * W, '') # Extract CLS token and image tokens. cls_token, img_tokens = x[:, :1], x[:, 1:] # [B, 1, C], [B, H*W, C] # Depthwise convolution. feat = img_tokens.transpose(1, 2).view(B, C, H, W) x = s...
69
134
213
347
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
17,538
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/coat.py
69,70
25,91
forward
ConvRelPosEnc
70,91
70,91
class ConvRelPosEnc(nn.Module): """ Convolutional relative position encoding. """ def __init__(self, head_chs, num_heads, window): """ Initialization. Ch: Channels per head. h: Number of heads. window: Window size(s) in convolutional relative positional encodi...
class ConvRelPosEnc(nn.Module): """ Convolutional relative position encoding. """ def __init__(self, head_chs, num_heads, window): """ Initialization. Ch: Channels per head. h: Number of heads. window: Window size(s) in convolutional relative positional encodi...
B, num_heads, N, C = q.shape H, W = size _assert(N == 1 + H * W, '') # Convolutional relative position encoding. q_img = q[:, :, 1:, :] # [B, h, H*W, Ch] v_img = v[:, :, 1:, :] # [B, h, H*W, Ch] v_img = v_img.transpose(-1, -2).reshape(B, num_heads * C, H, W) ...
B, num_heads, N, C = q.shape H, W = size _assert(N == 1 + H * W, '') # Convolutional relative position encoding. q_img = q[:, :, 1:, :] # [B, h, H*W, Ch] v_img = v[:, :, 1:, :] # [B, h, H*W, Ch] v_img = v_img.transpose(-1, -2).reshape(B, num_heads * C, H, W) ...
107
592
380
972
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
17,539
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/coat.py
115,116
91,141
forward
FactorAttnConvRelPosEnc
116,141
116,141
class FactorAttnConvRelPosEnc(nn.Module): """ Factorized attention with convolutional relative position encoding class. """ def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., shared_crpe=None, ...
class FactorAttnConvRelPosEnc(nn.Module): """ Factorized attention with convolutional relative position encoding class. """ def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., shared_crpe=None, ...
B, N, C = x.shape # Generate Q, K, V. qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) # [B, h, N, Ch] # Factorized attention. k_softmax = k.softmax(dim=2) factor_att = k_softmax.transpose(-1...
B, N, C = x.shape # Generate Q, K, V. qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) # [B, h, N, Ch] # Factorized attention. k_softmax = k.softmax(dim=2) factor_att = k_softmax.transpose(-1...
107
293
346
639
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
17,540
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/coat.py
319,320
226,354
forward
ParallelBlock
320,354
320,354
class ParallelBlock(nn.Module): """ Parallel block class. """ def __init__( self, dims, num_heads, mlp_ratios=[], qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, n...
class ParallelBlock(nn.Module): """ Parallel block class. """ def __init__( self, dims, num_heads, mlp_ratios=[], qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, n...
_, S2, S3, S4 = sizes cur2 = self.norm12(x2) cur3 = self.norm13(x3) cur4 = self.norm14(x4) cur2 = self.factoratt_crpe2(cur2, size=S2) cur3 = self.factoratt_crpe3(cur3, size=S3) cur4 = self.factoratt_crpe4(cur4, size=S4) upsample3_2 = self.upsample(cur3, fa...
_, S2, S3, S4 = sizes cur2 = self.norm12(x2) cur3 = self.norm13(x3) cur4 = self.norm14(x4) cur2 = self.factoratt_crpe2(cur2, size=S2) cur3 = self.factoratt_crpe3(cur3, size=S3) cur4 = self.factoratt_crpe4(cur4, size=S4) upsample3_2 = self.upsample(cur3, fa...
133
1,144
577
1,721
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
17,541
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/coat.py
211,212
168,226
forward
SerialBlock
212,226
212,226
class SerialBlock(nn.Module): """ Serial block class. Note: In this implementation, each serial block only contains a conv-attention and a FFN (MLP) module. """ def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, proj_...
class SerialBlock(nn.Module): """ Serial block class. Note: In this implementation, each serial block only contains a conv-attention and a FFN (MLP) module. """ def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, proj_...
# Conv-Attention. x = self.cpe(x, size) cur = self.norm1(x) cur = self.factoratt_crpe(cur, size) x = x + self.drop_path(cur) # MLP. cur = self.norm2(x) cur = self.mlp(cur) x = x + self.drop_path(cur) return x
# Conv-Attention. x = self.cpe(x, size) cur = self.norm1(x) cur = self.factoratt_crpe(cur, size) x = x + self.drop_path(cur) # MLP. cur = self.norm2(x) cur = self.mlp(cur) x = x + self.drop_path(cur) return x
33
437
129
566
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
""" 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 functools import partial from typing import Tuple, List, Union import torch import torch.nn...
17,543
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convit.py
234,235
188,240
forward
Block
235,240
235,240
class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=LayerNorm, use_gpsa=T...
class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=LayerNorm, use_gpsa=T...
x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x
x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x
12
454
59
513
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
17,544
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convit.py
359,360
240,384
forward_features
ConVit
360,372
360,372
class ConVit(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__( self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, global_pool='token', embed_dim=768, ...
class ConVit(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__( self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, global_pool='token', embed_dim=768, ...
x = self.patch_embed(x) if self.use_pos_embed: x = x + self.pos_embed x = self.pos_drop(x) cls_tokens = self.cls_token.expand(x.shape[0], -1, -1) for u, blk in enumerate(self.blocks): if u == self.local_up_to_layer: x = torch.cat((cls_token...
x = self.patch_embed(x) if self.use_pos_embed: x = x + self.pos_embed x = self.pos_drop(x) cls_tokens = self.cls_token.expand(x.shape[0], -1, -1) for u, blk in enumerate(self.blocks): if u == self.local_up_to_layer: x = torch.cat((cls_token...
40
1,575
160
1,735
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
17,545
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convit.py
69,70
41,133
forward
GPSA
70,80
70,80
@register_notrace_module # reason: FX can't symbolically trace control flow in forward method class GPSA(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., locality_strength=1., ): ...
@register_notrace_module # reason: FX can't symbolically trace control flow in forward method class GPSA(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., locality_strength=1., ): ...
B, N, C = x.shape if self.rel_indices is None or self.rel_indices.shape[1] != N: self.rel_indices = self.get_rel_indices(N) attn = self.get_attention(x) v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) x = (attn @ v).transpose(1, 2)...
B, N, C = x.shape if self.rel_indices is None or self.rel_indices.shape[1] != N: self.rel_indices = self.get_rel_indices(N) attn = self.get_attention(x) v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) x = (attn @ v).transpose(1, 2)...
46
1,361
183
1,544
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
17,546
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convit.py
173,174
133,188
forward
MHSA
174,188
174,188
class MHSA(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -...
class MHSA(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -...
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpos...
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpos...
53
574
210
784
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
""" ConViT Model @article{d2021convit, title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases}, author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent}, journal={arXiv preprint arXiv:2103.10697}, year={2021} } P...
17,547
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convmixer.py
135,137
1,145
convmixer_768_32
137,141
137,141
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
model_args = dict(dim=768, depth=32, kernel_size=7, patch_size=7, act_layer=nn.ReLU, **kwargs) return _create_convmixer('convmixer_768_32', pretrained, **model_args)
model_args = dict(dim=768, depth=32, kernel_size=7, patch_size=7, act_layer=nn.ReLU, **kwargs) return _create_convmixer('convmixer_768_32', pretrained, **model_args)
12
1,611
79
1,690
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
17,548
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convmixer.py
92,93
25,103
forward_head
ConvMixer
93,97
93,97
class ConvMixer(nn.Module): def __init__( self, dim, depth, kernel_size=9, patch_size=7, in_chans=3, num_classes=1000, global_pool='avg', drop_rate=0., act_layer=nn.GELU, **kwargs, ...
class ConvMixer(nn.Module): def __init__( self, dim, depth, kernel_size=9, patch_size=7, in_chans=3, num_classes=1000, global_pool='avg', drop_rate=0., act_layer=nn.GELU, **kwargs, ...
x = self.pooling(x) x = self.head_drop(x) return x if pre_logits else self.head(x)
x = self.pooling(x) x = self.head_drop(x) return x if pre_logits else self.head(x)
12
798
44
842
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
17,549
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convmixer.py
21,22
16,25
forward
Residual
22,25
22,25
class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): FILL_FUNC_BODY
class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): FILL_FUNC_BODY
return self.fn(x) + x
return self.fn(x) + x
4
54
16
70
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
""" ConvMixer """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d from ._registry import register_model, generate_default_cfgs from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq __all__ =...
17,552
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convnext.py
151,152
81,169
forward
ConvNeXtBlock
152,169
152,169
class ConvNeXtBlock(nn.Module): """ ConvNeXt Block There are two equivalent implementations: (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back U...
class ConvNeXtBlock(nn.Module): """ ConvNeXt Block There are two equivalent implementations: (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back U...
shortcut = x x = self.conv_dw(x) if self.use_conv_mlp: x = self.norm(x) x = self.mlp(x) else: x = x.permute(0, 2, 3, 1) x = self.norm(x) x = self.mlp(x) x = x.permute(0, 3, 1, 2) if self.gamma is not None: ...
shortcut = x x = self.conv_dw(x) if self.use_conv_mlp: x = self.norm(x) x = self.mlp(x) else: x = x.permute(0, 2, 3, 1) x = self.norm(x) x = self.mlp(x) x = x.permute(0, 3, 1, 2) if self.gamma is not None: ...
51
1,069
200
1,269
""" ConvNeXt Papers: * `A ConvNet for the 2020s` - https://arxiv.org/pdf/2201.03545.pdf @Article{liu2022convnet, author = {Zhuang Liu and Hanzi Mao and Chao-Yuan Wu and Christoph Feichtenhofer and Trevor Darrell and Saining Xie}, title = {A ConvNet for the 2020s}, journal = {Proceedings of the IEEE/CVF Confer...
""" ConvNeXt Papers: * `A ConvNet for the 2020s` - https://arxiv.org/pdf/2201.03545.pdf @Article{liu2022convnet, author = {Zhuang Liu and Hanzi Mao and Chao-Yuan Wu and Christoph Feichtenhofer and Trevor Darrell and Saining Xie}, title = {A ConvNet for the 2020s}, journal = {Proceedings of the IEEE/CVF Confer...
17,553
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convnext.py
229,230
169,238
forward
ConvNeXtStage
230,238
230,238
class ConvNeXtStage(nn.Module): def __init__( self, in_chs, out_chs, kernel_size=7, stride=2, depth=2, dilation=(1, 1), drop_path_rates=None, ls_init_value=1.0, conv_mlp=False, conv_b...
class ConvNeXtStage(nn.Module): def __init__( self, in_chs, out_chs, kernel_size=7, stride=2, depth=2, dilation=(1, 1), drop_path_rates=None, ls_init_value=1.0, conv_mlp=False, conv_b...
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
18
623
77
700
""" ConvNeXt Papers: * `A ConvNet for the 2020s` - https://arxiv.org/pdf/2201.03545.pdf @Article{liu2022convnet, author = {Zhuang Liu and Hanzi Mao and Chao-Yuan Wu and Christoph Feichtenhofer and Trevor Darrell and Saining Xie}, title = {A ConvNet for the 2020s}, journal = {Proceedings of the IEEE/CVF Confer...
""" ConvNeXt Papers: * `A ConvNet for the 2020s` - https://arxiv.org/pdf/2201.03545.pdf @Article{liu2022convnet, author = {Zhuang Liu and Hanzi Mao and Chao-Yuan Wu and Christoph Feichtenhofer and Trevor Darrell and Saining Xie}, title = {A ConvNet for the 2020s}, journal = {Proceedings of the IEEE/CVF Confer...
17,554
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/convnext.py
75,76
59,81
forward
Downsample
76,81
76,81
class Downsample(nn.Module): def __init__(self, in_chs, out_chs, stride=1, dilation=1): super().__init__() avg_stride = stride if dilation == 1 else 1 if stride > 1 or dilation > 1: avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d sel...
class Downsample(nn.Module): def __init__(self, in_chs, out_chs, stride=1, dilation=1): super().__init__() avg_stride = stride if dilation == 1 else 1 if stride > 1 or dilation > 1: avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d sel...
x = self.pool(x) x = self.conv(x) return x
x = self.pool(x) x = self.conv(x) return x
8
245
31
276
""" ConvNeXt Papers: * `A ConvNet for the 2020s` - https://arxiv.org/pdf/2201.03545.pdf @Article{liu2022convnet, author = {Zhuang Liu and Hanzi Mao and Chao-Yuan Wu and Christoph Feichtenhofer and Trevor Darrell and Saining Xie}, title = {A ConvNet for the 2020s}, journal = {Proceedings of the IEEE/CVF Confer...
""" ConvNeXt Papers: * `A ConvNet for the 2020s` - https://arxiv.org/pdf/2201.03545.pdf @Article{liu2022convnet, author = {Zhuang Liu and Hanzi Mao and Chao-Yuan Wu and Christoph Feichtenhofer and Trevor Darrell and Saining Xie}, title = {A ConvNet for the 2020s}, journal = {Proceedings of the IEEE/CVF Confer...
17,556
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/crossvit.py
110,111
88,129
forward
CrossAttention
111,129
111,129
class CrossAttention(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale fac...
class CrossAttention(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale fac...
B, N, C = x.shape # B1C -> B1H(C/H) -> BH1(C/H) q = self.wq(x[:, 0:1, ...]).reshape(B, 1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) # BNC -> BNH(C/H) -> BHN(C/H) k = self.wk(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) # BNC -> ...
B, N, C = x.shape # B1C -> B1H(C/H) -> BH1(C/H) q = self.wq(x[:, 0:1, ...]).reshape(B, 1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) # BNC -> BNH(C/H) -> BHN(C/H) k = self.wk(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) # BNC -> ...
104
285
435
720
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
17,557
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/crossvit.py
155,156
129,160
forward
CrossAttentionBlock
156,160
156,160
class CrossAttentionBlock(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, )...
class CrossAttentionBlock(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, )...
x = x[:, 0:1, ...] + self.drop_path(self.attn(self.norm1(x))) return x
x = x[:, 0:1, ...] + self.drop_path(self.attn(self.norm1(x))) return x
9
267
43
310
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
17,559
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/crossvit.py
249,250
160,271
forward
MultiScaleBlock
250,271
250,271
class MultiScaleBlock(nn.Module): def __init__( self, dim, patches, depth, num_heads, mlp_ratio, qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, ...
class MultiScaleBlock(nn.Module): def __init__( self, dim, patches, depth, num_heads, mlp_ratio, qkv_bias=False, proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, ...
outs_b = [] for i, block in enumerate(self.blocks): outs_b.append(block(x[i])) # only take the cls token out proj_cls_token = torch.jit.annotate(List[torch.Tensor], []) for i, proj in enumerate(self.projs): proj_cls_token.append(proj(outs_b[i][:, 0:1, .....
outs_b = [] for i, block in enumerate(self.blocks): outs_b.append(block(x[i])) # only take the cls token out proj_cls_token = torch.jit.annotate(List[torch.Tensor], []) for i, proj in enumerate(self.projs): proj_cls_token.append(proj(outs_b[i][:, 0:1, .....
70
995
318
1,313
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
17,560
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/crossvit.py
77,78
45,88
forward
PatchEmbed
78,88
78,88
class PatchEmbed(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, multi_conv=False): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) num_patches = (img_size[1] // patc...
class PatchEmbed(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, multi_conv=False): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) num_patches = (img_size[1] // patc...
B, C, H, W = x.shape # FIXME look at relaxing size constraints _assert(H == self.img_size[0], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).") _assert(W == self.img_size[1], f"Input image size ({H}*{W}) doesn't ma...
B, C, H, W = x.shape # FIXME look at relaxing size constraints _assert(H == self.img_size[0], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).") _assert(W == self.img_size[1], f"Input image size ({H}*{W}) doesn't ma...
41
587
173
760
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
""" CrossViT Model @inproceedings{ chen2021crossvit, title={{CrossViT: Cross-Attention Multi-Scale Vision Transformer for Image Classification}}, author={Chun-Fu (Richard) Chen and Quanfu Fan and Rameswar Panda}, booktitle={International Conference on Computer Vision (ICCV)}, year={2021} } Paper l...
17,562
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cspnet.py
172,173
135,186
forward
BottleneckBlock
173,186
173,186
class BottleneckBlock(nn.Module): """ ResNe(X)t Bottleneck Block """ def __init__( self, in_chs, out_chs, dilation=1, bottle_ratio=0.25, groups=1, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_l...
class BottleneckBlock(nn.Module): """ ResNe(X)t Bottleneck Block """ def __init__( self, in_chs, out_chs, dilation=1, bottle_ratio=0.25, groups=1, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_l...
shortcut = x x = self.conv1(x) x = self.conv2(x) x = self.attn2(x) x = self.conv3(x) x = self.attn3(x) x = self.drop_path(x) + shortcut # FIXME partial shortcut needed if first block handled as per original, not used for my current impl #x[:, :shor...
shortcut = x x = self.conv1(x) x = self.conv2(x) x = self.attn2(x) x = self.conv3(x) x = self.attn3(x) x = self.drop_path(x) + shortcut # FIXME partial shortcut needed if first block handled as per original, not used for my current impl #x[:, :shor...
50
537
145
682
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
17,563
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cspnet.py
333,334
266,343
forward
CrossStage
334,343
334,343
class CrossStage(nn.Module): """Cross Stage.""" def __init__( self, in_chs, out_chs, stride, dilation, depth, block_ratio=1., bottle_ratio=1., expand_ratio=1., groups=1, first_dila...
class CrossStage(nn.Module): """Cross Stage.""" def __init__( self, in_chs, out_chs, stride, dilation, depth, block_ratio=1., bottle_ratio=1., expand_ratio=1., groups=1, first_dila...
x = self.conv_down(x) x = self.conv_exp(x) xs, xb = x.split(self.expand_chs // 2, dim=1) xb = self.blocks(xb) xb = self.conv_transition_b(xb).contiguous() out = self.conv_transition(torch.cat([xs, xb], dim=1)) return out
x = self.conv_down(x) x = self.conv_exp(x) xs, xb = x.split(self.expand_chs // 2, dim=1) xb = self.blocks(xb) xb = self.conv_transition_b(xb).contiguous() out = self.conv_transition(torch.cat([xs, xb], dim=1)) return out
26
923
121
1,044
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
17,564
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cspnet.py
409,410
343,418
forward
CrossStage3
410,418
410,418
class CrossStage3(nn.Module): """Cross Stage 3. Similar to CrossStage, but with only one transition conv for the output. """ def __init__( self, in_chs, out_chs, stride, dilation, depth, block_ratio=1., bottl...
class CrossStage3(nn.Module): """Cross Stage 3. Similar to CrossStage, but with only one transition conv for the output. """ def __init__( self, in_chs, out_chs, stride, dilation, depth, block_ratio=1., bottl...
x = self.conv_down(x) x = self.conv_exp(x) x1, x2 = x.split(self.expand_chs // 2, dim=1) x1 = self.blocks(x1) out = self.conv_transition(torch.cat([x1, x2], dim=1)) return out
x = self.conv_down(x) x = self.conv_exp(x) x1, x2 = x.split(self.expand_chs // 2, dim=1) x1 = self.blocks(x1) out = self.conv_transition(torch.cat([x1, x2], dim=1)) return out
23
841
101
942
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
17,565
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cspnet.py
715,716
616,721
forward
CspNet
716,721
716,721
class CspNet(nn.Module): """Cross Stage Partial base model. Paper: `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Ref Impl: https://github.com/WongKinYiu/CrossStagePartialNetworks NOTE: There are differences in the way I handle the 1x1 'expansio...
class CspNet(nn.Module): """Cross Stage Partial base model. Paper: `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Ref Impl: https://github.com/WongKinYiu/CrossStagePartialNetworks NOTE: There are differences in the way I handle the 1x1 'expansio...
x = self.forward_features(x) x = self.forward_head(x) return x
x = self.forward_features(x) x = self.forward_head(x) return x
8
1,240
35
1,275
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
17,566
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cspnet.py
217,218
186,226
forward
DarkBlock
218,226
218,226
class DarkBlock(nn.Module): """ DarkNet Block """ def __init__( self, in_chs, out_chs, dilation=1, bottle_ratio=0.5, groups=1, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_layer=None, ...
class DarkBlock(nn.Module): """ DarkNet Block """ def __init__( self, in_chs, out_chs, dilation=1, bottle_ratio=0.5, groups=1, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_layer=None, ...
shortcut = x x = self.conv1(x) x = self.attn(x) x = self.conv2(x) x = self.drop_path(x) + shortcut return x
shortcut = x x = self.conv1(x) x = self.attn(x) x = self.conv2(x) x = self.drop_path(x) + shortcut return x
19
381
66
447
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
17,567
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cspnet.py
467,468
418,473
forward
DarkStage
468,473
468,473
class DarkStage(nn.Module): """DarkNet stage.""" def __init__( self, in_chs, out_chs, stride, dilation, depth, block_ratio=1., bottle_ratio=1., groups=1, first_dilation=None, avg_...
class DarkStage(nn.Module): """DarkNet stage.""" def __init__( self, in_chs, out_chs, stride, dilation, depth, block_ratio=1., bottle_ratio=1., groups=1, first_dilation=None, avg_...
x = self.conv_down(x) x = self.blocks(x) return x
x = self.conv_down(x) x = self.blocks(x) return x
8
577
33
610
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
17,568
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/cspnet.py
257,258
226,266
forward
EdgeBlock
258,266
258,266
class EdgeBlock(nn.Module): """ EdgeResidual / Fused-MBConv / MobileNetV1-like 3x3 + 1x1 block (w/ activated output) """ def __init__( self, in_chs, out_chs, dilation=1, bottle_ratio=0.5, groups=1, act_layer=nn.ReLU, ...
class EdgeBlock(nn.Module): """ EdgeResidual / Fused-MBConv / MobileNetV1-like 3x3 + 1x1 block (w/ activated output) """ def __init__( self, in_chs, out_chs, dilation=1, bottle_ratio=0.5, groups=1, act_layer=nn.ReLU, ...
shortcut = x x = self.conv1(x) x = self.attn(x) x = self.conv2(x) x = self.drop_path(x) + shortcut return x
shortcut = x x = self.conv1(x) x = self.attn(x) x = self.conv2(x) x = self.drop_path(x) + shortcut return x
19
409
66
475
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
"""PyTorch CspNet A PyTorch implementation of Cross Stage Partial Networks including: * CSPResNet50 * CSPResNeXt50 * CSPDarkNet53 * and DarkNet53 for good measure Based on paper `CSPNet: A New Backbone that can Enhance Learning Capability of CNN` - https://arxiv.org/abs/1911.11929 Reference impl via darknet cfg file...
17,570
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
122,123
111,137
forward
ChannelAttention
123,137
123,137
class ChannelAttention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(d...
class ChannelAttention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(d...
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) k = k * self.scale attention = k.transpose(-1, -2) @ v attention = attention.softmax(dim=-1) x = (attention @ q.transpose(-1,...
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) k = k * self.scale attention = k.transpose(-1, -2) @ v attention = attention.softmax(dim=-1) x = (attention @ q.transpose(-1,...
55
152
205
357
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,571
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
173,174
137,192
forward
ChannelBlock
174,192
174,192
class ChannelBlock(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ffn=True, cpe_act=False, ): ...
class ChannelBlock(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ffn=True, cpe_act=False, ): ...
B, C, H, W = x.shape x = self.cpe1(x).flatten(2).transpose(1, 2) cur = self.norm1(x) cur = self.attn(cur) x = x + self.drop_path1(cur) x = self.cpe2(x.transpose(1, 2).view(B, C, H, W)) if self.mlp is not None: x = x.flatten(2).transpose(1, 2) ...
B, C, H, W = x.shape x = self.cpe1(x).flatten(2).transpose(1, 2) cur = self.norm1(x) cur = self.attn(cur) x = x + self.drop_path1(cur) x = self.cpe2(x.transpose(1, 2).view(B, C, H, W)) if self.mlp is not None: x = x.flatten(2).transpose(1, 2) ...
51
405
213
618
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,572
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
40,41
33,46
forward
ConvPosEnc
41,46
41,46
class ConvPosEnc(nn.Module): def __init__(self, dim: int, k: int = 3, act: bool = False): super(ConvPosEnc, self).__init__() self.proj = nn.Conv2d(dim, dim, k, 1, k // 2, groups=dim) self.act = nn.GELU() if act else nn.Identity() def forward(self, x: Tensor): FILL_FUNC_BODY
class ConvPosEnc(nn.Module): def __init__(self, dim: int, k: int = 3, act: bool = False): super(ConvPosEnc, self).__init__() self.proj = nn.Conv2d(dim, dim, k, 1, k // 2, groups=dim) self.act = nn.GELU() if act else nn.Identity() def forward(self, x: Tensor): FILL_FUNC_BODY
feat = self.proj(x) x = x + self.act(feat) return x
feat = self.proj(x) x = x + self.act(feat) return x
10
127
34
161
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,573
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
574,575
443,592
forward_features
DaVit
575,583
575,583
class DaVit(nn.Module): r""" DaViT A PyTorch implementation of `DaViT: Dual Attention Vision Transformers` - https://arxiv.org/abs/2204.03645 Supports arbitrary input sizes and pyramid feature extraction Args: in_chans (int): Number of input image channels. Default: 3 n...
class DaVit(nn.Module): r""" DaViT A PyTorch implementation of `DaViT: Dual Attention Vision Transformers` - https://arxiv.org/abs/2204.03645 Supports arbitrary input sizes and pyramid feature extraction Args: in_chans (int): Number of input image channels. Default: 3 n...
x = self.stem(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.stages, x) else: x = self.stages(x) x = self.norm_pre(x) return x
x = self.stem(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.stages, x) else: x = self.stages(x) x = self.norm_pre(x) return x
21
1,797
90
1,887
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,574
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
434,435
365,443
forward
DaVitStage
435,443
435,443
class DaVitStage(nn.Module): def __init__( self, in_chs, out_chs, depth=1, downsample=True, attn_types=('spatial', 'channel'), num_heads=3, window_size=7, mlp_ratio=4, qkv_bias=True, d...
class DaVitStage(nn.Module): def __init__( self, in_chs, out_chs, depth=1, downsample=True, attn_types=('spatial', 'channel'), num_heads=3, window_size=7, mlp_ratio=4, qkv_bias=True, d...
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
18
708
77
785
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,575
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
102,103
82,111
forward
Downsample
103,111
103,111
class Downsample(nn.Module): def __init__( self, in_chs, out_chs, norm_layer=LayerNorm2d, ): super().__init__() self.in_chs = in_chs self.out_chs = out_chs self.norm = norm_layer(in_chs) self.conv = nn.Conv2d( i...
class Downsample(nn.Module): def __init__( self, in_chs, out_chs, norm_layer=LayerNorm2d, ): super().__init__() self.in_chs = in_chs self.out_chs = out_chs self.norm = norm_layer(in_chs) self.conv = nn.Conv2d( i...
B, C, H, W = x.shape x = self.norm(x) x = F.pad(x, (0, (2 - W % 2) % 2)) x = F.pad(x, (0, 0, 0, (2 - H % 2) % 2)) x = self.conv(x) return x
B, C, H, W = x.shape x = self.norm(x) x = F.pad(x, (0, (2 - W % 2) % 2)) x = F.pad(x, (0, 0, 0, (2 - H % 2) % 2)) x = self.conv(x) return x
38
173
103
276
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,576
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
325,326
267,365
forward
SpatialBlock
326,365
326,365
class SpatialBlock(nn.Module): r""" Windows Block. Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. window_size (int): Window size. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a...
class SpatialBlock(nn.Module): r""" Windows Block. Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. window_size (int): Window size. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a...
B, C, H, W = x.shape shortcut = self.cpe1(x).flatten(2).transpose(1, 2) x = self.norm1(shortcut) x = x.view(B, H, W, C) pad_l = pad_t = 0 pad_r = (self.window_size[1] - W % self.window_size[1]) % self.window_size[1] pad_b = (self.window_size[0] - H % self.windo...
B, C, H, W = x.shape shortcut = self.cpe1(x).flatten(2).transpose(1, 2) x = self.norm1(shortcut) x = x.view(B, H, W, C) pad_l = pad_t = 0 pad_r = (self.window_size[1] - W % self.window_size[1]) % self.window_size[1] pad_b = (self.window_size[0] - H % self.windo...
145
670
568
1,238
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,577
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
73,74
46,82
forward
Stem
74,82
74,82
class Stem(nn.Module): """ Size-agnostic implementation of 2D image to patch embedding, allowing input size to be adjusted during model forward operation """ def __init__( self, in_chs=3, out_chs=96, stride=4, norm_layer=LayerNorm2d, )...
class Stem(nn.Module): """ Size-agnostic implementation of 2D image to patch embedding, allowing input size to be adjusted during model forward operation """ def __init__( self, in_chs=3, out_chs=96, stride=4, norm_layer=LayerNorm2d, )...
B, C, H, W = x.shape x = F.pad(x, (0, (self.stride[1] - W % self.stride[1]) % self.stride[1])) x = F.pad(x, (0, 0, 0, (self.stride[0] - H % self.stride[0]) % self.stride[0])) x = self.conv(x) x = self.norm(x) return x
B, C, H, W = x.shape x = F.pad(x, (0, (self.stride[1] - W % self.stride[1]) % self.stride[1])) x = F.pad(x, (0, 0, 0, (self.stride[0] - H % self.stride[0]) % self.stride[0])) x = self.conv(x) x = self.norm(x) return x
38
260
131
391
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,578
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/davit.py
248,249
223,267
forward
WindowAttention
249,267
249,267
class WindowAttention(nn.Module): r""" Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_h...
class WindowAttention(nn.Module): r""" Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_h...
B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) if self.fused_attn: x = F.scaled_dot_product_attention(q, k, v) else: q = q * self.scale attn = (q @ k....
B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) if self.fused_attn: x = F.scaled_dot_product_attention(q, k, v) else: q = q * self.scale attn = (q @ k....
61
349
230
579
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/...
17,580
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/deit.py
54,56
29,121
group_matcher
VisionTransformerDistilled
56,63
56,63
class VisionTransformerDistilled(VisionTransformer): """ Vision Transformer w/ Distillation Token and Head Distillation token & head support for `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877 """ def __init__(self, *args, **kwargs): weight_init = kwargs.po...
class VisionTransformerDistilled(VisionTransformer): """ Vision Transformer w/ Distillation Token and Head Distillation token & head support for `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877 """ def __init__(self, *args, **kwargs): weight_init = kwargs.po...
return dict( stem=r'^cls_token|pos_embed|patch_embed|dist_token', blocks=[ (r'^blocks\.(\d+)', None), (r'^norm', (99999,))] # final norm w/ last block )
return dict( stem=r'^cls_token|pos_embed|patch_embed|dist_token', blocks=[ (r'^blocks\.(\d+)', None), (r'^norm', (99999,))] # final norm w/ last block )
15
1,107
85
1,192
""" DeiT - Data-efficient Image Transformers DeiT model defs and weights from https://github.com/facebookresearch/deit, original copyright below paper: `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877 paper: `DeiT III: Revenge of the ViT` - https://arxiv.org/abs/2204.07118 Modifications ...
""" DeiT - Data-efficient Image Transformers DeiT model defs and weights from https://github.com/facebookresearch/deit, original copyright below paper: `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877 paper: `DeiT III: Revenge of the ViT` - https://arxiv.org/abs/2204.07118 Modifications ...
17,582
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/dla.py
335,337
261,386
group_matcher
DLA
337,348
337,348
class DLA(nn.Module): def __init__( self, levels, channels, output_stride=32, num_classes=1000, in_chans=3, global_pool='avg', cardinality=1, base_width=64, block=DlaBottle2neck, short...
class DLA(nn.Module): def __init__( self, levels, channels, output_stride=32, num_classes=1000, in_chans=3, global_pool='avg', cardinality=1, base_width=64, block=DlaBottle2neck, short...
matcher = dict( stem=r'^base_layer', blocks=r'^level(\d+)' if coarse else [ # an unusual arch, this achieves somewhat more granularity without getting super messy (r'^level(\d+)\.tree(\d+)', None), (r'^level(\d+)\.root', (2,)), ...
matcher = dict( stem=r'^base_layer', blocks=r'^level(\d+)' if coarse else [ # an unusual arch, this achieves somewhat more granularity without getting super messy (r'^level(\d+)\.tree(\d+)', None), (r'^level(\d+)\.root', (2,)), ...
32
1,502
131
1,633
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
17,583
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/dla.py
39,40
23,56
forward
DlaBasic
40,56
40,56
class DlaBasic(nn.Module): """DLA Basic""" def __init__(self, inplanes, planes, stride=1, dilation=1, **_): super(DlaBasic, self).__init__() self.conv1 = nn.Conv2d( inplanes, planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation) s...
class DlaBasic(nn.Module): """DLA Basic""" def __init__(self, inplanes, planes, stride=1, dilation=1, **_): super(DlaBasic, self).__init__() self.conv1 = nn.Conv2d( inplanes, planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation) s...
if shortcut is None: shortcut = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out += shortcut out = self.relu(out) return out
if shortcut is None: shortcut = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out += shortcut out = self.relu(out) return out
30
272
109
381
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
17,584
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/dla.py
130,131
97,166
forward
DlaBottle2neck
131,166
131,166
class DlaBottle2neck(nn.Module): """ Res2Net/Res2NeXT DLA Bottleneck Adapted from https://github.com/gasvn/Res2Net/blob/master/dla.py """ expansion = 2 def __init__(self, inplanes, outplanes, stride=1, dilation=1, scale=4, cardinality=8, base_width=4): super(DlaBottle2neck, self).__init__()...
class DlaBottle2neck(nn.Module): """ Res2Net/Res2NeXT DLA Bottleneck Adapted from https://github.com/gasvn/Res2Net/blob/master/dla.py """ expansion = 2 def __init__(self, inplanes, outplanes, stride=1, dilation=1, scale=4, cardinality=8, base_width=4): super(DlaBottle2neck, self).__init__()...
if shortcut is None: shortcut = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) spx = torch.split(out, self.width, 1) spo = [] sp = spx[0] # redundant, for torchscript for i, (conv, bn) in enumerate(zip(self.convs, self.bns)):...
if shortcut is None: shortcut = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) spx = torch.split(out, self.width, 1) spo = [] sp = spx[0] # redundant, for torchscript for i, (conv, bn) in enumerate(zip(self.convs, self.bns)):...
101
583
352
935
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
17,585
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/dla.py
76,77
56,97
forward
DlaBottleneck
77,97
77,97
class DlaBottleneck(nn.Module): """DLA/DLA-X Bottleneck""" expansion = 2 def __init__(self, inplanes, outplanes, stride=1, dilation=1, cardinality=1, base_width=64): super(DlaBottleneck, self).__init__() self.stride = stride mid_planes = int(math.floor(outplanes * (base_width / 64))...
class DlaBottleneck(nn.Module): """DLA/DLA-X Bottleneck""" expansion = 2 def __init__(self, inplanes, outplanes, stride=1, dilation=1, cardinality=1, base_width=64): super(DlaBottleneck, self).__init__() self.stride = stride mid_planes = int(math.floor(outplanes * (base_width / 64))...
if shortcut is None: shortcut = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += shortcut ...
if shortcut is None: shortcut = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += shortcut ...
39
404
147
551
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
17,586
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/dla.py
175,176
166,185
forward
DlaRoot
176,185
176,185
class DlaRoot(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, shortcut): super(DlaRoot, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 1, stride=1, bias=False, padding=(kernel_size - 1) // 2) self.bn = nn.BatchNorm2d(out_channels) ...
class DlaRoot(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, shortcut): super(DlaRoot, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, 1, stride=1, bias=False, padding=(kernel_size - 1) // 2) self.bn = nn.BatchNorm2d(out_channels) ...
x = self.conv(torch.cat(x_children, 1)) x = self.bn(x) if self.shortcut: x += x_children[0] x = self.relu(x) return x
x = self.conv(torch.cat(x_children, 1)) x = self.bn(x) if self.shortcut: x += x_children[0] x = self.relu(x) return x
17
177
75
252
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
17,587
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/dla.py
244,245
185,261
forward
DlaTree
245,261
245,261
class DlaTree(nn.Module): def __init__( self, levels, block, in_channels, out_channels, stride=1, dilation=1, cardinality=1, base_width=64, level_root=False, root_dim=0, ro...
class DlaTree(nn.Module): def __init__( self, levels, block, in_channels, out_channels, stride=1, dilation=1, cardinality=1, base_width=64, level_root=False, root_dim=0, ro...
if children is None: children = [] bottom = self.downsample(x) shortcut = self.project(bottom) if self.level_root: children.append(bottom) x1 = self.tree1(x, shortcut) if self.root is not None: # levels == 1 x2 = self.tree2(x1) ...
if children is None: children = [] bottom = self.downsample(x) shortcut = self.project(bottom) if self.level_root: children.append(bottom) x1 = self.tree1(x, shortcut) if self.root is not None: # levels == 1 x2 = self.tree2(x1) ...
47
696
160
856
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
""" Deep Layer Aggregation and DLA w/ Res2Net DLA original adapted from Official Pytorch impl at: https://github.com/ucbdrive/dla DLA Paper: `Deep Layer Aggregation` - https://arxiv.org/abs/1707.06484 Res2Net additions from: https://github.com/gasvn/Res2Net/ Res2Net Paper: `Res2Net: A New Multi-scale Backbone Architec...
17,589
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/edgenext.py
91,92
67,108
forward
ConvBlock
92,108
92,108
class ConvBlock(nn.Module): def __init__( self, dim, dim_out=None, kernel_size=7, stride=1, conv_bias=True, expand_ratio=4, ls_init_value=1e-6, norm_layer=partial(nn.LayerNorm, eps=1e-6), act_laye...
class ConvBlock(nn.Module): def __init__( self, dim, dim_out=None, kernel_size=7, stride=1, conv_bias=True, expand_ratio=4, ls_init_value=1e-6, norm_layer=partial(nn.LayerNorm, eps=1e-6), act_laye...
shortcut = x x = self.conv_dw(x) if self.shortcut_after_dw: shortcut = x x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) x = self.norm(x) x = self.mlp(x) if self.gamma is not None: x = self.gamma * x x = x.permute(0, 3, 1...
shortcut = x x = self.conv_dw(x) if self.shortcut_after_dw: shortcut = x x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) x = self.norm(x) x = self.mlp(x) if self.gamma is not None: x = self.gamma * x x = x.permute(0, 3, 1...
66
342
200
542
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
17,590
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/edgenext.py
126,127
108,147
forward
CrossCovarianceAttn
127,142
127,142
class CrossCovarianceAttn(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0. ): super().__init__() self.num_heads = num_heads self.temperature = nn.Parameter(torch.ones(num_h...
class CrossCovarianceAttn(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0. ): super().__init__() self.num_heads = num_heads self.temperature = nn.Parameter(torch.ones(num_h...
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 4, 1) q, k, v = qkv.unbind(0) # NOTE, this is NOT spatial attn, q, k, v are B, num_heads, C, L --> C x C attn map attn = (F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1))...
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 4, 1) q, k, v = qkv.unbind(0) # NOTE, this is NOT spatial attn, q, k, v are B, num_heads, C, L --> C x C attn map attn = (F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1))...
79
251
275
526
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
17,591
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/edgenext.py
430,431
300,436
forward
EdgeNeXt
431,436
431,436
class EdgeNeXt(nn.Module): def __init__( self, in_chans=3, num_classes=1000, global_pool='avg', dims=(24, 48, 88, 168), depths=(3, 3, 9, 3), global_block_counts=(0, 1, 1, 1), kernel_sizes=(3, 5, 7, 9), heads=...
class EdgeNeXt(nn.Module): def __init__( self, in_chans=3, num_classes=1000, global_pool='avg', dims=(24, 48, 88, 168), depths=(3, 3, 9, 3), global_block_counts=(0, 1, 1, 1), kernel_sizes=(3, 5, 7, 9), heads=...
x = self.forward_features(x) x = self.forward_head(x) return x
x = self.forward_features(x) x = self.forward_head(x) return x
8
1,558
35
1,593
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
17,592
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/edgenext.py
291,292
223,300
forward
EdgeNeXtStage
292,300
292,300
class EdgeNeXtStage(nn.Module): def __init__( self, in_chs, out_chs, stride=2, depth=2, num_global_blocks=1, num_heads=4, scales=2, kernel_size=7, expand_ratio=4, use_pos_emb=False, ...
class EdgeNeXtStage(nn.Module): def __init__( self, in_chs, out_chs, stride=2, depth=2, num_global_blocks=1, num_heads=4, scales=2, kernel_size=7, expand_ratio=4, use_pos_emb=False, ...
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
18
679
77
756
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
17,593
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/edgenext.py
40,41
30,67
forward
PositionalEncodingFourier
41,67
41,67
@register_notrace_module # reason: FX can't symbolically trace torch.arange in forward method class PositionalEncodingFourier(nn.Module): def __init__(self, hidden_dim=32, dim=768, temperature=10000): super().__init__() self.token_projection = nn.Conv2d(hidden_dim * 2, dim, kernel_size=1) s...
@register_notrace_module # reason: FX can't symbolically trace torch.arange in forward method class PositionalEncodingFourier(nn.Module): def __init__(self, hidden_dim=32, dim=768, temperature=10000): super().__init__() self.token_projection = nn.Conv2d(hidden_dim * 2, dim, kernel_size=1) s...
device = self.token_projection.weight.device dtype = self.token_projection.weight.dtype inv_mask = ~torch.zeros(shape).to(device=device, dtype=torch.bool) y_embed = inv_mask.cumsum(1, dtype=torch.float32) x_embed = inv_mask.cumsum(2, dtype=torch.float32) eps = 1e-6 ...
device = self.token_projection.weight.device dtype = self.token_projection.weight.dtype inv_mask = ~torch.zeros(shape).to(device=device, dtype=torch.bool) y_embed = inv_mask.cumsum(1, dtype=torch.float32) x_embed = inv_mask.cumsum(2, dtype=torch.float32) eps = 1e-6 ...
112
176
505
681
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
17,594
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/edgenext.py
187,188
147,223
forward
SplitTransposeBlock
188,223
188,223
class SplitTransposeBlock(nn.Module): def __init__( self, dim, num_scales=1, num_heads=8, expand_ratio=4, use_pos_emb=True, conv_bias=True, qkv_bias=True, ls_init_value=1e-6, norm_layer=partial(nn...
class SplitTransposeBlock(nn.Module): def __init__( self, dim, num_scales=1, num_heads=8, expand_ratio=4, use_pos_emb=True, conv_bias=True, qkv_bias=True, ls_init_value=1e-6, norm_layer=partial(nn...
shortcut = x # scales code re-written for torchscript as per my res2net fixes -rw # NOTE torch.split(x, self.width, 1) causing issues with ONNX export spx = x.chunk(len(self.convs) + 1, dim=1) spo = [] sp = spx[0] for i, conv in enumerate(self.convs): ...
shortcut = x # scales code re-written for torchscript as per my res2net fixes -rw # NOTE torch.split(x, self.width, 1) causing issues with ONNX export spx = x.chunk(len(self.convs) + 1, dim=1) spo = [] sp = spx[0] for i, conv in enumerate(self.convs): ...
151
582
482
1,064
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
""" EdgeNeXt Paper: `EdgeNeXt: Efficiently Amalgamated CNN-Transformer Architecture for Mobile Vision Applications` - https://arxiv.org/abs/2206.10589 Original code and weights from https://github.com/mmaaz60/EdgeNeXt Modifications and additions for timm by / Copyright 2022, Ross Wightman """ import math from colle...
17,596
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
74,76
43,104
train
Attention
76,80
76,80
class Attention(torch.nn.Module): attention_bias_cache: Dict[str, torch.Tensor] def __init__( self, dim=384, key_dim=32, num_heads=8, attn_ratio=4, resolution=7 ): super().__init__() self.num_heads = num_heads s...
class Attention(torch.nn.Module): attention_bias_cache: Dict[str, torch.Tensor] def __init__( self, dim=384, key_dim=32, num_heads=8, attn_ratio=4, resolution=7 ): super().__init__() self.num_heads = num_heads s...
super().train(mode) if mode and self.attention_bias_cache: self.attention_bias_cache = {} # clear ab cache
super().train(mode) if mode and self.attention_bias_cache: self.attention_bias_cache = {} # clear ab cache
12
866
44
910
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,597
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
186,187
161,197
forward
ConvMlpWithNorm
187,197
187,197
class ConvMlpWithNorm(nn.Module): """ Implementation of MLP with 1*1 convolutions. Input: tensor with shape [B, C, H, W] """ def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, norm_laye...
class ConvMlpWithNorm(nn.Module): """ Implementation of MLP with 1*1 convolutions. Input: tensor with shape [B, C, H, W] """ def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, norm_laye...
x = self.fc1(x) x = self.norm1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.norm2(x) x = self.drop(x) return x
x = self.fc1(x) x = self.norm1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.norm2(x) x = self.drop(x) return x
23
305
90
395
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,598
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
131,132
117,137
forward
Downsample
132,137
132,137
class Downsample(nn.Module): """ Downsampling via strided conv w/ norm Input: tensor in shape [B, C, H, W] Output: tensor in shape [B, C, H/stride, W/stride] """ def __init__(self, in_chs, out_chs, kernel_size=3, stride=2, padding=None, norm_layer=nn.BatchNorm2d): super().__init__() ...
class Downsample(nn.Module): """ Downsampling via strided conv w/ norm Input: tensor in shape [B, C, H, W] Output: tensor in shape [B, C, H/stride, W/stride] """ def __init__(self, in_chs, out_chs, kernel_size=3, stride=2, padding=None, norm_layer=nn.BatchNorm2d): super().__init__() ...
x = self.conv(x) x = self.norm(x) return x
x = self.conv(x) x = self.norm(x) return x
8
212
31
243
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,600
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
347,348
285,356
forward
EfficientFormerStage
348,356
348,356
class EfficientFormerStage(nn.Module): def __init__( self, dim, dim_out, depth, downsample=True, num_vit=1, pool_size=3, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, no...
class EfficientFormerStage(nn.Module): def __init__( self, dim, dim_out, depth, downsample=True, num_vit=1, pool_size=3, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, no...
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
18
580
77
657
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,601
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
142,143
137,147
forward
Flat
143,147
143,147
class Flat(nn.Module): def __init__(self, ): super().__init__() def forward(self, x): FILL_FUNC_BODY
class Flat(nn.Module): def __init__(self, ): super().__init__() def forward(self, x): FILL_FUNC_BODY
x = x.flatten(2).transpose(1, 2) return x
x = x.flatten(2).transpose(1, 2) return x
6
47
29
76
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,602
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
203,204
197,207
forward
LayerScale
204,207
204,207
class LayerScale(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): FILL_FUNC_BODY
class LayerScale(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): FILL_FUNC_BODY
return x.mul_(self.gamma) if self.inplace else x * self.gamma
return x.mul_(self.gamma) if self.inplace else x * self.gamma
8
93
28
121
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,603
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
246,247
240,251
forward
LayerScale2d
247,251
247,251
class LayerScale2d(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): FILL_FUNC_BODY
class LayerScale2d(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): FILL_FUNC_BODY
gamma = self.gamma.view(1, -1, 1, 1) return x.mul_(gamma) if self.inplace else x * gamma
gamma = self.gamma.view(1, -1, 1, 1) return x.mul_(gamma) if self.inplace else x * gamma
14
95
46
141
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,604
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
234,235
207,240
forward
MetaBlock1d
235,240
235,240
class MetaBlock1d(nn.Module): def __init__( self, dim, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.LayerNorm, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5 ): super().__init__() self.nor...
class MetaBlock1d(nn.Module): def __init__( self, dim, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.LayerNorm, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5 ): super().__init__() self.nor...
x = x + self.drop_path(self.ls1(self.token_mixer(self.norm1(x)))) x = x + self.drop_path(self.ls2(self.mlp(self.norm2(x)))) return x
x = x + self.drop_path(self.ls1(self.token_mixer(self.norm1(x)))) x = x + self.drop_path(self.ls2(self.mlp(self.norm2(x)))) return x
12
287
73
360
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,605
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
279,280
251,285
forward
MetaBlock2d
280,285
280,285
class MetaBlock2d(nn.Module): def __init__( self, dim, pool_size=3, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5 ): super()....
class MetaBlock2d(nn.Module): def __init__( self, dim, pool_size=3, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5 ): super()....
x = x + self.drop_path1(self.ls1(self.token_mixer(x))) x = x + self.drop_path2(self.ls2(self.mlp(x))) return x
x = x + self.drop_path1(self.ls1(self.token_mixer(x))) x = x + self.drop_path2(self.ls2(self.mlp(x))) return x
12
321
63
384
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,606
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer.py
157,158
147,161
forward
Pooling
158,161
158,161
class Pooling(nn.Module): """ Implementation of pooling for PoolFormer --pool_size: pooling size """ def __init__(self, pool_size=3): super().__init__() self.pool = nn.AvgPool2d(pool_size, stride=1, padding=pool_size // 2, count_include_pad=False) def forward(self, x): FILL_FUN...
class Pooling(nn.Module): """ Implementation of pooling for PoolFormer --pool_size: pooling size """ def __init__(self, pool_size=3): super().__init__() self.pool = nn.AvgPool2d(pool_size, stride=1, padding=pool_size // 2, count_include_pad=False) def forward(self, x): FILL_FUN...
return self.pool(x) - x
return self.pool(x) - x
4
120
16
136
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
""" EfficientFormer @article{li2022efficientformer, title={EfficientFormer: Vision Transformers at MobileNet Speed}, author={Li, Yanyu and Yuan, Geng and Wen, Yang and Hu, Eric and Evangelidis, Georgios and Tulyakov, Sergey and Wang, Yanzhi and Ren, Jian}, journal={arXiv preprint arXiv:2206.01191}, year={20...
17,608
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
154,155
88,181
forward
Attention2d
155,181
155,181
class Attention2d(torch.nn.Module): attention_bias_cache: Dict[str, torch.Tensor] def __init__( self, dim=384, key_dim=32, num_heads=8, attn_ratio=4, resolution=7, act_layer=nn.GELU, stride=None, ): supe...
class Attention2d(torch.nn.Module): attention_bias_cache: Dict[str, torch.Tensor] def __init__( self, dim=384, key_dim=32, num_heads=8, attn_ratio=4, resolution=7, act_layer=nn.GELU, stride=None, ): supe...
B, C, H, W = x.shape if self.stride_conv is not None: x = self.stride_conv(x) q = self.q(x).reshape(B, self.num_heads, -1, self.N).permute(0, 1, 3, 2) k = self.k(x).reshape(B, self.num_heads, -1, self.N).permute(0, 1, 2, 3) v = self.v(x) v_local = self.v_loca...
B, C, H, W = x.shape if self.stride_conv is not None: x = self.stride_conv(x) q = self.q(x).reshape(B, self.num_heads, -1, self.N).permute(0, 1, 3, 2) k = self.k(x).reshape(B, self.num_heads, -1, self.N).permute(0, 1, 2, 3) v = self.v(x) v_local = self.v_loca...
98
980
401
1,381
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,609
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
259,260
196,279
forward
Attention2dDownsample
260,279
260,279
class Attention2dDownsample(torch.nn.Module): attention_bias_cache: Dict[str, torch.Tensor] def __init__( self, dim=384, key_dim=16, num_heads=8, attn_ratio=4, resolution=7, out_dim=None, act_layer=nn.GELU, ): ...
class Attention2dDownsample(torch.nn.Module): attention_bias_cache: Dict[str, torch.Tensor] def __init__( self, dim=384, key_dim=16, num_heads=8, attn_ratio=4, resolution=7, out_dim=None, act_layer=nn.GELU, ): ...
B, C, H, W = x.shape q = self.q(x).reshape(B, self.num_heads, -1, self.N2).permute(0, 1, 3, 2) k = self.k(x).reshape(B, self.num_heads, -1, self.N).permute(0, 1, 2, 3) v = self.v(x) v_local = self.v_local(v) v = v.reshape(B, self.num_heads, -1, self.N).permute(0, 1, 3, 2...
B, C, H, W = x.shape q = self.q(x).reshape(B, self.num_heads, -1, self.N2).permute(0, 1, 3, 2) k = self.k(x).reshape(B, self.num_heads, -1, self.N).permute(0, 1, 2, 3) v = self.v(x) v_local = self.v_local(v) v = v.reshape(B, self.num_heads, -1, self.N).permute(0, 1, 3, 2...
76
924
316
1,240
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,610
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
356,357
324,365
forward
ConvMlpWithNorm
357,365
357,365
class ConvMlpWithNorm(nn.Module): """ Implementation of MLP with 1*1 convolutions. Input: tensor with shape [B, C, H, W] """ def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, norm_laye...
class ConvMlpWithNorm(nn.Module): """ Implementation of MLP with 1*1 convolutions. Input: tensor with shape [B, C, H, W] """ def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, norm_laye...
x = self.fc1(x) x = self.mid(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x
x = self.fc1(x) x = self.mid(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x
17
362
68
430
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,611
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
82,83
54,88
forward
ConvNorm
83,88
83,88
class ConvNorm(nn.Module): def __init__( self, in_channels, out_channels, kernel_size=1, stride=1, padding='', dilation=1, groups=1, bias=True, norm_layer='batchnorm2d', norm_kwargs=No...
class ConvNorm(nn.Module): def __init__( self, in_channels, out_channels, kernel_size=1, stride=1, padding='', dilation=1, groups=1, bias=True, norm_layer='batchnorm2d', norm_kwargs=No...
x = self.conv(x) x = self.bn(x) return x
x = self.conv(x) x = self.bn(x) return x
8
238
31
269
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,612
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
317,318
279,324
forward
Downsample
318,324
318,324
class Downsample(nn.Module): def __init__( self, in_chs, out_chs, kernel_size=3, stride=2, padding=1, resolution=7, use_attn=False, act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, ): sup...
class Downsample(nn.Module): def __init__( self, in_chs, out_chs, kernel_size=3, stride=2, padding=1, resolution=7, use_attn=False, act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, ): sup...
out = self.conv(x) if self.attn is not None: return self.attn(x) + out return out
out = self.conv(x) if self.attn is not None: return self.attn(x) + out return out
14
319
45
364
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,613
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
615,616
508,652
reset_classifier
EfficientFormerV2
616,622
616,622
class EfficientFormerV2(nn.Module): def __init__( self, depths, in_chans=3, img_size=224, global_pool='avg', embed_dims=None, downsamples=None, mlp_ratios=4, norm_layer='batchnorm2d', norm_eps=1e-...
class EfficientFormerV2(nn.Module): def __init__( self, depths, in_chans=3, img_size=224, global_pool='avg', embed_dims=None, downsamples=None, mlp_ratios=4, norm_layer='batchnorm2d', norm_eps=1e-...
self.num_classes = num_classes if global_pool is not None: self.global_pool = global_pool self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() self.head_dist = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity...
self.num_classes = num_classes if global_pool is not None: self.global_pool = global_pool self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() self.head_dist = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity...
31
1,598
107
1,705
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,614
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
419,420
376,426
forward
EfficientFormerV2Block
420,426
420,426
class EfficientFormerV2Block(nn.Module): def __init__( self, dim, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5, resolution=7, ...
class EfficientFormerV2Block(nn.Module): def __init__( self, dim, mlp_ratio=4., act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, proj_drop=0., drop_path=0., layer_scale_init_value=1e-5, resolution=7, ...
if self.token_mixer is not None: x = x + self.drop_path1(self.ls1(self.token_mixer(x))) x = x + self.drop_path2(self.ls2(self.mlp(x))) return x
if self.token_mixer is not None: x = x + self.drop_path1(self.ls1(self.token_mixer(x))) x = x + self.drop_path2(self.ls2(self.mlp(x))) return x
17
453
77
530
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,615
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
499,500
440,508
forward
EfficientFormerV2Stage
500,508
500,508
class EfficientFormerV2Stage(nn.Module): def __init__( self, dim, dim_out, depth, resolution=7, downsample=True, block_stride=None, downsample_use_attn=False, block_use_attn=False, num_vit=1, ...
class EfficientFormerV2Stage(nn.Module): def __init__( self, dim, dim_out, depth, resolution=7, downsample=True, block_stride=None, downsample_use_attn=False, block_use_attn=False, num_vit=1, ...
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
18
548
77
625
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,616
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
371,372
365,376
forward
LayerScale2d
372,376
372,376
class LayerScale2d(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): FILL_FUNC_BODY
class LayerScale2d(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): FILL_FUNC_BODY
gamma = self.gamma.view(1, -1, 1, 1) return x.mul_(gamma) if self.inplace else x * gamma
gamma = self.gamma.view(1, -1, 1, 1) return x.mul_(gamma) if self.inplace else x * gamma
14
95
46
141
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,617
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientformer_v2.py
188,189
181,196
forward
LocalGlobalQuery
189,196
189,196
class LocalGlobalQuery(torch.nn.Module): def __init__(self, in_dim, out_dim): super().__init__() self.pool = nn.AvgPool2d(1, 2, 0) self.local = nn.Conv2d(in_dim, in_dim, kernel_size=3, stride=2, padding=1, groups=in_dim) self.proj = ConvNorm(in_dim, out_dim, 1) def forward(self,...
class LocalGlobalQuery(torch.nn.Module): def __init__(self, in_dim, out_dim): super().__init__() self.pool = nn.AvgPool2d(1, 2, 0) self.local = nn.Conv2d(in_dim, in_dim, kernel_size=3, stride=2, padding=1, groups=in_dim) self.proj = ConvNorm(in_dim, out_dim, 1) def forward(self,...
local_q = self.local(x) pool_q = self.pool(x) q = local_q + pool_q q = self.proj(q) return q
local_q = self.local(x) pool_q = self.pool(x) q = local_q + pool_q q = self.proj(q) return q
16
144
58
202
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
""" EfficientFormer-V2 @article{ li2022rethinking, title={Rethinking Vision Transformers for MobileNet Size and Speed}, author={Li, Yanyu and Hu, Ju and Wen, Yang and Evangelidis, Georgios and Salahi, Kamyar and Wang, Yanzhi and Tulyakov, Sergey and Ren, Jian}, journal={arXiv preprint arXiv:2212.08059}...
17,620
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientnet.py
330,331
265,351
forward
EfficientNetFeatures
331,351
331,351
class EfficientNetFeatures(nn.Module): """ EfficientNet Feature Extractor A work-in-progress feature extraction module for EfficientNet, to use as a backbone for segmentation and object detection models. """ def __init__( self, block_args, out_indices=(0, 1, 2, ...
class EfficientNetFeatures(nn.Module): """ EfficientNet Feature Extractor A work-in-progress feature extraction module for EfficientNet, to use as a backbone for segmentation and object detection models. """ def __init__( self, block_args, out_indices=(0, 1, 2, ...
x = self.conv_stem(x) x = self.bn1(x) if self.feature_hooks is None: features = [] if 0 in self._stage_out_idx: features.append(x) # add stem out for i, b in enumerate(self.blocks): if self.grad_checkpointing and not torch.jit....
x = self.conv_stem(x) x = self.bn1(x) if self.feature_hooks is None: features = [] if 0 in self._stage_out_idx: features.append(x) # add stem out for i, b in enumerate(self.blocks): if self.grad_checkpointing and not torch.jit....
56
782
217
999
""" The EfficientNet Family in PyTorch An implementation of EfficienNet that covers variety of related models with efficient architectures: * EfficientNet-V2 - `EfficientNetV2: Smaller Models and Faster Training` - https://arxiv.org/abs/2104.00298 * EfficientNet (B0-B8, L2 + Tensorflow pretrained AutoAug/RandAug/A...
""" The EfficientNet Family in PyTorch An implementation of EfficienNet that covers variety of related models with efficient architectures: * EfficientNet-V2 - `EfficientNetV2: Smaller Models and Faster Training` - https://arxiv.org/abs/2104.00298 * EfficientNet (B0-B8, L2 + Tensorflow pretrained AutoAug/RandAug/A...
17,622
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
655,656
632,664
forward
ClassifierHead
656,664
656,664
class ClassifierHead(nn.Module): def __init__( self, in_channels, widths, n_classes=1000, dropout=0., norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, global_pool='avg', norm_eps=1e-5, ): super(ClassifierHead, self).__init__() ...
class ClassifierHead(nn.Module): def __init__( self, in_channels, widths, n_classes=1000, dropout=0., norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, global_pool='avg', norm_eps=1e-5, ): super(ClassifierHead, self).__init__() ...
x = self.in_conv(x) x = self.global_pool(x) if pre_logits: return x x = self.classifier(x) return x
x = self.in_conv(x) x = self.global_pool(x) if pre_logits: return x x = self.classifier(x) return x
15
342
61
403
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,623
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
164,165
126,170
forward
ConvBlock
165,170
165,170
class ConvBlock(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=1, use_bias=False, norm_layer=(nn.BatchNorm2d, nn.BatchNorm2d), act_layer=(nn.ReLU6, None), ...
class ConvBlock(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=1, use_bias=False, norm_layer=(nn.BatchNorm2d, nn.BatchNorm2d), act_layer=(nn.ReLU6, None), ...
x = self.conv1(x) x = self.conv2(x) return x
x = self.conv1(x) x = self.conv2(x) return x
8
384
33
417
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,624
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
77,78
49,85
forward
ConvNormAct
78,85
78,85
class ConvNormAct(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, dilation=1, groups=1, bias=False, dropout=0., norm_layer=nn.BatchNorm2d, act_layer=nn.ReLU, ): super(Con...
class ConvNormAct(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, dilation=1, groups=1, bias=False, dropout=0., norm_layer=nn.BatchNorm2d, act_layer=nn.ReLU, ): super(Con...
x = self.dropout(x) x = self.conv(x) x = self.norm(x) x = self.act(x) return x
x = self.dropout(x) x = self.conv(x) x = self.norm(x) x = self.act(x) return x
14
290
54
344
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,625
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
120,121
85,126
forward
DSConv
121,126
121,126
class DSConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, use_bias=False, norm_layer=(nn.BatchNorm2d, nn.BatchNorm2d), act_layer=(nn.ReLU6, None), ): super(DSConv, self).__init__() us...
class DSConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, use_bias=False, norm_layer=(nn.BatchNorm2d, nn.BatchNorm2d), act_layer=(nn.ReLU6, None), ): super(DSConv, self).__init__() us...
x = self.depth_conv(x) x = self.point_conv(x) return x
x = self.depth_conv(x) x = self.point_conv(x) return x
8
349
35
384
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,626
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
735,737
664,778
set_grad_checkpointing
EfficientVit
737,739
737,739
class EfficientVit(nn.Module): def __init__( self, in_chans=3, widths=(), depths=(), head_dim=32, expand_ratio=4, norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, global_pool='avg', head_widths=(), drop_rate=0.0, num_c...
class EfficientVit(nn.Module): def __init__( self, in_chans=3, widths=(), depths=(), head_dim=32, expand_ratio=4, norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, global_pool='avg', head_widths=(), drop_rate=0.0, num_c...
self.grad_checkpointing = enable
self.grad_checkpointing = enable
3
1,151
14
1,165
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,627
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
401,402
368,407
forward
EfficientVitBlock
402,407
402,407
class EfficientVitBlock(nn.Module): def __init__( self, in_channels, heads_ratio=1.0, head_dim=32, expand_ratio=4, norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, ): super(EfficientVitBlock, self).__init__() self.context_module = Residua...
class EfficientVitBlock(nn.Module): def __init__( self, in_channels, heads_ratio=1.0, head_dim=32, expand_ratio=4, norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, ): super(EfficientVitBlock, self).__init__() self.context_module = Residua...
x = self.context_module(x) x = self.local_module(x) return x
x = self.context_module(x) x = self.local_module(x) return x
8
320
35
355
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,628
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
861,862
778,897
reset_classifier
EfficientVitLarge
862,880
862,880
class EfficientVitLarge(nn.Module): def __init__( self, in_chans=3, widths=(), depths=(), head_dim=32, norm_layer=nn.BatchNorm2d, act_layer=GELUTanh, global_pool='avg', head_widths=(), drop_rate=0.0, num_classes=1000, no...
class EfficientVitLarge(nn.Module): def __init__( self, in_chans=3, widths=(), depths=(), head_dim=32, norm_layer=nn.BatchNorm2d, act_layer=GELUTanh, global_pool='avg', head_widths=(), drop_rate=0.0, num_classes=1000, no...
self.num_classes = num_classes if global_pool is not None: self.global_pool = global_pool if num_classes > 0: self.head = ClassifierHead( self.num_features, self.head_widths, n_classes=num_classes, dropout=se...
self.num_classes = num_classes if global_pool is not None: self.global_pool = global_pool if num_classes > 0: self.head = ClassifierHead( self.num_features, self.head_widths, n_classes=num_classes, dropout=se...
38
1,063
196
1,259
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,629
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
628,629
569,632
forward
EfficientVitLargeStage
629,632
629,632
class EfficientVitLargeStage(nn.Module): def __init__( self, in_chs, out_chs, depth, norm_layer, act_layer, head_dim, vit_stage=False, fewer_norm=False, ): super(EfficientVitLargeStage, self).__in...
class EfficientVitLargeStage(nn.Module): def __init__( self, in_chs, out_chs, depth, norm_layer, act_layer, head_dim, vit_stage=False, fewer_norm=False, ): super(EfficientVitLargeStage, self).__in...
return self.blocks(x)
return self.blocks(x)
2
514
14
528
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,630
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
565,566
509,569
forward
EfficientVitStage
566,569
566,569
class EfficientVitStage(nn.Module): def __init__( self, in_chs, out_chs, depth, norm_layer, act_layer, expand_ratio, head_dim, vit_stage=False, ): super(EfficientVitStage, self).__init__() ...
class EfficientVitStage(nn.Module): def __init__( self, in_chs, out_chs, depth, norm_layer, act_layer, expand_ratio, head_dim, vit_stage=False, ): super(EfficientVitStage, self).__init__() ...
return self.blocks(x)
return self.blocks(x)
2
457
14
471
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,631
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
263,264
224,269
forward
FusedMBConv
264,269
264,269
class FusedMBConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=6, groups=1, use_bias=False, norm_layer=(nn.BatchNorm2d, nn.BatchNorm2d), act_layer=...
class FusedMBConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=6, groups=1, use_bias=False, norm_layer=(nn.BatchNorm2d, nn.BatchNorm2d), act_layer=...
x = self.spatial_conv(x) x = self.point_conv(x) return x
x = self.spatial_conv(x) x = self.point_conv(x) return x
8
400
36
436
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
17,632
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models
/home/hieuvd/dung_repo/raw/stars_01/huggingface_pytorch-image-models/pytorch-image-models/timm/models/efficientvit_mit.py
336,337
269,365
forward
LiteMLA
337,365
337,365
class LiteMLA(nn.Module): """Lightweight multi-scale linear attention""" def __init__( self, in_channels: int, out_channels: int, heads: int or None = None, heads_ratio: float = 1.0, dim=8, use_bias=False, norm_layer=(None, nn.BatchNorm2d), ...
class LiteMLA(nn.Module): """Lightweight multi-scale linear attention""" def __init__( self, in_channels: int, out_channels: int, heads: int or None = None, heads_ratio: float = 1.0, dim=8, use_bias=False, norm_layer=(None, nn.BatchNorm2d), ...
B, _, H, W = x.shape # generate multi-scale q, k, v qkv = self.qkv(x) multi_scale_qkv = [qkv] for op in self.aggreg: multi_scale_qkv.append(op(qkv)) multi_scale_qkv = torch.cat(multi_scale_qkv, dim=1) multi_scale_qkv = multi_scale_qkv.reshape(B, -1, 3...
B, _, H, W = x.shape # generate multi-scale q, k, v qkv = self.qkv(x) multi_scale_qkv = [qkv] for op in self.aggreg: multi_scale_qkv.append(op(qkv)) multi_scale_qkv = torch.cat(multi_scale_qkv, dim=1) multi_scale_qkv = multi_scale_qkv.reshape(B, -1, 3...
93
696
386
1,082
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...
""" EfficientViT (by MIT Song Han's Lab) Paper: `Efficientvit: Enhanced linear attention for high-resolution low-computation visual recognition` - https://arxiv.org/abs/2205.14756 Adapted from official impl at https://github.com/mit-han-lab/efficientvit """ __all__ = ['EfficientVit'] from typing import Optional ...