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,276
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/ln_tuning/model.py
162,163
30,202
set_adapter
LNTuningModel
163,171
163,171
class LNTuningModel(BaseTuner): """ Creates LayerNorm tuning from a pretrained transformer model. The method is described in detail in https://arxiv.org/abs/2312.11420. Args: model ([`torch.nn.Module`]): The model to be adapted. config ([`LNTuningConfig`]): The configuration of the Lor...
class LNTuningModel(BaseTuner): """ Creates LayerNorm tuning from a pretrained transformer model. The method is described in detail in https://arxiv.org/abs/2312.11420. Args: model ([`torch.nn.Module`]): The model to be adapted. config ([`LNTuningConfig`]): The configuration of the Lor...
for module in self.model.modules(): if isinstance(module, LNTuningLayer): if module.merged: warnings.warn("Adapter cannot be set when the model is merged. Unmerging the model first.") module.unmerge() module.set_adapter(adapter_...
for module in self.model.modules(): if isinstance(module, LNTuningLayer): if module.merged: warnings.warn("Adapter cannot be set when the model is merged. Unmerging the model first.") module.unmerge() module.set_adapter(adapter_...
27
1,865
97
1,962
# Copyright 2024-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2024-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,277
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/loha/model.py
89,98
27,115
_create_and_replace
LoHaModel
101,115
98,115
class LoHaModel(LycorisTuner): """ Creates Low-Rank Hadamard Product model from a pretrained model. The method is partially described in https://arxiv.org/abs/2108.06098 Current implementation heavily borrows from https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/ly...
class LoHaModel(LycorisTuner): """ Creates Low-Rank Hadamard Product model from a pretrained model. The method is partially described in https://arxiv.org/abs/2108.06098 Current implementation heavily borrows from https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/ly...
# Regexp matching - Find key which matches current target_name in patterns provided pattern_keys = list(chain(config.rank_pattern.keys(), config.alpha_pattern.keys())) target_name_key = next(filter(lambda key: re.match(rf"(.*\.)?{key}$", current_key), pattern_keys), target_name) kwargs...
""" A private method to create and replace the target module with the adapter module. """ # Regexp matching - Find key which matches current target_name in patterns provided pattern_keys = list(chain(config.rank_pattern.keys(), config.alpha_pattern.keys())) target_name_k...
52
888
247
1,135
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,278
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/lokr/model.py
90,99
27,116
_create_and_replace
LoKrModel
102,116
99,116
class LoKrModel(LycorisTuner): """ Creates Low-Rank Kronecker Product model from a pretrained model. The original method is partially described in https://arxiv.org/abs/2108.06098 and in https://arxiv.org/abs/2309.14859 Current implementation heavily borrows from https://github.com/KohakuBlueleaf/Ly...
class LoKrModel(LycorisTuner): """ Creates Low-Rank Kronecker Product model from a pretrained model. The original method is partially described in https://arxiv.org/abs/2108.06098 and in https://arxiv.org/abs/2309.14859 Current implementation heavily borrows from https://github.com/KohakuBlueleaf/Ly...
# Regexp matching - Find key which matches current target_name in patterns provided pattern_keys = list(chain(config.rank_pattern.keys(), config.alpha_pattern.keys())) target_name_key = next(filter(lambda key: re.match(rf"(.*\.)?{key}$", current_key), pattern_keys), target_name) kwargs...
""" A private method to create and replace the target module with the adapter module. """ # Regexp matching - Find key which matches current target_name in patterns provided pattern_keys = list(chain(config.rank_pattern.keys(), config.alpha_pattern.keys())) target_name_k...
52
929
248
1,177
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,281
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/lora/gptq.py
95,100
1,115
dispatch_gptq
100,115
100,115
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
new_module = None if isinstance(target, BaseTunerLayer): target_base_layer = target.get_base_layer() else: target_base_layer = target gptq_quantization_config = kwargs.get("gptq_quantization_config", None) AutoGPTQQuantLinear = get_auto_gptq_quant_linear(gptq_quantization_config) ...
new_module = None if isinstance(target, BaseTunerLayer): target_base_layer = target.get_base_layer() else: target_base_layer = target gptq_quantization_config = kwargs.get("gptq_quantization_config", None) AutoGPTQQuantLinear = get_auto_gptq_quant_linear(gptq_quantization_config) ...
38
1,072
195
1,267
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,282
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/lora/gptq.py
57,58
24,95
forward
QuantLinear
58,84
58,84
class QuantLinear(torch.nn.Module, LoraLayer): def __init__( self, base_layer, adapter_name: str, r: int = 0, lora_alpha: int = 1, lora_dropout: float = 0.0, init_lora_weights: bool = True, use_rslora: bool = False, use_dora: bool = False, ...
class QuantLinear(torch.nn.Module, LoraLayer): def __init__( self, base_layer, adapter_name: str, r: int = 0, lora_alpha: int = 1, lora_dropout: float = 0.0, init_lora_weights: bool = True, use_rslora: bool = False, use_dora: bool = False, ...
# note: logic differs from default Linear because merging is not supported result = self.quant_linear_module(x) if self.disable_adapters: return result for active_adapter in self.active_adapters: if active_adapter not in self.lora_A.keys(): conti...
# note: logic differs from default Linear because merging is not supported result = self.quant_linear_module(x) if self.disable_adapters: return result for active_adapter in self.active_adapters: if active_adapter not in self.lora_A.keys(): conti...
71
523
296
819
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,284
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/lora/tp_layer.py
155,156
28,191
forward
LoraParallelLinear
156,191
156,191
class LoraParallelLinear(nn.Module, LoraLayer): """ When the target layer parallel_linear is RowParallelLinear, in order to keep the input and output shapes consistent, we need to split the lora matrix A into rows, and the lora_B at this time should be a complete linear layer; In the same way, when the ...
class LoraParallelLinear(nn.Module, LoraLayer): """ When the target layer parallel_linear is RowParallelLinear, in order to keep the input and output shapes consistent, we need to split the lora matrix A into rows, and the lora_B at this time should be a complete linear layer; In the same way, when the ...
previous_dtype = x.dtype # If weight is used for matrix multiplication here, the final aggregation operation of the original # parallel_linear layer will be missing, so we need to directly call its forward function to obtain the # output of the original parallel_linear layer. if ...
previous_dtype = x.dtype # If weight is used for matrix multiplication here, the final aggregation operation of the original # parallel_linear layer will be missing, so we need to directly call its forward function to obtain the # output of the original parallel_linear layer. if ...
129
1,552
459
2,011
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,286
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/multitask_prompt_tuning/model.py
107,108
27,120
forward
MultitaskPromptEmbedding
108,120
108,120
class MultitaskPromptEmbedding(PromptEmbedding): def __init__(self, config: MultitaskPromptTuningConfig, word_embeddings): super().__init__(config, word_embeddings) self.num_tasks = config.num_tasks self.num_ranks = config.num_ranks self.num_virtual_tokens = config.num_virtual_token...
class MultitaskPromptEmbedding(PromptEmbedding): def __init__(self, config: MultitaskPromptTuningConfig, word_embeddings): super().__init__(config, word_embeddings) self.num_tasks = config.num_tasks self.num_ranks = config.num_ranks self.num_virtual_tokens = config.num_virtual_token...
if task_ids is None: raise ValueError("task_ids cannot be None") prompt_embeddings = self.embedding(indices) task_cols = torch.index_select(self.prefix_task_cols, 0, task_ids) task_rows = torch.index_select(self.prefix_task_rows, 0, task_ids) task_prompts = torch.ma...
if task_ids is None: raise ValueError("task_ids cannot be None") prompt_embeddings = self.embedding(indices) task_cols = torch.index_select(self.prefix_task_cols, 0, task_ids) task_rows = torch.index_select(self.prefix_task_rows, 0, task_ids) task_prompts = torch.ma...
31
1,126
155
1,281
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,287
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/oft/model.py
82,91
26,107
_create_and_replace
OFTModel
94,107
91,107
class OFTModel(LycorisTuner): """ Creates Orthogonal Finetuning model from a pretrained model. The method is described in https://arxiv.org/abs/2306.07280 Args: model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. config ([`OFTConfig`]): The configura...
class OFTModel(LycorisTuner): """ Creates Orthogonal Finetuning model from a pretrained model. The method is described in https://arxiv.org/abs/2306.07280 Args: model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. config ([`OFTConfig`]): The configura...
# Regexp matching - Find key which matches current target_name in patterns provided pattern_keys = list(config.rank_pattern.keys()) target_name_key = next(filter(lambda key: re.match(rf"(.*\.)?{key}$", current_key), pattern_keys), target_name) kwargs = config.to_dict() kwargs["...
""" A private method to create and replace the target module with the adapter module. """ # Regexp matching - Find key which matches current target_name in patterns provided pattern_keys = list(config.rank_pattern.keys()) target_name_key = next(filter(lambda key: re.matc...
47
746
209
955
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,288
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/p_tuning/model.py
121,122
24,131
forward
PromptEncoder
122,131
122,131
class PromptEncoder(torch.nn.Module): """ The prompt encoder network that is used to generate the virtual token embeddings for p-tuning. Args: config ([`PromptEncoderConfig`]): The configuration of the prompt encoder. Example: ```py >>> from peft import PromptEncoder, PromptEncoderCon...
class PromptEncoder(torch.nn.Module): """ The prompt encoder network that is used to generate the virtual token embeddings for p-tuning. Args: config ([`PromptEncoderConfig`]): The configuration of the prompt encoder. Example: ```py >>> from peft import PromptEncoder, PromptEncoderCon...
input_embeds = self.embedding(indices) if self.encoder_type == PromptEncoderReparameterizationType.LSTM: output_embeds = self.mlp_head(self.lstm_head(input_embeds)[0]) elif self.encoder_type == PromptEncoderReparameterizationType.MLP: output_embeds = self.mlp_head(input_e...
input_embeds = self.embedding(indices) if self.encoder_type == PromptEncoderReparameterizationType.LSTM: output_embeds = self.mlp_head(self.lstm_head(input_embeds)[0]) elif self.encoder_type == PromptEncoderReparameterizationType.MLP: output_embeds = self.mlp_head(input_e...
34
1,290
157
1,447
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,289
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/poly/model.py
153,154
33,188
_register_pre_hooks
PolyModel
155,171
154,171
class PolyModel(BaseTuner): prefix: str = "poly_" def __init__(self, model, config, adapter_name) -> None: super().__init__(model, config, adapter_name) @staticmethod def _check_target_module_exists(poly_config, key): return check_target_module_exists(poly_config, key) def _create...
class PolyModel(BaseTuner): prefix: str = "poly_" def __init__(self, model, config, adapter_name) -> None: super().__init__(model, config, adapter_name) @staticmethod def _check_target_module_exists(poly_config, key): return check_target_module_exists(poly_config, key) def _create...
if task_ids is None: return [] def pre_hook(_, args, kwargs): kwargs["task_ids"] = task_ids return args, kwargs handles = [] for module in self.model.modules(): if isinstance(module, Linear): handle = module.register_forw...
"""Helper method to register pre hooks.""" if task_ids is None: return [] def pre_hook(_, args, kwargs): kwargs["task_ids"] = task_ids return args, kwargs handles = [] for module in self.model.modules(): if isinstance(module, Lin...
33
1,561
133
1,694
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,290
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/poly/router.py
27,28
1,84
get_router
28,38
28,38
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
if poly_config.poly_type == "poly": return PolyRouter(poly_config) else: raise ValueError( f"Unsupported poly_type: {poly_config.poly_type}. " "Currently, only the following types are supported: " "`poly`." )
if poly_config.poly_type == "poly": return PolyRouter(poly_config) else: raise ValueError( f"Unsupported poly_type: {poly_config.poly_type}. " "Currently, only the following types are supported: " "`poly`." )
23
868
91
959
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,291
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/poly/router.py
64,65
48,84
forward
PolyRouter
65,84
65,84
class PolyRouter(Router): # It's a simplified implementation of # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L138 def __init__(self, poly_config: PolyConfig): super().__init__() self.poly_type = poly_config.poly_type self.n_ta...
class PolyRouter(Router): # It's a simplified implementation of # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L138 def __init__(self, poly_config: PolyConfig): super().__init__() self.poly_type = poly_config.poly_type self.n_ta...
if task_ids is None: raise ValueError("task_ids should not be None.") if task_ids.max().item() >= self.n_tasks: raise ValueError(f"Only {self.n_tasks} tasks available. Found task id = {task_ids.max().item()}") # move task id to input's device task_ids = task_ids....
if task_ids is None: raise ValueError("task_ids should not be None.") if task_ids.max().item() >= self.n_tasks: raise ValueError(f"Only {self.n_tasks} tasks available. Found task id = {task_ids.max().item()}") # move task id to input's device task_ids = task_ids....
62
290
283
573
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,292
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/poly/router.py
39,41
38,48
reset
Router
41,43
41,43
class Router(nn.Module, ABC): @abstractmethod def reset(self): FILL_FUNC_BODY @abstractmethod def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor): ...
class Router(nn.Module, ABC): @abstractmethod def reset(self): FILL_FUNC_BODY @abstractmethod def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor): ...
...
...
1
72
6
78
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,293
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/prefix_tuning/model.py
74,75
20,81
forward
PrefixEncoder
75,81
75,81
class PrefixEncoder(torch.nn.Module): r""" The `torch.nn` model to encode the prefix. Args: config ([`PrefixTuningConfig`]): The configuration of the prefix encoder. Example: ```py >>> from peft import PrefixEncoder, PrefixTuningConfig >>> config = PrefixTuningConfig( ... ...
class PrefixEncoder(torch.nn.Module): r""" The `torch.nn` model to encode the prefix. Args: config ([`PrefixTuningConfig`]): The configuration of the prefix encoder. Example: ```py >>> from peft import PrefixEncoder, PrefixTuningConfig >>> config = PrefixTuningConfig( ... ...
if self.prefix_projection: prefix_tokens = self.embedding(prefix) past_key_values = self.transform(prefix_tokens) else: past_key_values = self.embedding(prefix) return past_key_values
if self.prefix_projection: prefix_tokens = self.embedding(prefix) past_key_values = self.transform(prefix_tokens) else: past_key_values = self.embedding(prefix) return past_key_values
14
679
74
753
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,294
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/prompt_tuning/model.py
88,89
24,92
forward
PromptEmbedding
89,92
89,92
class PromptEmbedding(torch.nn.Module): """ The model to encode virtual tokens into prompt embeddings. Args: config ([`PromptTuningConfig`]): The configuration of the prompt embedding. word_embeddings (`torch.nn.Module`): The word embeddings of the base transformer model. **Attributes*...
class PromptEmbedding(torch.nn.Module): """ The model to encode virtual tokens into prompt embeddings. Args: config ([`PromptTuningConfig`]): The configuration of the prompt embedding. word_embeddings (`torch.nn.Module`): The word embeddings of the base transformer model. **Attributes*...
# Just get embeddings prompt_embeddings = self.embedding(indices) return prompt_embeddings
# Just get embeddings prompt_embeddings = self.embedding(indices) return prompt_embeddings
9
933
32
965
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
17,295
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft
/home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/vera/buffer_dict.py
100,101
19,161
items
BufferDict
101,104
101,104
class BufferDict(Module): r""" Holds buffers in a dictionary. BufferDict can be indexed like a regular Python dictionary, but buffers it contains are properly registered, and will be visible by all Module methods. `torch.nn.BufferDict` is an **ordered** dictionary that respects * the order of inse...
class BufferDict(Module): r""" Holds buffers in a dictionary. BufferDict can be indexed like a regular Python dictionary, but buffers it contains are properly registered, and will be visible by all Module methods. `torch.nn.BufferDict` is an **ordered** dictionary that respects * the order of inse...
r"""Return an iterable of the BufferDict key/value pairs.""" return self._buffers.items()
r"""Return an iterable of the BufferDict key/value pairs.""" return self._buffers.items()
10
1,456
33
1,489
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Adapted from https://botorch.org/api/_modules/botorch/utils/torch.html # TODO: To be removed once (if) https://github.com/pytorch/pytorch...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Adapted from https://botorch.org/api/_modules/botorch/utils/torch.html # TODO: To be removed once (if) https://github.com/pytorch/pytorch...
17,301
/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/avg_checkpoints.py
46,47
1,153
checkpoint_metric
47,61
47,61
#!/usr/bin/env python3 """ Checkpoint Averaging Script This script averages all model weights for checkpoints in specified path that match the specified filter wildcard. All checkpoints must be from the exact same model. For any hope of decent results, the checkpoints should be from the same or child (via resumes) tr...
#!/usr/bin/env python3 """ Checkpoint Averaging Script This script averages all model weights for checkpoints in specified path that match the specified filter wildcard. All checkpoints must be from the exact same model. For any hope of decent results, the checkpoints should be from the same or child (via resumes) tr...
if not checkpoint_path or not os.path.isfile(checkpoint_path): return {} print("=> Extracting metric from checkpoint '{}'".format(checkpoint_path)) checkpoint = torch.load(checkpoint_path, map_location='cpu') metric = None if 'metric' in checkpoint: metric = checkpoint['metric'] ...
if not checkpoint_path or not os.path.isfile(checkpoint_path): return {} print("=> Extracting metric from checkpoint '{}'".format(checkpoint_path)) checkpoint = torch.load(checkpoint_path, map_location='cpu') metric = None if 'metric' in checkpoint: metric = checkpoint['metric'] ...
45
1,733
165
1,898
#!/usr/bin/env python3 """ Checkpoint Averaging Script This script averages all model weights for checkpoints in specified path that match the specified filter wildcard. All checkpoints must be from the exact same model. For any hope of decent results, the checkpoints should be from the same or child (via resumes) tr...
#!/usr/bin/env python3 """ Checkpoint Averaging Script This script averages all model weights for checkpoints in specified path that match the specified filter wildcard. All checkpoints must be from the exact same model. For any hope of decent results, the checkpoints should be from the same or child (via resumes) tr...
17,302
/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/clean_checkpoint.py
55,63
1,116
clean_checkpoint
63,114
63,114
#!/usr/bin/env python3 """ Checkpoint Cleaning Script Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc. and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256 calculation for model zoo compatibility. Hacked together by / Copyright 2020 Ross Wightman (https:...
#!/usr/bin/env python3 """ Checkpoint Cleaning Script Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc. and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256 calculation for model zoo compatibility. Hacked together by / Copyright 2020 Ross Wightman (https:...
# Load an existing checkpoint to CPU, strip everything but the state_dict and re-save if checkpoint and os.path.isfile(checkpoint): print("=> Loading checkpoint '{}'".format(checkpoint)) state_dict = load_state_dict(checkpoint, use_ema=use_ema) new_state_dict = {} for k, v in sta...
# Load an existing checkpoint to CPU, strip everything but the state_dict and re-save if checkpoint and os.path.isfile(checkpoint): print("=> Loading checkpoint '{}'".format(checkpoint)) state_dict = load_state_dict(checkpoint, use_ema=use_ema) new_state_dict = {} for k, v in sta...
179
658
695
1,353
#!/usr/bin/env python3 """ Checkpoint Cleaning Script Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc. and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256 calculation for model zoo compatibility. Hacked together by / Copyright 2020 Ross Wightman (https:...
#!/usr/bin/env python3 """ Checkpoint Cleaning Script Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc. and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256 calculation for model zoo compatibility. Hacked together by / Copyright 2020 Ross Wightman (https:...
17,303
/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/onnx_export.py
63,64
1,103
main
64,101
64,101
""" ONNX export script Export PyTorch models as ONNX graphs. This export script originally started as an adaptation of code snippets found at https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html The default parameters work with PyTorch 1.6 and ONNX 1.7 and produce an optimal ONNX graph for h...
""" ONNX export script Export PyTorch models as ONNX graphs. This export script originally started as an adaptation of code snippets found at https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html The default parameters work with PyTorch 1.6 and ONNX 1.7 and produce an optimal ONNX graph for h...
args = parser.parse_args() args.pretrained = True if args.checkpoint: args.pretrained = False print("==> Creating PyTorch {} model".format(args.model)) # NOTE exportable=True flag disables autofn/jit scripted activations and uses Conv2dSameExport layers # for models using SAME padding ...
args = parser.parse_args() args.pretrained = True if args.checkpoint: args.pretrained = False print("==> Creating PyTorch {} model".format(args.model)) # NOTE exportable=True flag disables autofn/jit scripted activations and uses Conv2dSameExport layers # for models using SAME padding ...
65
1,112
376
1,488
""" ONNX export script Export PyTorch models as ONNX graphs. This export script originally started as an adaptation of code snippets found at https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html The default parameters work with PyTorch 1.6 and ONNX 1.7 and produce an optimal ONNX graph for h...
""" ONNX export script Export PyTorch models as ONNX graphs. This export script originally started as an adaptation of code snippets found at https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html The default parameters work with PyTorch 1.6 and ONNX 1.7 and produce an optimal ONNX graph for h...
17,304
/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/data/config.py
8,15
1,130
resolve_data_config
15,103
15,103
import logging from .constants import * _logger = logging.getLogger(__name__) def resolve_data_config( args=None, pretrained_cfg=None, model=None, use_test_size=False, verbose=False ): FILL_FUNC_BODYdef resolve_model_data_config( model, args=None, pret...
import logging from .constants import * _logger = logging.getLogger(__name__) def resolve_data_config( args=None, pretrained_cfg=None, model=None, use_test_size=False, verbose=False ): FILL_FUNC_BODYdef resolve_model_data_config( model, args=None, pret...
assert model or args or pretrained_cfg, "At least one of model, args, or pretrained_cfg required for data config." args = args or {} pretrained_cfg = pretrained_cfg or {} if not pretrained_cfg and model is not None and hasattr(model, 'pretrained_cfg'): pretrained_cfg = model.pretrained_cfg d...
assert model or args or pretrained_cfg, "At least one of model, args, or pretrained_cfg required for data config." args = args or {} pretrained_cfg = pretrained_cfg or {} if not pretrained_cfg and model is not None and hasattr(model, 'pretrained_cfg'): pretrained_cfg = model.pretrained_cfg d...
320
337
1,209
1,546
import logging from .constants import * _logger = logging.getLogger(__name__) def resolve_data_config( args=None, pretrained_cfg=None, model=None, use_test_size=False, verbose=False ): FILL_FUNC_BODYdef resolve_model_data_config( model, args=None, pret...
import logging from .constants import * _logger = logging.getLogger(__name__) def resolve_data_config( args=None, pretrained_cfg=None, model=None, use_test_size=False, verbose=False ): FILL_FUNC_BODYdef resolve_model_data_config( model, args=None, pret...
17,305
/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/data/dataset.py
174,175
163,201
_set_transforms
AugMixDataset
175,180
175,180
class AugMixDataset(torch.utils.data.Dataset): """Dataset wrapper to perform AugMix or other clean/augmentation mixes""" def __init__(self, dataset, num_splits=2): self.augmentation = None self.normalize = None self.dataset = dataset if self.dataset.transform is not None: ...
class AugMixDataset(torch.utils.data.Dataset): """Dataset wrapper to perform AugMix or other clean/augmentation mixes""" def __init__(self, dataset, num_splits=2): self.augmentation = None self.normalize = None self.dataset = dataset if self.dataset.transform is not None: ...
assert isinstance(x, (list, tuple)) and len(x) == 3, 'Expecting a tuple/list of 3 transforms' self.dataset.transform = x[0] self.augmentation = x[1] self.normalize = x[2]
assert isinstance(x, (list, tuple)) and len(x) == 3, 'Expecting a tuple/list of 3 transforms' self.dataset.transform = x[0] self.augmentation = x[1] self.normalize = x[2]
23
365
76
441
""" Quick n Simple Image Folder, Tarfile based DataSet Hacked together by / Copyright 2019, Ross Wightman """ import io import logging from typing import Optional import torch import torch.utils.data as data from PIL import Image from .readers import create_reader _logger = logging.getLogger(__name__) _ERROR_RETR...
""" Quick n Simple Image Folder, Tarfile based DataSet Hacked together by / Copyright 2019, Ross Wightman """ import io import logging from typing import Optional import torch import torch.utils.data as data from PIL import Image from .readers import create_reader _logger = logging.getLogger(__name__) _ERROR_RETR...
17,306
/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/data/dataset.py
80,81
21,84
filenames
ImageDataset
81,84
81,84
class ImageDataset(data.Dataset): def __init__( self, root, reader=None, split='train', class_map=None, load_bytes=False, input_img_mode='RGB', transform=None, target_transform=None, ): if reader...
class ImageDataset(data.Dataset): def __init__( self, root, reader=None, split='train', class_map=None, load_bytes=False, input_img_mode='RGB', transform=None, target_transform=None, ): if reader...
return self.reader.filenames(basename, absolute)
return self.reader.filenames(basename, absolute)
3
538
21
559
""" Quick n Simple Image Folder, Tarfile based DataSet Hacked together by / Copyright 2019, Ross Wightman """ import io import logging from typing import Optional import torch import torch.utils.data as data from PIL import Image from .readers import create_reader _logger = logging.getLogger(__name__) _ERROR_RETR...
""" Quick n Simple Image Folder, Tarfile based DataSet Hacked together by / Copyright 2019, Ross Wightman """ import io import logging from typing import Optional import torch import torch.utils.data as data from PIL import Image from .readers import create_reader _logger = logging.getLogger(__name__) _ERROR_RETR...
17,307
/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/data/dataset.py
148,152
84,163
set_loader_cfg
IterableImageDataset
152,156
152,156
class IterableImageDataset(data.IterableDataset): def __init__( self, root, reader=None, split='train', class_map=None, is_training=False, batch_size=1, num_samples=None, seed=42, repeats=0, ...
class IterableImageDataset(data.IterableDataset): def __init__( self, root, reader=None, split='train', class_map=None, is_training=False, batch_size=1, num_samples=None, seed=42, repeats=0, ...
# TFDS and WDS readers need # workers for correct # samples estimate before loader processes created if hasattr(self.reader, 'set_loader_cfg'): self.reader.set_loader_cfg(num_workers=num_workers)
# TFDS and WDS readers need # workers for correct # samples estimate before loader processes created if hasattr(self.reader, 'set_loader_cfg'): self.reader.set_loader_cfg(num_workers=num_workers)
21
636
67
703
""" Quick n Simple Image Folder, Tarfile based DataSet Hacked together by / Copyright 2019, Ross Wightman """ import io import logging from typing import Optional import torch import torch.utils.data as data from PIL import Image from .readers import create_reader _logger = logging.getLogger(__name__) _ERROR_RETR...
""" Quick n Simple Image Folder, Tarfile based DataSet Hacked together by / Copyright 2019, Ross Wightman """ import io import logging from typing import Optional import torch import torch.utils.data as data from PIL import Image from .readers import create_reader _logger = logging.getLogger(__name__) _ERROR_RETR...
17,309
/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/data/dataset_info.py
62,63
35,74
label_name_to_description
CustomDatasetInfo
63,67
63,67
class CustomDatasetInfo(DatasetInfo): """ DatasetInfo that wraps passed values for custom datasets.""" def __init__( self, label_names: Union[List[str], Dict[int, str]], label_descriptions: Optional[Dict[str, str]] = None ): super().__init__() assert len(...
class CustomDatasetInfo(DatasetInfo): """ DatasetInfo that wraps passed values for custom datasets.""" def __init__( self, label_names: Union[List[str], Dict[int, str]], label_descriptions: Optional[Dict[str, str]] = None ): super().__init__() assert len(...
if self._label_descriptions: return self._label_descriptions[label] return label # return label name itself if a descriptions is not present
if self._label_descriptions: return self._label_descriptions[label] return label # return label name itself if a descriptions is not present
17
441
45
486
from abc import ABC, abstractmethod from typing import Dict, List, Optional, Union class DatasetInfo(ABC): def __init__(self): pass @abstractmethod def num_classes(self): pass @abstractmethod def label_names(self): pass @abstractmethod def label_descriptions(sel...
from abc import ABC, abstractmethod from typing import Dict, List, Optional, Union class DatasetInfo(ABC): def __init__(self): pass @abstractmethod def num_classes(self): pass @abstractmethod def label_names(self): pass @abstractmethod def label_descriptions(sel...
17,310
/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/data/distributed_sampler.py
134,135
54,136
set_epoch
RepeatAugSampler
135,136
135,136
class RepeatAugSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset for distributed, with repeated augmentation. It ensures that different each augmented version of a sample will be visible to a different process (GPU). Heavily based on torch.utils.data.DistributedSampler ...
class RepeatAugSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset for distributed, with repeated augmentation. It ensures that different each augmented version of a sample will be visible to a different process (GPU). Heavily based on torch.utils.data.DistributedSampler ...
self.epoch = epoch
self.epoch = epoch
3
1,066
9
1,075
import math import torch from torch.utils.data import Sampler import torch.distributed as dist class OrderedDistributedSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset. It is especially useful in conjunction with :class:`torch.nn.parallel.DistributedDataParallel`. In suc...
import math import torch from torch.utils.data import Sampler import torch.distributed as dist class OrderedDistributedSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset. It is especially useful in conjunction with :class:`torch.nn.parallel.DistributedDataParallel`. In suc...
17,311
/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/data/imagenet_info.py
33,34
1,96
infer_imagenet_subset
34,48
34,48
import csv import os import pkgutil import re from typing import Dict, List, Optional, Union from .dataset_info import DatasetInfo # NOTE no ambiguity wrt to mapping from # classes to ImageNet subset so far, but likely to change _NUM_CLASSES_TO_SUBSET = { 1000: 'imagenet-1k', 11221: 'imagenet-21k-miil', # m...
import csv import os import pkgutil import re from typing import Dict, List, Optional, Union from .dataset_info import DatasetInfo # NOTE no ambiguity wrt to mapping from # classes to ImageNet subset so far, but likely to change _NUM_CLASSES_TO_SUBSET = { 1000: 'imagenet-1k', 11221: 'imagenet-21k-miil', # m...
if isinstance(model_or_cfg, dict): num_classes = model_or_cfg.get('num_classes', None) else: num_classes = getattr(model_or_cfg, 'num_classes', None) if not num_classes: pretrained_cfg = getattr(model_or_cfg, 'pretrained_cfg', {}) # FIXME at some point pretrained_...
if isinstance(model_or_cfg, dict): num_classes = model_or_cfg.get('num_classes', None) else: num_classes = getattr(model_or_cfg, 'num_classes', None) if not num_classes: pretrained_cfg = getattr(model_or_cfg, 'pretrained_cfg', {}) # FIXME at some point pretrained_...
58
1,258
212
1,470
import csv import os import pkgutil import re from typing import Dict, List, Optional, Union from .dataset_info import DatasetInfo # NOTE no ambiguity wrt to mapping from # classes to ImageNet subset so far, but likely to change _NUM_CLASSES_TO_SUBSET = { 1000: 'imagenet-1k', 11221: 'imagenet-21k-miil', # m...
import csv import os import pkgutil import re from typing import Dict, List, Optional, Union from .dataset_info import DatasetInfo # NOTE no ambiguity wrt to mapping from # classes to ImageNet subset so far, but likely to change _NUM_CLASSES_TO_SUBSET = { 1000: 'imagenet-1k', 11221: 'imagenet-21k-miil', # m...
17,312
/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/data/imagenet_info.py
86,87
48,96
index_to_description
ImageNetInfo
87,90
87,90
class ImageNetInfo(DatasetInfo): def __init__(self, subset: str = 'imagenet-1k'): super().__init__() subset = re.sub(r'[-_\s]', '', subset.lower()) assert subset in _SUBSETS, f'Unknown imagenet subset {subset}.' # WordNet synsets (part-of-speach + offset) are the unique class label...
class ImageNetInfo(DatasetInfo): def __init__(self, subset: str = 'imagenet-1k'): super().__init__() subset = re.sub(r'[-_\s]', '', subset.lower()) assert subset in _SUBSETS, f'Unknown imagenet subset {subset}.' # WordNet synsets (part-of-speach + offset) are the unique class label...
label = self.index_to_label_name(index) return self.label_name_to_description(label, detailed=detailed)
label = self.index_to_label_name(index) return self.label_name_to_description(label, detailed=detailed)
6
703
40
743
import csv import os import pkgutil import re from typing import Dict, List, Optional, Union from .dataset_info import DatasetInfo # NOTE no ambiguity wrt to mapping from # classes to ImageNet subset so far, but likely to change _NUM_CLASSES_TO_SUBSET = { 1000: 'imagenet-1k', 11221: 'imagenet-21k-miil', # m...
import csv import os import pkgutil import re from typing import Dict, List, Optional, Union from .dataset_info import DatasetInfo # NOTE no ambiguity wrt to mapping from # classes to ImageNet subset so far, but likely to change _NUM_CLASSES_TO_SUBSET = { 1000: 'imagenet-1k', 11221: 'imagenet-21k-miil', # m...
17,313
/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/data/random_erasing.py
14,15
1,118
_get_pixels
15,26
15,26
""" Random Erasing (Cutout) Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0 Copyright Zhun Zhong & Liang Zheng Hacked together by / Copyright 2019, Ross Wightman """ import random import math import torch def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float3...
""" Random Erasing (Cutout) Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0 Copyright Zhun Zhong & Liang Zheng Hacked together by / Copyright 2019, Ross Wightman """ import random import math import torch def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float3...
# NOTE I've seen CUDA illegal memory access errors being caused by the normal_() # paths, flip the order so normal is run on CPU if this becomes a problem # Issue has been fixed in master https://github.com/pytorch/pytorch/issues/19508 if per_pixel: return torch.empty(patch_size, dtype=dtype, de...
# NOTE I've seen CUDA illegal memory access errors being caused by the normal_() # paths, flip the order so normal is run on CPU if this becomes a problem # Issue has been fixed in master https://github.com/pytorch/pytorch/issues/19508 if per_pixel: return torch.empty(patch_size, dtype=dtype, de...
59
1,332
194
1,526
""" Random Erasing (Cutout) Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0 Copyright Zhun Zhong & Liang Zheng Hacked together by / Copyright 2019, Ross Wightman """ import random import math import torch def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float3...
""" Random Erasing (Cutout) Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0 Copyright Zhun Zhong & Liang Zheng Hacked together by / Copyright 2019, Ross Wightman """ import random import math import torch def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float3...
17,314
/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/data/random_erasing.py
78,79
26,118
_erase
RandomErasing
79,102
79,102
class RandomErasing: """ Randomly selects a rectangle region in an image and erases its pixels. 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/pdf/1708.04896.pdf This variant of RandomErasing is intended to be applied to either a batch or single image tenso...
class RandomErasing: """ Randomly selects a rectangle region in an image and erases its pixels. 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/pdf/1708.04896.pdf This variant of RandomErasing is intended to be applied to either a batch or single image tenso...
if random.random() > self.probability: return area = img_h * img_w count = self.min_count if self.min_count == self.max_count else \ random.randint(self.min_count, self.max_count) for _ in range(count): for attempt in range(10): target_...
if random.random() > self.probability: return area = img_h * img_w count = self.min_count if self.min_count == self.max_count else \ random.randint(self.min_count, self.max_count) for _ in range(count): for attempt in range(10): target_...
88
902
323
1,225
""" Random Erasing (Cutout) Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0 Copyright Zhun Zhong & Liang Zheng Hacked together by / Copyright 2019, Ross Wightman """ import random import math import torch def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float3...
""" Random Erasing (Cutout) Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0 Copyright Zhun Zhong & Liang Zheng Hacked together by / Copyright 2019, Ross Wightman """ import random import math import torch def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float3...
17,315
/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/data/readers/class_map.py
5,6
1,24
load_class_map
6,24
6,24
import os import pickle def load_class_map(map_or_filename, root=''): FILL_FUNC_BODY
import os import pickle def load_class_map(map_or_filename, root=''): FILL_FUNC_BODY
if isinstance(map_or_filename, dict): assert dict, 'class_map dict must be non-empty' return map_or_filename class_map_path = map_or_filename if not os.path.exists(class_map_path): class_map_path = os.path.join(root, class_map_path) assert os.path.exists(class_map_path), 'Can...
if isinstance(map_or_filename, dict): assert dict, 'class_map dict must be non-empty' return map_or_filename class_map_path = map_or_filename if not os.path.exists(class_map_path): class_map_path = os.path.join(root, class_map_path) assert os.path.exists(class_map_path), 'Can...
76
37
296
333
import os import pickle def load_class_map(map_or_filename, root=''): FILL_FUNC_BODY
import os import pickle def load_class_map(map_or_filename, root=''): FILL_FUNC_BODY
17,316
/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/data/readers/img_extensions.py
10,11
1,51
_set_extensions
11,18
11,18
from copy import deepcopy __all__ = ['get_img_extensions', 'is_img_extension', 'set_img_extensions', 'add_img_extensions', 'del_img_extensions'] IMG_EXTENSIONS = ('.png', '.jpg', '.jpeg') # singleton, kept public for bwd compat use _IMG_EXTENSIONS_SET = set(IMG_EXTENSIONS) # set version, private, kept in sync de...
from copy import deepcopy __all__ = ['get_img_extensions', 'is_img_extension', 'set_img_extensions', 'add_img_extensions', 'del_img_extensions'] IMG_EXTENSIONS = ('.png', '.jpg', '.jpeg') # singleton, kept public for bwd compat use _IMG_EXTENSIONS_SET = set(IMG_EXTENSIONS) # set version, private, kept in sync de...
global IMG_EXTENSIONS global _IMG_EXTENSIONS_SET dedupe = set() # NOTE de-duping tuple while keeping original order IMG_EXTENSIONS = tuple(x for x in extensions if x not in dedupe and not dedupe.add(x)) _IMG_EXTENSIONS_SET = set(extensions)
global IMG_EXTENSIONS global _IMG_EXTENSIONS_SET dedupe = set() # NOTE de-duping tuple while keeping original order IMG_EXTENSIONS = tuple(x for x in extensions if x not in dedupe and not dedupe.add(x)) _IMG_EXTENSIONS_SET = set(extensions)
33
434
105
539
from copy import deepcopy __all__ = ['get_img_extensions', 'is_img_extension', 'set_img_extensions', 'add_img_extensions', 'del_img_extensions'] IMG_EXTENSIONS = ('.png', '.jpg', '.jpeg') # singleton, kept public for bwd compat use _IMG_EXTENSIONS_SET = set(IMG_EXTENSIONS) # set version, private, kept in sync de...
from copy import deepcopy __all__ = ['get_img_extensions', 'is_img_extension', 'set_img_extensions', 'add_img_extensions', 'del_img_extensions'] IMG_EXTENSIONS = ('.png', '.jpg', '.jpeg') # singleton, kept public for bwd compat use _IMG_EXTENSIONS_SET = set(IMG_EXTENSIONS) # set version, private, kept in sync de...
17,317
/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/data/readers/reader.py
15,16
4,18
filenames
Reader
16,18
16,18
class Reader: def __init__(self): pass @abstractmethod def _filename(self, index, basename=False, absolute=False): pass def filename(self, index, basename=False, absolute=False): return self._filename(index, basename=basename, absolute=absolute) def filenames(self, basenam...
class Reader: def __init__(self): pass @abstractmethod def _filename(self, index, basename=False, absolute=False): pass def filename(self, index, basename=False, absolute=False): return self._filename(index, basename=basename, absolute=absolute) def filenames(self, basenam...
return [self._filename(index, basename=basename, absolute=absolute) for index in range(len(self))]
return [self._filename(index, basename=basename, absolute=absolute) for index in range(len(self))]
8
112
34
146
from abc import abstractmethod class Reader: def __init__(self): pass @abstractmethod def _filename(self, index, basename=False, absolute=False): pass def filename(self, index, basename=False, absolute=False): return self._filename(index, basename=basename, absolute=absolute)...
from abc import abstractmethod class Reader: def __init__(self): pass @abstractmethod def _filename(self, index, basename=False, absolute=False): pass def filename(self, index, basename=False, absolute=False): return self._filename(index, basename=basename, absolute=absolute)...
17,318
/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/data/readers/reader_factory.py
8,14
1,46
create_reader
14,46
14,46
import os from typing import Optional from .reader_image_folder import ReaderImageFolder from .reader_image_in_tar import ReaderImageInTar def create_reader( name: str, root: Optional[str] = None, split: str = 'train', **kwargs, ): FILL_FUNC_BODY
import os from typing import Optional from .reader_image_folder import ReaderImageFolder from .reader_image_in_tar import ReaderImageInTar def create_reader( name: str, root: Optional[str] = None, split: str = 'train', **kwargs, ): FILL_FUNC_BODY
kwargs = {k: v for k, v in kwargs.items() if v is not None} name = name.lower() name = name.split('/', 1) prefix = '' if len(name) > 1: prefix = name[0] name = name[-1] # FIXME improve the selection right now just tfds prefix or fallback path, will need options to # explicitly s...
kwargs = {k: v for k, v in kwargs.items() if v is not None} name = name.lower() name = name.split('/', 1) prefix = '' if len(name) > 1: prefix = name[0] name = name[-1] # FIXME improve the selection right now just tfds prefix or fallback path, will need options to # explicitly s...
175
88
484
572
import os from typing import Optional from .reader_image_folder import ReaderImageFolder from .reader_image_in_tar import ReaderImageInTar def create_reader( name: str, root: Optional[str] = None, split: str = 'train', **kwargs, ): FILL_FUNC_BODY
import os from typing import Optional from .reader_image_folder import ReaderImageFolder from .reader_image_in_tar import ReaderImageInTar def create_reader( name: str, root: Optional[str] = None, split: str = 'train', **kwargs, ): FILL_FUNC_BODY
17,319
/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/data/readers/reader_hfds.py
22,23
1,85
get_class_labels
23,30
23,30
""" Dataset reader that wraps Hugging Face datasets Hacked together by / Copyright 2022 Ross Wightman """ import io import math from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets except ImportError as e: print("Please install Hugging Face data...
""" Dataset reader that wraps Hugging Face datasets Hacked together by / Copyright 2022 Ross Wightman """ import io import math from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets except ImportError as e: print("Please install Hugging Face data...
if 'label' not in info.features: return {} class_label = info.features[label_key] class_to_idx = {n: class_label.str2int(n) for n in class_label.names} return class_to_idx
if 'label' not in info.features: return {} class_label = info.features[label_key] class_to_idx = {n: class_label.str2int(n) for n in class_label.names} return class_to_idx
20
710
77
787
""" Dataset reader that wraps Hugging Face datasets Hacked together by / Copyright 2022 Ross Wightman """ import io import math from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets except ImportError as e: print("Please install Hugging Face data...
""" Dataset reader that wraps Hugging Face datasets Hacked together by / Copyright 2022 Ross Wightman """ import io import math from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets except ImportError as e: print("Please install Hugging Face data...
17,320
/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/data/readers/reader_hfds.py
82,83
30,85
_filename
ReaderHfds
83,85
83,85
class ReaderHfds(Reader): def __init__( self, name: str, root: Optional[str] = None, split: str = 'train', class_map: dict = None, image_key: str = 'image', target_key: str = 'label', download: bool = False, ): ...
class ReaderHfds(Reader): def __init__( self, name: str, root: Optional[str] = None, split: str = 'train', class_map: dict = None, image_key: str = 'image', target_key: str = 'label', download: bool = False, ): ...
item = self.dataset[index] return item[self.image_key]['path']
item = self.dataset[index] return item[self.image_key]['path']
5
549
26
575
""" Dataset reader that wraps Hugging Face datasets Hacked together by / Copyright 2022 Ross Wightman """ import io import math from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets except ImportError as e: print("Please install Hugging Face data...
""" Dataset reader that wraps Hugging Face datasets Hacked together by / Copyright 2022 Ross Wightman """ import io import math from typing import Optional import torch import torch.distributed as dist from PIL import Image try: import datasets except ImportError as e: print("Please install Hugging Face data...
17,322
/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/data/readers/reader_image_folder.py
18,25
1,100
find_images_and_targets
37,59
25,59
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
types = get_img_extensions(as_set=True) if not types else set(types) labels = [] filenames = [] for root, subdirs, files in os.walk(folder, topdown=False, followlinks=True): rel_path = os.path.relpath(root, folder) if (root != folder) else '' label = os.path.basename(rel_path) if leaf_na...
""" Walk folder recursively to discover images and map them to classes by folder names. Args: folder: root of folder to recrusively search types: types (file extensions) to search for in path class_to_idx: specify mapping for class (folder name) to class index if set leaf_name_o...
104
712
375
1,087
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
17,323
/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/data/readers/reader_image_folder.py
93,94
59,100
_filename
ReaderImageFolder
94,100
94,100
class ReaderImageFolder(Reader): def __init__( self, root, class_map='', input_key=None, ): super().__init__() self.root = root class_to_idx = None if class_map: class_to_idx = load_class_map(class_map, root) f...
class ReaderImageFolder(Reader): def __init__( self, root, class_map='', input_key=None, ): super().__init__() self.root = root class_to_idx = None if class_map: class_to_idx = load_class_map(class_map, root) f...
filename = self.samples[index][0] if basename: filename = os.path.basename(filename) elif not absolute: filename = os.path.relpath(filename, self.root) return filename
filename = self.samples[index][0] if basename: filename = os.path.basename(filename) elif not absolute: filename = os.path.relpath(filename, self.root) return filename
17
318
65
383
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
""" A dataset reader that extracts images from folders Folders are scanned recursively to find image files. Labels are based on the folder hierarchy, just leaf folders by default. Hacked together by / Copyright 2020 Ross Wightman """ import os from typing import Dict, List, Optional, Set, Tuple, Union from timm.util...
17,324
/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/data/readers/reader_image_tar.py
18,19
1,75
extract_tarinfo
19,41
19,41
""" A dataset reader that reads single tarfile based datasets This reader can read datasets consisting if a single tarfile containing images. I am planning to deprecated it in favour of ParerImageInTar. Hacked together by / Copyright 2020 Ross Wightman """ import os import tarfile from timm.utils.misc import natural...
""" A dataset reader that reads single tarfile based datasets This reader can read datasets consisting if a single tarfile containing images. I am planning to deprecated it in favour of ParerImageInTar. Hacked together by / Copyright 2020 Ross Wightman """ import os import tarfile from timm.utils.misc import natural...
extensions = get_img_extensions(as_set=True) files = [] labels = [] for ti in tarfile.getmembers(): if not ti.isfile(): continue dirname, basename = os.path.split(ti.path) label = os.path.basename(dirname) ext = os.path.splitext(basename)[1] if ext.low...
extensions = get_img_extensions(as_set=True) files = [] labels = [] for ti in tarfile.getmembers(): if not ti.isfile(): continue dirname, basename = os.path.split(ti.path) label = os.path.basename(dirname) ext = os.path.splitext(basename)[1] if ext.low...
78
533
315
848
""" A dataset reader that reads single tarfile based datasets This reader can read datasets consisting if a single tarfile containing images. I am planning to deprecated it in favour of ParerImageInTar. Hacked together by / Copyright 2020 Ross Wightman """ import os import tarfile from timm.utils.misc import natural...
""" A dataset reader that reads single tarfile based datasets This reader can read datasets consisting if a single tarfile containing images. I am planning to deprecated it in favour of ParerImageInTar. Hacked together by / Copyright 2020 Ross Wightman """ import os import tarfile from timm.utils.misc import natural...
17,325
/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/data/readers/reader_image_tar.py
70,71
41,75
_filename
ReaderImageTar
71,75
71,75
class ReaderImageTar(Reader): """ Single tarfile dataset where classes are mapped to folders within tar NOTE: This class is being deprecated in favour of the more capable ReaderImageInTar that can operate on folders of tars or tars in tars. """ def __init__(self, root, class_map=''): super()...
class ReaderImageTar(Reader): """ Single tarfile dataset where classes are mapped to folders within tar NOTE: This class is being deprecated in favour of the more capable ReaderImageInTar that can operate on folders of tars or tars in tars. """ def __init__(self, root, class_map=''): super()...
filename = self.samples[index][0].name if basename: filename = os.path.basename(filename) return filename
filename = self.samples[index][0].name if basename: filename = os.path.basename(filename) return filename
10
354
41
395
""" A dataset reader that reads single tarfile based datasets This reader can read datasets consisting if a single tarfile containing images. I am planning to deprecated it in favour of ParerImageInTar. Hacked together by / Copyright 2020 Ross Wightman """ import os import tarfile from timm.utils.misc import natural...
""" A dataset reader that reads single tarfile based datasets This reader can read datasets consisting if a single tarfile containing images. I am planning to deprecated it in favour of ParerImageInTar. Hacked together by / Copyright 2020 Ross Wightman """ import os import tarfile from timm.utils.misc import natural...
17,328
/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/data/readers/reader_wds.py
197,198
184,214
run
detshuffle2
198,214
198,214
class detshuffle2(wds.PipelineStage): def __init__( self, bufsize=1000, initial=100, seed=0, epoch=-1, ): self.bufsize = bufsize self.initial = initial self.seed = seed sel...
class detshuffle2(wds.PipelineStage): def __init__( self, bufsize=1000, initial=100, seed=0, epoch=-1, ): self.bufsize = bufsize self.initial = initial self.seed = seed sel...
if isinstance(self.epoch, SharedCount): epoch = self.epoch.value else: # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) # situation as different workers may wrap at different times (or not at all). ...
if isinstance(self.epoch, SharedCount): epoch = self.epoch.value else: # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) # situation as different workers may wrap at different times (or not at all). ...
75
112
211
323
""" Dataset reader for webdataset Hacked together by / Copyright 2022 Ross Wightman """ import io import json import logging import math import os import random import sys from dataclasses import dataclass from functools import partial from itertools import islice from typing import Any, Callable, Dict, List, Optional...
""" Dataset reader for webdataset Hacked together by / Copyright 2022 Ross Wightman """ import io import json import logging import math import os import random import sys from dataclasses import dataclass from functools import partial from itertools import islice from typing import Any, Callable, Dict, List, Optional...
17,329
/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/data/readers/shared_count.py
12,14
4,15
value
SharedCount
14,15
14,15
class SharedCount: def __init__(self, epoch: int = 0): self.shared_epoch = Value('i', epoch) @property def value(self): return self.shared_epoch.value @value.setter def value(self, epoch): FILL_FUNC_BODY
class SharedCount: def __init__(self, epoch: int = 0): self.shared_epoch = Value('i', epoch) @property def value(self): return self.shared_epoch.value @value.setter def value(self, epoch): FILL_FUNC_BODY
self.shared_epoch.value = epoch
self.shared_epoch.value = epoch
3
85
13
98
from multiprocessing import Value class SharedCount: def __init__(self, epoch: int = 0): self.shared_epoch = Value('i', epoch) @property def value(self): return self.shared_epoch.value @value.setter def value(self, epoch): FILL_FUNC_BODY
from multiprocessing import Value class SharedCount: def __init__(self, epoch: int = 0): self.shared_epoch = Value('i', epoch) @property def value(self): return self.shared_epoch.value @value.setter def value(self, epoch): FILL_FUNC_BODY
17,330
/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/data/real_labels.py
30,31
13,48
add_result
RealLabelsImagenet
31,43
31,43
class RealLabelsImagenet: def __init__(self, filenames, real_json=None, topk=(1, 5)): if real_json is not None: with open(real_json) as real_labels: real_labels = json.load(real_labels) else: real_labels = json.loads( pkgutil.get_data(__name__...
class RealLabelsImagenet: def __init__(self, filenames, real_json=None, topk=(1, 5)): if real_json is not None: with open(real_json) as real_labels: real_labels = json.load(real_labels) else: real_labels = json.loads( pkgutil.get_data(__name__...
maxk = max(self.topk) _, pred_batch = output.topk(maxk, 1, True, True) pred_batch = pred_batch.cpu().numpy() for pred in pred_batch: filename = self.filenames[self.sample_idx] filename = os.path.basename(filename) if self.real_labels[filename]: ...
maxk = max(self.topk) _, pred_batch = output.topk(maxk, 1, True, True) pred_batch = pred_batch.cpu().numpy() for pred in pred_batch: filename = self.filenames[self.sample_idx] filename = os.path.basename(filename) if self.real_labels[filename]: ...
40
356
165
521
""" Real labels evaluator for ImageNet Paper: `Are we done with ImageNet?` - https://arxiv.org/abs/2006.07159 Based on Numpy example at https://github.com/google-research/reassessed-imagenet Hacked together by / Copyright 2020 Ross Wightman """ import os import json import numpy as np import pkgutil class RealLabels...
""" Real labels evaluator for ImageNet Paper: `Are we done with ImageNet?` - https://arxiv.org/abs/2006.07159 Based on Numpy example at https://github.com/google-research/reassessed-imagenet Hacked together by / Copyright 2020 Ross Wightman """ import os import json import numpy as np import pkgutil class RealLabels...
17,332
/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/layers/activations.py
60,61
1,174
tanh
61,65
61,65
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
return x.tanh_() if inplace else x.tanh() # PyTorch has this, but not with a consistent inplace argmument interface
return x.tanh_() if inplace else x.tanh() # PyTorch has this, but not with a consistent inplace argmument interface
18
1,793
43
1,836
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,333
/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/layers/activations.py
144,145
138,148
forward
GELU
145,148
145,148
class GELU(nn.Module): """Applies the Gaussian Error Linear Units function (w/ dummy inplace arg) """ def __init__(self, inplace: bool = False): super(GELU, self).__init__() def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
class GELU(nn.Module): """Applies the Gaussian Error Linear Units function (w/ dummy inplace arg) """ def __init__(self, inplace: bool = False): super(GELU, self).__init__() def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
return F.gelu(input)
return F.gelu(input)
2
97
16
113
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,334
/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/layers/activations.py
158,159
152,162
forward
GELUTanh
159,162
159,162
class GELUTanh(nn.Module): """Applies the Gaussian Error Linear Units function (w/ dummy inplace arg) """ def __init__(self, inplace: bool = False): super(GELUTanh, self).__init__() def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
class GELUTanh(nn.Module): """Applies the Gaussian Error Linear Units function (w/ dummy inplace arg) """ def __init__(self, inplace: bool = False): super(GELUTanh, self).__init__() def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
return F.gelu(input, approximate='tanh')
return F.gelu(input, approximate='tanh')
3
101
22
123
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,335
/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/layers/activations.py
120,121
115,124
forward
HardMish
121,124
121,124
class HardMish(nn.Module): def __init__(self, inplace: bool = False): super(HardMish, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
class HardMish(nn.Module): def __init__(self, inplace: bool = False): super(HardMish, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
return hard_mish(x, self.inplace)
return hard_mish(x, self.inplace)
3
68
20
88
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,336
/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/layers/activations.py
100,101
95,104
forward
HardSigmoid
101,104
101,104
class HardSigmoid(nn.Module): def __init__(self, inplace: bool = False): super(HardSigmoid, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
class HardSigmoid(nn.Module): def __init__(self, inplace: bool = False): super(HardSigmoid, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
return hard_sigmoid(x, self.inplace)
return hard_sigmoid(x, self.inplace)
3
70
21
91
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,337
/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/layers/activations.py
84,85
79,88
forward
HardSwish
85,88
85,88
class HardSwish(nn.Module): def __init__(self, inplace: bool = False): super(HardSwish, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
class HardSwish(nn.Module): def __init__(self, inplace: bool = False): super(HardSwish, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
return hard_swish(x, self.inplace)
return hard_swish(x, self.inplace)
3
68
20
88
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,338
/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/layers/activations.py
42,43
36,46
forward
Mish
43,46
43,46
class Mish(nn.Module): """Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681 """ def __init__(self, inplace: bool = False): super(Mish, self).__init__() def forward(self, x): FILL_FUNC_BODY
class Mish(nn.Module): """Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681 """ def __init__(self, inplace: bool = False): super(Mish, self).__init__() def forward(self, x): FILL_FUNC_BODY
return mish(x)
return mish(x)
2
102
13
115
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,339
/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/layers/activations.py
130,131
124,134
forward
PReLU
131,134
131,134
class PReLU(nn.PReLU): """Applies PReLU (w/ dummy inplace arg) """ def __init__(self, num_parameters: int = 1, init: float = 0.25, inplace: bool = False) -> None: super(PReLU, self).__init__(num_parameters=num_parameters, init=init) def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_F...
class PReLU(nn.PReLU): """Applies PReLU (w/ dummy inplace arg) """ def __init__(self, num_parameters: int = 1, init: float = 0.25, inplace: bool = False) -> None: super(PReLU, self).__init__(num_parameters=num_parameters, init=init) def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_F...
return F.prelu(input, self.weight)
return F.prelu(input, self.weight)
3
131
19
150
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,340
/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/layers/activations.py
172,173
166,174
forward
QuickGELU
173,174
173,174
class QuickGELU(nn.Module): """Applies the Gaussian Error Linear Units function (w/ dummy inplace arg) """ def __init__(self, inplace: bool = False): super(QuickGELU, self).__init__() def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
class QuickGELU(nn.Module): """Applies the Gaussian Error Linear Units function (w/ dummy inplace arg) """ def __init__(self, inplace: bool = False): super(QuickGELU, self).__init__() def forward(self, input: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
return quick_gelu(input)
return quick_gelu(input)
2
99
12
111
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,341
/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/layers/activations.py
56,57
51,60
forward
Sigmoid
57,60
57,60
class Sigmoid(nn.Module): def __init__(self, inplace: bool = False): super(Sigmoid, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
class Sigmoid(nn.Module): def __init__(self, inplace: bool = False): super(Sigmoid, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
return x.sigmoid_() if self.inplace else x.sigmoid()
return x.sigmoid_() if self.inplace else x.sigmoid()
6
68
27
95
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,342
/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/layers/activations.py
25,26
20,29
forward
Swish
26,29
26,29
class Swish(nn.Module): def __init__(self, inplace: bool = False): super(Swish, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
class Swish(nn.Module): def __init__(self, inplace: bool = False): super(Swish, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
return swish(x, self.inplace)
return swish(x, self.inplace)
3
66
18
84
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,343
/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/layers/activations.py
70,71
65,74
forward
Tanh
71,74
71,74
class Tanh(nn.Module): def __init__(self, inplace: bool = False): super(Tanh, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
class Tanh(nn.Module): def __init__(self, inplace: bool = False): super(Tanh, self).__init__() self.inplace = inplace def forward(self, x): FILL_FUNC_BODY
return x.tanh_() if self.inplace else x.tanh()
return x.tanh_() if self.inplace else x.tanh()
6
67
25
92
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
17,344
/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/layers/activations_jit.py
62,64
1,91
hard_swish_jit
64,68
64,68
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
# return x * (F.relu6(x + 3.) / 6) return x * (x + 3).clamp(min=0, max=6).div(6.) # clamp seems ever so slightly faster?
# return x * (F.relu6(x + 3.) / 6) return x * (x + 3).clamp(min=0, max=6).div(6.) # clamp seems ever so slightly faster?
23
922
62
984
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
17,345
/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/layers/activations_jit.py
89,90
85,91
forward
HardMishJit
90,91
90,91
class HardMishJit(nn.Module): def __init__(self, inplace: bool = False): super(HardMishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
class HardMishJit(nn.Module): def __init__(self, inplace: bool = False): super(HardMishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
return hard_mish_jit(x)
return hard_mish_jit(x)
2
63
14
77
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
17,346
/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/layers/activations_jit.py
58,59
54,62
forward
HardSigmoidJit
59,62
59,62
class HardSigmoidJit(nn.Module): def __init__(self, inplace: bool = False): super(HardSigmoidJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
class HardSigmoidJit(nn.Module): def __init__(self, inplace: bool = False): super(HardSigmoidJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
return hard_sigmoid_jit(x)
return hard_sigmoid_jit(x)
2
65
19
84
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
17,347
/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/layers/activations_jit.py
72,73
68,76
forward
HardSwishJit
73,76
73,76
class HardSwishJit(nn.Module): def __init__(self, inplace: bool = False): super(HardSwishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
class HardSwishJit(nn.Module): def __init__(self, inplace: bool = False): super(HardSwishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
return hard_swish_jit(x)
return hard_swish_jit(x)
2
63
18
81
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
17,348
/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/layers/activations_jit.py
44,45
40,48
forward
MishJit
45,48
45,48
class MishJit(nn.Module): def __init__(self, inplace: bool = False): super(MishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
class MishJit(nn.Module): def __init__(self, inplace: bool = False): super(MishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
return mish_jit(x)
return mish_jit(x)
2
61
16
77
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
17,349
/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/layers/activations_jit.py
36,37
32,40
forward
SwishJit
37,40
37,40
class SwishJit(nn.Module): def __init__(self, inplace: bool = False): super(SwishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
class SwishJit(nn.Module): def __init__(self, inplace: bool = False): super(SwishJit, self).__init__() def forward(self, x): FILL_FUNC_BODY
return swish_jit(x)
return swish_jit(x)
2
61
16
77
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
""" Activations A collection of jit-scripted activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. All jit scripted activations are lacking in-place variations on purpose, scripted kernel fusion does not currently work across in-place op bou...
17,351
/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/layers/activations_me.py
200,202
190,206
backward
HardMishJitAutoFn
202,206
202,206
class HardMishJitAutoFn(torch.autograd.Function): """ A memory efficient, jit scripted variant of Hard Mish Experimental, based on notes by Mish author Diganta Misra at https://github.com/digantamisra98/H-Mish/blob/0da20d4bc58e696b6803f2523c58d3c8a82782d0/README.md """ @staticmethod def forwar...
class HardMishJitAutoFn(torch.autograd.Function): """ A memory efficient, jit scripted variant of Hard Mish Experimental, based on notes by Mish author Diganta Misra at https://github.com/digantamisra98/H-Mish/blob/0da20d4bc58e696b6803f2523c58d3c8a82782d0/README.md """ @staticmethod def forwar...
x = ctx.saved_tensors[0] return hard_mish_jit_bwd(x, grad_output)
x = ctx.saved_tensors[0] return hard_mish_jit_bwd(x, grad_output)
6
192
41
233
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,352
/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/layers/activations_me.py
214,215
210,219
forward
HardMishMe
215,219
215,219
class HardMishMe(nn.Module): def __init__(self, inplace: bool = False): super(HardMishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
class HardMishMe(nn.Module): def __init__(self, inplace: bool = False): super(HardMishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
return HardMishJitAutoFn.apply(x)
return HardMishJitAutoFn.apply(x)
2
61
22
83
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,353
/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/layers/activations_me.py
116,118
110,122
backward
HardSigmoidJitAutoFn
118,122
118,122
class HardSigmoidJitAutoFn(torch.autograd.Function): @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return hard_sigmoid_jit_fwd(x) @staticmethod def backward(ctx, grad_output): FILL_FUNC_BODY
class HardSigmoidJitAutoFn(torch.autograd.Function): @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return hard_sigmoid_jit_fwd(x) @staticmethod def backward(ctx, grad_output): FILL_FUNC_BODY
x = ctx.saved_tensors[0] return hard_sigmoid_jit_bwd(x, grad_output)
x = ctx.saved_tensors[0] return hard_sigmoid_jit_bwd(x, grad_output)
6
91
42
133
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,354
/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/layers/activations_me.py
130,131
126,134
forward
HardSigmoidMe
131,134
131,134
class HardSigmoidMe(nn.Module): def __init__(self, inplace: bool = False): super(HardSigmoidMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
class HardSigmoidMe(nn.Module): def __init__(self, inplace: bool = False): super(HardSigmoidMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
return HardSigmoidJitAutoFn.apply(x)
return HardSigmoidJitAutoFn.apply(x)
2
63
21
84
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,355
/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/layers/activations_me.py
158,160
146,166
symbolic
HardSwishJitAutoFn
160,166
160,166
class HardSwishJitAutoFn(torch.autograd.Function): """A memory efficient, jit-scripted HardSwish activation""" @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return hard_swish_jit_fwd(x) @staticmethod def backward(ctx, grad_output): x = ctx.saved_tensors[0] ...
class HardSwishJitAutoFn(torch.autograd.Function): """A memory efficient, jit-scripted HardSwish activation""" @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return hard_swish_jit_fwd(x) @staticmethod def backward(ctx, grad_output): x = ctx.saved_tensors[0] ...
input = g.op("Add", self, g.op('Constant', value_t=torch.tensor(3, dtype=torch.float))) hardtanh_ = g.op("Clip", input, g.op('Constant', value_t=torch.tensor(0, dtype=torch.float)), g.op('Constant', value_t=torch.tensor(6, dtype=torch.float))) hardtanh_ = g.op("Div", hardtanh_, g.op('Constant', ...
input = g.op("Add", self, g.op('Constant', value_t=torch.tensor(3, dtype=torch.float))) hardtanh_ = g.op("Clip", input, g.op('Constant', value_t=torch.tensor(0, dtype=torch.float)), g.op('Constant', value_t=torch.tensor(6, dtype=torch.float))) hardtanh_ = g.op("Div", hardtanh_, g.op('Constant', ...
28
156
169
325
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,356
/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/layers/activations_me.py
174,175
170,178
forward
HardSwishMe
175,178
175,178
class HardSwishMe(nn.Module): def __init__(self, inplace: bool = False): super(HardSwishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
class HardSwishMe(nn.Module): def __init__(self, inplace: bool = False): super(HardSwishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
return HardSwishJitAutoFn.apply(x)
return HardSwishJitAutoFn.apply(x)
2
61
20
81
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,357
/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/layers/activations_me.py
81,83
72,87
backward
MishJitAutoFn
83,87
83,87
class MishJitAutoFn(torch.autograd.Function): """ Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681 A memory efficient, jit scripted variant of Mish """ @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return mish_jit_fwd(...
class MishJitAutoFn(torch.autograd.Function): """ Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681 A memory efficient, jit scripted variant of Mish """ @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return mish_jit_fwd(...
x = ctx.saved_tensors[0] return mish_jit_bwd(x, grad_output)
x = ctx.saved_tensors[0] return mish_jit_bwd(x, grad_output)
6
145
39
184
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,358
/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/layers/activations_me.py
95,96
91,99
forward
MishMe
96,99
96,99
class MishMe(nn.Module): def __init__(self, inplace: bool = False): super(MishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
class MishMe(nn.Module): def __init__(self, inplace: bool = False): super(MishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
return MishJitAutoFn.apply(x)
return MishJitAutoFn.apply(x)
2
59
19
78
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,359
/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/layers/activations_me.py
42,44
28,48
backward
SwishJitAutoFn
44,48
44,48
class SwishJitAutoFn(torch.autograd.Function): """ torch.jit.script optimised Swish w/ memory-efficient checkpoint Inspired by conversation btw Jeremy Howard & Adam Pazske https://twitter.com/jeremyphoward/status/1188251041835315200 """ @staticmethod def symbolic(g, x): return g.op("Mul"...
class SwishJitAutoFn(torch.autograd.Function): """ torch.jit.script optimised Swish w/ memory-efficient checkpoint Inspired by conversation btw Jeremy Howard & Adam Pazske https://twitter.com/jeremyphoward/status/1188251041835315200 """ @staticmethod def symbolic(g, x): return g.op("Mul"...
x = ctx.saved_tensors[0] return swish_jit_bwd(x, grad_output)
x = ctx.saved_tensors[0] return swish_jit_bwd(x, grad_output)
6
200
39
239
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,360
/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/layers/activations_me.py
56,57
52,60
forward
SwishMe
57,60
57,60
class SwishMe(nn.Module): def __init__(self, inplace: bool = False): super(SwishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
class SwishMe(nn.Module): def __init__(self, inplace: bool = False): super(SwishMe, self).__init__() def forward(self, x): FILL_FUNC_BODY
return SwishJitAutoFn.apply(x)
return SwishJitAutoFn.apply(x)
2
59
19
78
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
""" Activations (memory-efficient w/ custom autograd) A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. These activations are not compatible with jit scripting or ONNX export of the model, please use either the JIT or bas...
17,362
/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/layers/adaptive_avgmax_pool.py
111,112
106,115
forward
AdaptiveAvgMaxPool2d
112,115
112,115
class AdaptiveAvgMaxPool2d(nn.Module): def __init__(self, output_size: _int_tuple_2_t = 1): super(AdaptiveAvgMaxPool2d, self).__init__() self.output_size = output_size def forward(self, x): FILL_FUNC_BODY
class AdaptiveAvgMaxPool2d(nn.Module): def __init__(self, output_size: _int_tuple_2_t = 1): super(AdaptiveAvgMaxPool2d, self).__init__() self.output_size = output_size def forward(self, x): FILL_FUNC_BODY
return adaptive_avgmax_pool2d(x, self.output_size)
return adaptive_avgmax_pool2d(x, self.output_size)
3
91
27
118
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
17,363
/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/layers/adaptive_avgmax_pool.py
120,121
115,124
forward
AdaptiveCatAvgMaxPool2d
121,124
121,124
class AdaptiveCatAvgMaxPool2d(nn.Module): def __init__(self, output_size: _int_tuple_2_t = 1): super(AdaptiveCatAvgMaxPool2d, self).__init__() self.output_size = output_size def forward(self, x): FILL_FUNC_BODY
class AdaptiveCatAvgMaxPool2d(nn.Module): def __init__(self, output_size: _int_tuple_2_t = 1): super(AdaptiveCatAvgMaxPool2d, self).__init__() self.output_size = output_size def forward(self, x): FILL_FUNC_BODY
return adaptive_catavgmax_pool2d(x, self.output_size)
return adaptive_catavgmax_pool2d(x, self.output_size)
3
93
28
121
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
17,364
/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/layers/adaptive_avgmax_pool.py
84,85
78,90
forward
FastAdaptiveAvgMaxPool
85,90
85,90
class FastAdaptiveAvgMaxPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'): super(FastAdaptiveAvgMaxPool, self).__init__() self.flatten = flatten self.dim = get_spatial_dim(input_fmt) def forward(self, x): FILL_FUNC_BODY
class FastAdaptiveAvgMaxPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'): super(FastAdaptiveAvgMaxPool, self).__init__() self.flatten = flatten self.dim = get_spatial_dim(input_fmt) def forward(self, x): FILL_FUNC_BODY
x_avg = x.mean(self.dim, keepdim=not self.flatten) x_max = x.amax(self.dim, keepdim=not self.flatten) return 0.5 * x_avg + 0.5 * x_max
x_avg = x.mean(self.dim, keepdim=not self.flatten) x_max = x.amax(self.dim, keepdim=not self.flatten) return 0.5 * x_avg + 0.5 * x_max
18
109
75
184
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
17,365
/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/layers/adaptive_avgmax_pool.py
64,65
58,68
forward
FastAdaptiveAvgPool
65,68
65,68
class FastAdaptiveAvgPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: F = 'NCHW'): super(FastAdaptiveAvgPool, self).__init__() self.flatten = flatten self.dim = get_spatial_dim(input_fmt) def forward(self, x): FILL_FUNC_BODY
class FastAdaptiveAvgPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: F = 'NCHW'): super(FastAdaptiveAvgPool, self).__init__() self.flatten = flatten self.dim = get_spatial_dim(input_fmt) def forward(self, x): FILL_FUNC_BODY
return x.mean(self.dim, keepdim=not self.flatten)
return x.mean(self.dim, keepdim=not self.flatten)
4
107
25
132
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
17,366
/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/layers/adaptive_avgmax_pool.py
100,101
90,106
forward
FastAdaptiveCatAvgMaxPool
101,106
101,106
class FastAdaptiveCatAvgMaxPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'): super(FastAdaptiveCatAvgMaxPool, self).__init__() self.flatten = flatten self.dim_reduce = get_spatial_dim(input_fmt) if flatten: self.dim_cat = 1 else:...
class FastAdaptiveCatAvgMaxPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'): super(FastAdaptiveCatAvgMaxPool, self).__init__() self.flatten = flatten self.dim_reduce = get_spatial_dim(input_fmt) if flatten: self.dim_cat = 1 else:...
x_avg = x.mean(self.dim_reduce, keepdim=not self.flatten) x_max = x.amax(self.dim_reduce, keepdim=not self.flatten) return torch.cat((x_avg, x_max), self.dim_cat)
x_avg = x.mean(self.dim_reduce, keepdim=not self.flatten) x_max = x.amax(self.dim_reduce, keepdim=not self.flatten) return torch.cat((x_avg, x_max), self.dim_cat)
14
152
84
236
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
17,367
/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/layers/adaptive_avgmax_pool.py
74,75
68,78
forward
FastAdaptiveMaxPool
75,78
75,78
class FastAdaptiveMaxPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'): super(FastAdaptiveMaxPool, self).__init__() self.flatten = flatten self.dim = get_spatial_dim(input_fmt) def forward(self, x): FILL_FUNC_BODY
class FastAdaptiveMaxPool(nn.Module): def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'): super(FastAdaptiveMaxPool, self).__init__() self.flatten = flatten self.dim = get_spatial_dim(input_fmt) def forward(self, x): FILL_FUNC_BODY
return x.amax(self.dim, keepdim=not self.flatten)
return x.amax(self.dim, keepdim=not self.flatten)
4
105
26
131
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
17,368
/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/layers/adaptive_avgmax_pool.py
168,169
124,184
is_identity
SelectAdaptivePool2d
169,171
169,171
class SelectAdaptivePool2d(nn.Module): """Selectable global pooling layer with dynamic input kernel size """ def __init__( self, output_size: _int_tuple_2_t = 1, pool_type: str = 'fast', flatten: bool = False, input_fmt: str = 'NCHW', ): ...
class SelectAdaptivePool2d(nn.Module): """Selectable global pooling layer with dynamic input kernel size """ def __init__( self, output_size: _int_tuple_2_t = 1, pool_type: str = 'fast', flatten: bool = False, input_fmt: str = 'NCHW', ): ...
return not self.pool_type
return not self.pool_type
3
822
12
834
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
""" PyTorch selectable adaptive pooling Adaptive pooling with the ability to select the type of pooling from: * 'avg' - Average pooling * 'max' - Max pooling * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles fea...
17,369
/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/layers/attention_pool.py
70,71
12,104
forward
AttentionPoolLatent
71,104
71,104
class AttentionPoolLatent(nn.Module): """ Attention pooling w/ latent query """ fused_attn: torch.jit.Final[bool] def __init__( self, in_features: int, out_features: int = None, embed_dim: int = None, num_heads: int = 8, mlp_ratio:...
class AttentionPoolLatent(nn.Module): """ Attention pooling w/ latent query """ fused_attn: torch.jit.Final[bool] def __init__( self, in_features: int, out_features: int = None, embed_dim: int = None, num_heads: int = 8, mlp_ratio:...
B, N, C = x.shape if self.pos_embed is not None: # FIXME interpolate x = x + self.pos_embed.unsqueeze(0).to(x.dtype) q_latent = self.latent.expand(B, -1, -1) q = self.q(q_latent).reshape(B, self.latent_len, self.num_heads, self.head_dim).transpose(1, 2) ...
B, N, C = x.shape if self.pos_embed is not None: # FIXME interpolate x = x + self.pos_embed.unsqueeze(0).to(x.dtype) q_latent = self.latent.expand(B, -1, -1) q = self.q(q_latent).reshape(B, self.latent_len, self.num_heads, self.head_dim).transpose(1, 2) ...
124
762
470
1,232
from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from .config import use_fused_attn from .mlp import Mlp from .weight_init import trunc_normal_tf_ class AttentionPoolLatent(nn.Module): """ Attention pooling w/ latent query """ fused_attn: torch.jit.Final[boo...
from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from .config import use_fused_attn from .mlp import Mlp from .weight_init import trunc_normal_tf_ class AttentionPoolLatent(nn.Module): """ Attention pooling w/ latent query """ fused_attn: torch.jit.Final[boo...
17,370
/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/layers/attention_pool2d.py
115,116
79,132
forward
AttentionPool2d
116,132
116,132
class AttentionPool2d(nn.Module): """ Attention based 2D feature pooling w/ learned (absolute) pos embedding. This is a multi-head attention based replacement for (spatial) average pooling in NN architectures. It was based on impl in CLIP by OpenAI https://github.com/openai/CLIP/blob/3b473b0e682c091a9e...
class AttentionPool2d(nn.Module): """ Attention based 2D feature pooling w/ learned (absolute) pos embedding. This is a multi-head attention based replacement for (spatial) average pooling in NN architectures. It was based on impl in CLIP by OpenAI https://github.com/openai/CLIP/blob/3b473b0e682c091a9e...
B, _, H, W = x.shape N = H * W assert self.feat_size[0] == H assert self.feat_size[1] == W x = x.reshape(B, -1, N).permute(0, 2, 1) x = torch.cat([x.mean(1, keepdim=True), x], dim=1) x = x + self.pos_embed.unsqueeze(0).to(x.dtype) x = self.qkv(x).reshape(...
B, _, H, W = x.shape N = H * W assert self.feat_size[0] == H assert self.feat_size[1] == W x = x.reshape(B, -1, N).permute(0, 2, 1) x = torch.cat([x.mean(1, keepdim=True), x], dim=1) x = x + self.pos_embed.unsqueeze(0).to(x.dtype) x = self.qkv(x).reshape(...
84
550
307
857
""" Attention Pool 2D Implementations of 2D spatial feature pooling using multi-head attention instead of average pool. Based on idea in CLIP by OpenAI, licensed Apache 2.0 https://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca1657385717/clip/model.py Hacked together by / Copyright 2021 Ross Wightman """...
""" Attention Pool 2D Implementations of 2D spatial feature pooling using multi-head attention instead of average pool. Based on idea in CLIP by OpenAI, licensed Apache 2.0 https://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca1657385717/clip/model.py Hacked together by / Copyright 2021 Ross Wightman """...
17,371
/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/layers/attention_pool2d.py
52,53
20,79
forward
RotAttentionPool2d
53,79
53,79
class RotAttentionPool2d(nn.Module): """ Attention based 2D feature pooling w/ rotary (relative) pos embedding. This is a multi-head attention based replacement for (spatial) average pooling in NN architectures. Adapted from the AttentionPool2d in CLIP w/ rotary embedding instead of learned embed. http...
class RotAttentionPool2d(nn.Module): """ Attention based 2D feature pooling w/ rotary (relative) pos embedding. This is a multi-head attention based replacement for (spatial) average pooling in NN architectures. Adapted from the AttentionPool2d in CLIP w/ rotary embedding instead of learned embed. http...
B, _, H, W = x.shape N = H * W x = x.reshape(B, -1, N).permute(0, 2, 1) x = torch.cat([x.mean(1, keepdim=True), x], dim=1) x = self.qkv(x).reshape(B, N + 1, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k, v = x[0], x[1], x[2] qc, q = q[:, :, :1],...
B, _, H, W = x.shape N = H * W x = x.reshape(B, -1, N).permute(0, 2, 1) x = torch.cat([x.mean(1, keepdim=True), x], dim=1) x = self.qkv(x).reshape(B, N + 1, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k, v = x[0], x[1], x[2] qc, q = q[:, :, :1],...
114
492
415
907
""" Attention Pool 2D Implementations of 2D spatial feature pooling using multi-head attention instead of average pool. Based on idea in CLIP by OpenAI, licensed Apache 2.0 https://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca1657385717/clip/model.py Hacked together by / Copyright 2021 Ross Wightman """...
""" Attention Pool 2D Implementations of 2D spatial feature pooling using multi-head attention instead of average pool. Based on idea in CLIP by OpenAI, licensed Apache 2.0 https://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca1657385717/clip/model.py Hacked together by / Copyright 2021 Ross Wightman """...
17,372
/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/layers/blur_pool.py
40,41
16,43
forward
BlurPool2d
41,43
41,43
class BlurPool2d(nn.Module): r"""Creates a module that computes blurs and downsample a given feature map. See :cite:`zhang2019shiftinvar` for more details. Corresponds to the Downsample class, which does blurring and subsampling Args: channels = Number of input channels filt_size (int):...
class BlurPool2d(nn.Module): r"""Creates a module that computes blurs and downsample a given feature map. See :cite:`zhang2019shiftinvar` for more details. Corresponds to the Downsample class, which does blurring and subsampling Args: channels = Number of input channels filt_size (int):...
x = F.pad(x, self.padding, 'reflect') return F.conv2d(x, self.filt, stride=self.stride, groups=self.channels)
x = F.pad(x, self.padding, 'reflect') return F.conv2d(x, self.filt, stride=self.stride, groups=self.channels)
10
409
50
459
""" BlurPool layer inspired by - Kornia's Max_BlurPool2d - Making Convolutional Networks Shift-Invariant Again :cite:`zhang2019shiftinvar` Hacked together by Chris Ha and Ross Wightman """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from .padding import get_padding class ...
""" BlurPool layer inspired by - Kornia's Max_BlurPool2d - Making Convolutional Networks Shift-Invariant Again :cite:`zhang2019shiftinvar` Hacked together by Chris Ha and Ross Wightman """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from .padding import get_padding class ...
17,374
/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/layers/bottleneck_attn.py
135,136
84,158
forward
BottleneckAttn
136,158
136,158
class BottleneckAttn(nn.Module): """ Bottleneck Attention Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605 The internal dimensions of the attention module are controlled by the interaction of several arguments. * the output dimension of the module is specifie...
class BottleneckAttn(nn.Module): """ Bottleneck Attention Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605 The internal dimensions of the attention module are controlled by the interaction of several arguments. * the output dimension of the module is specifie...
B, C, H, W = x.shape _assert(H == self.pos_embed.height, '') _assert(W == self.pos_embed.width, '') x = self.qkv(x) # B, (2 * dim_head_qk + dim_head_v) * num_heads, H, W # NOTE head vs channel split ordering in qkv projection was decided before I allowed qk to differ from v ...
B, C, H, W = x.shape _assert(H == self.pos_embed.height, '') _assert(W == self.pos_embed.width, '') x = self.qkv(x) # B, (2 * dim_head_qk + dim_head_v) * num_heads, H, W # NOTE head vs channel split ordering in qkv projection was decided before I allowed qk to differ from v ...
158
960
482
1,442
""" Bottleneck Self Attention (Bottleneck Transformers) Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605 @misc{2101.11605, Author = {Aravind Srinivas and Tsung-Yi Lin and Niki Parmar and Jonathon Shlens and Pieter Abbeel and Ashish Vaswani}, Title = {Bottleneck Transformers f...
""" Bottleneck Self Attention (Bottleneck Transformers) Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605 @misc{2101.11605, Author = {Aravind Srinivas and Tsung-Yi Lin and Niki Parmar and Jonathon Shlens and Pieter Abbeel and Ashish Vaswani}, Title = {Bottleneck Transformers f...
17,375
/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/layers/bottleneck_attn.py
68,69
56,84
forward
PosEmbedRel
69,84
69,84
class PosEmbedRel(nn.Module): """ Relative Position Embedding As per: https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2 Originally from: `Attention Augmented Convolutional Networks` - https://arxiv.org/abs/1904.09925 """ def __init__(self, feat_size, dim_head, scale): ...
class PosEmbedRel(nn.Module): """ Relative Position Embedding As per: https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2 Originally from: `Attention Augmented Convolutional Networks` - https://arxiv.org/abs/1904.09925 """ def __init__(self, feat_size, dim_head, scale): ...
B, HW, _ = q.shape # relative logits in width dimension. q = q.reshape(B, self.height, self.width, -1) rel_logits_w = rel_logits_1d(q, self.width_rel, permute_mask=(0, 1, 3, 2, 4)) # relative logits in height dimension. q = q.transpose(1, 2) rel_logits_h = rel_l...
B, HW, _ = q.shape # relative logits in width dimension. q = q.reshape(B, self.height, self.width, -1) rel_logits_w = rel_logits_1d(q, self.width_rel, permute_mask=(0, 1, 3, 2, 4)) # relative logits in height dimension. q = q.transpose(1, 2) rel_logits_h = rel_l...
57
263
228
491
""" Bottleneck Self Attention (Bottleneck Transformers) Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605 @misc{2101.11605, Author = {Aravind Srinivas and Tsung-Yi Lin and Niki Parmar and Jonathon Shlens and Pieter Abbeel and Ashish Vaswani}, Title = {Bottleneck Transformers f...
""" Bottleneck Self Attention (Bottleneck Transformers) Paper: `Bottleneck Transformers for Visual Recognition` - https://arxiv.org/abs/2101.11605 @misc{2101.11605, Author = {Aravind Srinivas and Tsung-Yi Lin and Niki Parmar and Jonathon Shlens and Pieter Abbeel and Ashish Vaswani}, Title = {Bottleneck Transformers f...
17,376
/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/layers/cbam.py
92,93
82,98
forward
CbamModule
93,98
93,98
class CbamModule(nn.Module): def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, spatial_kernel_size=7, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(CbamModule, self).__init__() self.channel = ChannelAttn( channels, rd_...
class CbamModule(nn.Module): def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, spatial_kernel_size=7, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(CbamModule, self).__init__() self.channel = ChannelAttn( channels, rd_...
x = self.channel(x) x = self.spatial(x) return x
x = self.channel(x) x = self.spatial(x) return x
8
223
32
255
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
17,377
/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/layers/cbam.py
33,34
19,39
forward
ChannelAttn
34,39
34,39
class ChannelAttn(nn.Module): """ Original CBAM channel attention module, currently avg + max pool variant only. """ def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(ChannelAttn, self...
class ChannelAttn(nn.Module): """ Original CBAM channel attention module, currently avg + max pool variant only. """ def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(ChannelAttn, self...
x_avg = self.fc2(self.act(self.fc1(x.mean((2, 3), keepdim=True)))) x_max = self.fc2(self.act(self.fc1(x.amax((2, 3), keepdim=True)))) return x * self.gate(x_avg + x_max)
x_avg = self.fc2(self.act(self.fc1(x.mean((2, 3), keepdim=True)))) x_max = self.fc2(self.act(self.fc1(x.amax((2, 3), keepdim=True)))) return x * self.gate(x_avg + x_max)
16
276
97
373
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
17,378
/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/layers/cbam.py
108,109
98,113
forward
LightCbamModule
109,113
109,113
class LightCbamModule(nn.Module): def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, spatial_kernel_size=7, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(LightCbamModule, self).__init__() self.channel = LightChannelAttn( ...
class LightCbamModule(nn.Module): def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, spatial_kernel_size=7, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(LightCbamModule, self).__init__() self.channel = LightChannelAttn( ...
x = self.channel(x) x = self.spatial(x) return x
x = self.channel(x) x = self.spatial(x) return x
8
220
30
250
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
17,379
/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/layers/cbam.py
48,49
39,54
forward
LightChannelAttn
49,54
49,54
class LightChannelAttn(ChannelAttn): """An experimental 'lightweight' that sums avg + max pool first """ def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(LightChannelAttn, self).__ini...
class LightChannelAttn(ChannelAttn): """An experimental 'lightweight' that sums avg + max pool first """ def __init__( self, channels, rd_ratio=1./16, rd_channels=None, rd_divisor=1, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False): super(LightChannelAttn, self).__ini...
x_pool = 0.5 * x.mean((2, 3), keepdim=True) + 0.5 * x.amax((2, 3), keepdim=True) x_attn = self.fc2(self.act(self.fc1(x_pool))) return x * F.sigmoid(x_attn)
x_pool = 0.5 * x.mean((2, 3), keepdim=True) + 0.5 * x.amax((2, 3), keepdim=True) x_attn = self.fc2(self.act(self.fc1(x_pool))) return x * F.sigmoid(x_attn)
20
167
92
259
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
17,380
/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/layers/cbam.py
76,77
68,82
forward
LightSpatialAttn
77,82
77,82
class LightSpatialAttn(nn.Module): """An experimental 'lightweight' variant that sums avg_pool and max_pool results. """ def __init__(self, kernel_size=7, gate_layer='sigmoid'): super(LightSpatialAttn, self).__init__() self.conv = ConvNormAct(1, 1, kernel_size, apply_act=False) self....
class LightSpatialAttn(nn.Module): """An experimental 'lightweight' variant that sums avg_pool and max_pool results. """ def __init__(self, kernel_size=7, gate_layer='sigmoid'): super(LightSpatialAttn, self).__init__() self.conv = ConvNormAct(1, 1, kernel_size, apply_act=False) self....
x_attn = 0.5 * x.mean(dim=1, keepdim=True) + 0.5 * x.amax(dim=1, keepdim=True) x_attn = self.conv(x_attn) return x * self.gate(x_attn)
x_attn = 0.5 * x.mean(dim=1, keepdim=True) + 0.5 * x.amax(dim=1, keepdim=True) x_attn = self.conv(x_attn) return x * self.gate(x_attn)
18
141
80
221
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
17,381
/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/layers/cbam.py
62,63
54,68
forward
SpatialAttn
63,68
63,68
class SpatialAttn(nn.Module): """ Original CBAM spatial attention module """ def __init__(self, kernel_size=7, gate_layer='sigmoid'): super(SpatialAttn, self).__init__() self.conv = ConvNormAct(2, 1, kernel_size, apply_act=False) self.gate = create_act_layer(gate_layer) def forw...
class SpatialAttn(nn.Module): """ Original CBAM spatial attention module """ def __init__(self, kernel_size=7, gate_layer='sigmoid'): super(SpatialAttn, self).__init__() self.conv = ConvNormAct(2, 1, kernel_size, apply_act=False) self.gate = create_act_layer(gate_layer) def forw...
x_attn = torch.cat([x.mean(dim=1, keepdim=True), x.amax(dim=1, keepdim=True)], dim=1) x_attn = self.conv(x_attn) return x * self.gate(x_attn)
x_attn = torch.cat([x.mean(dim=1, keepdim=True), x.amax(dim=1, keepdim=True)], dim=1) x_attn = self.conv(x_attn) return x * self.gate(x_attn)
14
126
81
207
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
""" CBAM (sort-of) Attention Experimental impl of CBAM: Convolutional Block Attention Module: https://arxiv.org/abs/1807.06521 WARNING: Results with these attention layers have been mixed. They can significantly reduce performance on some tasks, especially fine-grained it seems. I may end up removing this impl. Hack...
17,383
/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/layers/classifier.py
129,130
75,138
forward
ClassifierHead
130,138
130,138
class ClassifierHead(nn.Module): """Classifier head w/ configurable global pooling and dropout.""" def __init__( self, in_features: int, num_classes: int, pool_type: str = 'avg', drop_rate: float = 0., use_conv: bool = False, i...
class ClassifierHead(nn.Module): """Classifier head w/ configurable global pooling and dropout.""" def __init__( self, in_features: int, num_classes: int, pool_type: str = 'avg', drop_rate: float = 0., use_conv: bool = False, i...
x = self.global_pool(x) x = self.drop(x) if pre_logits: return self.flatten(x) x = self.fc(x) return self.flatten(x)
x = self.global_pool(x) x = self.drop(x) if pre_logits: return self.flatten(x) x = self.fc(x) return self.flatten(x)
15
598
70
668
""" Classifier head and layer factory Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from functools import partial from typing import Optional, Union, Callable import torch import torch.nn as nn from torch.nn import functional as F from .adaptive_avgmax_pool import SelectAd...
""" Classifier head and layer factory Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from functools import partial from typing import Optional, Union, Callable import torch import torch.nn as nn from torch.nn import functional as F from .adaptive_avgmax_pool import SelectAd...
17,384
/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/layers/classifier.py
183,184
138,209
reset
NormMlpClassifierHead
184,199
184,199
class NormMlpClassifierHead(nn.Module): def __init__( self, in_features: int, num_classes: int, hidden_size: Optional[int] = None, pool_type: str = 'avg', drop_rate: float = 0., norm_layer: Union[str, Callable] = 'layernorm2d', ...
class NormMlpClassifierHead(nn.Module): def __init__( self, in_features: int, num_classes: int, hidden_size: Optional[int] = None, pool_type: str = 'avg', drop_rate: float = 0., norm_layer: Union[str, Callable] = 'layernorm2d', ...
if pool_type is not None: self.global_pool = SelectAdaptivePool2d(pool_type=pool_type) self.flatten = nn.Flatten(1) if pool_type else nn.Identity() self.use_conv = self.global_pool.is_identity() linear_layer = partial(nn.Conv2d, kernel_size=1) if self.use_conv else nn.Lin...
if pool_type is not None: self.global_pool = SelectAdaptivePool2d(pool_type=pool_type) self.flatten = nn.Flatten(1) if pool_type else nn.Identity() self.use_conv = self.global_pool.is_identity() linear_layer = partial(nn.Conv2d, kernel_size=1) if self.use_conv else nn.Lin...
60
698
329
1,027
""" Classifier head and layer factory Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from functools import partial from typing import Optional, Union, Callable import torch import torch.nn as nn from torch.nn import functional as F from .adaptive_avgmax_pool import SelectAd...
""" Classifier head and layer factory Hacked together by / Copyright 2020 Ross Wightman """ from collections import OrderedDict from functools import partial from typing import Optional, Union, Callable import torch import torch.nn as nn from torch.nn import functional as F from .adaptive_avgmax_pool import SelectAd...
17,385
/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/layers/cond_conv2d.py
21,22
1,124
get_condconv_initializer
22,34
22,34
""" PyTorch Conditionally Parameterized Convolution (CondConv) Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference (https://arxiv.org/abs/1904.04971) Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial import numpy as np import torch from torc...
""" PyTorch Conditionally Parameterized Convolution (CondConv) Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference (https://arxiv.org/abs/1904.04971) Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial import numpy as np import torch from torc...
def condconv_initializer(weight): """CondConv initializer function.""" num_params = np.prod(expert_shape) if (len(weight.shape) != 2 or weight.shape[0] != num_experts or weight.shape[1] != num_params): raise (ValueError( 'CondConv variables must ha...
def condconv_initializer(weight): """CondConv initializer function.""" num_params = np.prod(expert_shape) if (len(weight.shape) != 2 or weight.shape[0] != num_experts or weight.shape[1] != num_params): raise (ValueError( 'CondConv variables must ha...
36
1,559
155
1,714
""" PyTorch Conditionally Parameterized Convolution (CondConv) Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference (https://arxiv.org/abs/1904.04971) Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial import numpy as np import torch from torc...
""" PyTorch Conditionally Parameterized Convolution (CondConv) Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference (https://arxiv.org/abs/1904.04971) Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial import numpy as np import torch from torc...
17,386
/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/layers/cond_conv2d.py
84,85
34,124
forward
CondConv2d
85,124
85,124
class CondConv2d(nn.Module): """ Conditionally Parameterized Convolution Inspired by: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/condconv/condconv_layers.py Grouped convolution hackery for parallel execution of the per-sample kernel filters inspired by this discussion: h...
class CondConv2d(nn.Module): """ Conditionally Parameterized Convolution Inspired by: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/condconv/condconv_layers.py Grouped convolution hackery for parallel execution of the per-sample kernel filters inspired by this discussion: h...
B, C, H, W = x.shape weight = torch.matmul(routing_weights, self.weight) new_weight_shape = (B * self.out_channels, self.in_channels // self.groups) + self.kernel_size weight = weight.view(new_weight_shape) bias = None if self.bias is not None: bias = torch.ma...
B, C, H, W = x.shape weight = torch.matmul(routing_weights, self.weight) new_weight_shape = (B * self.out_channels, self.in_channels // self.groups) + self.kernel_size weight = weight.view(new_weight_shape) bias = None if self.bias is not None: bias = torch.ma...
199
759
656
1,415
""" PyTorch Conditionally Parameterized Convolution (CondConv) Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference (https://arxiv.org/abs/1904.04971) Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial import numpy as np import torch from torc...
""" PyTorch Conditionally Parameterized Convolution (CondConv) Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference (https://arxiv.org/abs/1904.04971) Hacked together by / Copyright 2020 Ross Wightman """ import math from functools import partial import numpy as np import torch from torc...
17,387
/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/layers/config.py
130,131
1,150
use_fused_attn
131,139
131,139
""" Model / Layer Config singleton state """ import os import warnings from typing import Any, Optional import torch __all__ = [ 'is_exportable', 'is_scriptable', 'is_no_jit', 'use_fused_attn', 'set_exportable', 'set_scriptable', 'set_no_jit', 'set_layer_config', 'set_fused_attn' ] # Set to True if prefer to...
""" Model / Layer Config singleton state """ import os import warnings from typing import Any, Optional import torch __all__ = [ 'is_exportable', 'is_scriptable', 'is_no_jit', 'use_fused_attn', 'set_exportable', 'set_scriptable', 'set_no_jit', 'set_layer_config', 'set_fused_attn' ] # Set to True if prefer to...
# NOTE: ONNX export cannot handle F.scaled_dot_product_attention as of pytorch 2.0 if not _HAS_FUSED_ATTN or _EXPORTABLE: return False if experimental: return _USE_FUSED_ATTN > 1 return _USE_FUSED_ATTN > 0
# NOTE: ONNX export cannot handle F.scaled_dot_product_attention as of pytorch 2.0 if not _HAS_FUSED_ATTN or _EXPORTABLE: return False if experimental: return _USE_FUSED_ATTN > 1 return _USE_FUSED_ATTN > 0
28
1,343
101
1,444
""" Model / Layer Config singleton state """ import os import warnings from typing import Any, Optional import torch __all__ = [ 'is_exportable', 'is_scriptable', 'is_no_jit', 'use_fused_attn', 'set_exportable', 'set_scriptable', 'set_no_jit', 'set_layer_config', 'set_fused_attn' ] # Set to True if prefer to...
""" Model / Layer Config singleton state """ import os import warnings from typing import Any, Optional import torch __all__ = [ 'is_exportable', 'is_scriptable', 'is_no_jit', 'use_fused_attn', 'set_exportable', 'set_scriptable', 'set_no_jit', 'set_layer_config', 'set_fused_attn' ] # Set to True if prefer to...
17,388
/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/layers/conv_bn_act.py
67,68
1,130
create_aa
68,81
68,81
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
if not aa_layer or not enable: return nn.Identity() if isinstance(aa_layer, functools.partial): if issubclass(aa_layer.func, nn.AvgPool2d): return aa_layer() else: return aa_layer(channels) elif issubclass(aa_layer, nn.AvgPool2d): return aa_layer(strid...
if not aa_layer or not enable: return nn.Identity() if isinstance(aa_layer, functools.partial): if issubclass(aa_layer.func, nn.AvgPool2d): return aa_layer() else: return aa_layer(channels) elif issubclass(aa_layer, nn.AvgPool2d): return aa_layer(strid...
28
1,086
151
1,237
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
17,389
/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/layers/conv_bn_act.py
50,52
12,64
in_channels
ConvNormAct
52,54
52,54
class ConvNormAct(nn.Module): def __init__( self, in_channels, out_channels, kernel_size=1, stride=1, padding='', dilation=1, groups=1, bias=False, apply_act=True, norm_layer=nn.BatchN...
class ConvNormAct(nn.Module): def __init__( self, in_channels, out_channels, kernel_size=1, stride=1, padding='', dilation=1, groups=1, bias=False, apply_act=True, norm_layer=nn.BatchN...
return self.conv.in_channels
return self.conv.in_channels
2
447
14
461
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
17,390
/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/layers/conv_bn_act.py
125,126
81,130
forward
ConvNormActAa
126,130
126,130
class ConvNormActAa(nn.Module): def __init__( self, in_channels, out_channels, kernel_size=1, stride=1, padding='', dilation=1, groups=1, bias=False, apply_act=True, norm_layer=nn.Batc...
class ConvNormActAa(nn.Module): def __init__( self, in_channels, out_channels, kernel_size=1, stride=1, padding='', dilation=1, groups=1, bias=False, apply_act=True, norm_layer=nn.Batc...
x = self.conv(x) x = self.bn(x) x = self.aa(x) return x
x = self.conv(x) x = self.bn(x) x = self.aa(x) return x
11
490
38
528
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
""" Conv2d + BN + Act Hacked together by / Copyright 2020 Ross Wightman """ import functools from torch import nn as nn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer class ConvNormAct(nn.Module): def __init__( self, in_channels, out_...
17,392
/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/layers/create_attn.py
21,22
1,90
get_attn
22,84
22,84
""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import Gl...
""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import Gl...
if isinstance(attn_type, torch.nn.Module): return attn_type module_cls = None if attn_type: if isinstance(attn_type, str): attn_type = attn_type.lower() # Lightweight attention modules (channel and/or coarse spatial). # Typically added to existing network ...
if isinstance(attn_type, torch.nn.Module): return attn_type module_cls = None if attn_type: if isinstance(attn_type, str): attn_type = attn_type.lower() # Lightweight attention modules (channel and/or coarse spatial). # Typically added to existing network ...
253
298
740
1,038
""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import Gl...
""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import Gl...
17,393
/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/layers/create_conv2d.py
11,12
1,37
create_conv2d
17,37
12,37
""" Create Conv2d Factory Method Hacked together by / Copyright 2020 Ross Wightman """ from .mixed_conv2d import MixedConv2d from .cond_conv2d import CondConv2d from .conv2d_same import create_conv2d_pad def create_conv2d(in_channels, out_channels, kernel_size, **kwargs): FILL_FUNC_BODY
""" Create Conv2d Factory Method Hacked together by / Copyright 2020 Ross Wightman """ from .mixed_conv2d import MixedConv2d from .cond_conv2d import CondConv2d from .conv2d_same import create_conv2d_pad def create_conv2d(in_channels, out_channels, kernel_size, **kwargs): """ Select a 2d convolution implementat...
if isinstance(kernel_size, list): assert 'num_experts' not in kwargs # MixNet + CondConv combo not supported currently if 'groups' in kwargs: groups = kwargs.pop('groups') if groups == in_channels: kwargs['depthwise'] = True else: ...
""" Select a 2d convolution implementation based on arguments Creates and returns one of torch.nn.Conv2d, Conv2dSame, MixedConv2d, or CondConv2d. Used extensively by EfficientNet, MobileNetv3 and related networks. """ if isinstance(kernel_size, list): assert 'num_experts' not in kwargs # M...
125
185
359
544
""" Create Conv2d Factory Method Hacked together by / Copyright 2020 Ross Wightman """ from .mixed_conv2d import MixedConv2d from .cond_conv2d import CondConv2d from .conv2d_same import create_conv2d_pad def create_conv2d(in_channels, out_channels, kernel_size, **kwargs): FILL_FUNC_BODY
""" Create Conv2d Factory Method Hacked together by / Copyright 2020 Ross Wightman """ from .mixed_conv2d import MixedConv2d from .cond_conv2d import CondConv2d from .conv2d_same import create_conv2d_pad def create_conv2d(in_channels, out_channels, kernel_size, **kwargs): """ Select a 2d convolution implementat...
17,394
/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/layers/create_norm.py
36,37
1,58
get_norm_layer
37,58
37,58
""" Norm Layer Factory Create norm modules by string (to mirror create_act and creat_norm-act fns) Copyright 2022 Ross Wightman """ import functools import types from typing import Type import torch.nn as nn from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d, RmsNorm from torchvision.ops.misc import Fr...
""" Norm Layer Factory Create norm modules by string (to mirror create_act and creat_norm-act fns) Copyright 2022 Ross Wightman """ import functools import types from typing import Type import torch.nn as nn from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d, RmsNorm from torchvision.ops.misc import Fr...
if norm_layer is None: return None assert isinstance(norm_layer, (type, str, types.FunctionType, functools.partial)) norm_kwargs = {} # unbind partial fn, so args can be rebound later if isinstance(norm_layer, functools.partial): norm_kwargs.update(norm_layer.keywords) norm_...
if norm_layer is None: return None assert isinstance(norm_layer, (type, str, types.FunctionType, functools.partial)) norm_kwargs = {} # unbind partial fn, so args can be rebound later if isinstance(norm_layer, functools.partial): norm_kwargs.update(norm_layer.keywords) norm_...
62
331
237
568
""" Norm Layer Factory Create norm modules by string (to mirror create_act and creat_norm-act fns) Copyright 2022 Ross Wightman """ import functools import types from typing import Type import torch.nn as nn from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d, RmsNorm from torchvision.ops.misc import Fr...
""" Norm Layer Factory Create norm modules by string (to mirror create_act and creat_norm-act fns) Copyright 2022 Ross Wightman """ import functools import types from typing import Type import torch.nn as nn from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d, RmsNorm from torchvision.ops.misc import Fr...