code stringlengths 17 6.64M |
|---|
def _key_is_deprecated(full_key):
if (full_key in _DEPRECATED_KEYS):
logger.warn('Deprecated config key (ignoring): {}'.format(full_key))
return True
return False
|
def _key_is_renamed(full_key):
return (full_key in _RENAMED_KEYS)
|
def _raise_key_rename_error(full_key):
new_key = _RENAMED_KEYS[full_key]
if isinstance(new_key, tuple):
msg = (' Note: ' + new_key[1])
new_key = new_key[0]
else:
msg = ''
raise KeyError('Key {} was renamed to {}; please update your config.{}'.format(full_key, new_key, msg))
|
def _decode_cfg_value(v):
'Decodes a raw config value (e.g., from a yaml config files or command\n line argument) into a Python object.\n '
if isinstance(v, dict):
return AttrDict(v)
try:
v = literal_eval(v)
except ValueError:
pass
except SyntaxError:
pass
... |
def _check_and_coerce_cfg_value_type(value_a, value_b, key, full_key):
'Checks that `value_a`, which is intended to replace `value_b` is of the\n right type. The type is correct if it matches exactly or is one of a few\n cases in which the type can be easily coerced.\n '
type_b = type(value_b)
ty... |
def save_object(obj, file_name):
'Save a Python object by pickling it.'
file_name = os.path.abspath(file_name)
with open(file_name, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
|
def cache_url(url_or_file, cache_dir):
'Download the file specified by the URL to the cache_dir and return the\n path to the cached file. If the argument is not a URL, simply return it as\n is.\n '
is_url = (re.match('^(?:http)s?://', url_or_file, re.IGNORECASE) is not None)
if (not is_url):
... |
def assert_cache_file_is_ok(url, file_path):
'Check that cache file has the correct hash.'
cache_file_md5sum = _get_file_md5sum(file_path)
ref_md5sum = _get_reference_md5sum(url)
assert (cache_file_md5sum == ref_md5sum), 'Target URL {} appears to be downloaded to the local cache file {}, but the md5 h... |
def _progress_bar(count, total):
'Report download progress.\n Credit:\n https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console/27871113\n '
bar_len = 60
filled_len = int(round(((bar_len * count) / float(total))))
percents = round(((100.0 * count) / float(total)), 1)
... |
def download_url(url, dst_file_path, chunk_size=8192, progress_hook=_progress_bar):
'Download url and write it to dst_file_path.\n Credit:\n https://stackoverflow.com/questions/2028517/python-urllib2-progress-hook\n '
response = urllib.request.urlopen(url)
total_size = response.info().getheader('... |
def _get_file_md5sum(file_name):
'Compute the md5 hash of a file.'
hash_obj = hashlib.md5()
with open(file_name, 'r') as f:
hash_obj.update(f.read())
return hash_obj.hexdigest()
|
def _get_reference_md5sum(url):
"By convention the md5 hash for url is stored in url + '.md5sum'."
url_md5sum = (url + '.md5sum')
md5sum = urllib.request.urlopen(url_md5sum).read().strip()
return md5sum
|
class CosineRestartAnnealingLR(object):
def __init__(self, optimizer, T_max, lr_period, lr_step, eta_min=0, last_step=(- 1), use_warmup=False, warmup_mode='linear', warmup_steps=0, warmup_startlr=0, warmup_targetlr=0, use_restart=False):
self.use_warmup = use_warmup
self.warmup_mode = warmup_mode... |
def get_lr_scheduler(config, optimizer, num_examples=None, batch_size=None):
if (num_examples is None):
num_examples = config.data.num_examples
epoch_steps = ((num_examples // batch_size) + 1)
if config.optim.use_multi_stage:
max_steps = (epoch_steps * config.optim.multi_stage.stage_epochs... |
def comp_multadds(model, input_size=(3, 224, 224)):
input_size = ((1,) + tuple(input_size))
model = model.cuda()
input_data = torch.randn(input_size).cuda()
model = add_flops_counting_methods(model)
model.start_flops_count()
with torch.no_grad():
_ = model(input_data)
mult_adds = (... |
def comp_multadds_fw(model, input_data, use_gpu=True):
model = add_flops_counting_methods(model)
if use_gpu:
model = model.cuda()
model.start_flops_count()
with torch.no_grad():
output_data = model(input_data)
mult_adds = (model.compute_average_flops_cost() / 1000000.0)
return ... |
def add_flops_counting_methods(net_main_module):
'Adds flops counting functions to an existing model. After that\n the flops count should be activated and the model should be run on an input\n image.\n Example:\n fcn = add_flops_counting_methods(fcn)\n fcn = fcn.cuda().train()\n fcn.start_flops_... |
def compute_average_flops_cost(self):
'\n A method that will be available after add_flops_counting_methods() is called\n 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 called\n 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 called\n 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 called\n 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) or isinstance(module, torch.nn.Linear)):
module.__mask__ = mask
module.apply(add_flops_mask_func)
|
def remove_flops_mask(module):
module.apply(add_flops_mask_variable_or_reset)
|
def conv_flops_counter_hook(conv_module, input, output):
input = input[0]
batch_size = input.shape[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
conv_... |
def linear_flops_counter_hook(linear_module, input, output):
input = input[0]
batch_size = input.shape[0]
overall_flops = ((linear_module.in_features * linear_module.out_features) * batch_size)
linear_module.__flops__ += overall_flops
|
def batch_counter_hook(module, input, output):
input = input[0]
batch_size = input.shape[0]
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 (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)):
module.__flops__ = 0
|
def add_flops_counter_hook_function(module):
if isinstance(module, torch.nn.Conv2d):
if hasattr(module, '__flops_handle__'):
return
handle = module.register_forward_hook(conv_flops_counter_hook)
module.__flops_handle__ = handle
elif isinstance(module, torch.nn.Linear):
... |
def remove_flops_counter_hook_function(module):
if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)):
if hasattr(module, '__flops_handle__'):
module.__flops_handle__.remove()
del module.__flops_handle__
|
def add_flops_mask_variable_or_reset(module):
if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)):
module.__mask__ = None
|
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.cur = val
self.sum += (val * n)
self.cnt += n
self.avg = (self.sum / self.cnt)
|
def accuracy(output, target, topk=(1, 5)):
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.reshape(1, (- 1)).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape((- 1)).float().su... |
def count_parameters_in_MB(model):
return (np.sum((np.prod(v.size()) for (name, v) in model.named_parameters() if ('aux' not in name))) / 1000000.0)
|
def save_checkpoint(state, is_best, save):
filename = os.path.join(save, 'checkpoint.pth.tar')
torch.save(state, filename)
if is_best:
best_filename = os.path.join(save, 'model_best.pth.tar')
shutil.copyfile(filename, best_filename)
|
def save(model, model_path):
torch.save(model.state_dict(), model_path)
|
def load_net_config(path):
with open(path, 'r') as f:
net_config = ''
while True:
line = f.readline().strip()
if ('net_type' in line):
net_type = line.split(': ')[(- 1)]
break
else:
net_config += line
return (n... |
def load_model(model, model_path):
logging.info(('Start loading the model from ' + model_path))
if ('http' in model_path):
model_addr = model_path
model_path = model_path.split('/')[(- 1)]
if os.path.isfile(model_path):
os.system(('rm ' + model_path))
os.system(('wg... |
def create_exp_dir(path):
if (not os.path.exists(path)):
os.mkdir(path)
print('Experiment dir : {}'.format(path))
|
def cross_entropy_with_label_smoothing(pred, target, label_smoothing=0.0):
'\n Label smoothing implementation.\n This function is taken from https://github.com/MIT-HAN-LAB/ProxylessNAS/blob/master/proxyless_nas/utils.py\n '
logsoftmax = nn.LogSoftmax().cuda()
n_classes = pred.size(1)
target =... |
def parse_net_config(net_config):
str_configs = net_config.split('|')
return [eval(str_config) for str_config in str_configs]
|
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
|
def set_logging(save_path, log_name='log.txt'):
log_format = '%(asctime)s %(message)s'
date_format = '%m/%d %H:%M:%S'
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt=date_format)
fh = logging.FileHandler(os.path.join(save_path, log_name))
fh.setFormatter(loggi... |
def create_save_dir(save_path, job_name):
if (job_name != ''):
job_name = (time.strftime('%Y%m%d-%H%M%S-') + job_name)
save_path = os.path.join(save_path, job_name)
create_exp_dir(save_path)
os.system(('cp -r ./* ' + save_path))
save_path = os.path.join(save_path, 'output')... |
def latency_measure(module, input_size, batch_size, meas_times, mode='gpu'):
assert (mode in ['gpu', 'cpu'])
latency = []
module.eval()
input_size = ((batch_size,) + tuple(input_size))
input_data = torch.randn(input_size)
if (mode == 'gpu'):
input_data = input_data.cuda()
modul... |
def latency_measure_fw(module, input_data, meas_times):
latency = []
module.eval()
for i in range(meas_times):
with torch.no_grad():
start = time.time()
output_data = module(input_data)
torch.cuda.synchronize()
if (i >= 100):
latency.... |
def record_topk(k, rec_list, data, comp_attr, check_attr):
def get_insert_idx(orig_list, data, comp_attr):
start = 0
end = len(orig_list)
while (start < end):
mid = ((start + end) // 2)
if (data[comp_attr] < orig_list[mid][comp_attr]):
start = (mid ... |
class BilevelDataset(Dataset):
def __init__(self, dataset):
'\n We will split the data into a train split and a validation split\n and return one image from each split as a single observation.\n Args:\n dataset: PyTorch Dataset object\n '
inds = np.arange(le... |
def download_from_s3(s3_bucket, task, download_dir):
s3 = boto3.client('s3')
if (task == 'smnist'):
data_files = ['s2_mnist.gz']
s3_folder = 'spherical'
if (task == 'scifar100'):
data_files = ['s2_cifar100.gz']
s3_folder = 'spherical'
elif (task == 'sEMG'):
data... |
class ImageNet12(object):
def __init__(self, trainFolder, testFolder, num_workers=8, pin_memory=True, size_images=224, scaled_size=256, type_of_data_augmentation='rand_scale', data_config=None):
self.data_config = data_config
self.trainFolder = trainFolder
self.testFolder = testFolder
... |
class Datum(object):
def __init__(self, shape=None, image=None, label=None):
self.shape = shape
self.image = image
self.label = label
def SerializeToString(self, img=None):
image_data = self.image.astype(np.uint8).tobytes()
label_data = np.uint16(self.label).tobytes()... |
def create_dataset(output_path, image_folder, image_list, image_size):
image_name_list = [i.strip() for i in open(image_list)]
n_samples = len(image_name_list)
env = lmdb.open(output_path, map_size=1099511627776, meminit=False, map_async=True)
txn = env.begin(write=True)
classes = [d for d in os.l... |
class Datum(object):
def __init__(self, shape=None, image=None, label=None):
self.shape = shape
self.image = image
self.label = label
def SerializeToString(self):
image_data = self.image.astype(np.uint8).tobytes()
label_data = np.uint16(self.label).tobytes()
r... |
class DatasetFolder(data.Dataset):
'\n Args:\n root (string): Root directory path.\n transform (callable, optional): A function/transform that takes in\n a sample and returns a transformed version.\n E.g, ``transforms.RandomCrop`` for images.\n target_transform (calla... |
class ImageFolder(DatasetFolder):
def __init__(self, root, list_path, transform=None, target_transform=None, patch_dataset=False):
super(ImageFolder, self).__init__(root, list_path, transform=transform, target_transform=target_transform, patch_dataset=patch_dataset)
self.imgs = self.samples
|
def get_list(data_path, output_path):
for split in os.listdir(data_path):
split_path = os.path.join(data_path, split)
if (not os.path.isdir(split_path)):
continue
f = open(os.path.join(output_path, (split + '_datalist')), 'a+')
for sub in os.listdir(split_path):
... |
def get_list(data_path, output_path):
for split in os.listdir(data_path):
if (split == 'train'):
split_path = os.path.join(data_path, split)
if (not os.path.isdir(split_path)):
continue
f_train = open(os.path.join(output_path, (split + '_datalist')), 'w'... |
class Lighting(object):
'Lighting noise(AlexNet - style PCA - based noise)'
def __init__(self, alphastd, eigval, eigvec):
self.alphastd = alphastd
self.eigval = eigval
self.eigvec = eigvec
def __call__(self, img):
if (self.alphastd == 0):
return img
al... |
class RandomScale(object):
'ResNet style data augmentation'
def __init__(self, minSize, maxSize):
self.minSize = minSize
self.maxSize = maxSize
def __call__(self, img):
targetSz = int(round(random.uniform(self.minSize, self.maxSize)))
return F.resize(img, targetSz)
|
def generate_arch(task, net_type, threshold_arch):
update_cfg_from_cfg(search_cfg, cfg)
if (task in ['cifar10', 'cifar100']):
merge_cfg_from_file('configs/cifar_random_search_cfg_resnet.yaml', cfg)
input_shape = (3, 32, 32)
elif (task in ['scifar100', 'smnist']):
merge_cfg_from_fil... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class DenseNASSearchTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
update_cfg_from_cfg(search_cfg, cfg)
if (self.hparams.task in ['ci... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class DenseNASSearchTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
update_cfg_from_cfg(search_cfg, cfg)
if (self.hparams.task == 'aud... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class DenseNASTrainTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
pprint.pformat(config)
cudnn.benchmark = True
cudnn.enabled... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class DenseNASTrainTrial(PyTorchTrial):
def __init__(self, trial_context: PyTorchTrialContext) -> None:
self.context = trial_context
self.hparams = AttrDict(trial_context.get_hparams())
self.last_epoch = 0
pprint.pformat(config)
cudnn.benchmark = True
cudnn.enabled... |
class MixedOp(nn.Module):
def __init__(self, dropped_mixed_ops, softmax_temp=1.0):
super(MixedOp, self).__init__()
self.softmax_temp = softmax_temp
self._ops = nn.ModuleList()
for op in dropped_mixed_ops:
self._ops.append(op)
def forward(self, x, alphas, branch_in... |
class HeadLayer(nn.Module):
def __init__(self, dropped_mixed_ops, softmax_temp=1.0):
super(HeadLayer, self).__init__()
self.head_branches = nn.ModuleList()
for mixed_ops in dropped_mixed_ops:
self.head_branches.append(MixedOp(mixed_ops, softmax_temp))
def forward(self, in... |
class StackLayers(nn.Module):
def __init__(self, num_block_layers, dropped_mixed_ops, softmax_temp=1.0):
super(StackLayers, self).__init__()
if (num_block_layers != 0):
self.stack_layers = nn.ModuleList()
for i in range(num_block_layers):
self.stack_layers.... |
class Block(nn.Module):
def __init__(self, num_block_layers, dropped_mixed_ops, softmax_temp=1.0):
super(Block, self).__init__()
self.head_layer = HeadLayer(dropped_mixed_ops[0], softmax_temp)
self.stack_layers = StackLayers(num_block_layers, dropped_mixed_ops[1], softmax_temp)
def f... |
class Dropped_Network(nn.Module):
def __init__(self, super_model, alpha_head_index=None, alpha_stack_index=None, softmax_temp=1.0):
super(Dropped_Network, self).__init__()
self.softmax_temp = softmax_temp
self.input_block = super_model.input_block
if hasattr(super_model, 'head_blo... |
class Block(nn.Module):
def __init__(self, in_ch, block_ch, head_op, stack_ops, stride):
super(Block, self).__init__()
self.head_layer = OPS[head_op](in_ch, block_ch, stride, affine=True, track_running_stats=True)
modules = []
for stack_op in stack_ops:
modules.append(... |
class Conv1_1_Block(nn.Module):
def __init__(self, in_ch, block_ch):
super(Conv1_1_Block, self).__init__()
self.conv1_1 = nn.Sequential(nn.Conv2d(in_channels=in_ch, out_channels=block_ch, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm2d(block_ch), nn.ReLU6(inplace=True))
def f... |
class MBV2_Net(nn.Module):
def __init__(self, net_config, task='cifar10', config=None):
'\n net_config=[[in_ch, out_ch], head_op, [stack_ops], num_stack_layers, stride]\n '
super(MBV2_Net, self).__init__()
self.config = config
self.net_config = parse_net_config(net_c... |
class RES_Net(nn.Module):
def __init__(self, net_config, task='cifar10', config=None):
'\n net_config=[[in_ch, out_ch], head_op, [stack_ops], num_stack_layers, stride]\n '
super(RES_Net, self).__init__()
self.config = config
self.net_config = parse_net_config(net_con... |
class MixedOp(nn.Module):
def __init__(self, C_in, C_out, stride, primitives):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in primitives:
op = OPS[primitive](C_in, C_out, stride, affine=False, track_running_stats=True)
self._ops.append... |
class HeadLayer(nn.Module):
def __init__(self, in_chs, ch, strides, config):
super(HeadLayer, self).__init__()
self.head_branches = nn.ModuleList()
for (in_ch, stride) in zip(in_chs, strides):
self.head_branches.append(MixedOp(in_ch, ch, stride, config.search_params.PRIMITIVES... |
class StackLayers(nn.Module):
def __init__(self, ch, num_block_layers, config, primitives):
super(StackLayers, self).__init__()
if (num_block_layers != 0):
self.stack_layers = nn.ModuleList()
for i in range(num_block_layers):
self.stack_layers.append(MixedO... |
class Block(nn.Module):
def __init__(self, in_chs, block_ch, strides, num_block_layers, config):
super(Block, self).__init__()
assert (len(in_chs) == len(strides))
self.head_layer = HeadLayer(in_chs, block_ch, strides, config)
self.stack_layers = StackLayers(block_ch, num_block_la... |
class Conv1_1_Branch(nn.Module):
def __init__(self, in_ch, block_ch):
super(Conv1_1_Branch, self).__init__()
self.conv1_1 = nn.Sequential(nn.Conv2d(in_channels=in_ch, out_channels=block_ch, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm2d(block_ch, affine=False, track_running_stats... |
class Conv1_1_Block(nn.Module):
def __init__(self, in_chs, block_ch):
super(Conv1_1_Block, self).__init__()
self.conv1_1_branches = nn.ModuleList()
for in_ch in in_chs:
self.conv1_1_branches.append(Conv1_1_Branch(in_ch, block_ch))
def forward(self, inputs, betas, block_su... |
class Network(nn.Module):
def __init__(self, init_ch, dataset, config):
super(Network, self).__init__()
self.config = config
self._C_input = init_ch
self._head_dim = self.config.optim.head_dim
self._dataset = dataset
self._num_classes = 10
self.initialize()... |
class Network(BaseSearchSpace):
def __init__(self, init_ch, dataset, config):
super(Network, self).__init__(init_ch, dataset, config)
self.input_block = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=self._C_input, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(self._C_input... |
class Network(BaseSearchSpace):
def __init__(self, init_ch, dataset, config, groups=1, base_width=64, dilation=1, norm_layer=None):
super(Network, self).__init__(init_ch, dataset, config)
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
if ((groups != 1) or (base_width != ... |
class BaseArchGenerate(object):
def __init__(self, super_network, config):
self.config = config
self.num_blocks = len(super_network.block_chs)
self.super_chs = super_network.block_chs
self.input_configs = super_network.input_configs
def update_arch_params(self, betas, head_al... |
class ArchGenerate(BaseArchGenerate):
def __init__(self, super_network, config):
super(ArchGenerate, self).__init__(super_network, config)
def derive_archs(self, betas, head_alphas, stack_alphas, if_display=True):
self.update_arch_params(betas, head_alphas, stack_alphas)
derived_arch... |
class ArchGenerate(BaseArchGenerate):
def __init__(self, super_network, config):
super(ArchGenerate, self).__init__(super_network, config)
def derive_archs(self, betas, head_alphas, stack_alphas, if_display=True):
self.update_arch_params(betas, head_alphas, stack_alphas)
derived_arch... |
class Optimizer(object):
def __init__(self, model, criterion, config):
self.config = config
self.weight_sample_num = self.config.search_params.weight_sample_num
self.criterion = criterion
self.Dropped_Network = (lambda model: Dropped_Network(model, softmax_temp=config.search_param... |
class Trainer(object):
def __init__(self, train_data, val_data, optimizer=None, criterion=None, scheduler=None, config=None, report_freq=None):
self.train_data = train_data
self.val_data = val_data
self.optimizer = optimizer
self.criterion = criterion
self.scheduler = sche... |
class SearchTrainer(object):
def __init__(self, train_data, val_data, search_optim, criterion, scheduler, config, args):
self.train_data = train_data
self.val_data = val_data
self.search_optim = search_optim
self.criterion = criterion
self.scheduler = scheduler
sel... |
class AttrDict(dict):
IMMUTABLE = '__immutable__'
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__[AttrDict.IMMUTABLE] = False
def __getattr__(self, name):
if (name in self.__dict__):
return self.__dict__[name]
... |
def load_cfg(cfg_to_load):
'Wrapper around yaml.load used for maintaining backward compatibility'
if isinstance(cfg_to_load, IOBase):
cfg_to_load = ''.join(cfg_to_load.readlines())
return yaml.load(cfg_to_load)
|
def load_cfg_to_dict(cfg_filename):
with open(cfg_filename, 'r') as f:
yaml_cfg = load_cfg(f)
return yaml_cfg
|
def merge_cfg_from_file(cfg_filename, global_config):
'Load a yaml config file and merge it into the global config.'
with open(cfg_filename, 'r') as f:
yaml_cfg = AttrDict(load_cfg(f))
_merge_a_into_b(yaml_cfg, global_config)
|
def merge_cfg_from_cfg(cfg_other, global_config):
'Merge `cfg_other` into the global config.'
_merge_a_into_b(cfg_other, global_config)
|
def update_cfg_from_file(cfg_filename, global_config):
with open(cfg_filename, 'r') as f:
yaml_cfg = AttrDict(load_cfg(f))
update_cfg_from_cfg(yaml_cfg, global_config)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.