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,890
/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/tiny_vit.py
79,80
67,92
forward
MBConv
80,92
80,92
class MBConv(nn.Module): def __init__(self, in_chs, out_chs, expand_ratio, act_layer, drop_path): super().__init__() mid_chs = int(in_chs * expand_ratio) self.conv1 = ConvNorm(in_chs, mid_chs, ks=1) self.act1 = act_layer() self.conv2 = ConvNorm(mid_chs, mid_chs, ks=3, stride=...
class MBConv(nn.Module): def __init__(self, in_chs, out_chs, expand_ratio, act_layer, drop_path): super().__init__() mid_chs = int(in_chs * expand_ratio) self.conv1 = ConvNorm(in_chs, mid_chs, ks=1) self.act1 = act_layer() self.conv2 = ConvNorm(mid_chs, mid_chs, ks=3, stride=...
shortcut = x x = self.conv1(x) x = self.act1(x) x = self.conv2(x) x = self.act2(x) x = self.conv3(x) x = self.drop_path(x) x += shortcut x = self.act3(x) return x
shortcut = x x = self.conv1(x) x = self.act1(x) x = self.conv2(x) x = self.act2(x) x = self.conv3(x) x = self.drop_path(x) x += shortcut x = self.act3(x) return x
29
252
106
358
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
17,891
/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/tiny_vit.py
155,156
135,165
forward
NormMlp
156,165
156,165
class NormMlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, norm_layer=nn.LayerNorm, act_layer=nn.GELU, drop=0., ): super().__init__() out_features = out_features or in_fea...
class NormMlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, norm_layer=nn.LayerNorm, act_layer=nn.GELU, drop=0., ): super().__init__() out_features = out_features or in_fea...
x = self.norm(x) x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x
x = self.norm(x) x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x
20
223
79
302
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
17,892
/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/tiny_vit.py
60,61
52,67
forward
PatchEmbed
61,67
61,67
class PatchEmbed(nn.Module): def __init__(self, in_chs, out_chs, act_layer): super().__init__() self.stride = 4 self.conv1 = ConvNorm(in_chs, out_chs // 2, 3, 2, 1) self.act = act_layer() self.conv2 = ConvNorm(out_chs // 2, out_chs, 3, 2, 1) def forward(self, x): FILL_FU...
class PatchEmbed(nn.Module): def __init__(self, in_chs, out_chs, act_layer): super().__init__() self.stride = 4 self.conv1 = ConvNorm(in_chs, out_chs // 2, 3, 2, 1) self.act = act_layer() self.conv2 = ConvNorm(out_chs // 2, out_chs, 3, 2, 1) def forward(self, x): FILL_FU...
x = self.conv1(x) x = self.act(x) x = self.conv2(x) return x
x = self.conv1(x) x = self.act(x) x = self.conv2(x) return x
11
146
44
190
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
17,893
/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/tiny_vit.py
101,102
92,110
forward
PatchMerging
102,110
102,110
class PatchMerging(nn.Module): def __init__(self, dim, out_dim, act_layer): super().__init__() self.conv1 = ConvNorm(dim, out_dim, 1, 1, 0) self.act1 = act_layer() self.conv2 = ConvNorm(out_dim, out_dim, 3, 2, 1, groups=out_dim) self.act2 = act_layer() self.conv3 = Co...
class PatchMerging(nn.Module): def __init__(self, dim, out_dim, act_layer): super().__init__() self.conv1 = ConvNorm(dim, out_dim, 1, 1, 0) self.act1 = act_layer() self.conv2 = ConvNorm(out_dim, out_dim, 3, 2, 1, groups=out_dim) self.act2 = act_layer() self.conv3 = Co...
x = self.conv1(x) x = self.act1(x) x = self.conv2(x) x = self.act2(x) x = self.conv3(x) return x
x = self.conv1(x) x = self.act1(x) x = self.conv2(x) x = self.act2(x) x = self.conv3(x) return x
17
168
69
237
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
17,894
/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/tiny_vit.py
517,519
419,558
group_matcher
TinyVit
519,528
519,528
class TinyVit(nn.Module): def __init__( self, in_chans=3, num_classes=1000, global_pool='avg', embed_dims=(96, 192, 384, 768), depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), window_sizes=(7, 7, 14, 7), mlp_ra...
class TinyVit(nn.Module): def __init__( self, in_chans=3, num_classes=1000, global_pool='avg', embed_dims=(96, 192, 384, 768), depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), window_sizes=(7, 7, 14, 7), mlp_ra...
matcher = dict( stem=r'^patch_embed', blocks=r'^stages\.(\d+)' if coarse else [ (r'^stages\.(\d+).downsample', (0,)), (r'^stages\.(\d+)\.\w+\.(\d+)', None), ] ) return matcher
matcher = dict( stem=r'^patch_embed', blocks=r'^stages\.(\d+)' if coarse else [ (r'^stages\.(\d+).downsample', (0,)), (r'^stages\.(\d+)\.\w+\.(\d+)', None), ] ) return matcher
17
1,382
105
1,487
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
17,895
/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/tiny_vit.py
299,300
247,344
forward
TinyVitBlock
300,339
300,339
class TinyVitBlock(nn.Module): """ TinyViT 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. drop (float, optional): Dropout rate. Def...
class TinyVitBlock(nn.Module): """ TinyViT 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. drop (float, optional): Dropout rate. Def...
B, H, W, C = x.shape L = H * W shortcut = x if H == self.window_size and W == self.window_size: x = x.reshape(B, L, C) x = self.attn(x) x = x.view(B, H, W, C) else: pad_b = (self.window_size - H % self.window_size) % self.window_si...
B, H, W, C = x.shape L = H * W shortcut = x if H == self.window_size and W == self.window_size: x = x.reshape(B, L, C) x = self.attn(x) x = x.view(B, H, W, C) else: pad_b = (self.window_size - H % self.window_size) % self.window_si...
171
666
553
1,219
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
17,896
/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/tiny_vit.py
408,409
347,419
forward
TinyVitStage
409,415
409,415
class TinyVitStage(nn.Module): """ A basic TinyViT layer for one stage. Args: dim (int): Number of input channels. out_dim: the output dimension of the layer depth (int): Number of blocks. num_heads (int): Number of attention heads. window_size (int): Local window size. ...
class TinyVitStage(nn.Module): """ A basic TinyViT layer for one stage. Args: dim (int): Number of input channels. out_dim: the output dimension of the layer depth (int): Number of blocks. num_heads (int): Number of attention heads. window_size (int): Local window size. ...
x = self.downsample(x) x = x.permute(0, 2, 3, 1) # BCHW -> BHWC x = self.blocks(x) x = x.permute(0, 3, 1, 2) # BHWC -> BCHW return x
x = self.downsample(x) x = x.permute(0, 2, 3, 1) # BCHW -> BHWC x = self.blocks(x) x = x.permute(0, 3, 1, 2) # BHWC -> BCHW return x
28
628
96
724
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
""" TinyViT Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` - https://arxiv.org/abs/2207.10666 Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT """ __all__ = ['TinyVit'] import math import itertools from functools import partial from typing import ...
17,898
/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/tnt.py
63,64
46,79
forward
Attention
64,79
64,79
class Attention(nn.Module): """ Multi-Head Attention """ def __init__(self, dim, hidden_dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.hidden_dim = hidden_dim self.num_heads = num_heads head_dim = hidden_dim // num_heads self.he...
class Attention(nn.Module): """ Multi-Head Attention """ def __init__(self, dim, hidden_dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.hidden_dim = hidden_dim self.num_heads = num_heads head_dim = hidden_dim // num_heads self.he...
B, N, C = x.shape qk = self.qk(x).reshape(B, N, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k = qk.unbind(0) # make torchscript happy (cannot use tensor as tuple) v = self.v(x).reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) attn = (q @ k.transpose(-2, -1...
B, N, C = x.shape qk = self.qk(x).reshape(B, N, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k = qk.unbind(0) # make torchscript happy (cannot use tensor as tuple) v = self.v(x).reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) attn = (q @ k.transpose(-2, -1...
68
274
260
534
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
17,899
/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/tnt.py
142,143
79,156
forward
Block
143,156
143,156
class Block(nn.Module): """ TNT Block """ def __init__( self, dim, dim_out, num_pixel, num_heads_in=4, num_heads_out=12, mlp_ratio=4., qkv_bias=False, proj_drop=0., attn_drop=0., ...
class Block(nn.Module): """ TNT Block """ def __init__( self, dim, dim_out, num_pixel, num_heads_in=4, num_heads_out=12, mlp_ratio=4., qkv_bias=False, proj_drop=0., attn_drop=0., ...
# inner pixel_embed = pixel_embed + self.drop_path(self.attn_in(self.norm_in(pixel_embed))) pixel_embed = pixel_embed + self.drop_path(self.mlp_in(self.norm_mlp_in(pixel_embed))) # outer B, N, C = patch_embed.size() patch_embed = torch.cat( [patch_embed[:, 0:1...
# inner pixel_embed = pixel_embed + self.drop_path(self.attn_in(self.norm_in(pixel_embed))) pixel_embed = pixel_embed + self.drop_path(self.mlp_in(self.norm_mlp_in(pixel_embed))) # outer B, N, C = patch_embed.size() patch_embed = torch.cat( [patch_embed[:, 0:1...
46
612
252
864
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
17,900
/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/tnt.py
175,176
156,189
forward
PixelEmbed
176,189
176,189
class PixelEmbed(nn.Module): """ Image to Pixel Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, in_dim=48, stride=4): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) # grid_size property necessary for resizing pos...
class PixelEmbed(nn.Module): """ Image to Pixel Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, in_dim=48, stride=4): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) # grid_size property necessary for resizing pos...
B, C, H, W = x.shape _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 match model ({self.img_size[0]}*{self.img_size[1]}).") ...
B, C, H, W = x.shape _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 match model ({self.img_size[0]}*{self.img_size[1]}).") ...
58
354
259
613
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
17,901
/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/tnt.py
332,333
189,338
forward
TNT
333,338
333,338
class TNT(nn.Module): """ Transformer in Transformer - https://arxiv.org/abs/2103.00112 """ def __init__( self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, global_pool='token', embed_dim=768, inner...
class TNT(nn.Module): """ Transformer in Transformer - https://arxiv.org/abs/2103.00112 """ def __init__( self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, global_pool='token', embed_dim=768, inner...
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,846
35
1,881
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
""" Transformer in Transformer (TNT) in PyTorch A PyTorch implement of TNT as described in 'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 The official mindspore code is released and available at https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT """ import math import torch ...
17,903
/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/tresnet.py
54,55
23,68
forward
BasicBlock
55,68
55,68
class BasicBlock(nn.Module): expansion = 1 def __init__( self, inplanes, planes, stride=1, downsample=None, use_se=True, aa_layer=None, drop_path_rate=0. ): super(BasicBlock, self).__init__() sel...
class BasicBlock(nn.Module): expansion = 1 def __init__( self, inplanes, planes, stride=1, downsample=None, use_se=True, aa_layer=None, drop_path_rate=0. ): super(BasicBlock, self).__init__() sel...
if self.downsample is not None: shortcut = self.downsample(x) else: shortcut = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.drop_path(out) + shortcut out = self.act(out) ...
if self.downsample is not None: shortcut = self.downsample(x) else: shortcut = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.drop_path(out) + shortcut out = self.act(out) ...
36
407
116
523
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SE...
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SE...
17,904
/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/tresnet.py
105,106
68,120
forward
Bottleneck
106,120
106,120
class Bottleneck(nn.Module): expansion = 4 def __init__( self, inplanes, planes, stride=1, downsample=None, use_se=True, act_layer=None, aa_layer=None, drop_path_rate=0., ): super(Bottleneck,...
class Bottleneck(nn.Module): expansion = 4 def __init__( self, inplanes, planes, stride=1, downsample=None, use_se=True, act_layer=None, aa_layer=None, drop_path_rate=0., ): super(Bottleneck,...
if self.downsample is not None: shortcut = self.downsample(x) else: shortcut = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.conv3(out) out = self.drop_path(out) + shortcut ...
if self.downsample is not None: shortcut = self.downsample(x) else: shortcut = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.conv3(out) out = self.drop_path(out) + shortcut ...
39
464
128
592
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SE...
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SE...
17,905
/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/tresnet.py
198,199
120,262
_make_layer
TResNet
199,223
199,223
class TResNet(nn.Module): def __init__( self, layers, in_chans=3, num_classes=1000, width_factor=1.0, v2=False, global_pool='fast', drop_rate=0., drop_path_rate=0., ): self.num_classes = num_class...
class TResNet(nn.Module): def __init__( self, layers, in_chans=3, num_classes=1000, width_factor=1.0, v2=False, global_pool='fast', drop_rate=0., drop_path_rate=0., ): self.num_classes = num_class...
downsample = None if stride != 1 or self.inplanes != planes * block.expansion: layers = [] if stride == 2: # avg pooling before 1x1 conv layers.append(nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True, count_include_pad=False)) layer...
downsample = None if stride != 1 or self.inplanes != planes * block.expansion: layers = [] if stride == 2: # avg pooling before 1x1 conv layers.append(nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True, count_include_pad=False)) layer...
84
1,584
332
1,916
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SE...
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SE...
17,907
/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/twins.py
226,227
192,232
forward
Block
227,232
227,232
class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1, ws=None, ...
class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1, ws=None, ...
x = x + self.drop_path1(self.attn(self.norm1(x), size)) x = x + self.drop_path2(self.mlp(self.norm2(x))) return x
x = x + self.drop_path1(self.attn(self.norm1(x), size)) x = x + self.drop_path2(self.mlp(self.norm2(x))) return x
13
400
63
463
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
17,908
/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/twins.py
162,163
133,192
forward
GlobalSubSampleAttn
163,192
163,192
class GlobalSubSampleAttn(nn.Module): """ GSA: using a key to summarize the information for a group to be efficient. """ fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, attn_drop=0., proj_drop=0., sr_ratio=1): super().__init__() assert dim % num_heads == 0, f"dim...
class GlobalSubSampleAttn(nn.Module): """ GSA: using a key to summarize the information for a group to be efficient. """ fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, attn_drop=0., proj_drop=0., sr_ratio=1): super().__init__() assert dim % num_heads == 0, f"dim...
B, N, C = x.shape q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) if self.sr is not None: x = x.permute(0, 2, 1).reshape(B, C, *size) x = self.sr(x).reshape(B, C, -1).permute(0, 2, 1) x = self.norm(x) kv = self.kv(...
B, N, C = x.shape q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) if self.sr is not None: x = x.permute(0, 2, 1).reshape(B, C, *size) x = self.sr(x).reshape(B, C, -1).permute(0, 2, 1) x = self.norm(x) kv = self.kv(...
106
409
429
838
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
17,909
/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/twins.py
58,59
35,133
forward
LocallyGroupedAttn
59,133
59,133
@register_notrace_module # reason: FX can't symbolically trace control flow in forward method class LocallyGroupedAttn(nn.Module): """ LSA: self attention within a group """ fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, attn_drop=0., proj_drop=0., ws=1): assert ws != 1...
@register_notrace_module # reason: FX can't symbolically trace control flow in forward method class LocallyGroupedAttn(nn.Module): """ LSA: self attention within a group """ fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, attn_drop=0., proj_drop=0., ws=1): assert ws != 1...
# There are two implementations for this function, zero padding or mask. We don't observe obvious difference for # both. You can choose any one, we recommend forward_padding because it's neat. However, # the masking implementation is more reasonable and accurate. B, N, C = x.shape ...
# There are two implementations for this function, zero padding or mask. We don't observe obvious difference for # both. You can choose any one, we recommend forward_padding because it's neat. However, # the masking implementation is more reasonable and accurate. B, N, C = x.shape ...
506
342
1,612
1,954
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
17,910
/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/twins.py
272,273
254,282
forward
PatchEmbed
273,282
273,282
class PatchEmbed(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) self.img_size = img_size self.patch_size = ...
class PatchEmbed(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) self.img_size = img_size self.patch_size = ...
B, C, H, W = x.shape x = self.proj(x).flatten(2).transpose(1, 2) x = self.norm(x) out_size = (H // self.patch_size[0], W // self.patch_size[1]) return x, out_size
B, C, H, W = x.shape x = self.proj(x).flatten(2).transpose(1, 2) x = self.norm(x) out_size = (H // self.patch_size[0], W // self.patch_size[1]) return x, out_size
24
327
94
421
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
17,911
/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/twins.py
241,242
232,254
forward
PosConv
242,250
242,250
class PosConv(nn.Module): # PEG from https://arxiv.org/abs/2102.10882 def __init__(self, in_chans, embed_dim=768, stride=1): super(PosConv, self).__init__() self.proj = nn.Sequential( nn.Conv2d(in_chans, embed_dim, 3, stride, 1, bias=True, groups=embed_dim), ) self.s...
class PosConv(nn.Module): # PEG from https://arxiv.org/abs/2102.10882 def __init__(self, in_chans, embed_dim=768, stride=1): super(PosConv, self).__init__() self.proj = nn.Sequential( nn.Conv2d(in_chans, embed_dim, 3, stride, 1, bias=True, groups=embed_dim), ) self.s...
B, N, C = x.shape cnn_feat_token = x.transpose(1, 2).view(B, C, *size) x = self.proj(cnn_feat_token) if self.stride == 1: x += cnn_feat_token x = x.flatten(2).transpose(1, 2) return x
B, N, C = x.shape cnn_feat_token = x.transpose(1, 2).view(B, C, *size) x = self.proj(cnn_feat_token) if self.stride == 1: x += cnn_feat_token x = x.flatten(2).transpose(1, 2) return x
27
199
109
308
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
""" Twins A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers` - https://arxiv.org/pdf/2104.13840.pdf Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below """ # -------------------------------------------------------- # Twins # ...
17,914
/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/vgg.py
53,54
31,66
forward
ConvMlp
54,66
54,66
@register_notrace_module # reason: FX can't symbolically trace control flow in forward method class ConvMlp(nn.Module): def __init__( self, in_features=512, out_features=4096, kernel_size=7, mlp_ratio=1.0, drop_rate: float = 0.2, ...
@register_notrace_module # reason: FX can't symbolically trace control flow in forward method class ConvMlp(nn.Module): def __init__( self, in_features=512, out_features=4096, kernel_size=7, mlp_ratio=1.0, drop_rate: float = 0.2, ...
if x.shape[-2] < self.input_kernel_size or x.shape[-1] < self.input_kernel_size: # keep the input size >= 7x7 output_size = (max(self.input_kernel_size, x.shape[-2]), max(self.input_kernel_size, x.shape[-1])) x = F.adaptive_avg_pool2d(x, output_size) x = self.fc1(x) ...
if x.shape[-2] < self.input_kernel_size or x.shape[-1] < self.input_kernel_size: # keep the input size >= 7x7 output_size = (max(self.input_kernel_size, x.shape[-2]), max(self.input_kernel_size, x.shape[-1])) x = F.adaptive_avg_pool2d(x, output_size) x = self.fc1(x) ...
42
290
178
468
"""VGG Adapted from https://github.com/pytorch/vision 'vgg.py' (BSD-3-Clause) with a few changes for timm functionality. Copyright 2021 Ross Wightman """ from typing import Union, List, Dict, Any, cast import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IM...
"""VGG Adapted from https://github.com/pytorch/vision 'vgg.py' (BSD-3-Clause) with a few changes for timm functionality. Copyright 2021 Ross Wightman """ from typing import Union, List, Dict, Any, cast import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IM...
17,915
/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/vgg.py
128,130
66,177
group_matcher
VGG
130,133
130,133
class VGG(nn.Module): def __init__( self, cfg: List[Any], num_classes: int = 1000, in_chans: int = 3, output_stride: int = 32, mlp_ratio: float = 1.0, act_layer: nn.Module = nn.ReLU, conv_layer: nn.Module = nn.Conv2d, ...
class VGG(nn.Module): def __init__( self, cfg: List[Any], num_classes: int = 1000, in_chans: int = 3, output_stride: int = 32, mlp_ratio: float = 1.0, act_layer: nn.Module = nn.ReLU, conv_layer: nn.Module = nn.Conv2d, ...
# this treats BN layers as separate groups for bn variants, a lot of effort to fix that return dict(stem=r'^features\.0', blocks=r'^features\.(\d+)')
# this treats BN layers as separate groups for bn variants, a lot of effort to fix that return dict(stem=r'^features\.0', blocks=r'^features\.(\d+)')
21
1,236
56
1,292
"""VGG Adapted from https://github.com/pytorch/vision 'vgg.py' (BSD-3-Clause) with a few changes for timm functionality. Copyright 2021 Ross Wightman """ from typing import Union, List, Dict, Any, cast import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IM...
"""VGG Adapted from https://github.com/pytorch/vision 'vgg.py' (BSD-3-Clause) with a few changes for timm functionality. Copyright 2021 Ross Wightman """ from typing import Union, List, Dict, Any, cast import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IM...
17,917
/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/visformer.py
90,91
73,112
forward
Attention
91,112
91,112
class Attention(nn.Module): fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, head_dim_ratio=1., attn_drop=0., proj_drop=0.): super().__init__() self.dim = dim self.num_heads = num_heads head_dim = round(dim // num_heads * head_dim_ratio) self.head_d...
class Attention(nn.Module): fused_attn: torch.jit.Final[bool] def __init__(self, dim, num_heads=8, head_dim_ratio=1., attn_drop=0., proj_drop=0.): super().__init__() self.dim = dim self.num_heads = num_heads head_dim = round(dim // num_heads * head_dim_ratio) self.head_d...
B, C, H, W = x.shape x = self.qkv(x).reshape(B, 3, self.num_heads, self.head_dim, -1).permute(1, 0, 2, 4, 3) q, k, v = x.unbind(0) if self.fused_attn: x = torch.nn.functional.scaled_dot_product_attention( q.contiguous(), k.contiguous(), v.contiguous(), ...
B, C, H, W = x.shape x = self.qkv(x).reshape(B, 3, self.num_heads, self.head_dim, -1).permute(1, 0, 2, 4, 3) q, k, v = x.unbind(0) if self.fused_attn: x = torch.nn.functional.scaled_dot_product_attention( q.contiguous(), k.contiguous(), v.contiguous(), ...
73
315
309
624
""" Visformer Paper: Visformer: The Vision-friendly Transformer - https://arxiv.org/abs/2104.12533 From original at https://github.com/danczs/Visformer Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAU...
""" Visformer Paper: Visformer: The Vision-friendly Transformer - https://arxiv.org/abs/2104.12533 From original at https://github.com/danczs/Visformer Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAU...
17,918
/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/visformer.py
154,155
112,161
forward
Block
155,161
155,161
class Block(nn.Module): def __init__( self, dim, num_heads, head_dim_ratio=1., mlp_ratio=4., proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=LayerNorm2d, group=...
class Block(nn.Module): def __init__( self, dim, num_heads, head_dim_ratio=1., mlp_ratio=4., proj_drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=LayerNorm2d, group=...
if self.attn is not None: x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x
if self.attn is not None: x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x
17
386
71
457
""" Visformer Paper: Visformer: The Vision-friendly Transformer - https://arxiv.org/abs/2104.12533 From original at https://github.com/danczs/Visformer Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAU...
""" Visformer Paper: Visformer: The Vision-friendly Transformer - https://arxiv.org/abs/2104.12533 From original at https://github.com/danczs/Visformer Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAU...
17,919
/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/visformer.py
61,62
22,73
forward
SpatialMlp
62,73
62,73
class SpatialMlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0., group=8, spatial_conv=False, ): super().__init__() out_features = out...
class SpatialMlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0., group=8, spatial_conv=False, ): super().__init__() out_features = out...
x = self.conv1(x) x = self.act1(x) x = self.drop1(x) if self.conv2 is not None: x = self.conv2(x) x = self.act2(x) x = self.conv3(x) x = self.drop3(x) return x
x = self.conv1(x) x = self.act1(x) x = self.drop1(x) if self.conv2 is not None: x = self.conv2(x) x = self.act2(x) x = self.conv3(x) x = self.drop3(x) return x
28
470
105
575
""" Visformer Paper: Visformer: The Vision-friendly Transformer - https://arxiv.org/abs/2104.12533 From original at https://github.com/danczs/Visformer Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAU...
""" Visformer Paper: Visformer: The Vision-friendly Transformer - https://arxiv.org/abs/2104.12533 From original at https://github.com/danczs/Visformer Modifications and additions for timm hacked together by / Copyright 2021, Ross Wightman """ import torch import torch.nn as nn from timm.data import IMAGENET_DEFAU...
17,922
/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/vision_transformer_hybrid.py
119,120
32,136
forward
HybridEmbed
120,136
120,136
class HybridEmbed(nn.Module): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ output_fmt: Format dynamic_img_pad: torch.jit.Final[bool] def __init__( self, backbone, img_size=224, patch_size=1, ...
class HybridEmbed(nn.Module): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ output_fmt: Format dynamic_img_pad: torch.jit.Final[bool] def __init__( self, backbone, img_size=224, patch_size=1, ...
x = self.backbone(x) if isinstance(x, (list, tuple)): x = x[-1] # last feature if backbone outputs list/tuple of features _, _, H, W = x.shape if self.dynamic_img_pad: pad_h = (self.patch_size[0] - H % self.patch_size[0]) % self.patch_size[0] pad_w = ...
x = self.backbone(x) if isinstance(x, (list, tuple)): x = x[-1] # last feature if backbone outputs list/tuple of features _, _, H, W = x.shape if self.dynamic_img_pad: pad_h = (self.patch_size[0] - H % self.patch_size[0]) % self.patch_size[0] pad_w = ...
75
1,150
267
1,417
""" Hybrid Vision Transformer (ViT) in PyTorch A PyTorch implement of the Hybrid Vision Transformers as described in: 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 `How to train your ViT? Data, Augmentation, and Regularization in Vision Transfor...
""" Hybrid Vision Transformer (ViT) in PyTorch A PyTorch implement of the Hybrid Vision Transformers as described in: 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 `How to train your ViT? Data, Augmentation, and Regularization in Vision Transfor...
17,923
/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/vision_transformer_hybrid.py
160,161
136,168
forward
HybridEmbedWithSize
161,168
161,168
class HybridEmbedWithSize(nn.Module): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ def __init__( self, backbone, img_size=224, patch_size=1, feature_size=None, in_chans=3, ...
class HybridEmbedWithSize(nn.Module): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ def __init__( self, backbone, img_size=224, patch_size=1, feature_size=None, in_chans=3, ...
x = self.backbone(x) if isinstance(x, (list, tuple)): x = x[-1] # last feature if backbone outputs list/tuple of features x = self.proj(x) return x.flatten(2).transpose(1, 2), x.shape[-2:]
x = self.backbone(x) if isinstance(x, (list, tuple)): x = x[-1] # last feature if backbone outputs list/tuple of features x = self.proj(x) return x.flatten(2).transpose(1, 2), x.shape[-2:]
26
225
90
315
""" Hybrid Vision Transformer (ViT) in PyTorch A PyTorch implement of the Hybrid Vision Transformers as described in: 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 `How to train your ViT? Data, Augmentation, and Regularization in Vision Transfor...
""" Hybrid Vision Transformer (ViT) in PyTorch A PyTorch implement of the Hybrid Vision Transformers as described in: 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 `How to train your ViT? Data, Augmentation, and Regularization in Vision Transfor...
17,925
/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/vision_transformer_sam.py
149,150
107,189
forward
Attention
150,189
150,189
class Attention(nn.Module): fused_attn: Final[bool] def __init__( self, dim, num_heads=8, qkv_bias=True, qk_norm=False, attn_drop=0., proj_drop=0., norm_layer=nn.LayerNorm, use_rel_pos: bool = False, ...
class Attention(nn.Module): fused_attn: Final[bool] def __init__( self, dim, num_heads=8, qkv_bias=True, qk_norm=False, attn_drop=0., proj_drop=0., norm_layer=nn.LayerNorm, use_rel_pos: bool = False, ...
B, H, W, _ = x.shape N = H * W x = x.reshape(B, N, -1) qkv = self.qkv(x).view(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # qkv with shape (3, B, nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, N, -1).unbind(0) # q, k, v with shape (B * nHead...
B, H, W, _ = x.shape N = H * W x = x.reshape(B, N, -1) qkv = self.qkv(x).view(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # qkv with shape (3, B, nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, N, -1).unbind(0) # q, k, v with shape (B * nHead...
165
554
618
1,172
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'Exploring Plain Vision Transformer Backbones for Object Detection' - https://arxiv.org/abs/2203.16527 'Segment Anything Model (SAM)' - https://github.com/facebookresearch/segment-anything/ """ import logging...
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'Exploring Plain Vision Transformer Backbones for Object Detection' - https://arxiv.org/abs/2203.16527 'Segment Anything Model (SAM)' - https://github.com/facebookresearch/segment-anything/ """ import logging...
17,926
/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/vision_transformer_sam.py
248,249
199,273
forward
Block
249,273
249,273
class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=True, qk_norm=False, proj_drop=0., attn_drop=0., init_values=None, drop_path=0., act_layer=nn.GELU, ...
class Block(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=True, qk_norm=False, proj_drop=0., attn_drop=0., init_values=None, drop_path=0., act_layer=nn.GELU, ...
B, H, W, _ = x.shape shortcut = x x = self.norm1(x) # Window partition pad_hw: Optional[Tuple[int, int]] = None if self.window_size > 0: x, pad_hw = window_partition(x, self.window_size) x = self.drop_path1(self.ls1(self.attn(x))) # Reverse ...
B, H, W, _ = x.shape shortcut = x x = self.norm1(x) # Window partition pad_hw: Optional[Tuple[int, int]] = None if self.window_size > 0: x, pad_hw = window_partition(x, self.window_size) x = self.drop_path1(self.ls1(self.attn(x))) # Reverse ...
81
540
273
813
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'Exploring Plain Vision Transformer Backbones for Object Detection' - https://arxiv.org/abs/2203.16527 'Segment Anything Model (SAM)' - https://github.com/facebookresearch/segment-anything/ """ import logging...
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'Exploring Plain Vision Transformer Backbones for Object Detection' - https://arxiv.org/abs/2203.16527 'Segment Anything Model (SAM)' - https://github.com/facebookresearch/segment-anything/ """ import logging...
17,927
/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/vision_transformer_sam.py
195,196
189,199
forward
LayerScale
196,199
196,199
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
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'Exploring Plain Vision Transformer Backbones for Object Detection' - https://arxiv.org/abs/2203.16527 'Segment Anything Model (SAM)' - https://github.com/facebookresearch/segment-anything/ """ import logging...
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in: 'Exploring Plain Vision Transformer Backbones for Object Detection' - https://arxiv.org/abs/2203.16527 'Segment Anything Model (SAM)' - https://github.com/facebookresearch/segment-anything/ """ import logging...
17,930
/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/volo.py
162,163
140,187
forward
Attention
163,187
163,187
class Attention(nn.Module): fused_attn: torch.jit.Final[bool] 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 // ...
class Attention(nn.Module): fused_attn: torch.jit.Final[bool] 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 // ...
B, H, W, C = x.shape qkv = self.qkv(x).reshape(B, H * W, 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, dropout_p=self.attn_drop.p if sel...
B, H, W, C = x.shape qkv = self.qkv(x).reshape(B, H * W, 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, dropout_p=self.attn_drop.p if sel...
78
252
300
552
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,931
/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/volo.py
241,242
215,258
forward
ClassAttention
242,258
242,258
class ClassAttention(nn.Module): def __init__( self, dim, num_heads=8, head_dim=None, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() self.num_heads = num_heads if head_dim is not None:...
class ClassAttention(nn.Module): def __init__( self, dim, num_heads=8, head_dim=None, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() self.num_heads = num_heads if head_dim is not None:...
B, N, C = x.shape kv = self.kv(x).reshape(B, N, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) k, v = kv.unbind(0) q = self.q(x[:, :1, :]).reshape(B, self.num_heads, 1, self.head_dim) * self.scale attn = q @ k.transpose(-2, -1) attn = attn.softmax(dim=-1) ...
B, N, C = x.shape kv = self.kv(x).reshape(B, N, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) k, v = kv.unbind(0) q = self.q(x[:, :1, :]).reshape(B, self.num_heads, 1, self.head_dim) * self.scale attn = q @ k.transpose(-2, -1) attn = attn.softmax(dim=-1) ...
60
317
270
587
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,932
/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/volo.py
294,295
258,301
forward
ClassBlock
295,301
295,301
class ClassBlock(nn.Module): def __init__( self, dim, num_heads, head_dim=None, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.Lay...
class ClassBlock(nn.Module): def __init__( self, dim, num_heads, head_dim=None, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.Lay...
cls_embed = x[:, :1] cls_embed = cls_embed + self.drop_path1(self.attn(self.norm1(x))) cls_embed = cls_embed + self.drop_path2(self.mlp(self.norm2(cls_embed))) return torch.cat([cls_embed, x[:, 1:]], dim=1)
cls_embed = x[:, :1] cls_embed = cls_embed + self.drop_path1(self.attn(self.norm1(x))) cls_embed = cls_embed + self.drop_path2(self.mlp(self.norm2(cls_embed))) return torch.cat([cls_embed, x[:, 1:]], dim=1)
19
351
108
459
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,933
/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/volo.py
380,381
372,387
forward
Downsample
381,387
381,387
class Downsample(nn.Module): """ Image to Patch Embedding, downsampling between stage1 and stage2 """ def __init__(self, in_embed_dim, out_embed_dim, patch_size=2): super().__init__() self.proj = nn.Conv2d(in_embed_dim, out_embed_dim, kernel_size=patch_size, stride=patch_size) def forw...
class Downsample(nn.Module): """ Image to Patch Embedding, downsampling between stage1 and stage2 """ def __init__(self, in_embed_dim, out_embed_dim, patch_size=2): super().__init__() self.proj = nn.Conv2d(in_embed_dim, out_embed_dim, kernel_size=patch_size, stride=patch_size) def forw...
x = x.permute(0, 3, 1, 2) x = self.proj(x) # B, C, H, W x = x.permute(0, 2, 3, 1) return x
x = x.permute(0, 3, 1, 2) x = self.proj(x) # B, C, H, W x = x.permute(0, 2, 3, 1) return x
22
127
73
200
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,934
/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/volo.py
71,72
40,98
forward
OutlookAttention
72,98
72,98
class OutlookAttention(nn.Module): def __init__( self, dim, num_heads, kernel_size=3, padding=1, stride=1, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() head_dim = dim...
class OutlookAttention(nn.Module): def __init__( self, dim, num_heads, kernel_size=3, padding=1, stride=1, qkv_bias=False, attn_drop=0., proj_drop=0., ): super().__init__() head_dim = dim...
B, H, W, C = x.shape v = self.v(x).permute(0, 3, 1, 2) # B, C, H, W h, w = math.ceil(H / self.stride), math.ceil(W / self.stride) v = self.unfold(v).reshape( B, self.num_heads, C // self.num_heads, self.kernel_size * self.kernel_size, h * w).permute(0, 1, 4, 3,...
B, H, W, C = x.shape v = self.v(x).permute(0, 3, 1, 2) # B, C, H, W h, w = math.ceil(H / self.stride), math.ceil(W / self.stride) v = self.unfold(v).reshape( B, self.num_heads, C // self.num_heads, self.kernel_size * self.kernel_size, h * w).permute(0, 1, 4, 3,...
122
353
502
855
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,935
/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/volo.py
134,135
98,140
forward
Outlooker
135,140
135,140
class Outlooker(nn.Module): def __init__( self, dim, kernel_size, padding, stride=1, num_heads=1, mlp_ratio=3., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ...
class Outlooker(nn.Module): def __init__( self, dim, kernel_size, padding, stride=1, num_heads=1, mlp_ratio=3., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ...
x = x + self.drop_path1(self.attn(self.norm1(x))) x = x + self.drop_path2(self.mlp(self.norm2(x))) return x
x = x + self.drop_path1(self.attn(self.norm1(x))) x = x + self.drop_path2(self.mlp(self.norm2(x))) return x
12
351
61
412
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,936
/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/volo.py
365,366
329,372
forward
PatchEmbed
366,372
366,372
class PatchEmbed(nn.Module): """ Image to Patch Embedding. Different with ViT use 1 conv layer, we use 4 conv layers to do patch embedding """ def __init__( self, img_size=224, stem_conv=False, stem_stride=1, patch_size=8, in_chans...
class PatchEmbed(nn.Module): """ Image to Patch Embedding. Different with ViT use 1 conv layer, we use 4 conv layers to do patch embedding """ def __init__( self, img_size=224, stem_conv=False, stem_stride=1, patch_size=8, in_chans...
if self.conv is not None: x = self.conv(x) x = self.proj(x) # B, C, H, W return x
if self.conv is not None: x = self.conv(x) x = self.proj(x) # B, C, H, W return x
18
512
51
563
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,937
/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/volo.py
209,210
187,215
forward
Transformer
210,215
210,215
class Transformer(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ): super().__init__() ...
class Transformer(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ): super().__init__() ...
x = x + self.drop_path1(self.attn(self.norm1(x))) x = x + self.drop_path2(self.mlp(self.norm2(x))) return x
x = x + self.drop_path1(self.attn(self.norm1(x))) x = x + self.drop_path2(self.mlp(self.norm2(x))) return x
12
291
61
352
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
""" Vision OutLOoker (VOLO) implementation Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below Modifications and additions for timm by / Copyright 2022, Ross Wightman """ # Co...
17,940
/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/vovnet.py
89,90
43,104
forward
OsaBlock
90,104
90,104
class OsaBlock(nn.Module): def __init__( self, in_chs, mid_chs, out_chs, layer_per_block, residual=False, depthwise=False, attn='', norm_layer=BatchNormAct2d, act_layer=nn.ReLU, drop_...
class OsaBlock(nn.Module): def __init__( self, in_chs, mid_chs, out_chs, layer_per_block, residual=False, depthwise=False, attn='', norm_layer=BatchNormAct2d, act_layer=nn.ReLU, drop_...
output = [x] if self.conv_reduction is not None: x = self.conv_reduction(x) x = self.conv_mid(x, output) x = self.conv_concat(x) if self.attn is not None: x = self.attn(x) if self.drop_path is not None: x = self.drop_path(x) if ...
output = [x] if self.conv_reduction is not None: x = self.conv_reduction(x) x = self.conv_mid(x, output) x = self.conv_concat(x) if self.attn is not None: x = self.attn(x) if self.drop_path is not None: x = self.drop_path(x) if ...
43
501
143
644
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
17,941
/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/vovnet.py
143,144
104,153
forward
OsaStage
144,153
144,153
class OsaStage(nn.Module): def __init__( self, in_chs, mid_chs, out_chs, block_per_stage, layer_per_block, downsample=True, residual=True, depthwise=False, attn='ese', norm_layer=Batc...
class OsaStage(nn.Module): def __init__( self, in_chs, mid_chs, out_chs, block_per_stage, layer_per_block, downsample=True, residual=True, depthwise=False, attn='ese', norm_layer=Batc...
if self.pool is not None: x = self.pool(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
if self.pool is not None: x = self.pool(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x
23
420
87
507
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
17,942
/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/vovnet.py
33,34
29,43
forward
SequentialAppendList
34,43
34,43
class SequentialAppendList(nn.Sequential): def __init__(self, *args): super(SequentialAppendList, self).__init__(*args) def forward(self, x: torch.Tensor, concat_list: List[torch.Tensor]) -> torch.Tensor: FILL_FUNC_BODY
class SequentialAppendList(nn.Sequential): def __init__(self, *args): super(SequentialAppendList, self).__init__(*args) def forward(self, x: torch.Tensor, concat_list: List[torch.Tensor]) -> torch.Tensor: FILL_FUNC_BODY
for i, module in enumerate(self): if i == 0: concat_list.append(module(x)) else: concat_list.append(module(concat_list[-1])) x = torch.cat(concat_list, dim=1) return x
for i, module in enumerate(self): if i == 0: concat_list.append(module(x)) else: concat_list.append(module(concat_list[-1])) x = torch.cat(concat_list, dim=1) return x
18
90
85
175
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
17,943
/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/vovnet.py
261,262
153,272
forward_head
VovNet
262,264
262,264
class VovNet(nn.Module): def __init__( self, cfg, in_chans=3, num_classes=1000, global_pool='avg', output_stride=32, norm_layer=BatchNormAct2d, act_layer=nn.ReLU, drop_rate=0., drop_path_rate=0.,...
class VovNet(nn.Module): def __init__( self, cfg, in_chans=3, num_classes=1000, global_pool='avg', output_stride=32, norm_layer=BatchNormAct2d, act_layer=nn.ReLU, drop_rate=0., drop_path_rate=0.,...
return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x)
return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x)
7
1,631
34
1,665
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
""" VoVNet (V1 & V2) Papers: * `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 * `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 Looked at https://github.com/youngwanLEE/vovnet-detectron2 & https://github.com/stigma0617/VoVNe...
17,945
/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/xception.py
80,81
49,93
forward
Block
81,93
81,93
class Block(nn.Module): def __init__(self, in_channels, out_channels, reps, strides=1, start_with_relu=True, grow_first=True): super(Block, self).__init__() if out_channels != in_channels or strides != 1: self.skip = nn.Conv2d(in_channels, out_channels, 1, stride=strides, bias=False) ...
class Block(nn.Module): def __init__(self, in_channels, out_channels, reps, strides=1, start_with_relu=True, grow_first=True): super(Block, self).__init__() if out_channels != in_channels or strides != 1: self.skip = nn.Conv2d(in_channels, out_channels, 1, stride=strides, bias=False) ...
x = self.rep(inp) if self.skip is not None: skip = self.skip(inp) skip = self.skipbn(skip) else: skip = inp x += skip return x
x = self.rep(inp) if self.skip is not None: skip = self.skip(inp) skip = self.skipbn(skip) else: skip = inp x += skip return x
23
408
78
486
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Ke...
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Ke...
17,946
/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/xception.py
43,44
35,49
forward
SeparableConv2d
44,49
44,49
class SeparableConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1): super(SeparableConv2d, self).__init__() self.conv1 = nn.Conv2d( in_channels, in_channels, kernel_size, stride, padding, dilation, groups=in_channels, bias=Fal...
class SeparableConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1): super(SeparableConv2d, self).__init__() self.conv1 = nn.Conv2d( in_channels, in_channels, kernel_size, stride, padding, dilation, groups=in_channels, bias=Fal...
x = self.conv1(x) x = self.pointwise(x) return x
x = self.conv1(x) x = self.pointwise(x) return x
8
184
33
217
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Ke...
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Ke...
17,947
/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/xception.py
181,182
93,224
forward_features
Xception
182,212
182,212
class Xception(nn.Module): """ Xception optimized for the ImageNet dataset, as specified in https://arxiv.org/pdf/1610.02357.pdf """ def __init__(self, num_classes=1000, in_chans=3, drop_rate=0., global_pool='avg'): """ Constructor Args: num_classes: number of classes ...
class Xception(nn.Module): """ Xception optimized for the ImageNet dataset, as specified in https://arxiv.org/pdf/1610.02357.pdf """ def __init__(self, num_classes=1000, in_chans=3, drop_rate=0., global_pool='avg'): """ Constructor Args: num_classes: number of classes ...
x = self.conv1(x) x = self.bn1(x) x = self.act1(x) x = self.conv2(x) x = self.bn2(x) x = self.act2(x) x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x) x = self.block5(x) x = self.block6(x) ...
x = self.conv1(x) x = self.bn1(x) x = self.act1(x) x = self.conv2(x) x = self.bn2(x) x = self.act2(x) x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x) x = self.block5(x) x = self.block6(x) ...
74
1,440
306
1,746
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Ke...
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Ke...
17,951
/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/optim/adamp.py
25,26
1,106
projection
26,43
26,43
""" AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ impor...
""" AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ impor...
wd = 1. expand_size = (-1,) + (1,) * (len(p.shape) - 1) for view_func in [_channel_view, _layer_view]: param_view = view_func(p) grad_view = view_func(grad) cosine_sim = F.cosine_similarity(grad_view, param_view, dim=1, eps=eps).abs_() # FIXME this is a problem for PyTorch X...
wd = 1. expand_size = (-1,) + (1,) * (len(p.shape) - 1) for view_func in [_channel_view, _layer_view]: param_view = view_func(p) grad_view = view_func(grad) cosine_sim = F.cosine_similarity(grad_view, param_view, dim=1, eps=eps).abs_() # FIXME this is a problem for PyTorch X...
66
971
259
1,230
""" AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ impor...
""" AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ impor...
17,952
/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/optim/adamp.py
51,53
43,106
step
AdamP
53,106
53,106
class AdamP(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, delta=0.1, wd_ratio=0.1, nesterov=False): defaults = dict( lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, delta=delta, wd_ratio=wd_ratio, nesterov=neste...
class AdamP(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, delta=0.1, wd_ratio=0.1, nesterov=False): defaults = dict( lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, delta=delta, wd_ratio=wd_ratio, nesterov=neste...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad beta1, ...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad beta1, ...
157
187
590
777
""" AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ impor...
""" AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ impor...
17,953
/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/optim/adamw.py
58,60
12,123
step
AdamW
66,123
60,123
class AdamW(Optimizer): r"""Implements AdamW algorithm. The original Adam algorithm was proposed in `Adam: A Method for Stochastic Optimization`_. The AdamW variant was proposed in `Decoupled Weight Decay Regularization`_. Arguments: params (iterable): iterable of parameters to optimize or dic...
class AdamW(Optimizer): r"""Implements AdamW algorithm. The original Adam algorithm was proposed in `Adam: A Method for Stochastic Optimization`_. The AdamW variant was proposed in `Decoupled Weight Decay Regularization`_. Arguments: params (iterable): iterable of parameters to optimize or dic...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue # Perform stepweight decay ...
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() ...
207
752
743
1,495
""" AdamW Optimizer Impl copied from PyTorch master NOTE: Builtin optim.AdamW is used by the factory, this impl only serves as a Python based reference, will be removed someday """ import math import torch from torch.optim.optimizer import Optimizer class AdamW(Optimizer): r"""Implements AdamW algorithm. Th...
""" AdamW Optimizer Impl copied from PyTorch master NOTE: Builtin optim.AdamW is used by the factory, this impl only serves as a Python based reference, will be removed someday """ import math import torch from torch.optim.optimizer import Optimizer class AdamW(Optimizer): r"""Implements AdamW algorithm. Th...
17,954
/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/optim/adan.py
71,73
16,125
step
Adan
75,125
73,125
class Adan(Optimizer): """ Implements a pytorch variant of Adan Adan was proposed in Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models[J]. arXiv preprint arXiv:2208.06677, 2022. https://arxiv.org/abs/2208.06677 Arguments: params (iterable): iterable of paramete...
class Adan(Optimizer): """ Implements a pytorch variant of Adan Adan was proposed in Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models[J]. arXiv preprint arXiv:2208.06677, 2022. https://arxiv.org/abs/2208.06677 Arguments: params (iterable): iterable of paramete...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: beta1, beta2, beta3 = group['betas'] # assume same step across group now to simplify things # per parameter step can be ...
""" Performs a single optimization step. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: beta1, beta2, beta3 = group['betas'] # assume same step across group no...
187
829
702
1,531
""" Adan Optimizer Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models[J]. arXiv preprint arXiv:2208.06677, 2022. https://arxiv.org/abs/2208.06677 Implementation adapted from https://github.com/sail-sg/Adan """ import math import torch from torch.optim import Optimizer class Adan(Opt...
""" Adan Optimizer Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models[J]. arXiv preprint arXiv:2208.06677, 2022. https://arxiv.org/abs/2208.06677 Implementation adapted from https://github.com/sail-sg/Adan """ import math import torch from torch.optim import Optimizer class Adan(Opt...
17,955
/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/optim/lamb.py
96,98
60,193
step
Lamb
103,193
98,193
class Lamb(Optimizer): """Implements a pure pytorch variant of FuseLAMB (NvLamb variant) optimizer from apex.optimizers.FusedLAMB reference: https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/Transformer-XL/pytorch/lamb.py LAMB was proposed in `Large Batch Optimization for ...
class Lamb(Optimizer): """Implements a pure pytorch variant of FuseLAMB (NvLamb variant) optimizer from apex.optimizers.FusedLAMB reference: https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/Transformer-XL/pytorch/lamb.py LAMB was proposed in `Large Batch Optimization for ...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() device = self.param_groups[0]['params'][0].device one_tensor = torch.tensor(1.0, device=device) # because torch.where doesn't handle scalars correctly global_grad_norm = t...
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() ...
360
730
1,218
1,948
""" PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb This optimizer code was adapted from the following (starting with latest) * https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py * https://github.com/NVIDIA/DeepLearningExample...
""" PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb This optimizer code was adapted from the following (starting with latest) * https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py * https://github.com/NVIDIA/DeepLearningExample...
17,956
/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/optim/lars.py
75,77
17,136
step
Lars
82,136
77,136
class Lars(Optimizer): """ LARS for PyTorch Paper: `Large batch training of Convolutional Networks` - https://arxiv.org/pdf/1708.03888.pdf Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate (default: 1.0)....
class Lars(Optimizer): """ LARS for PyTorch Paper: `Large batch training of Convolutional Networks` - https://arxiv.org/pdf/1708.03888.pdf Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate (default: 1.0)....
loss = None if closure is not None: with torch.enable_grad(): loss = closure() device = self.param_groups[0]['params'][0].device one_tensor = torch.tensor(1.0, device=device) # because torch.where doesn't handle scalars correctly for group in self.p...
"""Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() device = sel...
179
739
698
1,437
""" PyTorch LARS / LARC Optimizer An implementation of LARS (SGD) + LARC in PyTorch Based on: * PyTorch SGD: https://github.com/pytorch/pytorch/blob/1.7/torch/optim/sgd.py#L100 * NVIDIA APEX LARC: https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py Additional cleanup and modifications to properly su...
""" PyTorch LARS / LARC Optimizer An implementation of LARS (SGD) + LARC in PyTorch Based on: * PyTorch SGD: https://github.com/pytorch/pytorch/blob/1.7/torch/optim/sgd.py#L100 * NVIDIA APEX LARC: https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py Additional cleanup and modifications to properly su...
17,958
/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/optim/lion.py
69,71
25,122
step
Lion
80,122
71,122
class Lion(Optimizer): r"""Implements Lion algorithm.""" def __init__( self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0, maximize=False, foreach=None, ): """Initialize the hyperparameters. Args: ...
class Lion(Optimizer): r"""Implements Lion algorithm.""" def __init__( self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0, maximize=False, foreach=None, ): """Initialize the hyperparameters. Args: ...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad = [] grads = [] exp_avgs = [] beta1, beta2 = group['betas'] for p in group['pa...
"""Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. Returns: the loss. """ loss = None if closure is not None: with torch.enable_grad(): ...
78
524
361
885
""" Lion Optimizer Paper: `Symbolic Discovery of Optimization Algorithms` - https://arxiv.org/abs/2302.06675 Original Impl: https://github.com/google/automl/tree/master/lion """ # Copyright 2023 Google Research. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t...
""" Lion Optimizer Paper: `Symbolic Discovery of Optimization Algorithms` - https://arxiv.org/abs/2302.06675 Original Impl: https://github.com/google/automl/tree/master/lion """ # Copyright 2023 Google Research. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t...
17,959
/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/optim/lookahead.py
35,37
15,67
update_slow
Lookahead
37,48
37,48
class Lookahead(Optimizer): def __init__(self, base_optimizer, alpha=0.5, k=6): # NOTE super().__init__() not called on purpose self._optimizer_step_pre_hooks: Dict[int, Callable] = OrderedDict() self._optimizer_step_post_hooks: Dict[int, Callable] = OrderedDict() if not 0.0 <= alpha...
class Lookahead(Optimizer): def __init__(self, base_optimizer, alpha=0.5, k=6): # NOTE super().__init__() not called on purpose self._optimizer_step_pre_hooks: Dict[int, Callable] = OrderedDict() self._optimizer_step_post_hooks: Dict[int, Callable] = OrderedDict() if not 0.0 <= alpha...
for fast_p in group["params"]: if fast_p.grad is None: continue param_state = self._base_optimizer.state[fast_p] if 'lookahead_slow_buff' not in param_state: param_state['lookahead_slow_buff'] = torch.empty_like(fast_p) param_st...
for fast_p in group["params"]: if fast_p.grad is None: continue param_state = self._base_optimizer.state[fast_p] if 'lookahead_slow_buff' not in param_state: param_state['lookahead_slow_buff'] = torch.empty_like(fast_p) param_st...
29
552
169
721
""" Lookahead Optimizer Wrapper. Implementation modified from: https://github.com/alphadl/lookahead.pytorch Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610 Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from typing import Callable...
""" Lookahead Optimizer Wrapper. Implementation modified from: https://github.com/alphadl/lookahead.pytorch Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610 Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from typing import Callable...
17,960
/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/optim/madgrad.py
85,87
24,185
step
MADGRAD
92,185
87,185
class MADGRAD(torch.optim.Optimizer): """ MADGRAD_: A Momentumized, Adaptive, Dual Averaged Gradient Method for Stochastic Optimization. .. _MADGRAD: https://arxiv.org/abs/2101.11075 MADGRAD is a general purpose optimizer that can be used in place of SGD or Adam may converge faster and general...
class MADGRAD(torch.optim.Optimizer): """ MADGRAD_: A Momentumized, Adaptive, Dual Averaged Gradient Method for Stochastic Optimization. .. _MADGRAD: https://arxiv.org/abs/2101.11075 MADGRAD is a general purpose optimizer that can be used in place of SGD or Adam may converge faster and general...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: eps = group['eps'] lr = group['lr'] + eps weight_decay = group['weight_decay'] momentum = group['momentum'] ...
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() for gro...
286
775
1,153
1,928
""" PyTorch MADGRAD optimizer MADGRAD: https://arxiv.org/abs/2101.11075 Code from: https://github.com/facebookresearch/madgrad """ # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import ma...
""" PyTorch MADGRAD optimizer MADGRAD: https://arxiv.org/abs/2101.11075 Code from: https://github.com/facebookresearch/madgrad """ # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import ma...
17,961
/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/optim/nadam.py
43,45
7,98
step
Nadam
51,98
45,98
class Nadam(Optimizer): """Implements Nadam algorithm (a variant of Adam based on Nesterov momentum). It has been proposed in `Incorporating Nesterov Momentum into Adam`__. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (f...
class Nadam(Optimizer): """Implements Nadam algorithm (a variant of Adam based on Nesterov momentum). It has been proposed in `Incorporating Nesterov Momentum into Adam`__. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (f...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad state = ...
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() ...
183
548
689
1,237
import math import torch from torch.optim.optimizer import Optimizer class Nadam(Optimizer): """Implements Nadam algorithm (a variant of Adam based on Nesterov momentum). It has been proposed in `Incorporating Nesterov Momentum into Adam`__. Arguments: params (iterable): iterable of parameters ...
import math import torch from torch.optim.optimizer import Optimizer class Nadam(Optimizer): """Implements Nadam algorithm (a variant of Adam based on Nesterov momentum). It has been proposed in `Incorporating Nesterov Momentum into Adam`__. Arguments: params (iterable): iterable of parameters ...
17,963
/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/optim/nadamw.py
80,82
15,143
step
NAdamW
88,143
82,143
class NAdamW(torch.optim.Optimizer): r"""Implements NAdamW algorithm. See Table 1 in https://arxiv.org/abs/1910.05446 for the implementation of the NAdam algorithm (there is also a comment in the code which highlights the only difference of NAdamW and AdamW). For further details regarding t...
class NAdamW(torch.optim.Optimizer): r"""Implements NAdamW algorithm. See Table 1 in https://arxiv.org/abs/1910.05446 for the implementation of the NAdam algorithm (there is also a comment in the code which highlights the only difference of NAdamW and AdamW). For further details regarding t...
self._cuda_graph_capture_health_check() loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad = [] grads = [] exp_avgs = [] exp_avg_sqs ...
"""Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ self._cuda_graph_capture_health_check() loss = None if closure is not None: with to...
112
872
544
1,416
""" NAdamW Optimizer Based on simplified algorithm in https://github.com/mlcommons/algorithmic-efficiency/tree/main/baselines/nadamw Added multi-tensor (foreach) path. """ import math from typing import List, Optional import torch from torch import Tensor # Modified from github.com/pytorch/pytorch/blob/v1.12.1/tor...
""" NAdamW Optimizer Based on simplified algorithm in https://github.com/mlcommons/algorithmic-efficiency/tree/main/baselines/nadamw Added multi-tensor (foreach) path. """ import math from typing import List, Optional import torch from torch import Tensor # Modified from github.com/pytorch/pytorch/blob/v1.12.1/tor...
17,964
/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/optim/nvnovograd.py
54,56
13,121
step
NvNovoGrad
62,121
56,121
class NvNovoGrad(Optimizer): """ Implements Novograd algorithm. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for...
class NvNovoGrad(Optimizer): """ Implements Novograd algorithm. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad if grad....
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() ...
173
636
722
1,358
""" Nvidia NovoGrad Optimizer. Original impl by Nvidia from Jasper example: - https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/SpeechRecognition/Jasper Paper: `Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks` - https://arxiv.org/abs/1905.11286 """ im...
""" Nvidia NovoGrad Optimizer. Original impl by Nvidia from Jasper example: - https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/SpeechRecognition/Jasper Paper: `Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks` - https://arxiv.org/abs/1905.11286 """ im...
17,965
/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/optim/radam.py
21,23
10,90
step
RAdam
23,90
23,90
class RAdam(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): defaults = dict( lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, buffer=[[None, None, None] for _ in range(10)]) super(RAdam, self).__init__(params, defaults) ...
class RAdam(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): defaults = dict( lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, buffer=[[None, None, None] for _ in range(10)]) super(RAdam, self).__init__(params, defaults) ...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.float() ...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.float() ...
224
191
904
1,095
"""RAdam Optimizer. Implementation lifted from: https://github.com/LiyuanLucasLiu/RAdam Paper: `On the Variance of the Adaptive Learning Rate and Beyond` - https://arxiv.org/abs/1908.03265 """ import math import torch from torch.optim.optimizer import Optimizer class RAdam(Optimizer): def __init__(self, params, ...
"""RAdam Optimizer. Implementation lifted from: https://github.com/LiyuanLucasLiu/RAdam Paper: `On the Variance of the Adaptive Learning Rate and Beyond` - https://arxiv.org/abs/1908.03265 """ import math import torch from torch.optim.optimizer import Optimizer class RAdam(Optimizer): def __init__(self, params, ...
17,966
/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/optim/rmsprop_tf.py
72,74
14,140
step
RMSpropTF
80,140
74,140
class RMSpropTF(Optimizer): """Implements RMSprop algorithm (TensorFlow style epsilon) NOTE: This is a direct cut-and-paste of PyTorch RMSprop with eps applied before sqrt and a few other modifications to closer match Tensorflow for matching hyper-params. Noteworthy changes include: 1. Epsilon app...
class RMSpropTF(Optimizer): """Implements RMSprop algorithm (TensorFlow style epsilon) NOTE: This is a direct cut-and-paste of PyTorch RMSprop with eps applied before sqrt and a few other modifications to closer match Tensorflow for matching hyper-params. Noteworthy changes include: 1. Epsilon app...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad if grad....
"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() ...
197
931
801
1,732
""" RMSProp modified to behave like Tensorflow impl Originally cut & paste from PyTorch RMSProp https://github.com/pytorch/pytorch/blob/063946d2b3f3f1e953a2a3b54e0b34f1393de295/torch/optim/rmsprop.py Licensed under BSD-Clause 3 (ish), https://github.com/pytorch/pytorch/blob/master/LICENSE Modifications Copyright 2021...
""" RMSProp modified to behave like Tensorflow impl Originally cut & paste from PyTorch RMSProp https://github.com/pytorch/pytorch/blob/063946d2b3f3f1e953a2a3b54e0b34f1393de295/torch/optim/rmsprop.py Licensed under BSD-Clause 3 (ish), https://github.com/pytorch/pytorch/blob/master/LICENSE Modifications Copyright 2021...
17,967
/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/optim/sgdp.py
27,29
19,71
step
SGDP
29,71
29,71
class SGDP(Optimizer): def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, eps=1e-8, delta=0.1, wd_ratio=0.1): defaults = dict( lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov, e...
class SGDP(Optimizer): def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, eps=1e-8, delta=0.1, wd_ratio=0.1): defaults = dict( lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov, e...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = ...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = ...
116
185
411
596
""" SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ import ...
""" SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ import ...
17,969
/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/optim/sgdw.py
74,76
16,116
step
SGDW
82,116
76,116
class SGDW(Optimizer): def __init__( self, params, lr=1e-3, momentum=0, dampening=0, weight_decay=0, nesterov=False, *, maximize: bool = False, foreach: Optional[bool] = None, differen...
class SGDW(Optimizer): def __init__( self, params, lr=1e-3, momentum=0, dampening=0, weight_decay=0, nesterov=False, *, maximize: bool = False, foreach: Optional[bool] = None, differen...
loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad = [] d_p_list = [] momentum_buffer_list = [] has_sparse_grad = self._init_group(group, par...
"""Performs a single optimization step. Args: closure (Callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() ...
64
679
327
1,006
from functools import update_wrapper, wraps import torch from torch import Tensor from torch.optim.optimizer import Optimizer try: from torch.optim.optimizer import _use_grad_for_differentiable, _default_to_fused_or_foreach has_recent_pt = True except ImportError: has_recent_pt = False from typing import L...
from functools import update_wrapper, wraps import torch from torch import Tensor from torch.optim.optimizer import Optimizer try: from torch.optim.optimizer import _use_grad_for_differentiable, _default_to_fused_or_foreach has_recent_pt = True except ImportError: has_recent_pt = False from typing import L...
17,970
/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/scheduler/cosine_lr.py
81,82
19,117
_get_lr
CosineLRScheduler
82,111
82,111
class CosineLRScheduler(Scheduler): """ Cosine decay with restarts. This is described in the paper https://arxiv.org/abs/1608.03983. Inspiration from https://github.com/allenai/allennlp/blob/master/allennlp/training/learning_rate_schedulers/cosine.py k-decay option based on `k-decay: A New Met...
class CosineLRScheduler(Scheduler): """ Cosine decay with restarts. This is described in the paper https://arxiv.org/abs/1608.03983. Inspiration from https://github.com/allenai/allennlp/blob/master/allennlp/training/learning_rate_schedulers/cosine.py k-decay option based on `k-decay: A New Met...
if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: if self.warmup_prefix: t = t - self.warmup_t if self.cycle_mul != 1: i = math.floor(math.log(1 - t / self.t_initial * (1 - self.cycle_mul), self...
if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: if self.warmup_prefix: t = t - self.warmup_t if self.cycle_mul != 1: i = math.floor(math.log(1 - t / self.t_initial * (1 - self.cycle_mul), self...
135
863
419
1,282
""" Cosine Scheduler Cosine LR schedule with warmup, cycle/restarts, noise, k-decay. Hacked together by / Copyright 2021 Ross Wightman """ import logging import math import numpy as np import torch from typing import List from .scheduler import Scheduler _logger = logging.getLogger(__name__) class CosineLRSchedu...
""" Cosine Scheduler Cosine LR schedule with warmup, cycle/restarts, noise, k-decay. Hacked together by / Copyright 2021 Ross Wightman """ import logging import math import numpy as np import torch from typing import List from .scheduler import Scheduler _logger = logging.getLogger(__name__) class CosineLRSchedu...
17,971
/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/scheduler/multistep_lr.py
51,52
10,64
get_curr_decay_steps
MultiStepLRScheduler
52,56
52,56
class MultiStepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch.optim.Optimizer, decay_t: List[int], decay_rate: float = 1., warmup_t=0, warmup_lr_init=0, warmup_prefix=True, t_in_epochs=True...
class MultiStepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch.optim.Optimizer, decay_t: List[int], decay_rate: float = 1., warmup_t=0, warmup_lr_init=0, warmup_prefix=True, t_in_epochs=True...
# find where in the array t goes, # assumes self.decay_t is sorted return bisect.bisect_right(self.decay_t, t + 1)
# find where in the array t goes, # assumes self.decay_t is sorted return bisect.bisect_right(self.decay_t, t + 1)
18
589
50
639
""" MultiStep LR Scheduler Basic multi step LR schedule with warmup, noise. """ import torch import bisect from timm.scheduler.scheduler import Scheduler from typing import List class MultiStepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch.optim.Optimizer, ...
""" MultiStep LR Scheduler Basic multi step LR schedule with warmup, noise. """ import torch import bisect from timm.scheduler.scheduler import Scheduler from typing import List class MultiStepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch.optim.Optimizer, ...
17,972
/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/scheduler/plateau_lr.py
72,73
13,112
load_state_dict
PlateauLRScheduler
73,78
73,78
class PlateauLRScheduler(Scheduler): """Decay the LR by a factor every time the validation loss plateaus.""" def __init__( self, optimizer, decay_rate=0.1, patience_t=10, verbose=True, threshold=1e-4, cooldown_t=0, ...
class PlateauLRScheduler(Scheduler): """Decay the LR by a factor every time the validation loss plateaus.""" def __init__( self, optimizer, decay_rate=0.1, patience_t=10, verbose=True, threshold=1e-4, cooldown_t=0, ...
self.lr_scheduler.best = state_dict['best'] if 'last_epoch' in state_dict: self.lr_scheduler.last_epoch = state_dict['last_epoch'] # override the base class step fn completely
self.lr_scheduler.best = state_dict['best'] if 'last_epoch' in state_dict: self.lr_scheduler.last_epoch = state_dict['last_epoch'] # override the base class step fn completely
18
1,030
72
1,102
""" Plateau Scheduler Adapts PyTorch plateau scheduler and allows application of noise, warmup. Hacked together by / Copyright 2020 Ross Wightman """ import torch from typing import List from .scheduler import Scheduler class PlateauLRScheduler(Scheduler): """Decay the LR by a factor every time the validation ...
""" Plateau Scheduler Adapts PyTorch plateau scheduler and allows application of noise, warmup. Hacked together by / Copyright 2020 Ross Wightman """ import torch from typing import List from .scheduler import Scheduler class PlateauLRScheduler(Scheduler): """Decay the LR by a factor every time the validation ...
17,973
/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/scheduler/poly_lr.py
107,108
19,113
get_cycle_length
PolyLRScheduler
108,113
108,113
class PolyLRScheduler(Scheduler): """ Polynomial LR Scheduler w/ warmup, noise, and k-decay k-decay option based on `k-decay: A New Method For Learning Rate Schedule` - https://arxiv.org/abs/2004.05909 """ def __init__( self, optimizer: torch.optim.Optimizer, t_init...
class PolyLRScheduler(Scheduler): """ Polynomial LR Scheduler w/ warmup, noise, and k-decay k-decay option based on `k-decay: A New Method For Learning Rate Schedule` - https://arxiv.org/abs/2004.05909 """ def __init__( self, optimizer: torch.optim.Optimizer, t_init...
cycles = max(1, cycles or self.cycle_limit) if self.cycle_mul == 1.0: return self.t_initial * cycles else: return int(math.floor(-self.t_initial * (self.cycle_mul ** cycles - 1) / (1 - self.cycle_mul)))
cycles = max(1, cycles or self.cycle_limit) if self.cycle_mul == 1.0: return self.t_initial * cycles else: return int(math.floor(-self.t_initial * (self.cycle_mul ** cycles - 1) / (1 - self.cycle_mul)))
27
1,111
88
1,199
""" Polynomial Scheduler Polynomial LR schedule with warmup, noise. Hacked together by / Copyright 2021 Ross Wightman """ import math import logging from typing import List import torch from .scheduler import Scheduler _logger = logging.getLogger(__name__) class PolyLRScheduler(Scheduler): """ Polynomial LR...
""" Polynomial Scheduler Polynomial LR schedule with warmup, noise. Hacked together by / Copyright 2021 Ross Wightman """ import math import logging from typing import List import torch from .scheduler import Scheduler _logger = logging.getLogger(__name__) class PolyLRScheduler(Scheduler): """ Polynomial LR...
17,974
/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/scheduler/scheduler.py
106,107
8,128
_is_apply_noise
Scheduler
108,116
107,116
class Scheduler(ABC): """ Parameter Scheduler Base Class A scheduler base class that can be used to schedule any optimizer parameter groups. Unlike the builtin PyTorch schedulers, this is intended to be consistently called * At the END of each epoch, before incrementing the epoch count, to calculate ne...
class Scheduler(ABC): """ Parameter Scheduler Base Class A scheduler base class that can be used to schedule any optimizer parameter groups. Unlike the builtin PyTorch schedulers, this is intended to be consistently called * At the END of each epoch, before incrementing the epoch count, to calculate ne...
apply_noise = False if self.noise_range_t is not None: if isinstance(self.noise_range_t, (list, tuple)): apply_noise = self.noise_range_t[0] <= t < self.noise_range_t[1] else: apply_noise = t >= self.noise_range_t return apply_noise
"""Return True if scheduler in noise range.""" apply_noise = False if self.noise_range_t is not None: if isinstance(self.noise_range_t, (list, tuple)): apply_noise = self.noise_range_t[0] <= t < self.noise_range_t[1] else: apply_noise = t >...
27
1,514
104
1,618
import abc from abc import ABC from typing import Any, Dict, List, Optional import torch class Scheduler(ABC): """ Parameter Scheduler Base Class A scheduler base class that can be used to schedule any optimizer parameter groups. Unlike the builtin PyTorch schedulers, this is intended to be consistently...
import abc from abc import ABC from typing import Any, Dict, List, Optional import torch class Scheduler(ABC): """ Parameter Scheduler Base Class A scheduler base class that can be used to schedule any optimizer parameter groups. Unlike the builtin PyTorch schedulers, this is intended to be consistently...
17,975
/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/scheduler/step_lr.py
56,57
15,64
_get_lr
StepLRScheduler
57,64
57,64
class StepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch.optim.Optimizer, decay_t: float, decay_rate: float = 1., warmup_t=0, warmup_lr_init=0, warmup_prefix=True, t_in_epochs=True, ...
class StepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch.optim.Optimizer, decay_t: float, decay_rate: float = 1., warmup_t=0, warmup_lr_init=0, warmup_prefix=True, t_in_epochs=True, ...
if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: if self.warmup_prefix: t = t - self.warmup_t lrs = [v * (self.decay_rate ** (t // self.decay_t)) for v in self.base_values] return lrs
if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: if self.warmup_prefix: t = t - self.warmup_t lrs = [v * (self.decay_rate ** (t // self.decay_t)) for v in self.base_values] return lrs
38
453
119
572
""" Step Scheduler Basic step LR schedule with warmup, noise. Hacked together by / Copyright 2020 Ross Wightman """ import math import torch from typing import List from .scheduler import Scheduler class StepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch....
""" Step Scheduler Basic step LR schedule with warmup, noise. Hacked together by / Copyright 2020 Ross Wightman """ import math import torch from typing import List from .scheduler import Scheduler class StepLRScheduler(Scheduler): """ """ def __init__( self, optimizer: torch....
17,976
/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/scheduler/tanh_lr.py
79,80
19,114
_get_lr
TanhLRScheduler
80,108
80,108
class TanhLRScheduler(Scheduler): """ Hyberbolic-Tangent decay with restarts. This is described in the paper https://arxiv.org/abs/1806.01593 """ def __init__( self, optimizer: torch.optim.Optimizer, t_initial: int, lb: float = -7., ub: fl...
class TanhLRScheduler(Scheduler): """ Hyberbolic-Tangent decay with restarts. This is described in the paper https://arxiv.org/abs/1806.01593 """ def __init__( self, optimizer: torch.optim.Optimizer, t_initial: int, lb: float = -7., ub: fl...
if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: if self.warmup_prefix: t = t - self.warmup_t if self.cycle_mul != 1: i = math.floor(math.log(1 - t / self.t_initial * (1 - self.cycle_mul), self...
if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: if self.warmup_prefix: t = t - self.warmup_t if self.cycle_mul != 1: i = math.floor(math.log(1 - t / self.t_initial * (1 - self.cycle_mul), self...
137
783
420
1,203
""" TanH Scheduler TanH schedule with warmup, cycle/restarts, noise. Hacked together by / Copyright 2021 Ross Wightman """ import logging import math import numpy as np import torch from typing import List from .scheduler import Scheduler _logger = logging.getLogger(__name__) class TanhLRScheduler(Scheduler): ...
""" TanH Scheduler TanH schedule with warmup, cycle/restarts, noise. Hacked together by / Copyright 2021 Ross Wightman """ import logging import math import numpy as np import torch from typing import List from .scheduler import Scheduler _logger = logging.getLogger(__name__) class TanhLRScheduler(Scheduler): ...
17,977
/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/utils/agc.py
21,22
1,43
unitwise_norm
22,30
22,30
""" Adaptive Gradient Clipping An impl of AGC, as per (https://arxiv.org/abs/2102.06171): @article{brock2021high, author={Andrew Brock and Soham De and Samuel L. Smith and Karen Simonyan}, title={High-Performance Large-Scale Image Recognition Without Normalization}, journal={arXiv preprint arXiv:}, year={2021...
""" Adaptive Gradient Clipping An impl of AGC, as per (https://arxiv.org/abs/2102.06171): @article{brock2021high, author={Andrew Brock and Soham De and Samuel L. Smith and Karen Simonyan}, title={High-Performance Large-Scale Image Recognition Without Normalization}, journal={arXiv preprint arXiv:}, year={2021...
if x.ndim <= 1: return x.norm(norm_type) else: # works for nn.ConvNd and nn,Linear where output dim is first in the kernel/weight tensor # might need special cases for other weights (possibly MHA) where this may not be true return x.norm(norm_type, dim=tuple(range(1, x.ndim)), ke...
if x.ndim <= 1: return x.norm(norm_type) else: # works for nn.ConvNd and nn,Linear where output dim is first in the kernel/weight tensor # might need special cases for other weights (possibly MHA) where this may not be true return x.norm(norm_type, dim=tuple(range(1, x.ndim)), ke...
43
507
115
622
""" Adaptive Gradient Clipping An impl of AGC, as per (https://arxiv.org/abs/2102.06171): @article{brock2021high, author={Andrew Brock and Soham De and Samuel L. Smith and Karen Simonyan}, title={High-Performance Large-Scale Image Recognition Without Normalization}, journal={arXiv preprint arXiv:}, year={2021...
""" Adaptive Gradient Clipping An impl of AGC, as per (https://arxiv.org/abs/2102.06171): @article{brock2021high, author={Andrew Brock and Soham De and Samuel L. Smith and Karen Simonyan}, title={High-Performance Large-Scale Image Recognition Without Normalization}, journal={arXiv preprint arXiv:}, year={2021...
17,978
/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/utils/clip_grad.py
6,7
1,24
dispatch_clip_grad
15,24
7,24
import torch from timm.utils.agc import adaptive_clip_grad def dispatch_clip_grad(parameters, value: float, mode: str = 'norm', norm_type: float = 2.0): FILL_FUNC_BODY
import torch from timm.utils.agc import adaptive_clip_grad def dispatch_clip_grad(parameters, value: float, mode: str = 'norm', norm_type: float = 2.0): """ Dispatch to gradient clipping method Args: parameters (Iterable): model parameters to clip value (float): clipping value/factor/norm, m...
if mode == 'norm': torch.nn.utils.clip_grad_norm_(parameters, value, norm_type=norm_type) elif mode == 'value': torch.nn.utils.clip_grad_value_(parameters, value) elif mode == 'agc': adaptive_clip_grad(parameters, value, norm_type=norm_type) else: assert False, f"Unknown ...
""" Dispatch to gradient clipping method Args: parameters (Iterable): model parameters to clip value (float): clipping value/factor/norm, mode dependant mode (str): clipping mode, one of 'norm', 'value', 'agc' norm_type (float): p-norm, default 2.0 """ if mode == 'norm':...
27
150
121
271
import torch from timm.utils.agc import adaptive_clip_grad def dispatch_clip_grad(parameters, value: float, mode: str = 'norm', norm_type: float = 2.0): FILL_FUNC_BODY
import torch from timm.utils.agc import adaptive_clip_grad def dispatch_clip_grad(parameters, value: float, mode: str = 'norm', norm_type: float = 2.0): """ Dispatch to gradient clipping method Args: parameters (Iterable): model parameters to clip value (float): clipping value/factor/norm, m...
17,979
/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/utils/cuda.py
37,38
17,46
state_dict
ApexScaler
38,41
38,41
class ApexScaler: state_dict_key = "amp" def __call__( self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False, need_update=True, ): with amp.scale_loss(loss, optimiz...
class ApexScaler: state_dict_key = "amp" def __call__( self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False, need_update=True, ): with amp.scale_loss(loss, optimiz...
if 'state_dict' in amp.__dict__: return amp.state_dict()
if 'state_dict' in amp.__dict__: return amp.state_dict()
6
236
27
263
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call__( sel...
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call__( sel...
17,980
/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/utils/cuda.py
71,72
46,76
state_dict
NativeScaler
72,74
72,74
class NativeScaler: state_dict_key = "amp_scaler" def __init__(self): self._scaler = torch.cuda.amp.GradScaler() def __call__( self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=...
class NativeScaler: state_dict_key = "amp_scaler" def __init__(self): self._scaler = torch.cuda.amp.GradScaler() def __call__( self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=...
return self._scaler.state_dict()
return self._scaler.state_dict()
2
280
15
295
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call__( sel...
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call__( sel...
17,981
/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/utils/decay_batch.py
32,33
1,44
check_batch_size_retry
35,44
33,44
""" Batch size decay and retry helpers. Copyright 2022 Ross Wightman """ import math def decay_batch_step(batch_size, num_intra_steps=2, no_odd=False): """ power of two batch-size decay with intra steps Decay by stepping between powers of 2: * determine power-of-2 floor of current batch size (base batch...
""" Batch size decay and retry helpers. Copyright 2022 Ross Wightman """ import math def decay_batch_step(batch_size, num_intra_steps=2, no_odd=False): """ power of two batch-size decay with intra steps Decay by stepping between powers of 2: * determine power-of-2 floor of current batch size (base batch...
error_str = error_str.lower() if 'required rank' in error_str: # Errors involving phrase 'required rank' typically happen when a conv is used that's # not compatible with channels_last memory format. return False if 'illegal' in error_str: # 'Illegal memory access' errors in ...
""" check failure error string for conditions where batch decay retry should not be attempted """ error_str = error_str.lower() if 'required rank' in error_str: # Errors involving phrase 'required rank' typically happen when a conv is used that's # not compatible with channels_last memor...
52
577
110
687
""" Batch size decay and retry helpers. Copyright 2022 Ross Wightman """ import math def decay_batch_step(batch_size, num_intra_steps=2, no_odd=False): """ power of two batch-size decay with intra steps Decay by stepping between powers of 2: * determine power-of-2 floor of current batch size (base batch...
""" Batch size decay and retry helpers. Copyright 2022 Ross Wightman """ import math def decay_batch_step(batch_size, num_intra_steps=2, no_odd=False): """ power of two batch-size decay with intra steps Decay by stepping between powers of 2: * determine power-of-2 floor of current batch size (base batch...
17,982
/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/utils/distributed.py
24,25
1,176
distribute_bn
25,37
25,37
""" Distributed training/validation utils Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from typing import Optional import torch from torch import distributed as dist from .model import unwrap_model _logger = logging.getLogger(__name__) def reduce_tensor(tensor, n): rt = tenso...
""" Distributed training/validation utils Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from typing import Optional import torch from torch import distributed as dist from .model import unwrap_model _logger = logging.getLogger(__name__) def reduce_tensor(tensor, n): rt = tenso...
# ensure every node has the same running bn stats for bn_name, bn_buf in unwrap_model(model).named_buffers(recurse=True): if ('running_mean' in bn_name) or ('running_var' in bn_name): if reduce: # average bn stats across whole group torch.distributed.all_reduc...
# ensure every node has the same running bn stats for bn_name, bn_buf in unwrap_model(model).named_buffers(recurse=True): if ('running_mean' in bn_name) or ('running_var' in bn_name): if reduce: # average bn stats across whole group torch.distributed.all_reduc...
50
1,706
178
1,884
""" Distributed training/validation utils Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from typing import Optional import torch from torch import distributed as dist from .model import unwrap_model _logger = logging.getLogger(__name__) def reduce_tensor(tensor, n): rt = tenso...
""" Distributed training/validation utils Hacked together by / Copyright 2020 Ross Wightman """ import logging import os from typing import Optional import torch from torch import distributed as dist from .model import unwrap_model _logger = logging.getLogger(__name__) def reduce_tensor(tensor, n): rt = tenso...
17,983
/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/utils/jit.py
23,24
1,59
set_jit_fuser
24,59
24,59
""" JIT scripting/tracing utils Hacked together by / Copyright 2020 Ross Wightman """ import os import torch def set_jit_legacy(): """ Set JIT executor to legacy w/ support for op fusion This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes in the JIT exectutor. These...
""" JIT scripting/tracing utils Hacked together by / Copyright 2020 Ross Wightman """ import os import torch def set_jit_legacy(): """ Set JIT executor to legacy w/ support for op fusion This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes in the JIT exectutor. These...
if fuser == "te": # default fuser should be == 'te' torch._C._jit_set_profiling_executor(True) torch._C._jit_set_profiling_mode(True) torch._C._jit_override_can_fuse_on_cpu(False) torch._C._jit_override_can_fuse_on_gpu(True) torch._C._jit_set_texpr_fuser_enabled(True)...
if fuser == "te": # default fuser should be == 'te' torch._C._jit_set_profiling_executor(True) torch._C._jit_set_profiling_mode(True) torch._C._jit_override_can_fuse_on_cpu(False) torch._C._jit_override_can_fuse_on_gpu(True) torch._C._jit_set_texpr_fuser_enabled(True)...
71
269
650
919
""" JIT scripting/tracing utils Hacked together by / Copyright 2020 Ross Wightman """ import os import torch def set_jit_legacy(): """ Set JIT executor to legacy w/ support for op fusion This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes in the JIT exectutor. These...
""" JIT scripting/tracing utils Hacked together by / Copyright 2020 Ross Wightman """ import os import torch def set_jit_legacy(): """ Set JIT executor to legacy w/ support for op fusion This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes in the JIT exectutor. These...
17,984
/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/utils/log.py
19,20
1,29
setup_default_logging
20,29
20,29
""" Logging helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import logging.handlers class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): if record.levelno =...
""" Logging helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import logging.handlers class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): if record.levelno =...
console_handler = logging.StreamHandler() console_handler.setFormatter(FormatterNoInfo()) logging.root.addHandler(console_handler) logging.root.setLevel(default_level) if log_path: file_handler = logging.handlers.RotatingFileHandler(log_path, maxBytes=(1024 ** 2 * 2), backupCount=3) ...
console_handler = logging.StreamHandler() console_handler.setFormatter(FormatterNoInfo()) logging.root.addHandler(console_handler) logging.root.setLevel(default_level) if log_path: file_handler = logging.handlers.RotatingFileHandler(log_path, maxBytes=(1024 ** 2 * 2), backupCount=3) ...
27
166
179
345
""" Logging helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import logging.handlers class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): if record.levelno =...
""" Logging helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import logging.handlers class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): if record.levelno =...
17,985
/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/utils/log.py
13,14
9,19
format
FormatterNoInfo
14,19
14,19
class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): FILL_FUNC_BODY
class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): FILL_FUNC_BODY
if record.levelno == logging.INFO: return str(record.getMessage()) return logging.Formatter.format(self, record)
if record.levelno == logging.INFO: return str(record.getMessage()) return logging.Formatter.format(self, record)
9
70
42
112
""" Logging helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import logging.handlers class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): FILL_FUNC_BODYdef setup_def...
""" Logging helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import logging.handlers class FormatterNoInfo(logging.Formatter): def __init__(self, fmt='%(levelname)s: %(message)s'): logging.Formatter.__init__(self, fmt) def format(self, record): FILL_FUNC_BODYdef setup_def...
17,986
/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/utils/metrics.py
25,26
1,33
accuracy
27,33
26,33
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:min(k, maxk)].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
"""Computes the accuracy over the k top predictions for the specified values of k""" maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:min(k,...
32
198
130
328
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
17,987
/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/utils/metrics.py
12,13
7,25
reset
AverageMeter
13,18
13,18
class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): FILL_FUNC_BODY def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count
class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): FILL_FUNC_BODY def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count
self.val = 0 self.avg = 0 self.sum = 0 self.count = 0
self.val = 0 self.avg = 0 self.sum = 0 self.count = 0
12
104
35
139
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): FILL_FUNC_BODY def update(self, val, n=1): self.val = val self.sum +...
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): FILL_FUNC_BODY def update(self, val, n=1): self.val = val self.sum +...
17,988
/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/utils/misc.py
15,16
1,33
add_bool_arg
16,23
16,23
""" Misc utils Hacked together by / Copyright 2020 Ross Wightman """ import argparse import ast import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def add_bool_arg(parser, nam...
""" Misc utils Hacked together by / Copyright 2020 Ross Wightman """ import argparse import ast import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def add_bool_arg(parser, nam...
dest_name = name.replace('-', '_') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('--' + name, dest=dest_name, action='store_true', help=help) group.add_argument('--no-' + name, dest=dest_name, action='store_false', help=help) parser.set_defaults(**{dest_name: default...
dest_name = name.replace('-', '_') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('--' + name, dest=dest_name, action='store_true', help=help) group.add_argument('--no-' + name, dest=dest_name, action='store_false', help=help) parser.set_defaults(**{dest_name: default...
21
271
121
392
""" Misc utils Hacked together by / Copyright 2020 Ross Wightman """ import argparse import ast import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def add_bool_arg(parser, nam...
""" Misc utils Hacked together by / Copyright 2020 Ross Wightman """ import argparse import ast import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def add_bool_arg(parser, nam...
17,990
/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/utils/model.py
81,82
45,88
register_hook
ActivationStatsHook
82,88
82,88
class ActivationStatsHook: """Iterates through each of `model`'s modules and matches modules using unix pattern matching based on `hook_fn_locs` and registers `hook_fn` to the module if there is a match. Arguments: model (nn.Module): model from which we will extract the activation stats ...
class ActivationStatsHook: """Iterates through each of `model`'s modules and matches modules using unix pattern matching based on `hook_fn_locs` and registers `hook_fn` to the module if there is a match. Arguments: model (nn.Module): model from which we will extract the activation stats ...
for name, module in self.model.named_modules(): if not fnmatch.fnmatch(name, hook_fn_loc): continue module.register_forward_hook(self._create_hook(hook_fn))
for name, module in self.model.named_modules(): if not fnmatch.fnmatch(name, hook_fn_loc): continue module.register_forward_hook(self._create_hook(hook_fn))
11
546
64
610
""" Model / state_dict utils Hacked together by / Copyright 2020 Ross Wightman """ import fnmatch from copy import deepcopy import torch from torchvision.ops.misc import FrozenBatchNorm2d from timm.layers import BatchNormAct2d, SyncBatchNormAct, FrozenBatchNormAct2d,\ freeze_batch_norm_2d, unfreeze_batch_norm_2d...
""" Model / state_dict utils Hacked together by / Copyright 2020 Ross Wightman """ import fnmatch from copy import deepcopy import torch from torchvision.ops.misc import FrozenBatchNorm2d from timm.layers import BatchNormAct2d, SyncBatchNormAct, FrozenBatchNormAct2d,\ freeze_batch_norm_2d, unfreeze_batch_norm_2d...
17,991
/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/utils/model_ema.py
52,53
16,83
_load_checkpoint
ModelEma
53,69
53,69
class ModelEma: """ Model Exponential Moving Average (DEPRECATED) Keep a moving average of everything in the model state_dict (parameters and buffers). This version is deprecated, it does not work with scripted models. Will be removed eventually. This is intended to allow functionality like https:...
class ModelEma: """ Model Exponential Moving Average (DEPRECATED) Keep a moving average of everything in the model state_dict (parameters and buffers). This version is deprecated, it does not work with scripted models. Will be removed eventually. This is intended to allow functionality like https:...
checkpoint = torch.load(checkpoint_path, map_location='cpu') assert isinstance(checkpoint, dict) if 'state_dict_ema' in checkpoint: new_state_dict = OrderedDict() for k, v in checkpoint['state_dict_ema'].items(): # ema model may have been wrapped by DataPa...
checkpoint = torch.load(checkpoint_path, map_location='cpu') assert isinstance(checkpoint, dict) if 'state_dict_ema' in checkpoint: new_state_dict = OrderedDict() for k, v in checkpoint['state_dict_ema'].items(): # ema model may have been wrapped by DataPa...
64
672
226
898
""" Exponential Moving Average (EMA) of model updates Hacked together by / Copyright 2020 Ross Wightman """ import logging from collections import OrderedDict from copy import deepcopy from typing import Optional import torch import torch.nn as nn _logger = logging.getLogger(__name__) class ModelEma: """ Model...
""" Exponential Moving Average (EMA) of model updates Hacked together by / Copyright 2020 Ross Wightman """ import logging from collections import OrderedDict from copy import deepcopy from typing import Optional import torch import torch.nn as nn _logger = logging.getLogger(__name__) class ModelEma: """ Model...
17,992
/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/utils/model_ema.py
129,130
83,133
forward
ModelEmaV2
130,133
130,133
class ModelEmaV2(nn.Module): """ Model Exponential Moving Average V2 Keep a moving average of everything in the model state_dict (parameters and buffers). V2 of this module is simpler, it does not match params/buffers based on name but simply iterates in order. It works with torchscript (JIT of full mo...
class ModelEmaV2(nn.Module): """ Model Exponential Moving Average V2 Keep a moving average of everything in the model state_dict (parameters and buffers). V2 of this module is simpler, it does not match params/buffers based on name but simply iterates in order. It works with torchscript (JIT of full mo...
return self.module(*args, **kwargs)
return self.module(*args, **kwargs)
3
652
17
669
""" Exponential Moving Average (EMA) of model updates Hacked together by / Copyright 2020 Ross Wightman """ import logging from collections import OrderedDict from copy import deepcopy from typing import Optional import torch import torch.nn as nn _logger = logging.getLogger(__name__) class ModelEma: """ Model...
""" Exponential Moving Average (EMA) of model updates Hacked together by / Copyright 2020 Ross Wightman """ import logging from collections import OrderedDict from copy import deepcopy from typing import Optional import torch import torch.nn as nn _logger = logging.getLogger(__name__) class ModelEma: """ Model...
17,993
/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/utils/model_ema.py
254,256
133,261
set
ModelEmaV3
256,259
256,259
class ModelEmaV3(nn.Module): """ Model Exponential Moving Average V3 Keep a moving average of everything in the model state_dict (parameters and buffers). V3 of this module leverages for_each and in-place operations for faster performance. Decay warmup based on code by @crowsonkb, her comments: ...
class ModelEmaV3(nn.Module): """ Model Exponential Moving Average V3 Keep a moving average of everything in the model state_dict (parameters and buffers). V3 of this module leverages for_each and in-place operations for faster performance. Decay warmup based on code by @crowsonkb, her comments: ...
for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): ema_v.copy_(model_v.to(device=self.device))
for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): ema_v.copy_(model_v.to(device=self.device))
7
1,620
58
1,678
""" Exponential Moving Average (EMA) of model updates Hacked together by / Copyright 2020 Ross Wightman """ import logging from collections import OrderedDict from copy import deepcopy from typing import Optional import torch import torch.nn as nn _logger = logging.getLogger(__name__) class ModelEma: """ Model...
""" Exponential Moving Average (EMA) of model updates Hacked together by / Copyright 2020 Ross Wightman """ import logging from collections import OrderedDict from copy import deepcopy from typing import Optional import torch import torch.nn as nn _logger = logging.getLogger(__name__) class ModelEma: """ Model...
17,994
/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/utils/random.py
6,7
1,10
random_seed
7,10
7,10
import random import numpy as np import torch def random_seed(seed=42, rank=0): FILL_FUNC_BODY
import random import numpy as np import torch def random_seed(seed=42, rank=0): FILL_FUNC_BODY
torch.manual_seed(seed + rank) np.random.seed(seed + rank) random.seed(seed + rank)
torch.manual_seed(seed + rank) np.random.seed(seed + rank) random.seed(seed + rank)
9
40
39
79
import random import numpy as np import torch def random_seed(seed=42, rank=0): FILL_FUNC_BODY
import random import numpy as np import torch def random_seed(seed=42, rank=0): FILL_FUNC_BODY
17,995
/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/utils/summary.py
30,39
1,52
update_summary
39,52
39,52
""" Summary utilities Hacked together by / Copyright 2020 Ross Wightman """ import csv import os from collections import OrderedDict try: import wandb except ImportError: pass def get_outdir(path, *paths, inc=False): outdir = os.path.join(path, *paths) if not os.path.exists(outdir): os.maked...
""" Summary utilities Hacked together by / Copyright 2020 Ross Wightman """ import csv import os from collections import OrderedDict try: import wandb except ImportError: pass def get_outdir(path, *paths, inc=False): outdir = os.path.join(path, *paths) if not os.path.exists(outdir): os.maked...
rowd = OrderedDict(epoch=epoch) rowd.update([('train_' + k, v) for k, v in train_metrics.items()]) if eval_metrics: rowd.update([('eval_' + k, v) for k, v in eval_metrics.items()]) if lr is not None: rowd['lr'] = lr if log_wandb: wandb.log(rowd) with open(filename, mode='...
rowd = OrderedDict(epoch=epoch) rowd.update([('train_' + k, v) for k, v in train_metrics.items()]) if eval_metrics: rowd.update([('eval_' + k, v) for k, v in eval_metrics.items()]) if lr is not None: rowd['lr'] = lr if log_wandb: wandb.log(rowd) with open(filename, mode='...
56
281
211
492
""" Summary utilities Hacked together by / Copyright 2020 Ross Wightman """ import csv import os from collections import OrderedDict try: import wandb except ImportError: pass def get_outdir(path, *paths, inc=False): outdir = os.path.join(path, *paths) if not os.path.exists(outdir): os.maked...
""" Summary utilities Hacked together by / Copyright 2020 Ross Wightman """ import csv import os from collections import OrderedDict try: import wandb except ImportError: pass def get_outdir(path, *paths, inc=False): outdir = os.path.join(path, *paths) if not os.path.exists(outdir): os.maked...
18,015
/home/hieuvd/dung_repo/raw/stars_01/idank_explainshell/explainshell
/home/hieuvd/dung_repo/raw/stars_01/idank_explainshell/explainshell/explainshell/algo/features.py
3,4
1,64
extract_first_line
14,26
4,26
import re def extract_first_line(paragraph): FILL_FUNC_BODYdef starts_with_hyphen(paragraph): return paragraph.lstrip()[0] == '-' def is_indented(paragraph): return paragraph != paragraph.lstrip() def par_length(paragraph): return round(len(paragraph.strip()), -1) / 2 def first_line_contains(paragraph, ...
import re def extract_first_line(paragraph): ''' >>> extract_first_line('a b cd') 'a b' >>> extract_first_line('a b cd') 'a b cd' >>> extract_first_line(' a b cd') 'a b cd' >>> extract_first_line(' a b cd') 'a b' ''' FILL_FUNC_BODYdef starts_with_hyphen(paragraph): retu...
lines = paragraph.splitlines() first = lines[0].strip() spaces = list(re.finditer(r'(\s+)', first)) # handle options that have their description in the first line by trying # to treat it as two lines (looking at spaces between option and the rest # of the text) if spaces: longest = m...
''' >>> extract_first_line('a b cd') 'a b' >>> extract_first_line('a b cd') 'a b cd' >>> extract_first_line(' a b cd') 'a b cd' >>> extract_first_line(' a b cd') 'a b' ''' lines = paragraph.splitlines() first = lines[0].strip() spaces = list(re.finditer(r'(\s+)',...
69
431
166
597
import re def extract_first_line(paragraph): FILL_FUNC_BODYdef starts_with_hyphen(paragraph): return paragraph.lstrip()[0] == '-' def is_indented(paragraph): return paragraph != paragraph.lstrip() def par_length(paragraph): return round(len(paragraph.strip()), -1) / 2 def first_line_contains(paragraph, ...
import re def extract_first_line(paragraph): ''' >>> extract_first_line('a b cd') 'a b' >>> extract_first_line('a b cd') 'a b cd' >>> extract_first_line(' a b cd') 'a b cd' >>> extract_first_line(' a b cd') 'a b' ''' FILL_FUNC_BODYdef starts_with_hyphen(paragraph): retu...
18,360
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape/core/colorama/ansi.py
21,22
1,103
clear_line
22,25
22,25
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' OSC = '\033]' BEL = '\007' def code_to_chars(code): return CSI + str(code) + 'm' def set...
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' OSC = '\033]' BEL = '\007' def code_to_chars(code): return CSI + str(code) + 'm' def set...
return CSI + str(mode) + 'K'
return CSI + str(mode) + 'K'
6
954
19
973
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' OSC = '\033]' BEL = '\007' def code_to_chars(code): return CSI + str(code) + 'm' def set...
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' OSC = '\033]' BEL = '\007' def code_to_chars(code): return CSI + str(code) + 'm' def set...
18,361
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape/core/colorama/ansi.py
39,40
36,49
DOWN
AnsiCursor
40,41
40,41
class AnsiCursor(object): def UP(self, n=1): return CSI + str(n) + 'A' def DOWN(self, n=1): FILL_FUNC_BODY def FORWARD(self, n=1): return CSI + str(n) + 'C' def BACK(self, n=1): return CSI + str(n) + 'D' def POS(self, x=1, y=1): return CSI + str(y) + ';' + str(x) + 'H'...
class AnsiCursor(object): def UP(self, n=1): return CSI + str(n) + 'A' def DOWN(self, n=1): FILL_FUNC_BODY def FORWARD(self, n=1): return CSI + str(n) + 'C' def BACK(self, n=1): return CSI + str(n) + 'D' def POS(self, x=1, y=1): return CSI + str(y) + ';' + str(x) + 'H'...
return CSI + str(n) + 'B'
return CSI + str(n) + 'B'
6
149
15
164
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' OSC = '\033]' BEL = '\007' def code_to_chars(code): return CSI + str(code) + 'm' def set...
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. ''' This module generates ANSI character codes to printing colors to terminals. See: http://en.wikipedia.org/wiki/ANSI_escape_code ''' CSI = '\033[' OSC = '\033]' BEL = '\007' def code_to_chars(code): return CSI + str(code) + 'm' def set...
18,364
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape/core/colorama/ansitowin32.py
39,40
24,43
write
StreamWrapper
40,43
40,43
class StreamWrapper(object): ''' Wraps a stream (such as stdout), acting as a transparent proxy for all attribute access apart from method 'write()', which is delegated to our Converter instance. ''' def __init__(self, wrapped, converter): # double-underscore everything to prevent clashe...
class StreamWrapper(object): ''' Wraps a stream (such as stdout), acting as a transparent proxy for all attribute access apart from method 'write()', which is delegated to our Converter instance. ''' def __init__(self, wrapped, converter): # double-underscore everything to prevent clashe...
self.__convertor.write(text)
self.__convertor.write(text)
1
154
16
170
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import re import sys import os from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style from .winterm import WinTerm, WinColor, WinStyle from .win32 import windll, winapi_test winterm = None if windll is not None: winterm = WinTerm() def ...
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import re import sys import os from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style from .winterm import WinTerm, WinColor, WinStyle from .win32 import windll, winapi_test winterm = None if windll is not None: winterm = WinTerm() def ...
18,365
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape/core/colorama/initialise.py
74,75
1,83
wrap_stream
75,83
75,83
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import atexit import contextlib import sys from .ansitowin32 import AnsiToWin32 orig_stdout = None orig_stderr = None wrapped_stdout = None wrapped_stderr = None atexit_done = False def reset_all(): if AnsiToWin32 is not None: # Is...
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import atexit import contextlib import sys from .ansitowin32 import AnsiToWin32 orig_stdout = None orig_stderr = None wrapped_stdout = None wrapped_stderr = None atexit_done = False def reset_all(): if AnsiToWin32 is not None: # Is...
if wrap: wrapper = AnsiToWin32(stream, convert=convert, strip=strip, autoreset=autoreset) if wrapper.should_wrap(): stream = wrapper.stream return stream
if wrap: wrapper = AnsiToWin32(stream, convert=convert, strip=strip, autoreset=autoreset) if wrapper.should_wrap(): stream = wrapper.stream return stream
15
583
66
649
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import atexit import contextlib import sys from .ansitowin32 import AnsiToWin32 orig_stdout = None orig_stderr = None wrapped_stdout = None wrapped_stderr = None atexit_done = False def reset_all(): if AnsiToWin32 is not None: # Is...
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import atexit import contextlib import sys from .ansitowin32 import AnsiToWin32 orig_stdout = None orig_stderr = None wrapped_stdout = None wrapped_stderr = None atexit_done = False def reset_all(): if AnsiToWin32 is not None: # Is...
18,367
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape
/home/hieuvd/dung_repo/raw/stars_01/jofpin_trape/trape/core/user_objects.py
67,68
1,112
victim_headers
68,78
68,78
#!/usr/bin/env python # -*- coding: utf-8 -*- # ** # ######### # trape # ######### # # trape depends of this file # For full copyright information this visit: https://github.com/jofpin/trape # # Copyright 2018 by Jose Pino (@jofpin) / <jofpin@gmail.com> # ** class victim(object): def __init__(self, vId, ip, device,...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ** # ######### # trape # ######### # # trape depends of this file # For full copyright information this visit: https://github.com/jofpin/trape # # Copyright 2018 by Jose Pino (@jofpin) / <jofpin@gmail.com> # ** class victim(object): def __init__(self, vId, ip, device,...
return [("User-Agent", ua), ("Content-Type", "text/html; charset=utf-8"), ("Accept", "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.8"), ("Connection", "keep-alive"), # Do Not Track (inf...
return [("User-Agent", ua), ("Content-Type", "text/html; charset=utf-8"), ("Accept", "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.8"), ("Connection", "keep-alive"), # Do Not Track (inf...
30
1,418
166
1,584
#!/usr/bin/env python # -*- coding: utf-8 -*- # ** # ######### # trape # ######### # # trape depends of this file # For full copyright information this visit: https://github.com/jofpin/trape # # Copyright 2018 by Jose Pino (@jofpin) / <jofpin@gmail.com> # ** class victim(object): def __init__(self, vId, ip, device,...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ** # ######### # trape # ######### # # trape depends of this file # For full copyright information this visit: https://github.com/jofpin/trape # # Copyright 2018 by Jose Pino (@jofpin) / <jofpin@gmail.com> # ** class victim(object): def __init__(self, vId, ip, device,...
18,385
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/custom-scopes/grades.py
18,19
1,133
require_scope
26,43
19,43
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
if isinstance(scopes, str): scopes = [scopes] def wrap(method): """The actual decorator""" @wraps(method) @authenticated def wrapped(self, *args, **kwargs): self.hub_scopes = scopes return method(self, *args, **kwargs) return wrapped ...
"""Decorator to require scopes For use if multiple methods on one Handler may want different scopes, so class-level .hub_scopes is insufficient (e.g. read for GET, write for POST). """ if isinstance(scopes, str): scopes = [scopes] def wrap(method): """The actual decorat...
28
1,127
118
1,245
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
18,386
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/custom-scopes/grades.py
65,66
61,105
_render
GradesHandler
66,92
66,92
class GradesHandler(HubOAuthenticated, RequestHandler): # default scope for this Handler: read-only hub_scopes = [READ_SCOPE] def _render(self): FILL_FUNC_BODY @require_scope([READ_SCOPE]) async def get(self): self._render() # POST requires WRITE_SCOPE instead of READ_SCOPE @require...
class GradesHandler(HubOAuthenticated, RequestHandler): # default scope for this Handler: read-only hub_scopes = [READ_SCOPE] def _render(self): FILL_FUNC_BODY @require_scope([READ_SCOPE]) async def get(self): self._render() # POST requires WRITE_SCOPE instead of READ_SCOPE @require...
grades = self.settings["grades"] self.write("<h1>All grades</h1>") self.write("<table>") self.write("<tr><th>Student</th><th>Grade</th></tr>") for student, grade in grades.items(): qstudent = escape(student) qgrade = escape(str(grade)) self.wri...
grades = self.settings["grades"] self.write("<h1>All grades</h1>") self.write("<table>") self.write("<tr><th>Student</th><th>Grade</th></tr>") for student, grade in grades.items(): qstudent = escape(student) qgrade = escape(str(grade)) self.wri...
51
175
291
466
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
18,387
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/custom-scopes/grades.py
47,49
43,61
get
MyGradesHandler
49,61
49,61
class MyGradesHandler(HubOAuthenticated, RequestHandler): # no hub_scopes, anyone with access to this service # will be able to visit this URL @authenticated def get(self): FILL_FUNC_BODY
class MyGradesHandler(HubOAuthenticated, RequestHandler): # no hub_scopes, anyone with access to this service # will be able to visit this URL @authenticated def get(self): FILL_FUNC_BODY
self.write("<h1>My grade</h1>") name = self.current_user["name"] grades = self.settings["grades"] self.write(f"<p>My name is: {escape(name)}</p>") if name in grades: self.write(f"<p>My grade is: {escape(str(grades[name]))}</p>") else: self.write("<...
self.write("<h1>My grade</h1>") name = self.current_user["name"] grades = self.settings["grades"] self.write(f"<p>My name is: {escape(name)}</p>") if name in grades: self.write(f"<p>My grade is: {escape(str(grades[name]))}</p>") else: self.write("<...
31
65
177
242
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
import os from functools import wraps from html import escape from urllib.parse import urlparse from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler, authenticated from jupyterhub.services.auth import HubOAuthCallbackHandler, HubOAuthenticated...
18,388
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/external-oauth/whoami-oauth-basic.py
100,101
1,132
main
101,130
101,130
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
log.enable_pretty_logging() # construct OAuth URLs from jupyterhub base URL hub_api = os.environ['JUPYTERHUB_URL'].rstrip('/') + '/hub/api' authorize_url = hub_api + '/oauth2/authorize' token_url = hub_api + '/oauth2/token' user_url = hub_api + '/user' app = web.Application( [('/oa...
log.enable_pretty_logging() # construct OAuth URLs from jupyterhub base URL hub_api = os.environ['JUPYTERHUB_URL'].rstrip('/') + '/hub/api' authorize_url = hub_api + '/oauth2/authorize' token_url = hub_api + '/oauth2/token' user_url = hub_api + '/user' app = web.Application( [('/oa...
62
971
411
1,382
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
18,389
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/external-oauth/whoami-oauth-basic.py
42,43
17,67
get
JupyterHubLoginHandler
43,67
43,67
class JupyterHubLoginHandler(web.RequestHandler): """Login Handler this handler both begins and ends the OAuth process """ async def token_for_code(self, code): """Complete OAuth by requesting an access token for an oauth code""" params = dict( client_id=self.settings['clie...
class JupyterHubLoginHandler(web.RequestHandler): """Login Handler this handler both begins and ends the OAuth process """ async def token_for_code(self, code): """Complete OAuth by requesting an access token for an oauth code""" params = dict( client_id=self.settings['clie...
code = self.get_argument('code', None) if code: # code is set, we are the oauth callback # complete oauth token = await self.token_for_code(code) # login successful, set cookie and redirect back to home self.set_secure_cookie('whoami-oauth-toke...
code = self.get_argument('code', None) if code: # code is set, we are the oauth callback # complete oauth token = await self.token_for_code(code) # login successful, set cookie and redirect back to home self.set_secure_cookie('whoami-oauth-toke...
65
266
230
496
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
18,390
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/external-oauth/whoami-oauth-basic.py
83,84
67,100
user_for_token
WhoAmIHandler
85,92
84,92
class WhoAmIHandler(web.RequestHandler): """Serve the JSON model for the authenticated user""" def get_current_user(self): """The login handler stored a JupyterHub API token in a cookie @web.authenticated calls this method. If a Falsy value is returned, the request is redirected to `lo...
class WhoAmIHandler(web.RequestHandler): """Serve the JSON model for the authenticated user""" def get_current_user(self): """The login handler stored a JupyterHub API token in a cookie @web.authenticated calls this method. If a Falsy value is returned, the request is redirected to `lo...
req = HTTPRequest( self.settings['user_url'], headers={'Authorization': f'token {token}'} ) response = await AsyncHTTPClient().fetch(req) return json.loads(response.body.decode('utf8', 'replace'))
"""Retrieve the user for a given token, via /hub/api/user""" req = HTTPRequest( self.settings['user_url'], headers={'Authorization': f'token {token}'} ) response = await AsyncHTTPClient().fetch(req) return json.loads(response.body.decode('utf8', 'replace'))
15
305
76
381
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
"""Basic implementation of OAuth without any inheritance Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ import json import os from urllib.parse import urlencode, urlparse from tornado import log, web from tornado.httpclient import AsyncHTTP...
18,391
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/server-api/start-stop-server.py
114,115
1,174
stop_server
119,154
115,154
#!/usr/bin/env python3 """ Example of starting/stopping a server via the JupyterHub API 1. get user status 2. start server 3. wait for server to be ready via progress api 4. make a request to the server itself 5. stop server via API 6. wait for server to finish stopping """ import json import logging import pathlib i...
#!/usr/bin/env python3 """ Example of starting/stopping a server via the JupyterHub API 1. get user status 2. start server 3. wait for server to be ready via progress api 4. make a request to the server itself 5. stop server via API 6. wait for server to finish stopping """ import json import logging import pathlib i...
# step 1: get user status user_url = f"{hub_url}/hub/api/users/{user}" server_url = f"{user_url}/servers/{server_name}" log_name = f"{user}/{server_name}".rstrip("/") log.info(f"Stopping server {log_name}") r = session.delete(server_url) if r.status_code == 404: log.info(f"Server {l...
"""Stop a server via the JupyterHub API Returns when the server has finished stopping """ # step 1: get user status user_url = f"{hub_url}/hub/api/users/{user}" server_url = f"{user_url}/servers/{server_name}" log_name = f"{user}/{server_name}".rstrip("/") log.info(f"Stopping server {l...
106
1,305
424
1,729
#!/usr/bin/env python3 """ Example of starting/stopping a server via the JupyterHub API 1. get user status 2. start server 3. wait for server to be ready via progress api 4. make a request to the server itself 5. stop server via API 6. wait for server to finish stopping """ import json import logging import pathlib i...
#!/usr/bin/env python3 """ Example of starting/stopping a server via the JupyterHub API 1. get user status 2. start server 3. wait for server to be ready via progress api 4. make a request to the server itself 5. stop server via API 6. wait for server to finish stopping """ import json import logging import pathlib i...
18,392
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/service-announcement/announcement.py
51,52
1,72
parse_arguments
52,65
52,65
import argparse import datetime import json import os from tornado import escape, ioloop, web from jupyterhub.services.auth import HubAuthenticated class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """C...
import argparse import datetime import json import os from tornado import escape, ioloop, web from jupyterhub.services.auth import HubAuthenticated class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """C...
parser = argparse.ArgumentParser() parser.add_argument( "--api-prefix", "-a", default=os.environ.get("JUPYTERHUB_SERVICE_PREFIX", "/"), help="application API prefix", ) parser.add_argument( "--port", "-p", default=8888, help="port for API to listen on", type=int ...
parser = argparse.ArgumentParser() parser.add_argument( "--api-prefix", "-a", default=os.environ.get("JUPYTERHUB_SERVICE_PREFIX", "/"), help="application API prefix", ) parser.add_argument( "--port", "-p", default=8888, help="port for API to listen on", type=int ...
26
505
133
638
import argparse import datetime import json import os from tornado import escape, ioloop, web from jupyterhub.services.auth import HubAuthenticated class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """C...
import argparse import datetime import json import os from tornado import escape, ioloop, web from jupyterhub.services.auth import HubAuthenticated class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """C...
18,393
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub
/home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/service-announcement/announcement.py
32,34
11,44
delete
AnnouncementRequestHandler
35,38
34,38
class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """Create storage for announcement text""" self.storage = storage @web.authenticated def post(self): """Update announcement""" ...
class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """Create storage for announcement text""" self.storage = storage @web.authenticated def post(self): """Update announcement""" ...
self.storage["announcement"] = "" self.write_to_json(self.storage)
"""Clear announcement""" self.storage["announcement"] = "" self.write_to_json(self.storage)
4
293
30
323
import argparse import datetime import json import os from tornado import escape, ioloop, web from jupyterhub.services.auth import HubAuthenticated class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """C...
import argparse import datetime import json import os from tornado import escape, ioloop, web from jupyterhub.services.auth import HubAuthenticated class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" def initialize(self, storage): """C...