code stringlengths 17 6.64M |
|---|
class SuperReLU(SuperModule):
'Applies a the rectified linear unit function element-wise.'
def __init__(self, inplace: bool=False) -> None:
super(SuperReLU, self).__init__()
self._inplace = inplace
@property
def abstract_search_space(self):
return spaces.VirtualNode(id(self))... |
class SuperGELU(SuperModule):
'Applies a the Gaussian Error Linear Units function element-wise.'
def __init__(self) -> None:
super(SuperGELU, self).__init__()
@property
def abstract_search_space(self):
return spaces.VirtualNode(id(self))
def forward_candidate(self, input: torch.... |
class SuperSigmoid(SuperModule):
'Applies a the Sigmoid function element-wise.'
def __init__(self) -> None:
super(SuperSigmoid, self).__init__()
@property
def abstract_search_space(self):
return spaces.VirtualNode(id(self))
def forward_candidate(self, input: torch.Tensor) -> tor... |
class SuperLeakyReLU(SuperModule):
'https://pytorch.org/docs/stable/_modules/torch/nn/modules/activation.html#LeakyReLU'
def __init__(self, negative_slope: float=0.01, inplace: bool=False) -> None:
super(SuperLeakyReLU, self).__init__()
self._negative_slope = negative_slope
self._inpl... |
class SuperTanh(SuperModule):
'Applies a the Tanh function element-wise.'
def __init__(self) -> None:
super(SuperTanh, self).__init__()
@property
def abstract_search_space(self):
return spaces.VirtualNode(id(self))
def forward_candidate(self, input: torch.Tensor) -> torch.Tensor... |
class SuperQKVAttentionV2(SuperModule):
'The super model for attention layer.'
def __init__(self, qk_att_dim: int, in_v_dim: int, hidden_dim: int, num_heads: int, proj_dim: int, qkv_bias: bool=False, attn_drop: Optional[float]=None, proj_drop: Optional[float]=None):
super(SuperQKVAttentionV2, self)._... |
class SuperSequential(SuperModule):
"A sequential container wrapped with 'Super' ability.\n\n Modules will be added to it in the order they are passed in the constructor.\n Alternatively, an ordered dict of modules can also be passed in.\n To make it easier to understand, here is a small example::\n ... |
class SuperDropout(SuperModule):
'Applies a the dropout function element-wise.'
def __init__(self, p: float=0.5, inplace: bool=False) -> None:
super(SuperDropout, self).__init__()
self._p = p
self._inplace = inplace
@property
def abstract_search_space(self):
return sp... |
class SuperDrop(SuperModule):
'Applies a the drop-path function element-wise.'
def __init__(self, p: float, dims: Tuple[int], recover: bool=True) -> None:
super(SuperDrop, self).__init__()
self._p = p
self._dims = dims
self._recover = recover
@property
def abstract_se... |
class SuperModule(abc.ABC, nn.Module):
'This class equips the nn.Module class with the ability to apply AutoDL.'
def __init__(self):
super(SuperModule, self).__init__()
self._super_run_type = SuperRunMode.Default
self._abstract_child = None
self._verbose = False
self._... |
class SuperLayerNorm1D(SuperModule):
'Super Layer Norm.'
def __init__(self, dim: IntSpaceType, eps: float=1e-06, elementwise_affine: bool=True) -> None:
super(SuperLayerNorm1D, self).__init__()
self._in_dim = dim
self._eps = eps
self._elementwise_affine = elementwise_affine
... |
class SuperSimpleNorm(SuperModule):
'Super simple normalization.'
def __init__(self, mean, std, inplace=False) -> None:
super(SuperSimpleNorm, self).__init__()
self.register_buffer('_mean', torch.tensor(mean, dtype=torch.float))
self.register_buffer('_std', torch.tensor(std, dtype=tor... |
class SuperSimpleLearnableNorm(SuperModule):
'Super simple normalization.'
def __init__(self, mean=0, std=1, eps=1e-06, inplace=False) -> None:
super(SuperSimpleLearnableNorm, self).__init__()
self.register_parameter('_mean', nn.Parameter(torch.tensor(mean, dtype=torch.float)))
self.r... |
class SuperIdentity(SuperModule):
'Super identity mapping layer.'
def __init__(self, inplace=False, **kwargs) -> None:
super(SuperIdentity, self).__init__()
self._inplace = inplace
@property
def abstract_search_space(self):
return spaces.VirtualNode(id(self))
def forward... |
class SuperReArrange(SuperModule):
'Applies the rearrange operation.'
def __init__(self, pattern, **axes_lengths):
super(SuperReArrange, self).__init__()
self._pattern = pattern
self._axes_lengths = axes_lengths
axes_lengths = tuple(sorted(self._axes_lengths.items()))
... |
class SuperAlphaEBDv1(SuperModule):
'A simple layer to convert the raw trading data from 1-D to 2-D data and apply an FC layer.'
def __init__(self, d_feat: int, embed_dim: IntSpaceType):
super(SuperAlphaEBDv1, self).__init__()
self._d_feat = d_feat
self._embed_dim = embed_dim
... |
class SuperTransformerEncoderLayer(SuperModule):
'TransformerEncoderLayer is made up of self-attn and feedforward network.\n This is a super model for TransformerEncoderLayer that can support search for the transformer encoder layer.\n\n Reference:\n - Paper: Attention Is All You Need, NeurIPS 2017\n ... |
class LayerOrder(Enum):
'This class defines the enumerations for order of operation in a residual or normalization-based layer.'
PreNorm = 'pre-norm'
PostNorm = 'post-norm'
|
class SuperRunMode(Enum):
'This class defines the enumerations for Super Model Running Mode.'
FullModel = 'fullmodel'
Candidate = 'candidate'
Default = 'fullmodel'
|
class ShapeContainer():
'A class to maintain the shape of each weight tensor for a model.'
def __init__(self):
self._names = []
self._shapes = []
self._name2index = dict()
self._param_or_buffers = []
@property
def shapes(self):
return self._shapes
def __g... |
class TensorContainer():
'A class to maintain both parameters and buffers for a model.'
def __init__(self):
self._names = []
self._tensors = []
self._param_or_buffers = []
self._name2index = dict()
def additive(self, tensors):
result = TensorContainer()
fo... |
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
def norm_cdf(x):
return ((1.0 + math.erf((x / math.sqrt(2.0)))) / 2.0)
if ((mean < (a - (2 * std))) or (mean > (b + (2 * std)))):
warnings.warn('mean is more than 2 std from [a, b] in nn.init.trunc_normal_. The distribution of values may be... |
def trunc_normal_(tensor, mean=0.0, std=1.0, a=(- 2.0), b=2.0):
'Fills the input Tensor with values drawn from a truncated\n normal distribution. The values are effectively drawn from the\n normal distribution :math:`\\mathcal{N}(\\text{mean}, \\text{std}^2)`\n with values outside :math:`[a, b]` redrawn ... |
def init_transformer(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if (isinstance(m, nn.Linear) and (m.bias is not None)):
nn.init.constant_(m.bias, 0)
elif isinstance(m, super_core.SuperLinear):
trunc_normal_(m._super_weight, std=0.02)
if (m._s... |
def get_scheduler(indicator, lr):
if (indicator == 'warm-cos'):
multiplier = WarmupParamScheduler(CosineParamScheduler(lr, (lr * 0.001)), warmup_factor=0.001, warmup_length=0.05, warmup_method='linear')
else:
raise ValueError('Unknown indicator: {:}'.format(indicator))
return multiplier
|
class Logger():
'A logger used in xautodl.'
def __init__(self, root_dir, prefix='', log_time=True):
'Create a summary writer logging to log_dir.'
self.root_dir = Path(root_dir)
self.log_dir = (self.root_dir / 'logs')
self.log_dir.mkdir(parents=True, exist_ok=True)
self... |
class AverageMeter():
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0.0
self.avg = 0.0
self.sum = 0.0
self.count = 0.0
def update(self, val, n=1):
self.val = val
self.sum += (v... |
class Metric(abc.ABC):
'The default meta metric class.'
def __init__(self):
self.reset()
def reset(self):
raise NotImplementedError
def __call__(self, predictions, targets):
raise NotImplementedError
def get_info(self):
raise NotImplementedError
def perf_st... |
class ComposeMetric(Metric):
'The composed metric class.'
def __init__(self, *metric_list):
self.reset()
for metric in metric_list:
self.append(metric)
def reset(self):
self._metric_list = []
def append(self, metric):
if (not isinstance(metric, Metric)):
... |
class CrossEntropyMetric(Metric):
'The metric for the cross entropy metric.'
def __init__(self, ignore_batch):
super(CrossEntropyMetric, self).__init__()
self._ignore_batch = ignore_batch
def reset(self):
self._loss = AverageMeter()
def __call__(self, predictions, targets):
... |
class Top1AccMetric(Metric):
'The metric for the top-1 accuracy.'
def __init__(self, ignore_batch):
super(Top1AccMetric, self).__init__()
self._ignore_batch = ignore_batch
def reset(self):
self._accuracy = AverageMeter()
def __call__(self, predictions, targets):
if (... |
def has_key_words(xdict):
if (not isinstance(xdict, dict)):
return False
key_set = set(KEYS)
cur_set = set(xdict.keys())
return (key_set.intersection(cur_set) == key_set)
|
def get_module_by_module_path(module_path):
'Load the module from the path.'
if module_path.endswith('.py'):
module_spec = importlib.util.spec_from_file_location('', module_path)
module = importlib.util.module_from_spec(module_spec)
module_spec.loader.exec_module(module)
else:
... |
def call_by_dict(config: Dict[(Text, Any)], *args, **kwargs) -> object:
"\n get initialized instance with config\n Parameters\n ----------\n config : a dictionary, such as:\n {\n 'cls_or_func': 'ClassName',\n 'args': list,\n 'kwargs': dict,\n ... |
def call_by_yaml(path, *args, **kwargs) -> object:
config = load_yaml(path)
return call_by_config(config, *args, **kwargs)
|
def nested_call_by_dict(config: Union[(Dict[(Text, Any)], Any)], *args, **kwargs) -> object:
'Similar to `call_by_dict`, but differently, the args may contain another dict needs to be called.'
if isinstance(config, list):
return [nested_call_by_dict(x) for x in config]
elif isinstance(config, tupl... |
def nested_call_by_yaml(path, *args, **kwargs) -> object:
config = load_yaml(path)
return nested_call_by_dict(config, *args, **kwargs)
|
class BatchSampler():
'A batch sampler used for single machine training.'
def __init__(self, dataset, batch, steps):
self._num_per_epoch = len(dataset)
self._iter_per_epoch = (self._num_per_epoch // batch)
self._steps = steps
self._batch = batch
if (self._num_per_epoch... |
class ParamScheduler():
'\n Base class for parameter schedulers.\n A parameter scheduler defines a mapping from a progress value in [0, 1) to\n a number (e.g. learning rate).\n '
WHERE_EPSILON = 1e-06
def __call__(self, where: float) -> float:
'\n Get the value of the param for... |
class ConstantParamScheduler(ParamScheduler):
'\n Returns a constant value for a param.\n '
def __init__(self, value: float) -> None:
self._value = value
def __call__(self, where: float) -> float:
if (where >= 1.0):
raise RuntimeError(f'where in ParamScheduler must be i... |
class CosineParamScheduler(ParamScheduler):
"\n Cosine decay or cosine warmup schedules based on start and end values.\n The schedule is updated based on the fraction of training progress.\n The schedule was proposed in 'SGDR: Stochastic Gradient Descent with\n Warm Restarts' (https://arxiv.org/abs/16... |
class ExponentialParamScheduler(ParamScheduler):
'\n Exponetial schedule parameterized by a start value and decay.\n The schedule is updated based on the fraction of training\n progress, `where`, with the formula\n `param_t = start_value * (decay ** where)`.\n\n Example:\n\n .. code-block:: ... |
class LinearParamScheduler(ParamScheduler):
'\n Linearly interpolates parameter between ``start_value`` and ``end_value``.\n Can be used for either warmup or decay based on start and end values.\n The schedule is updated after every train step by default.\n\n Example:\n\n .. code-block:: python... |
class MultiStepParamScheduler(ParamScheduler):
'\n Takes a predefined schedule for a param value, and a list of epochs or steps\n which stand for the upper boundary (excluded) of each range.\n\n Example:\n\n .. code-block:: python\n\n MultiStepParamScheduler(\n values=[0.1, 0.0... |
class PolynomialDecayParamScheduler(ParamScheduler):
'\n Decays the param value after every epoch according to a\n polynomial function with a fixed power.\n The schedule is updated after every train step by default.\n\n Example:\n\n .. code-block:: python\n\n PolynomialDecayParamSchedu... |
class StepParamScheduler(ParamScheduler):
'\n Takes a fixed schedule for a param value. If the length of the\n fixed schedule is less than the number of epochs, then the epochs\n are divided evenly among the param schedule.\n The schedule is updated after every train epoch by default.\n\n Example:... |
class StepWithFixedGammaParamScheduler(ParamScheduler):
'\n Decays the param value by gamma at equal number of steps so as to have the\n specified total number of decays.\n\n Example:\n\n .. code-block:: python\n\n StepWithFixedGammaParamScheduler(\n base_value=0.1, gamma=0.1, ... |
class CompositeParamScheduler(ParamScheduler):
"\n Composite parameter scheduler composed of intermediate schedulers.\n Takes a list of schedulers and a list of lengths corresponding to\n percentage of training each scheduler should run for. Schedulers\n are run in order. All values in lengths should ... |
class WarmupParamScheduler(CompositeParamScheduler):
'\n Add an initial warmup stage to another scheduler.\n '
def __init__(self, scheduler: ParamScheduler, warmup_factor: float, warmup_length: float, warmup_method: str='linear'):
'\n Args:\n scheduler: warmup will be added at... |
class LRMultiplier(torch.optim.lr_scheduler._LRScheduler):
'\n A LRScheduler which uses fvcore :class:`ParamScheduler` to multiply the\n learning rate of each param in the optimizer.\n Every step, the learning rate of each parameter becomes its initial value\n multiplied by the output of the given :cl... |
def time_for_file():
ISOTIMEFORMAT = '%d-%h-at-%H-%M-%S'
return '{:}'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time())))
|
def time_string():
ISOTIMEFORMAT = '%Y-%m-%d %X'
string = '[{:}]'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time())))
return string
|
def convert_secs2time(epoch_time, return_str=False):
need_hour = int((epoch_time / 3600))
need_mins = int(((epoch_time - (3600 * need_hour)) / 60))
need_secs = int(((epoch_time - (3600 * need_hour)) - (60 * need_mins)))
if return_str:
str = '[{:02d}:{:02d}:{:02d}]'.format(need_hour, need_mins,... |
def count_parameters(model_or_parameters, unit='mb'):
if isinstance(model_or_parameters, nn.Module):
counts = sum((np.prod(v.size()) for v in model_or_parameters.parameters()))
elif isinstance(model_or_parameters, nn.Parameter):
counts = models_or_parameters.numel()
elif isinstance(model_o... |
def load_yaml(path):
if (not os.path.isfile(path)):
raise ValueError('{:} is not a file.'.format(path))
with open(path, 'r') as stream:
data = yaml.safe_load(stream)
return data
|
def get_model(config: Dict[(Text, Any)], **kwargs):
model_type = config.get('model_type', 'simple_mlp').lower()
if (model_type == 'simple_mlp'):
act_cls = super_name2activation[kwargs['act_cls']]
norm_cls = super_name2norm[kwargs['norm_cls']]
(mean, std) = (kwargs.get('mean', None), kw... |
def eval_cosmic_seed(seed):
model = xgb.XGBClassifier()
model.load_model(f'../xgboost_model_cosmic_{seed}.json')
logits = model.predict([x.reshape((- 1)) for x in imgs]).reshape(*imgs.shape)
logits = logits.flatten()
test_predictions = (logits.reshape((- 1), 1, 128, 128) > 0.5).flatten()
test_... |
def process_log(fname, kwd='test score: '):
res = 0.0
with open(fname, 'r') as f:
for line in f.readlines():
if (kwd in line):
res = float(line.split(kwd)[1].strip())
return res
|
def dm_to_numpy(loader, n=None):
print(len(loader))
data = [xy for xy in loader]
x = np.vstack([xy[0] for xy in data])
y = np.concatenate([xy[1] for xy in data])
x = x[:n]
y = y[:n]
n = x.shape[0]
x = x.reshape(n, (- 1))
y = y.reshape(n, (- 1))
print(x.shape, y.shape)
retur... |
def main(task='cifar100', seed=7734, load_np=False, save_np=False, no_test=False):
model_params = {'random_state': seed, 'max_depth': 3, 'eta': 1, 'n_jobs': 10, 'gpu_id': 0, 'early_stopping_rounds': 5, 'tree_method': 'gpu_hist', 'subsample': 0.9, 'sampling_method': 'gradient_based'}
if (task == 'cifar100'):
... |
def get_model_complexity_info(model, input_res, print_per_layer_stat=True, as_strings=True, input_constructor=None, ost=sys.stdout):
assert (type(input_res) is tuple)
assert (len(input_res) >= 2)
flops_model = add_flops_counting_methods(model)
flops_model.eval().start_flops_count()
if input_constr... |
def flops_to_string(flops, units='GMac', precision=2):
if (units is None):
if ((flops // (10 ** 9)) > 0):
return (str(round((flops / (10.0 ** 9)), precision)) + ' GMac')
elif ((flops // (10 ** 6)) > 0):
return (str(round((flops / (10.0 ** 6)), precision)) + ' MMac')
... |
def params_to_string(params_num):
"converting number to string\n\n :param float params_num: number\n :returns str: number\n\n >>> params_to_string(1e9)\n '1000.0 M'\n >>> params_to_string(2e5)\n '200.0 k'\n >>> params_to_string(3e-9)\n '3e-09'\n "
if ((params_num // (10 ** 6)) > 0):... |
def print_model_with_flops(model, units='GMac', precision=3, ost=sys.stdout):
total_flops = model.compute_average_flops_cost()
def accumulate_flops(self):
if is_supported_instance(self):
return (self.__flops__ / model.__batch_counter__)
else:
sum = 0
for m ... |
def get_model_parameters_number(model):
params_num = sum((p.numel() for p in model.parameters() if p.requires_grad))
return params_num
|
def add_flops_counting_methods(net_main_module):
net_main_module.start_flops_count = start_flops_count.__get__(net_main_module)
net_main_module.stop_flops_count = stop_flops_count.__get__(net_main_module)
net_main_module.reset_flops_count = reset_flops_count.__get__(net_main_module)
net_main_module.co... |
def compute_average_flops_cost(self):
'\n A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n Returns current mean flops consumption per image.\n '
batches_count = self.__batch_counter__
flops_sum = 0
for module in self.modules():
... |
def start_flops_count(self):
'\n A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n Activates the computation of mean flops consumption per image.\n Call it before you run the network.\n '
add_batch_counter_hook_function(self)
self.appl... |
def stop_flops_count(self):
'\n A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n Stops computing the mean flops consumption per image.\n Call whenever you want to pause the computation.\n '
remove_batch_counter_hook_function(self)
sel... |
def reset_flops_count(self):
'\n A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n Resets statistics computed so far.\n '
add_batch_counter_variables_or_reset(self)
self.apply(add_flops_counter_variable_or_reset)
|
def add_flops_mask(module, mask):
def add_flops_mask_func(module):
if isinstance(module, torch.nn.Conv2d):
module.__mask__ = mask
module.apply(add_flops_mask_func)
|
def remove_flops_mask(module):
module.apply(add_flops_mask_variable_or_reset)
|
def is_supported_instance(module):
if isinstance(module, SUPPORTED_TYPES):
return True
else:
return False
|
def empty_flops_counter_hook(module, input, output):
module.__flops__ += 0
|
def upsample_flops_counter_hook(module, input, output):
output_size = output[0]
batch_size = output_size.shape[0]
output_elements_count = batch_size
for val in output_size.shape[1:]:
output_elements_count *= val
module.__flops__ += int(output_elements_count)
|
def relu_flops_counter_hook(module, input, output):
active_elements_count = output.numel()
module.__flops__ += int(active_elements_count)
|
def linear_flops_counter_hook(module, input, output):
input = input[0]
batch_size = input.shape[0]
module.__flops__ += int(((batch_size * input.shape[1]) * output.shape[1]))
|
def pool_flops_counter_hook(module, input, output):
input = input[0]
module.__flops__ += int(np.prod(input.shape))
|
def bn_flops_counter_hook(module, input, output):
module.affine
input = input[0]
batch_flops = np.prod(input.shape)
if module.affine:
batch_flops *= 2
module.__flops__ += int(batch_flops)
|
def deconv_flops_counter_hook(conv_module, input, output):
input = input[0]
batch_size = input.shape[0]
(input_height, input_width) = input.shape[2:]
(kernel_height, kernel_width) = conv_module.kernel_size
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups... |
def conv_flops_counter_hook(conv_module, input, output):
input = input[0]
batch_size = input.shape[0]
output_dims = list(output.shape[2:])
kernel_dims = list(conv_module.kernel_size)
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups = conv_module.groups
... |
def batch_counter_hook(module, input, output):
batch_size = 1
if (len(input) > 0):
input = input[0]
batch_size = len(input)
else:
print('Warning! No positional inputs found for a module, assuming batch size is 1.')
module.__batch_counter__ += batch_size
|
def add_batch_counter_variables_or_reset(module):
module.__batch_counter__ = 0
|
def add_batch_counter_hook_function(module):
if hasattr(module, '__batch_counter_handle__'):
return
handle = module.register_forward_hook(batch_counter_hook)
module.__batch_counter_handle__ = handle
|
def remove_batch_counter_hook_function(module):
if hasattr(module, '__batch_counter_handle__'):
module.__batch_counter_handle__.remove()
del module.__batch_counter_handle__
|
def add_flops_counter_variable_or_reset(module):
if is_supported_instance(module):
module.__flops__ = 0
|
def add_flops_counter_hook_function(module):
if is_supported_instance(module):
if hasattr(module, '__flops_handle__'):
return
if isinstance(module, CONV_TYPES):
handle = module.register_forward_hook(conv_flops_counter_hook)
elif isinstance(module, RELU_TYPES):
... |
def remove_flops_counter_hook_function(module):
if is_supported_instance(module):
if hasattr(module, '__flops_handle__'):
module.__flops_handle__.remove()
del module.__flops_handle__
|
def add_flops_mask_variable_or_reset(module):
if is_supported_instance(module):
module.__mask__ = None
|
def params_to_string(params_num):
"converting number to string\n\n :param float params_num: number\n :returns str: number\n\n >>> params_to_string(1e9)\n '1000.0 M'\n >>> params_to_string(2e5)\n '200.0 k'\n >>> params_to_string(3e-9)\n '3e-09'\n "
if ((params_num // (10 ** 6)) > 0):... |
def flops_to_string(flops, units='GMac', precision=2):
if (units is None):
if ((flops // (10 ** 9)) > 0):
return (str(round((flops / (10.0 ** 9)), precision)) + ' GMac')
elif ((flops // (10 ** 6)) > 0):
return (str(round((flops / (10.0 ** 6)), precision)) + ' MMac')
... |
def quantize(arr, min_val, max_val, levels, dtype=np.int64):
'Quantize an array of (-inf, inf) to [0, levels-1].\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization lev... |
def dequantize(arr, min_val, max_val, levels, dtype=np.float64):
'Dequantize an array.\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization levels.\n dtype (np.ty... |
class AlexNet(nn.Module):
'AlexNet backbone.\n\n Args:\n num_classes (int): number of classes for classification.\n '
def __init__(self, num_classes=(- 1)):
super(AlexNet, self).__init__()
self.num_classes = num_classes
self.features = nn.Sequential(nn.Conv2d(3, 64, kerne... |
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride, dilation)
self.bn1 = nn.BatchNorm2d(planes)
... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
'Bottleneck block.\n\n If style is "pytorch", the stride-two layer is the 3x3 conv layer,\n if it is "caffe", the stride-two layer is t... |
def make_res_layer(block, inplanes, planes, blocks, stride=1, dilation=1, style='pytorch', with_cp=False):
downsample = None
if ((stride != 1) or (inplanes != (planes * block.expansion))):
downsample = nn.Sequential(nn.Conv2d(inplanes, (planes * block.expansion), kernel_size=1, stride=stride, bias=Fal... |
class ResNet(nn.Module):
'ResNet backbone.\n\n Args:\n depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.\n num_stages (int): Resnet stages, normally 4.\n strides (Sequence[int]): Strides of the first block of each stage.\n dilations (Sequence[int]): Dilation of each stage.\... |
def conv3x3(in_planes, out_planes, dilation=1):
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, padding=dilation, dilation=dilation)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.