code stringlengths 17 6.64M |
|---|
def parse_channel_info(xstring):
blocks = xstring.split(' ')
blocks = [x.split('-') for x in blocks]
blocks = [[int(_) for _ in x] for x in blocks]
return blocks
|
def get_depth_choices(nDepth, return_num):
if (nDepth == 2):
choices = (1, 2)
elif (nDepth == 3):
choices = (1, 2, 3)
elif (nDepth > 3):
choices = list(range(1, (nDepth + 1), 2))
if (choices[(- 1)] < nDepth):
choices.append(nDepth)
else:
raise ValueE... |
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__()
self.InShape = None
self.OutShape = None
self.choices = get_width_choices(nOut)
self.register_buffer('c... |
class ResNetBasicblock(nn.Module):
expansion = 1
num_conv = 2
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 SearchDepthCifarResNet(nn.Module):
def __init__(self, block_name, depth, num_classes):
super(SearchDepthCifarResNet, self).__init__()
if (block_name == 'ResNetBasicblock'):
block = ResNetBasicblock
assert (((depth - 2) % 6) == 0), 'depth should be one of 20, 32, 44, ... |
class NetworkCIFAR(nn.Module):
def __init__(self, C, N, stem_multiplier, auxiliary, genotype, num_classes):
super(NetworkCIFAR, self).__init__()
self._C = C
self._layerN = N
self._stem_multiplier = stem_multiplier
C_curr = (self._stem_multiplier * C)
self.stem = Ci... |
class NetworkImageNet(nn.Module):
def __init__(self, C, N, auxiliary, genotype, num_classes):
super(NetworkImageNet, self).__init__()
self._C = C
self._layerN = N
layer_channels = ((((([C] * N) + [(C * 2)]) + ([(C * 2)] * N)) + [(C * 4)]) + ([(C * 4)] * N))
layer_reduction... |
class MixedOp(nn.Module):
def __init__(self, C, stride, PRIMITIVES):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
self.name2idx = {}
for (idx, primitive) in enumerate(PRIMITIVES):
op = OPS[primitive](C, C, stride, False)
self._ops.append(op)
... |
class SearchCell(nn.Module):
def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev, PRIMITIVES, use_residual):
super(SearchCell, self).__init__()
self.reduction = reduction
self.PRIMITIVES = deepcopy(PRIMITIVES)
if reduction_prev:
self... |
class InferCell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(InferCell, self).__init__()
print(C_prev_prev, C_prev, C)
if (reduction_prev is None):
self.preprocess0 = Identity()
elif reduction_prev:
self... |
def build_genotype_from_dict(xdict):
def remove_value(nodes):
return [tuple([(x[0], x[1]) for x in node]) for node in nodes]
genotype = Genotype(normal=remove_value(xdict['normal']), normal_concat=xdict['normal_concat'], reduce=remove_value(xdict['reduce']), reduce_concat=xdict['reduce_concat'], conn... |
class ImageNetHEAD(nn.Sequential):
def __init__(self, C, stride=2):
super(ImageNetHEAD, self).__init__()
self.add_module('conv1', nn.Conv2d(3, (C // 2), kernel_size=3, stride=2, padding=1, bias=False))
self.add_module('bn1', nn.BatchNorm2d((C // 2)))
self.add_module('relu1', nn.Re... |
class CifarHEAD(nn.Sequential):
def __init__(self, C):
super(CifarHEAD, self).__init__()
self.add_module('conv', nn.Conv2d(3, C, kernel_size=3, padding=1, bias=False))
self.add_module('bn', nn.BatchNorm2d(C))
|
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 AuxiliaryHeadImageNet(nn.Module):
def __init__(self, C, num_classes):
'assuming input size 14x14'
super(AuxiliaryHeadImageNet, self).__init__()
self.features = nn.Sequential(nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=2, padding=0, count_include_pad=False), nn.Conv2d(C, 128, 1, bi... |
def obtain_nas_infer_model(config, extra_model_path=None):
if (config.arch == 'dxys'):
from .DXYs import CifarNet, ImageNet, Networks
from .DXYs import build_genotype_from_dict
if (config.genotype is None):
if ((extra_model_path is not None) and (not os.path.isfile(extra_model_... |
def get_procedures(procedure):
from .basic_main import basic_train, basic_valid
from .search_main import search_train, search_valid
from .search_main_v2 import search_train_v2
from .simple_KD_main import simple_KD_train, simple_KD_valid
train_funcs = {'basic': basic_train, 'search': search_train, ... |
def get_device(tensors):
if isinstance(tensors, (list, tuple)):
return get_device(tensors[0])
elif isinstance(tensors, dict):
for (key, value) in tensors.items():
return get_device(value)
else:
return tensors.device
|
def basic_train_fn(xloader, network, criterion, optimizer, metric, logger):
results = procedure(xloader, network, criterion, optimizer, metric, 'train', logger)
return results
|
def basic_eval_fn(xloader, network, metric, logger):
with torch.no_grad():
results = procedure(xloader, network, None, None, metric, 'valid', logger)
return results
|
def procedure(xloader, network, criterion, optimizer, metric, mode: Text, logger_fn: Callable=None):
(data_time, batch_time) = (AverageMeter(), AverageMeter())
if (mode.lower() == 'train'):
network.train()
elif (mode.lower() == 'valid'):
network.eval()
else:
raise ValueError('T... |
def basic_train(xloader, network, criterion, scheduler, optimizer, optim_config, extra_info, print_freq, logger):
(loss, acc1, acc5) = procedure(xloader, network, criterion, scheduler, optimizer, 'train', optim_config, extra_info, print_freq, logger)
return (loss, acc1, acc5)
|
def basic_valid(xloader, network, criterion, optim_config, extra_info, print_freq, logger):
with torch.no_grad():
(loss, acc1, acc5) = procedure(xloader, network, criterion, None, None, 'valid', None, extra_info, print_freq, logger)
return (loss, acc1, acc5)
|
def procedure(xloader, network, criterion, scheduler, optimizer, mode, config, extra_info, print_freq, logger):
(data_time, batch_time, losses, top1, top5) = (AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter())
if (mode == 'train'):
network.train()
elif (mode == 'valid'... |
def obtain_accuracy(output, target, topk=(1,)):
'Computes the precision@k for the specified values of k'
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred))
res = []
for k in ... |
def pure_evaluate(xloader, network, criterion=torch.nn.CrossEntropyLoss()):
(data_time, batch_time, batch) = (AverageMeter(), AverageMeter(), None)
(losses, top1, top5) = (AverageMeter(), AverageMeter(), AverageMeter())
(latencies, device) = ([], torch.cuda.current_device())
network.eval()
with to... |
def procedure(xloader, network, criterion, scheduler, optimizer, mode: str):
(losses, top1, top5) = (AverageMeter(), AverageMeter(), AverageMeter())
if (mode == 'train'):
network.train()
elif (mode == 'valid'):
network.eval()
else:
raise ValueError('The mode is not right : {:}'... |
def evaluate_for_seed(arch_config, opt_config, train_loader, valid_loaders, seed: int, logger):
'A modular function to train and evaluate a single network, using the given random seed and optimization config with the provided loaders.'
prepare_seed(seed)
net = get_cell_based_tiny_net(arch_config)
(flo... |
def get_nas_bench_loaders(workers):
torch.set_num_threads(workers)
root_dir = ((pathlib.Path(__file__).parent / '..') / '..').resolve()
torch_dir = pathlib.Path(os.environ['TORCH_HOME'])
cifar_config_path = (((root_dir / 'configs') / 'nas-benchmark') / 'CIFAR.config')
cifar_config = load_config(ci... |
class AverageMeter(object):
'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... |
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 __repr_... |
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 MSEMetric(Metric):
'The metric for mse.'
def __init__(self, ignore_batch):
super(MSEMetric, self).__init__()
self._ignore_batch = ignore_batch
def reset(self):
self._mse = AverageMeter()
def __call__(self, predictions, targets):
if (isinstance(predictions, torc... |
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 (... |
class SaveMetric(Metric):
'The metric for mse.'
def reset(self):
self._predicts = []
def __call__(self, predictions, targets=None):
if isinstance(predictions, torch.Tensor):
predicts = predictions.cpu().numpy()
self._predicts.append(predicts)
return pr... |
class _LRScheduler(object):
def __init__(self, optimizer, warmup_epochs, epochs):
if (not isinstance(optimizer, Optimizer)):
raise TypeError('{:} is not an Optimizer'.format(type(optimizer).__name__))
self.optimizer = optimizer
for group in optimizer.param_groups:
... |
class CosineAnnealingLR(_LRScheduler):
def __init__(self, optimizer, warmup_epochs, epochs, T_max, eta_min):
self.T_max = T_max
self.eta_min = eta_min
super(CosineAnnealingLR, self).__init__(optimizer, warmup_epochs, epochs)
def extra_repr(self):
return 'type={:}, T-max={:}, ... |
class MultiStepLR(_LRScheduler):
def __init__(self, optimizer, warmup_epochs, epochs, milestones, gammas):
assert (len(milestones) == len(gammas)), 'invalid {:} vs {:}'.format(len(milestones), len(gammas))
self.milestones = milestones
self.gammas = gammas
super(MultiStepLR, self).... |
class ExponentialLR(_LRScheduler):
def __init__(self, optimizer, warmup_epochs, epochs, gamma):
self.gamma = gamma
super(ExponentialLR, self).__init__(optimizer, warmup_epochs, epochs)
def extra_repr(self):
return 'type={:}, gamma={:}, base-lrs={:}'.format('exponential', self.gamma, ... |
class LinearLR(_LRScheduler):
def __init__(self, optimizer, warmup_epochs, epochs, max_LR, min_LR):
self.max_LR = max_LR
self.min_LR = min_LR
super(LinearLR, self).__init__(optimizer, warmup_epochs, epochs)
def extra_repr(self):
return 'type={:}, max_LR={:}, min_LR={:}, base-... |
class CrossEntropyLabelSmooth(nn.Module):
def __init__(self, num_classes, epsilon):
super(CrossEntropyLabelSmooth, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
self.logsoftmax = nn.LogSoftmax(dim=1)
def forward(self, inputs, targets):
log_pro... |
def get_optim_scheduler(parameters, config):
assert (hasattr(config, 'optim') and hasattr(config, 'scheduler') and hasattr(config, 'criterion')), 'config must have optim / scheduler / criterion keys instead of {:}'.format(config)
if (config.optim == 'SGD'):
optim = torch.optim.SGD(parameters, config.L... |
def set_log_basic_config(filename=None, format=None, level=None):
'\n Set the basic configuration for the logging system.\n See details at https://docs.python.org/3/library/logging.html#logging.basicConfig\n :param filename: str or None\n The path to save the logs.\n :param format: the logging ... |
def update_gpu(config, gpu):
config = deepcopy(config)
if (('task' in config) and ('model' in config['task'])):
if ('GPU' in config['task']['model']):
config['task']['model']['GPU'] = gpu
elif (('kwargs' in config['task']['model']) and ('GPU' in config['task']['model']['kwargs'])):... |
def update_market(config, market):
config = deepcopy(config.copy())
config['market'] = market
config['data_handler_config']['instruments'] = market
return config
|
def run_exp(task_config, dataset, experiment_name, recorder_name, uri, model_obj_name='model.pkl'):
model = init_instance_by_config(task_config['model'])
model_fit_kwargs = dict(dataset=dataset)
with R.start(experiment_name=experiment_name, recorder_name=recorder_name, uri=uri, resume=True):
recor... |
def get_flop_loss(expected_flop, flop_cur, flop_need, flop_tolerant):
expected_flop = torch.mean(expected_flop)
if (flop_cur < (flop_need - flop_tolerant)):
loss = (- torch.log(expected_flop))
elif (flop_cur > flop_need):
loss = torch.log(expected_flop)
else:
loss = None
if... |
def search_train(search_loader, network, criterion, scheduler, base_optimizer, arch_optimizer, optim_config, extra_info, print_freq, logger):
(data_time, batch_time) = (AverageMeter(), AverageMeter())
(base_losses, arch_losses, top1, top5) = (AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter())
... |
def search_valid(xloader, network, criterion, extra_info, print_freq, logger):
(data_time, batch_time, losses, top1, top5) = (AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter())
network.eval()
network.apply(change_key('search_mode', 'search'))
end = time.time()
with tor... |
def get_flop_loss(expected_flop, flop_cur, flop_need, flop_tolerant):
expected_flop = torch.mean(expected_flop)
if (flop_cur < (flop_need - flop_tolerant)):
loss = (- torch.log(expected_flop))
elif (flop_cur > flop_need):
loss = torch.log(expected_flop)
else:
loss = None
if... |
def search_train_v2(search_loader, network, criterion, scheduler, base_optimizer, arch_optimizer, optim_config, extra_info, print_freq, logger):
(data_time, batch_time) = (AverageMeter(), AverageMeter())
(base_losses, arch_losses, top1, top5) = (AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter())
... |
def simple_KD_train(xloader, teacher, network, criterion, scheduler, optimizer, optim_config, extra_info, print_freq, logger):
(loss, acc1, acc5) = procedure(xloader, teacher, network, criterion, scheduler, optimizer, 'train', optim_config, extra_info, print_freq, logger)
return (loss, acc1, acc5)
|
def simple_KD_valid(xloader, teacher, network, criterion, optim_config, extra_info, print_freq, logger):
with torch.no_grad():
(loss, acc1, acc5) = procedure(xloader, teacher, network, criterion, None, None, 'valid', optim_config, extra_info, print_freq, logger)
return (loss, acc1, acc5)
|
def loss_KD_fn(criterion, student_logits, teacher_logits, studentFeatures, teacherFeatures, targets, alpha, temperature):
basic_loss = (criterion(student_logits, targets) * (1.0 - alpha))
log_student = F.log_softmax((student_logits / temperature), dim=1)
sof_teacher = F.softmax((teacher_logits / temperatu... |
def procedure(xloader, teacher, network, criterion, scheduler, optimizer, mode, config, extra_info, print_freq, logger):
(data_time, batch_time, losses, top1, top5) = (AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter(), AverageMeter())
(Ttop1, Ttop5) = (AverageMeter(), AverageMeter())
if (mode... |
def prepare_seed(rand_seed):
random.seed(rand_seed)
np.random.seed(rand_seed)
torch.manual_seed(rand_seed)
torch.cuda.manual_seed(rand_seed)
torch.cuda.manual_seed_all(rand_seed)
|
def prepare_logger(xargs):
args = copy.deepcopy(xargs)
from xautodl.log_utils import Logger
logger = Logger(args.save_dir, args.rand_seed)
logger.log('Main Function with logger : {:}'.format(logger))
logger.log('Arguments : -------------------------------')
for (name, value) in args._get_kwarg... |
def get_machine_info():
info = 'Python Version : {:}'.format(sys.version.replace('\n', ' '))
info += '\nPillow Version : {:}'.format(PIL.__version__)
info += '\nPyTorch Version : {:}'.format(torch.__version__)
info += '\ncuDNN Version : {:}'.format(torch.backends.cudnn.version())
info += '... |
def save_checkpoint(state, filename, logger):
if osp.isfile(filename):
if hasattr(logger, 'log'):
logger.log('Find {:} exist, delete is at first before saving'.format(filename))
os.remove(filename)
torch.save(state, filename)
assert osp.isfile(filename), 'save filename : {:} fa... |
def copy_checkpoint(src, dst, logger):
if osp.isfile(dst):
if hasattr(logger, 'log'):
logger.log('Find {:} exist, delete is at first before saving'.format(dst))
os.remove(dst)
copyfile(src, dst)
if hasattr(logger, 'log'):
logger.log('copy the file from {:} into {:}'.for... |
def has_categorical(space_or_value, x):
if isinstance(space_or_value, Space):
return space_or_value.has(x)
else:
return (space_or_value == x)
|
def has_continuous(space_or_value, x):
if isinstance(space_or_value, Space):
return space_or_value.has(x)
else:
return (abs((space_or_value - x)) <= _EPS)
|
def is_determined(space_or_value):
if isinstance(space_or_value, Space):
return space_or_value.determined
else:
return True
|
def get_determined_value(space_or_value):
if (not is_determined(space_or_value)):
raise ValueError('This input is not determined: {:}'.format(space_or_value))
if isinstance(space_or_value, Space):
if isinstance(space_or_value, Continuous):
return space_or_value.lower
elif i... |
def get_max(space_or_value):
if isinstance(space_or_value, Integer):
return max(space_or_value.candidates)
elif isinstance(space_or_value, Continuous):
return space_or_value.upper
elif isinstance(space_or_value, Categorical):
values = []
for index in range(len(space_or_valu... |
def get_min(space_or_value):
if isinstance(space_or_value, Integer):
return min(space_or_value.candidates)
elif isinstance(space_or_value, Continuous):
return space_or_value.lower
elif isinstance(space_or_value, Categorical):
values = []
for index in range(len(space_or_valu... |
class Space(metaclass=abc.ABCMeta):
'Basic search space describing the set of possible candidate values for hyperparameter.\n All search space must inherit from this basic class.\n '
def __init__(self):
self._last_sample = None
self._last_abstract = None
@abc.abstractproperty
d... |
class VirtualNode(Space):
'For a nested search space, we represent it as a tree structure.\n\n For example,\n '
def __init__(self, id=None, value=None):
super(VirtualNode, self).__init__()
self._id = id
self._value = value
self._attributes = OrderedDict()
@property
... |
class Categorical(Space):
'A space contains the categorical values.\n It can be a nested space, which means that the candidate in this space can also be a search space.\n '
def __init__(self, *data, default: Optional[int]=None):
super(Categorical, self).__init__()
self._candidates = [*d... |
class Integer(Categorical):
'A space contains the integer values.'
def __init__(self, lower: int, upper: int, default: Optional[int]=None):
if ((not isinstance(lower, int)) or (not isinstance(upper, int))):
raise ValueError('The lower [{:}] and uppwer [{:}] must be int.'.format(lower, upp... |
class Continuous(Space):
'A space contains the continuous values.'
def __init__(self, lower: float, upper: float, default: Optional[float]=None, log: bool=False, eps: float=_EPS):
super(Continuous, self).__init__()
self._lower = lower
self._upper = upper
self._default = defaul... |
def train_or_test_epoch(xloader, model, loss_fn, metric_fn, is_train, optimizer, device):
if is_train:
model.train()
else:
model.eval()
(score_meter, loss_meter) = (AverageMeter(), AverageMeter())
for (ibatch, (feats, labels)) in enumerate(xloader):
(feats, labels) = (feats.to(... |
class QuantTransformer(Model):
'Transformer-based Quant Model'
def __init__(self, net_config=None, opt_config=None, metric='', GPU=0, seed=None, **kwargs):
self.logger = get_module_logger('QuantTransformer')
self.logger.info('QuantTransformer PyTorch version...')
self.net_config = (ne... |
def obtain_accuracy(output, target, topk=(1,)):
'Computes the precision@k for the specified values of k'
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred))
res = []
for k in ... |
def count_parameters_in_MB(model):
return count_parameters(model, 'mb', deprecated=True)
|
def count_parameters(model_or_parameters, unit='mb', deprecated=False):
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 = model_or_parameters.numel()
elif i... |
def get_model_infos(model, shape):
model = add_flops_counting_methods(model)
model.eval()
cache_inputs = torch.rand(*shape)
if next(model.parameters()).is_cuda:
cache_inputs = cache_inputs.cuda()
with torch.no_grad():
_____ = model(cache_inputs)
FLOPs = (compute_average_flops_c... |
def add_flops_counting_methods(model):
model.__batch_counter__ = 0
add_batch_counter_hook_function(model)
model.apply(add_flops_counter_variable_or_reset)
model.apply(add_flops_counter_hook_function)
return model
|
def compute_average_flops_cost(model):
'\n A method that will be available after add_flops_counting_methods() is called on a desired net object.\n Returns current mean flops consumption per image.\n '
batches_count = model.__batch_counter__
flops_sum = 0
for module in model.modules():
... |
def pool_flops_counter_hook(pool_module, inputs, output):
batch_size = inputs[0].size(0)
kernel_size = pool_module.kernel_size
(out_C, output_height, output_width) = output.shape[1:]
assert (out_C == inputs[0].size(1)), '{:} vs. {:}'.format(out_C, inputs[0].size())
overall_flops = (((((batch_size ... |
def self_calculate_flops_counter_hook(self_module, inputs, output):
overall_flops = self_module.calculate_flop_self(inputs[0].shape, output.shape)
self_module.__flops__ += overall_flops
|
def fc_flops_counter_hook(fc_module, inputs, output):
batch_size = inputs[0].size(0)
(xin, xout) = (fc_module.in_features, fc_module.out_features)
assert ((xin == inputs[0].size(1)) and (xout == output.size(1))), 'IO=({:}, {:})'.format(xin, xout)
overall_flops = ((batch_size * xin) * xout)
if (fc_... |
def conv1d_flops_counter_hook(conv_module, inputs, outputs):
batch_size = inputs[0].size(0)
outL = outputs.shape[(- 1)]
[kernel] = conv_module.kernel_size
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups = conv_module.groups
conv_per_position_flops = (((... |
def conv2d_flops_counter_hook(conv_module, inputs, output):
batch_size = inputs[0].size(0)
(output_height, output_width) = output.shape[2:]
(kernel_height, kernel_width) = conv_module.kernel_size
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups = conv_module... |
def batch_counter_hook(module, inputs, output):
inputs = inputs[0]
batch_size = inputs.shape[0]
module.__batch_counter__ += batch_size
|
def add_batch_counter_hook_function(module):
if (not hasattr(module, '__batch_counter_handle__')):
handle = module.register_forward_hook(batch_counter_hook)
module.__batch_counter_handle__ = handle
|
def add_flops_counter_variable_or_reset(module):
if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear) or isinstance(module, torch.nn.Conv1d) or isinstance(module, torch.nn.AvgPool2d) or isinstance(module, torch.nn.MaxPool2d) or hasattr(module, 'calculate_flop_self')):
module.__fl... |
def add_flops_counter_hook_function(module):
if isinstance(module, torch.nn.Conv2d):
if (not hasattr(module, '__flops_handle__')):
handle = module.register_forward_hook(conv2d_flops_counter_hook)
module.__flops_handle__ = handle
elif isinstance(module, torch.nn.Conv1d):
... |
def remove_hook_function(module):
hookers = ['__batch_counter_handle__', '__flops_handle__']
for hooker in hookers:
if hasattr(module, hooker):
handle = getattr(module, hooker)
handle.remove()
keys = (['__flops__', '__batch_counter__', '__flops__'] + hookers)
for ckey i... |
class GPUManager():
queries = ('index', 'gpu_name', 'memory.free', 'memory.used', 'memory.total', 'power.draw', 'power.limit')
def __init__(self):
all_gpus = self.query_gpu(False)
def get_info(self, ctype):
cmd = 'nvidia-smi --query-gpu={} --format=csv,noheader'.format(ctype)
lin... |
def get_md5_file(file_path, post_truncated=5):
md5_hash = hashlib.md5()
if os.path.exists(file_path):
xfile = open(file_path, 'rb')
content = xfile.read()
md5_hash.update(content)
digest = md5_hash.hexdigest()
else:
raise ValueError('[get_md5_file] {:} does not exis... |
def evaluate_one_shot(model, xloader, api, cal_mode, seed=111):
print('This is an old version of codes to use NAS-Bench-API, and should be modified to align with the new version. Please contact me for more details if you use this function.')
weights = deepcopy(model.state_dict())
model.train(cal_mode)
... |
class QResult():
'A class to maintain the results of a qlib experiment.'
def __init__(self, name):
self._result = defaultdict(list)
self._name = name
self._recorder_paths = []
self._date2ICs = []
def append(self, key, value):
self._result[key].append(value)
d... |
def split_str2indexes(string: str, max_check: int, length_limit=5):
if (not isinstance(string, str)):
raise ValueError('Invalid scheme for {:}'.format(string))
srangestr = ''.join(string.split())
indexes = set()
for srange in srangestr.split(','):
srange = srange.split('-')
if ... |
def show_mean_var(xlist):
values = np.array(xlist)
print(((('{:.2f}'.format(values.mean()) + '$_{{\\pm}{') + '{:.2f}'.format(values.std())) + '}}$'))
|
def optimize_fn(xs, ys, device='cpu', max_iter=2000, max_lr=0.1):
xs = torch.FloatTensor(xs).view((- 1), 1).to(device)
ys = torch.FloatTensor(ys).view((- 1), 1).to(device)
model = SuperSequential(SuperSimpleNorm(xs.mean().item(), xs.std().item()), SuperLinear(1, 200), torch.nn.LeakyReLU(), SuperLinear(200... |
def evaluate_fn(model, xs, ys, loss_fn, device='cpu'):
with torch.no_grad():
inputs = torch.FloatTensor(xs).view((- 1), 1).to(device)
ys = torch.FloatTensor(ys).view((- 1), 1).to(device)
preds = model(inputs)
loss = loss_fn(preds, ys)
preds = preds.view((- 1)).cpu().numpy()... |
class AnonymousAxis():
'Important thing: all instances of this class are not equal to each other'
def __init__(self, value: str):
self.value = int(value)
if (self.value <= 1):
if (self.value == 1):
raise EinopsError('No need to create anonymous axis of length 1. Re... |
class ParsedExpression():
"\n non-mutable structure that contains information about one side of expression (e.g. 'b c (h w)')\n and keeps some information important for downstream\n "
def __init__(self, expression):
self.identifiers = set()
self.has_non_unitary_anonymous_axes = False... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.