code stringlengths 17 6.64M |
|---|
def search_func(xloader, network, criterion, scheduler, w_optimizer, a_optimizer, epoch_str, print_freq, algo, logger):
(data_time, batch_time) = (AverageMeter(), AverageMeter())
(base_losses, base_top1, base_top5) = (AverageMeter(), AverageMeter(), AverageMeter())
(arch_losses, arch_top1, arch_top5) = (A... |
def train_controller(xloader, network, criterion, optimizer, prev_baseline, epoch_str, print_freq, logger):
(data_time, batch_time) = (AverageMeter(), AverageMeter())
(GradnormMeter, LossMeter, ValAccMeter, EntropyMeter, BaselineMeter, RewardMeter, xend) = (AverageMeter(), AverageMeter(), AverageMeter(), Aver... |
def get_best_arch(xloader, network, n_samples, algo):
with torch.no_grad():
network.eval()
if (algo == 'random'):
(archs, valid_accs) = (network.return_topK(n_samples, True), [])
elif (algo == 'setn'):
(archs, valid_accs) = (network.return_topK(n_samples, False), []... |
def valid_func(xloader, network, criterion, algo, logger):
(data_time, batch_time) = (AverageMeter(), AverageMeter())
(arch_losses, arch_top1, arch_top5) = (AverageMeter(), AverageMeter(), AverageMeter())
end = time.time()
with torch.no_grad():
network.eval()
for (step, (arch_inputs, a... |
def main(xargs):
assert torch.cuda.is_available(), 'CUDA is not available.'
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.set_num_threads(xargs.workers)
prepare_seed(xargs.rand_seed)
logger = prepare_logger(args)
... |
def version():
versions = ['0.9.9']
versions = ['1.0.0']
return versions[(- 1)]
|
def arg_str2bool(v):
if isinstance(v, bool):
return v
elif (v.lower() in ('yes', 'true', 't', 'y', '1')):
return True
elif (v.lower() in ('no', 'false', 'f', 'n', '0')):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
|
def obtain_attention_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--init_model', typ... |
def obtain_basic_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--init_model', type=st... |
def obtain_cls_init_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--init_model', type... |
def obtain_cls_kd_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--init_model', type=s... |
def convert_param(original_lists):
assert isinstance(original_lists, list), 'The type is not right : {:}'.format(original_lists)
(ctype, value) = (original_lists[0], original_lists[1])
assert (ctype in support_types), 'Ctype={:}, support={:}'.format(ctype, support_types)
is_list = isinstance(value, li... |
def load_config(path, extra, logger):
path = str(path)
if hasattr(logger, 'log'):
logger.log(path)
assert os.path.exists(path), 'Can not find {:}'.format(path)
with open(path, 'r') as f:
data = json.load(f)
content = {k: convert_param(v) for (k, v) in data.items()}
assert ((ext... |
def configure2str(config, xpath=None):
if (not isinstance(config, dict)):
config = config._asdict()
def cstring(x):
return '"{:}"'.format(x)
def gtype(x):
if isinstance(x, list):
x = x[0]
if isinstance(x, str):
return 'str'
elif isinstance(... |
def dict2config(xdict, logger):
assert isinstance(xdict, dict), 'invalid type : {:}'.format(type(xdict))
Arguments = namedtuple('Configure', ' '.join(xdict.keys()))
content = Arguments(**xdict)
if hasattr(logger, 'log'):
logger.log('{:}'.format(content))
return content
|
def obtain_pruning_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--init_model', type=... |
def obtain_RandomSearch_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--init_model', ... |
def obtain_search_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--model_config', type... |
def obtain_search_single_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resume', type=str, help='Resume path.')
parser.add_argument('--model_config... |
def add_shared_args(parser):
parser.add_argument('--dataset', type=str, help='The dataset name.')
parser.add_argument('--data_path', type=str, help='The dataset name.')
parser.add_argument('--cutout_length', type=int, help='The cutout length, negative means not use.')
parser.add_argument('--print_freq... |
class PrintLogger(object):
def __init__(self):
'Create a summary writer logging to log_dir.'
self.name = 'PrintLogger'
def log(self, string):
print(string)
def close(self):
print(((('-' * 30) + ' close printer ') + ('-' * 30)))
|
class Logger(object):
def __init__(self, log_dir, seed, create_model_dir=True, use_tf=False):
'Create a summary writer logging to log_dir.'
self.seed = int(seed)
self.log_dir = Path(log_dir)
self.model_dir = (Path(log_dir) / 'checkpoint')
self.log_dir.mkdir(parents=True, e... |
def pickle_save(obj, path):
file_path = Path(path)
file_dir = file_path.parent
file_dir.mkdir(parents=True, exist_ok=True)
with file_path.open('wb') as f:
pickle.dump(obj, f)
|
def pickle_load(path):
if (not Path(path).exists()):
raise ValueError('{:} does not exists'.format(path))
with Path(path).open('rb') as f:
data = pickle.load(f)
return data
|
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 time_string_short():
ISOTIMEFORMAT = '%Y%m%d'
string = '{:}'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time())))
return string
|
def time_print(string, is_print=True):
if is_print:
print('{} : {}'.format(time_string(), 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 print_log(print_string, log):
if hasattr(log, 'log'):
log.log('{:}'.format(print_string))
else:
print('{:}'.format(print_string))
if (log is not None):
log.write('{:}\n'.format(print_string))
log.flush()
|
class Bottleneck(nn.Module):
def __init__(self, nChannels, growthRate):
super(Bottleneck, self).__init__()
interChannels = (4 * growthRate)
self.bn1 = nn.BatchNorm2d(nChannels)
self.conv1 = nn.Conv2d(nChannels, interChannels, kernel_size=1, bias=False)
self.bn2 = nn.BatchN... |
class SingleLayer(nn.Module):
def __init__(self, nChannels, growthRate):
super(SingleLayer, self).__init__()
self.bn1 = nn.BatchNorm2d(nChannels)
self.conv1 = nn.Conv2d(nChannels, growthRate, kernel_size=3, padding=1, bias=False)
def forward(self, x):
out = self.conv1(F.relu(... |
class Transition(nn.Module):
def __init__(self, nChannels, nOutChannels):
super(Transition, self).__init__()
self.bn1 = nn.BatchNorm2d(nChannels)
self.conv1 = nn.Conv2d(nChannels, nOutChannels, kernel_size=1, bias=False)
def forward(self, x):
out = self.conv1(F.relu(self.bn1(... |
class DenseNet(nn.Module):
def __init__(self, growthRate, depth, reduction, nClasses, bottleneck):
super(DenseNet, self).__init__()
if bottleneck:
nDenseBlocks = int(((depth - 4) / 6))
else:
nDenseBlocks = int(((depth - 4) / 3))
self.message = 'CifarDenseNe... |
class Downsample(nn.Module):
def __init__(self, nIn, nOut, stride):
super(Downsample, self).__init__()
assert ((stride == 2) and (nOut == (2 * nIn))), 'stride:{} IO:{},{}'.format(stride, nIn, nOut)
self.in_dim = nIn
self.out_dim = nOut
self.avg = nn.AvgPool2d(kernel_size=2... |
class ConvBNReLU(nn.Module):
def __init__(self, nIn, nOut, kernel, stride, padding, bias, relu):
super(ConvBNReLU, self).__init__()
self.conv = nn.Conv2d(nIn, nOut, kernel_size=kernel, stride=stride, padding=padding, bias=bias)
self.bn = nn.BatchNorm2d(nOut)
if relu:
s... |
class ResNetBasicblock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride):
super(ResNetBasicblock, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
self.conv_a = ConvBNReLU(inplanes, planes, 3, stride, 1, False, True)
... |
class ResNetBottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride):
super(ResNetBottleneck, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
self.conv_1x1 = ConvBNReLU(inplanes, planes, 1, 1, 0, False, True)
... |
class CifarResNet(nn.Module):
def __init__(self, block_name, depth, num_classes, zero_init_residual):
super(CifarResNet, self).__init__()
if (block_name == 'ResNetBasicblock'):
block = ResNetBasicblock
assert (((depth - 2) % 6) == 0), 'depth should be one of 20, 32, 44, 56... |
class WideBasicblock(nn.Module):
def __init__(self, inplanes, planes, stride, dropout=False):
super(WideBasicblock, self).__init__()
self.bn_a = nn.BatchNorm2d(inplanes)
self.conv_a = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn_b = nn.B... |
class CifarWideResNet(nn.Module):
'\n ResNet optimized for the Cifar dataset, as specified in\n https://arxiv.org/abs/1512.03385.pdf\n '
def __init__(self, depth, widen_factor, num_classes, dropout):
super(CifarWideResNet, self).__init__()
assert (((depth - 4) % 6) == 0), 'depth shou... |
class ConvBNReLU(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
super(ConvBNReLU, self).__init__()
padding = ((kernel_size - 1) // 2)
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False)
se... |
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
self.stride = stride
assert (stride in [1, 2])
hidden_dim = int(round((inp * expand_ratio)))
self.use_res_connect = ((self.stride == 1) and (inp ... |
class MobileNetV2(nn.Module):
def __init__(self, num_classes, width_mult, input_channel, last_channel, block_name, dropout):
super(MobileNetV2, self).__init__()
if (block_name == 'InvertedResidual'):
block = InvertedResidual
else:
raise ValueError('invalid block na... |
def conv3x3(in_planes, out_planes, stride=1, groups=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False)
|
def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64):
super(BasicBlock, self).__init__()
if ((groups != 1) or (base_width != 64)):
raise ValueError('BasicBlock only supports groups=1 and base_width=64')... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64):
super(Bottleneck, self).__init__()
width = (int((planes * (base_width / 64.0))) * groups)
self.conv1 = conv1x1(inplanes, width)
self.bn1 = nn.Ba... |
class ResNet(nn.Module):
def __init__(self, block_name, layers, deep_stem, num_classes, zero_init_residual, groups, width_per_group):
super(ResNet, self).__init__()
if (block_name == 'BasicBlock'):
block = BasicBlock
elif (block_name == 'Bottleneck'):
block = Bottl... |
def get_cell_based_tiny_net(config):
if isinstance(config, dict):
config = dict2config(config, None)
super_type = getattr(config, 'super_type', 'basic')
group_names = ['DARTS-V1', 'DARTS-V2', 'GDAS', 'SETN', 'ENAS', 'RANDOM', 'generic']
if ((super_type == 'basic') and (config.name in group_nam... |
def get_search_spaces(xtype, name) -> List[Text]:
if ((xtype == 'cell') or (xtype == 'tss')):
from .cell_operations import SearchSpaceNames
assert (name in SearchSpaceNames), 'invalid name [{:}] in {:}'.format(name, SearchSpaceNames.keys())
return SearchSpaceNames[name]
elif (xtype == ... |
def get_cifar_models(config, extra_path=None):
super_type = getattr(config, 'super_type', 'basic')
if (super_type == 'basic'):
from .CifarResNet import CifarResNet
from .CifarDenseNet import DenseNet
from .CifarWideResNet import CifarWideResNet
if (config.arch == 'resnet'):
... |
def get_imagenet_models(config):
super_type = getattr(config, 'super_type', 'basic')
if (super_type == 'basic'):
from .ImageNet_ResNet import ResNet
from .ImageNet_MobileNetV2 import MobileNetV2
if (config.arch == 'resnet'):
return ResNet(config.block_name, config.layers, c... |
def obtain_model(config, extra_path=None):
if (config.dataset == 'cifar'):
return get_cifar_models(config, extra_path)
elif (config.dataset == 'imagenet'):
return get_imagenet_models(config)
else:
raise ValueError('invalid dataset in the model config : {:}'.format(config))
|
def obtain_search_model(config):
if (config.dataset == 'cifar'):
if (config.arch == 'resnet'):
from .shape_searchs import SearchWidthCifarResNet
from .shape_searchs import SearchDepthCifarResNet
from .shape_searchs import SearchShapeCifarResNet
if (config.se... |
def load_net_from_checkpoint(checkpoint):
assert osp.isfile(checkpoint), 'checkpoint {:} does not exist'.format(checkpoint)
checkpoint = torch.load(checkpoint)
model_config = dict2config(checkpoint['model-config'], None)
model = obtain_model(model_config)
model.load_state_dict(checkpoint['base-mod... |
class InferCell(nn.Module):
def __init__(self, genotype, C_in, C_out, stride, affine=True, track_running_stats=True):
super(InferCell, self).__init__()
self.layers = nn.ModuleList()
self.node_IN = []
self.node_IX = []
self.genotype = deepcopy(genotype)
for i in ran... |
class NASNetInferCell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev, affine, track_running_stats):
super(NASNetInferCell, self).__init__()
self.reduction = reduction
if reduction_prev:
self.preprocess0 = OPS['skip_connect'](C_prev_p... |
class AuxiliaryHeadCIFAR(nn.Module):
def __init__(self, C, num_classes):
'assuming input size 8x8'
super(AuxiliaryHeadCIFAR, self).__init__()
self.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=3, padding=0, count_include_pad=False), nn.Conv2d(C, 128, 1, bias=False... |
class NASNetonCIFAR(nn.Module):
def __init__(self, C, N, stem_multiplier, num_classes, genotype, auxiliary, affine=True, track_running_stats=True):
super(NASNetonCIFAR, self).__init__()
self._C = C
self._layerN = N
self.stem = nn.Sequential(nn.Conv2d(3, (C * stem_multiplier), kern... |
class TinyNetwork(nn.Module):
def __init__(self, C, N, genotype, num_classes):
super(TinyNetwork, self).__init__()
self._C = C
self._layerN = N
self.channel = (1 if (num_classes == 18) else 3)
self.stem = nn.Sequential(nn.Conv2d(self.channel, C, kernel_size=3, padding=1, b... |
def main():
controller = Controller(6, 4)
predictions = controller()
|
class Controller(nn.Module):
def __init__(self, edge2index, op_names, max_nodes, lstm_size=32, lstm_num_layers=2, tanh_constant=2.5, temperature=5.0):
super(Controller, self).__init__()
self.max_nodes = max_nodes
self.num_edge = len(edge2index)
self.edge2index = edge2index
... |
class GenericNAS201Model(nn.Module):
def __init__(self, C, N, max_nodes, num_classes, search_space, affine, track_running_stats):
super(GenericNAS201Model, self).__init__()
self._C = C
self._layerN = N
self._max_nodes = max_nodes
self._stem = nn.Sequential(nn.Conv2d(1, C, ... |
def get_combination(space, num):
combs = []
for i in range(num):
if (i == 0):
for func in space:
combs.append([(func, i)])
else:
new_combs = []
for string in combs:
for func in space:
xstring = (string + [(... |
class Structure():
def __init__(self, genotype):
assert (isinstance(genotype, list) or isinstance(genotype, tuple)), 'invalid class of genotype : {:}'.format(type(genotype))
self.node_num = (len(genotype) + 1)
self.nodes = []
self.node_N = []
for (idx, node_info) in enumer... |
class NAS201SearchCell(nn.Module):
def __init__(self, C_in, C_out, stride, max_nodes, op_names, affine=False, track_running_stats=True):
super(NAS201SearchCell, self).__init__()
self.op_names = deepcopy(op_names)
self.edges = nn.ModuleDict()
self.max_nodes = max_nodes
self... |
class MixedOp(nn.Module):
def __init__(self, space, C, stride, affine, track_running_stats):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in space:
op = OPS[primitive](C, C, stride, affine, track_running_stats)
self._ops.append(op)
... |
class NASNetSearchCell(nn.Module):
def __init__(self, space, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev, affine, track_running_stats):
super(NASNetSearchCell, self).__init__()
self.reduction = reduction
self.op_names = deepcopy(space)
if reduction_prev:
... |
class TinyNetworkDarts(nn.Module):
def __init__(self, C, N, max_nodes, num_classes, search_space, affine, track_running_stats):
super(TinyNetworkDarts, self).__init__()
self._C = C
self._layerN = N
self.max_nodes = max_nodes
self.stem = nn.Sequential(nn.Conv2d(1, C, kernel... |
class NASNetworkDARTS(nn.Module):
def __init__(self, C: int, N: int, steps: int, multiplier: int, stem_multiplier: int, num_classes: int, search_space: List[Text], affine: bool, track_running_stats: bool):
super(NASNetworkDARTS, self).__init__()
self._C = C
self._layerN = N
self._... |
class TinyNetworkENAS(nn.Module):
def __init__(self, C, N, max_nodes, num_classes, search_space, affine, track_running_stats):
super(TinyNetworkENAS, self).__init__()
self._C = C
self._layerN = N
self.max_nodes = max_nodes
self.stem = nn.Sequential(nn.Conv2d(3, C, kernel_s... |
class Controller(nn.Module):
def __init__(self, num_edge, num_ops, lstm_size=32, lstm_num_layers=2, tanh_constant=2.5, temperature=5.0):
super(Controller, self).__init__()
self.num_edge = num_edge
self.num_ops = num_ops
self.lstm_size = lstm_size
self.lstm_N = lstm_num_lay... |
class TinyNetworkGDAS(nn.Module):
def __init__(self, C, N, max_nodes, num_classes, search_space, affine, track_running_stats):
super(TinyNetworkGDAS, self).__init__()
self._C = C
self._layerN = N
self.max_nodes = max_nodes
self.stem = nn.Sequential(nn.Conv2d(3, C, kernel_s... |
class NASNetworkGDAS_FRC(nn.Module):
def __init__(self, C, N, steps, multiplier, stem_multiplier, num_classes, search_space, affine, track_running_stats):
super(NASNetworkGDAS_FRC, self).__init__()
self._C = C
self._layerN = N
self._steps = steps
self._multiplier = multipl... |
class NASNetworkGDAS(nn.Module):
def __init__(self, C, N, steps, multiplier, stem_multiplier, num_classes, search_space, affine, track_running_stats):
super(NASNetworkGDAS, self).__init__()
self._C = C
self._layerN = N
self._steps = steps
self._multiplier = multiplier
... |
class TinyNetworkRANDOM(nn.Module):
def __init__(self, C, N, max_nodes, num_classes, search_space, affine, track_running_stats):
super(TinyNetworkRANDOM, self).__init__()
self._C = C
self._layerN = N
self.max_nodes = max_nodes
self.stem = nn.Sequential(nn.Conv2d(3, C, kern... |
class TinyNetworkSETN(nn.Module):
def __init__(self, C, N, max_nodes, num_classes, search_space, affine, track_running_stats):
super(TinyNetworkSETN, self).__init__()
self._C = C
self._layerN = N
self.max_nodes = max_nodes
self.stem = nn.Sequential(nn.Conv2d(3, C, kernel_s... |
class NASNetworkSETN(nn.Module):
def __init__(self, C: int, N: int, steps: int, multiplier: int, stem_multiplier: int, num_classes: int, search_space: List[Text], affine: bool, track_running_stats: bool):
super(NASNetworkSETN, self).__init__()
self._C = C
self._layerN = N
self._st... |
def initialize_resnet(m):
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if (m.bias is not None):
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
if (m.bias is not N... |
class ConvBNReLU(nn.Module):
def __init__(self, nIn, nOut, kernel, stride, padding, bias, has_avg, has_bn, has_relu):
super(ConvBNReLU, self).__init__()
if has_avg:
self.avg = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
else:
self.avg = None
self.conv ... |
class ResNetBasicblock(nn.Module):
num_conv = 2
expansion = 1
def __init__(self, iCs, stride):
super(ResNetBasicblock, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
assert (isinstance(iCs, tuple) or isinstance(iCs, list)), 'invalid t... |
class ResNetBottleneck(nn.Module):
expansion = 4
num_conv = 3
def __init__(self, iCs, stride):
super(ResNetBottleneck, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
assert (isinstance(iCs, tuple) or isinstance(iCs, list)), 'invalid t... |
class InferCifarResNet(nn.Module):
def __init__(self, block_name, depth, xblocks, xchannels, num_classes, zero_init_residual):
super(InferCifarResNet, self).__init__()
if (block_name == 'ResNetBasicblock'):
block = ResNetBasicblock
assert (((depth - 2) % 6) == 0), 'depth s... |
class ConvBNReLU(nn.Module):
def __init__(self, nIn, nOut, kernel, stride, padding, bias, has_avg, has_bn, has_relu):
super(ConvBNReLU, self).__init__()
if has_avg:
self.avg = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
else:
self.avg = None
self.conv ... |
class ResNetBasicblock(nn.Module):
num_conv = 2
expansion = 1
def __init__(self, inplanes, planes, stride):
super(ResNetBasicblock, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
self.conv_a = ConvBNReLU(inplanes, planes, 3, stride, 1... |
class ResNetBottleneck(nn.Module):
expansion = 4
num_conv = 3
def __init__(self, inplanes, planes, stride):
super(ResNetBottleneck, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
self.conv_1x1 = ConvBNReLU(inplanes, planes, 1, 1, 0, F... |
class InferDepthCifarResNet(nn.Module):
def __init__(self, block_name, depth, xblocks, num_classes, zero_init_residual):
super(InferDepthCifarResNet, self).__init__()
if (block_name == 'ResNetBasicblock'):
block = ResNetBasicblock
assert (((depth - 2) % 6) == 0), 'depth sh... |
class ConvBNReLU(nn.Module):
def __init__(self, nIn, nOut, kernel, stride, padding, bias, has_avg, has_bn, has_relu):
super(ConvBNReLU, self).__init__()
if has_avg:
self.avg = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
else:
self.avg = None
self.conv ... |
class ResNetBasicblock(nn.Module):
num_conv = 2
expansion = 1
def __init__(self, iCs, stride):
super(ResNetBasicblock, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
assert (isinstance(iCs, tuple) or isinstance(iCs, list)), 'invalid t... |
class ResNetBottleneck(nn.Module):
expansion = 4
num_conv = 3
def __init__(self, iCs, stride):
super(ResNetBottleneck, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
assert (isinstance(iCs, tuple) or isinstance(iCs, list)), 'invalid t... |
class InferWidthCifarResNet(nn.Module):
def __init__(self, block_name, depth, xchannels, num_classes, zero_init_residual):
super(InferWidthCifarResNet, self).__init__()
if (block_name == 'ResNetBasicblock'):
block = ResNetBasicblock
assert (((depth - 2) % 6) == 0), 'depth ... |
class ConvBNReLU(nn.Module):
num_conv = 1
def __init__(self, nIn, nOut, kernel, stride, padding, bias, has_avg, has_bn, has_relu):
super(ConvBNReLU, self).__init__()
if has_avg:
self.avg = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
else:
self.avg = None
... |
class ResNetBasicblock(nn.Module):
num_conv = 2
expansion = 1
def __init__(self, iCs, stride):
super(ResNetBasicblock, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
assert (isinstance(iCs, tuple) or isinstance(iCs, list)), 'invalid t... |
class ResNetBottleneck(nn.Module):
expansion = 4
num_conv = 3
def __init__(self, iCs, stride):
super(ResNetBottleneck, self).__init__()
assert ((stride == 1) or (stride == 2)), 'invalid stride {:}'.format(stride)
assert (isinstance(iCs, tuple) or isinstance(iCs, list)), 'invalid t... |
class InferImagenetResNet(nn.Module):
def __init__(self, block_name, layers, xblocks, xchannels, deep_stem, num_classes, zero_init_residual):
super(InferImagenetResNet, self).__init__()
if (block_name == 'BasicBlock'):
block = ResNetBasicblock
elif (block_name == 'Bottleneck')... |
class ConvBNReLU(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, groups, has_bn=True, has_relu=True):
super(ConvBNReLU, self).__init__()
padding = ((kernel_size - 1) // 2)
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, ... |
class InvertedResidual(nn.Module):
def __init__(self, channels, stride, expand_ratio, additive):
super(InvertedResidual, self).__init__()
self.stride = stride
assert (stride in [1, 2]), 'invalid stride : {:}'.format(stride)
assert (len(channels) in [2, 3]), 'invalid channels : {:}... |
class InferMobileNetV2(nn.Module):
def __init__(self, num_classes, xchannels, xblocks, dropout):
super(InferMobileNetV2, self).__init__()
block = InvertedResidual
inverted_residual_setting = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 32... |
class DynamicShapeTinyNet(nn.Module):
def __init__(self, channels: List[int], genotype: Any, num_classes: int):
super(DynamicShapeTinyNet, self).__init__()
self._channels = channels
if ((len(channels) % 3) != 2):
raise ValueError('invalid number of layers : {:}'.format(len(cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.