code stringlengths 17 6.64M |
|---|
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... |
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 evaluate_all_datasets(arch: Text, datasets: List[Text], xpaths: List[Text], splits: List[Text], config_path: Text, seed: int, raw_arch_config, workers, logger):
(machine_info, raw_arch_config) = (get_machine_info(), deepcopy(raw_arch_config))
all_infos = {'info': machine_info}
all_dataset_keys = []
... |
def main(save_dir: Path, workers: int, datasets: List[Text], xpaths: List[Text], splits: List[int], seeds: List[int], nets: List[str], opt_config: Dict[(Text, Any)], to_evaluate_indexes: tuple, cover_mode: bool, arch_config: Dict[(Text, Any)]):
log_dir = (save_dir / 'logs')
log_dir.mkdir(parents=True, exist_o... |
def train_single_model(save_dir, workers, datasets, xpaths, splits, use_less, seeds, model_str, arch_config):
assert torch.cuda.is_available(), 'CUDA is not available.'
torch.backends.cudnn.enabled = True
torch.backends.cudnn.deterministic = True
save_dir = ((Path(save_dir) / 'specifics') / '{:}-{:}-{... |
def generate_meta_info(save_dir, max_node, divide=40):
aa_nas_bench_ss = get_search_spaces('cell', 'nas-bench-201')
archs = CellStructure.gen_all(aa_nas_bench_ss, max_node, False)
print('There are {:} archs vs {:}.'.format(len(archs), (len(aa_nas_bench_ss) ** (((max_node - 1) * max_node) / 2))))
rando... |
def traverse_net(max_node):
aa_nas_bench_ss = get_search_spaces('cell', 'nats-bench')
archs = CellStructure.gen_all(aa_nas_bench_ss, max_node, False)
print('There are {:} archs vs {:}.'.format(len(archs), (len(aa_nas_bench_ss) ** (((max_node - 1) * max_node) / 2))))
random.seed(88)
random.shuffle(... |
def filter_indexes(xlist, mode, save_dir, seeds):
all_indexes = []
for index in xlist:
if (mode == 'cover'):
all_indexes.append(index)
else:
for seed in seeds:
temp_path = (save_dir / 'arch-{:06d}-seed-{:04d}.pth'.format(index, seed))
if ... |
def create_result_count(used_seed: int, dataset: Text, arch_config: Dict[(Text, Any)], results: Dict[(Text, Any)], dataloader_dict: Dict[(Text, Any)]) -> ResultsCount:
xresult = ResultsCount(dataset, results['net_state_dict'], results['train_acc1es'], results['train_losses'], results['param'], results['flop'], ar... |
def account_one_arch(arch_index, arch_str, checkpoints, datasets, dataloader_dict):
information = ArchResults(arch_index, arch_str)
for checkpoint_path in checkpoints:
checkpoint = torch.load(checkpoint_path, map_location='cpu')
used_seed = checkpoint_path.name.split('-')[(- 1)].split('.')[0]
... |
def correct_time_related_info(arch_index: int, arch_infos: Dict[(Text, ArchResults)]):
'\n cifar010_latency = (\n api.get_latency(arch_index, "cifar10-valid", hp="200")\n + api.get_latency(arch_index, "cifar10", hp="200")\n ) / 2\n cifar100_latency = api.get_latency(arch_index, "cifar100", ... |
def simplify(save_dir, save_name, nets, total, sup_config):
dataloader_dict = {}
(hps, seeds) = (['12'], set())
for hp in hps:
sub_save_dir = (save_dir / 'raw-data-{:}'.format(hp))
ckps = sorted(list(sub_save_dir.glob('arch-*-seed-*.pth')))
seed2names = defaultdict(list)
fo... |
def traverse_net(max_node):
aa_nas_bench_ss = get_search_spaces('cell', 'nats-bench')
archs = CellStructure.gen_all(aa_nas_bench_ss, max_node, False)
print('There are {:} archs vs {:}.'.format(len(archs), (len(aa_nas_bench_ss) ** (((max_node - 1) * max_node) / 2))))
random.seed(88)
random.shuffle(... |
def get_topology_config_space(search_space, max_nodes=4):
cs = ConfigSpace.ConfigurationSpace()
for i in range(1, max_nodes):
for j in range(i):
node_str = '{:}<-{:}'.format(i, j)
cs.add_hyperparameter(ConfigSpace.CategoricalHyperparameter(node_str, search_space))
return cs... |
def get_size_config_space(search_space):
cs = ConfigSpace.ConfigurationSpace()
for ilayer in range(search_space['numbers']):
node_str = 'layer-{:}'.format(ilayer)
cs.add_hyperparameter(ConfigSpace.CategoricalHyperparameter(node_str, search_space['candidates']))
return cs
|
def config2topology_func(max_nodes=4):
def config2structure(config):
genotypes = []
for i in range(1, max_nodes):
xlist = []
for j in range(i):
node_str = '{:}<-{:}'.format(i, j)
op_name = config[node_str]
xlist.append((op_na... |
def config2size_func(search_space):
def config2structure(config):
channels = []
for ilayer in range(search_space['numbers']):
node_str = 'layer-{:}'.format(ilayer)
channels.append(str(config[node_str]))
return ':'.join(channels)
return config2structure
|
class MyWorker(Worker):
def __init__(self, *args, convert_func=None, dataset=None, api=None, **kwargs):
super().__init__(*args, **kwargs)
self.convert_func = convert_func
self._dataset = dataset
self._api = api
self.total_times = []
self.trajectory = []
def co... |
def main(xargs, api, api_full):
torch.set_num_threads(4)
prepare_seed(xargs.rand_seed)
logger = prepare_logger(args)
logger.log('{:} use api : {:}'.format(time_string(), api))
api.reset_time()
search_space = get_search_spaces(xargs.search_space, 'nats-bench')
if (xargs.search_space == 'tss... |
def get_topology_config_space(search_space, max_nodes=4):
cs = ConfigSpace.ConfigurationSpace()
for i in range(1, max_nodes):
for j in range(i):
node_str = '{:}<-{:}'.format(i, j)
cs.add_hyperparameter(ConfigSpace.CategoricalHyperparameter(node_str, search_space))
return cs... |
def get_size_config_space(search_space):
cs = ConfigSpace.ConfigurationSpace()
for ilayer in range(search_space['numbers']):
node_str = 'layer-{:}'.format(ilayer)
cs.add_hyperparameter(ConfigSpace.CategoricalHyperparameter(node_str, search_space['candidates']))
return cs
|
def config2topology_func(max_nodes=4):
def config2structure(config):
genotypes = []
for i in range(1, max_nodes):
xlist = []
for j in range(i):
node_str = '{:}<-{:}'.format(i, j)
op_name = config[node_str]
xlist.append((op_na... |
def config2size_func(search_space):
def config2structure(config):
channels = []
for ilayer in range(search_space['numbers']):
node_str = 'layer-{:}'.format(ilayer)
channels.append(str(config[node_str]))
return ':'.join(channels)
return config2structure
|
class MyWorker(Worker):
def __init__(self, *args, convert_func=None, dataset=None, api=None, **kwargs):
super().__init__(*args, **kwargs)
self.convert_func = convert_func
self._dataset = dataset
self._api = api
self.total_times = []
self.trajectory = []
def co... |
def main(xargs, api, api_full):
torch.set_num_threads(4)
prepare_seed(xargs.rand_seed)
logger = prepare_logger(args)
logger.log('{:} use api : {:}'.format(time_string(), api))
api.reset_time()
search_space = get_search_spaces(xargs.search_space, 'nats-bench')
if (xargs.search_space == 'tss... |
def random_topology_func(op_names, max_nodes=4):
def random_architecture():
genotypes = []
for i in range(1, max_nodes):
xlist = []
for j in range(i):
node_str = '{:}<-{:}'.format(i, j)
op_name = random.choice(op_names)
xlist... |
def random_size_func(info):
def random_architecture():
channels = []
for i in range(info['numbers']):
channels.append(str(random.choice(info['candidates'])))
return ':'.join(channels)
return random_architecture
|
def main(xargs, api, api_full):
torch.set_num_threads(4)
prepare_seed(xargs.rand_seed)
logger = prepare_logger(args)
logger.log('{:} use api : {:}'.format(time_string(), api))
api.reset_time()
search_space = get_search_spaces(xargs.search_space, 'nats-bench')
if (xargs.search_space == 'tss... |
class Model(object):
def __init__(self):
self.arch = None
self.accuracy = None
def __str__(self):
'Prints a readable version of this bitstring.'
return '{:}'.format(self.arch)
|
def random_topology_func(op_names, max_nodes=4):
def random_architecture():
genotypes = []
for i in range(1, max_nodes):
xlist = []
for j in range(i):
node_str = '{:}<-{:}'.format(i, j)
op_name = random.choice(op_names)
xlist... |
def random_size_func(info):
def random_architecture():
channels = []
for i in range(info['numbers']):
channels.append(str(random.choice(info['candidates'])))
return ':'.join(channels)
return random_architecture
|
def mutate_topology_func(op_names):
'Computes the architecture for a child of the given parent architecture.\n The parent architecture is cloned and mutated to produce the child architecture. The child architecture is mutated by randomly switch one operation to another.\n '
def mutate_topology_func(par... |
def mutate_size_func(info):
'Computes the architecture for a child of the given parent architecture.\n The parent architecture is cloned and mutated to produce the child architecture. The child architecture is mutated by randomly switch one operation to another.\n '
def mutate_size_func(parent_arch):
... |
def regularized_evolution(cycles, population_size, sample_size, time_budget, random_arch, mutate_arch, api, use_proxy, dataset):
'Algorithm for regularized evolution (i.e. aging evolution).\n\n Follows "Algorithm 1" in Real et al. "Regularized Evolution for Image\n Classifier Architecture Search".\n\n Ar... |
def main(xargs, api, api_full):
torch.set_num_threads(4)
prepare_seed(xargs.rand_seed)
logger = prepare_logger(args)
search_space = get_search_spaces(xargs.search_space, 'nats-bench')
if (xargs.search_space == 'tss'):
random_arch = random_topology_func(search_space)
mutate_arch = m... |
class PolicyTopology(nn.Module):
def __init__(self, search_space, max_nodes=4):
super(PolicyTopology, self).__init__()
self.max_nodes = max_nodes
self.search_space = deepcopy(search_space)
self.edge2index = {}
for i in range(1, max_nodes):
for j in range(i):
... |
class PolicySize(nn.Module):
def __init__(self, search_space):
super(PolicySize, self).__init__()
self.candidates = search_space['candidates']
self.numbers = search_space['numbers']
self.arch_parameters = nn.Parameter((0.001 * torch.randn(self.numbers, len(self.candidates))))
... |
class ExponentialMovingAverage(object):
'Class that maintains an exponential moving average.'
def __init__(self, momentum):
self._numerator = 0
self._denominator = 0
self._momentum = momentum
def update(self, value):
self._numerator = ((self._momentum * self._numerator) +... |
def select_action(policy):
probs = policy()
m = Categorical(probs)
action = m.sample()
return (m.log_prob(action), action.cpu().tolist())
|
def main(xargs, api, api_full):
prepare_seed(xargs.rand_seed)
logger = prepare_logger(args)
search_space = get_search_spaces(xargs.search_space, 'nats-bench')
if (xargs.search_space == 'tss'):
policy = PolicyTopology(search_space)
else:
policy = PolicySize(search_space)
optimiz... |
def _concat(xs):
return torch.cat([x.view((- 1)) for x in xs])
|
def _hessian_vector_product(vector, network, criterion, base_inputs, base_targets, r=0.01):
R = (r / _concat(vector).norm())
for (p, v) in zip(network.weights, vector):
p.data.add_(R, v)
(_, logits) = network(base_inputs)
loss = criterion(logits, base_targets)
grads_p = torch.autograd.grad... |
def backward_step_unrolled(network, criterion, base_inputs, base_targets, w_optimizer, arch_inputs, arch_targets):
(_, logits) = network(base_inputs)
loss = criterion(logits, base_targets)
(LR, WD, momentum) = (w_optimizer.param_groups[0]['lr'], w_optimizer.param_groups[0]['weight_decay'], w_optimizer.par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.