code
stringlengths
17
6.64M
@provides('realnvp') def realnvp(dataset, model, use_baseline): return {'schema_type': 'flat-realnvp', 'num_density_layers': 20, 'coupler_shared_nets': True, 'coupler_hidden_channels': ([1024] * 2), 'st_nets': ([100] * 2), 'p_nets': ([100] * 2), 'q_nets': ([100] * 2)}
@provides('sos') def sos(dataset, model, use_baseline): assert use_baseline, 'A CIF version of this config has not yet been tested' return {'schema_type': 'sos', 'num_density_layers': 8, 'g_hidden_channels': ([200] * 2), 'num_polynomials_per_layer': 5, 'polynomial_degree': 4, 'lr': 0.001, 'opt': 'sgd'}
@provides('nsf-ar') def nsf(dataset, model, use_baseline): common = {'schema_type': 'nsf', 'autoregressive': True, 'num_density_layers': 10, 'tail_bound': 3, 'batch_norm': False, 'opt': 'adam', 'lr_schedule': 'cosine', 'weight_decay': 0.0, 'early_stopping': False, 'max_grad_norm': 5, 'valid_batch_size': 5000, 'te...
@base def config(dataset, use_baseline): return {'num_u_channels': 1, 'use_cond_affine': (not use_baseline), 'pure_cond_affine': False, 'dequantize': False, 'batch_norm': False, 'act_norm': False, 'max_epochs': 2000, 'max_grad_norm': None, 'early_stopping': True, 'max_bad_valid_epochs': 250, 'train_batch_size': 1...
@provides('resflow') def resflow(dataset, model, use_baseline): config = {'schema_type': 'flat-resflow', 'num_density_layers': 10, 'hidden_channels': ([128] * 4), 'lipschitz_constant': 0.9, 'max_train_lipschitz_iters': 5, 'max_test_lipschitz_iters': 200, 'lipschitz_tolerance': None, 'reduce_memory': True, 'st_net...
@provides('affine') def affine(dataset, model, use_baseline): assert use_baseline, 'Must use baseline model for this config' return {'schema_type': 'affine', 'num_density_layers': 10}
@provides('maf') def maf(dataset, model, use_baseline): return {'schema_type': 'maf', 'num_density_layers': (20 if use_baseline else 5), 'ar_map_hidden_channels': ([50] * 4), 'st_nets': ([10] * 2), 'p_nets': ([50] * 4), 'q_nets': ([50] * 4)}
@provides('maf-grid') def maf_grid(dataset, model, use_baseline): return {'schema_type': 'maf', 'num_density_layers': (20 if use_baseline else 5), 'ar_map_hidden_channels': GridParams(([10] * 2), ([50] * 4)), 'num_u_channels': 2, 'st_nets': GridParams(([10] * 2), ([50] * 4)), 'p_nets': ([10] * 2), 'q_nets': ([50]...
@provides('cond-affine-shallow-grid', 'cond-affine-deep-grid') def cond_affine_grid(dataset, model, use_baseline): assert (not use_baseline), 'Cannot use baseline model for this config' if ('deep' in model): num_layers = 5 net_factor = 1 else: num_layers = 1 net_factor = 5 ...
@provides('dlgm-deep', 'dlgm-shallow') def dlgm_deep(dataset, model, use_baseline): assert (not use_baseline), 'Cannot use baseline model for this config' if ('deep' in model): cond_affine_model = 'cond-affine-deep-grid' else: cond_affine_model = 'cond-affine-shallow-grid' config = con...
@provides('realnvp') def realnvp(dataset, model, use_baseline): return {'schema_type': 'flat-realnvp', 'num_density_layers': 1, 'coupler_shared_nets': True, 'coupler_hidden_channels': ([10] * 2), 'use_cond_affine': True, 'st_nets': ([10] * 2), 'p_nets': ([10] * 2), 'q_nets': ([10] * 2)}
@provides('sos') def sos(dataset, model, use_baseline): return {'schema_type': 'sos', 'num_density_layers': (3 if use_baseline else 2), 'g_hidden_channels': ([40] * 2), 'num_polynomials_per_layer': 2, 'polynomial_degree': 4, 'st_nets': ([40] * 2), 'p_nets': ([40] * 4), 'q_nets': ([40] * 4)}
@provides('planar') def planar(dataset, model, use_baseline): return {'schema_type': 'planar', 'num_density_layers': 10, 'use_cond_affine': False, 'cond_hidden_channels': ([10] * 2), 'p_nets': ([50] * 4), 'q_nets': ([10] * 2)}
@provides('nsf-ar') def nsf(dataset, model, use_baseline): return {'schema_type': 'nsf', 'autoregressive': True, 'use_linear': False, 'max_grad_norm': 5, 'num_density_layers': 5, 'num_bins': 8, 'num_hidden_channels': 256, 'num_hidden_layers': 2, 'tail_bound': 3, 'dropout_probability': 0.0, 'lr_schedule': 'cosine'...
@provides('bnaf') def bnaf(dataset, model, use_baseline): return {'schema_type': 'bnaf', 'num_density_layers': 1, 'num_hidden_layers': 2, 'hidden_channels_factor': (50 if use_baseline else 45), 'activation': 'soft-leaky-relu', 'st_nets': ([24] * 2), 'p_nets': ([24] * 3), 'q_nets': ([24] * 3), 'test_batch_size': 1...
@provides('ffjord') def ffjord(dataset, model, use_baseline): raise NotImplementedError('Currently broken; require changes in experiment.py') return {'schema_type': 'ffjord', 'num_density_layers': 1, 'hidden_channels': ([64] * 3), 'numerical_tolerance': 1e-05, 'st_nets': ([24] * 2), 'p_nets': ([24] * 3), 'q_n...
def parse_config_arg(key_value): assert ('=' in key_value), "Must specify config items with format `key=value'" (k, v) = key_value.split('=', maxsplit=1) assert k, "Config item can't have empty key" assert v, "Config item can't have empty value" try: v = ast.literal_eval(v) except Valu...
def test_cif_realnvp_config(): config = get_config(dataset='mnist', model='realnvp', use_baseline=False) true_config = {'schema_type': 'multiscale-realnvp', 'use_cond_affine': True, 'pure_cond_affine': False, 'g_hidden_channels': [64, 64, 64, 64], 'num_u_channels': 1, 'st_nets': [8, 8], 'p_nets': [64, 64], 'q...
def test_baseline_realnvp_config(): config = get_config(dataset='mnist', model='realnvp', use_baseline=True) true_config = {'schema_type': 'multiscale-realnvp', 'use_cond_affine': False, 'pure_cond_affine': False, 'g_hidden_channels': [64, 64, 64, 64, 64, 64, 64, 64], 'num_u_channels': 0, 'early_stopping': Tr...
class TestDiagonalGaussianDensity(unittest.TestCase): def setUp(self): self.shape = (10, 4, 2) self.mean = torch.rand(self.shape) self.stddev = (1 + (torch.rand(self.shape) ** 2)) self.density = DiagonalGaussianDensity(self.mean, self.stddev, num_fixed_samples=64) flat_mea...
class TestDiagonalGaussianConditionalDensity(unittest.TestCase): def setUp(self): dim = 25 cond_dim = 15 self.shape = (dim,) self.cond_shape = (cond_dim,) self.mean_log_std_map = ChunkedSharedCoupler(shift_log_scale_net=get_mlp(num_input_channels=cond_dim, hidden_channels=...
class TestCIFDensity(unittest.TestCase): def test_log_prob_format(self): batch_size = 1000 x_dim = 40 input_shape = (x_dim,) u_dim = 15 num_importance_samples = 5 prior = DiagonalGaussianDensity(mean=torch.zeros(input_shape), stddev=torch.ones(input_shape)) ...
class TestConcreteConditionalDensity(unittest.TestCase): def setUp(self): self.shape = (25,) self.cond_shape = (5,) self.lam = torch.exp(torch.rand(1)) self.log_alpha_map = get_mlp(num_input_channels=np.prod(self.cond_shape), hidden_channels=[10, 10, 10], num_output_channels=np.pr...
def load_schema(name): with open(((Path('tests') / 'schemas') / f'{name}.json'), 'r') as f: return json.load(f)
def test_baseline_multiscale_realnvp_schema(): config = get_config(dataset='mnist', model='realnvp', use_baseline=True) schema = get_schema(config) true_schema = load_schema('realnvp_schema') assert (schema == true_schema)
def test_cif_multiscale_realnvp_schema(): config = get_config(dataset='mnist', model='realnvp', use_baseline=False) schema = get_schema(config) true_schema = load_schema('cif_realnvp_schema') assert (schema == true_schema)
def main(args=None): if (args is None): parser = argparse.ArgumentParser() parser.add_argument('--game', type=str) parser.add_argument('--config', type=str, default='default') parser.add_argument('--seed', type=int, default=None) parser.add_argument('--device', type=str, de...
def update_metrics(metrics, new_metrics, prefix=None): def process(key, t): if isinstance(t, (int, float)): return t assert torch.is_tensor(t), key assert (not t.requires_grad), key assert ((t.ndim == 0) or (t.shape == (1,))), key return t.clone() if (prefi...
def combine_metrics(metrics, prefix=None): result = {} if (prefix is None): for met in metrics: update_metrics(result, met) else: for (met, pre) in zip(metrics, prefix): update_metrics(result, met, pre) return result
def mean_metrics(metrics_history, except_keys=None): if (len(metrics_history) == 0): return {} if (len(metrics_history) == 1): return metrics_history[0] except_keys = (set() if (except_keys is None) else set(except_keys)) result = {} value_history = collections.defaultdict((lambda ...
class MetricsSummarizer(): def __init__(self, except_keys=None): self.metrics_history = [] self.except_keys = (set() if (except_keys is None) else set(except_keys)) def append(self, metrics): self.metrics_history.append(metrics) def summarize(self): summary = mean_metric...
def compute_mean(values): if torch.is_tensor(values): return values.float().mean() if isinstance(values, (tuple, list)): return torch.stack([torch.as_tensor(x).detach() for x in values]).float().mean() raise ValueError()
def random_choice(n, num_samples, replacement=False, device=None): if replacement: return torch.randint(0, n, (num_samples,), device=device) weights = torch.ones(n, device=device) return torch.multinomial(weights, num_samples, replacement=False)
def windows(x, window_size, window_stride=1): x = x.unfold(1, window_size, window_stride) dims = list(range(x.ndim))[:(- 1)] dims.insert(2, (x.ndim - 1)) x = x.permute(dims) return x
def same_batch_shape(tensors, ndim=2): batch_shape = tensors[0].shape[:ndim] assert all(((t.ndim >= ndim) for t in tensors)) return all(((tensors[i].shape[:ndim] == batch_shape) for i in range(1, len(tensors))))
def same_batch_shape_time_offset(a, b, offset): assert ((a.ndim >= 2) and (b.ndim >= 2)) return (a.shape[:2] == (b.shape[0], (b.shape[1] + offset)))
def check_no_grad(*tensors): return all((((t is None) or (not t.requires_grad)) for t in tensors))
class AdamOptim(): def __init__(self, parameters, lr, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, grad_clip=0): self.parameters = list(parameters) self.grad_clip = grad_clip self.optimizer = optim.Adam(self.parameters, lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) def st...
def create_reward_transform(transform_type): if (transform_type == 'tanh'): def transform(r): if torch.is_tensor(r): return torch.tanh(r) return math.tanh(r) elif (transform_type == 'clip'): def transform(r): if torch.is_tensor(r): ...
def preprocess_atari_obs(obs, device=None): if isinstance(obs, gym.wrappers.LazyFrames): obs = np.array(obs) return (torch.as_tensor(obs, device=device).float() / 255.0)
def create_atari_env(game, noop_max=30, frame_skip=4, frame_stack=4, frame_size=84, episodic_lives=True, grayscale=True, time_limit=27000): env = AtariEnv(rom_name_to_id(game), frameskip=1, repeat_action_probability=0.0) env.spec = gym.spec((game + 'NoFrameskip-v4')) has_fire_action = (env.get_action_mean...
def create_vector_env(num_envs, env_fn): if (num_envs == 1): return gym.vector.SyncVectorEnv([env_fn]) else: return gym.vector.AsyncVectorEnv([env_fn for _ in range(num_envs)])
def compute_atari_hns(game, agent_score): random_score = atari_random_scores[game] human_score = atari_human_scores[game] return (((agent_score - random_score) / (human_score - random_score)) * 100.0)
class EpisodicLives(gym.Wrapper): def __init__(self, env): super().__init__(env) self.ale = env.unwrapped.ale self.lives = 0 self.was_real_done = True def reset(self, seed=None, options=None): if (self.was_real_done or ((options is not None) and options.get('force', F...
class NoAutoReset(gym.Wrapper): def __init__(self, env): super().__init__(env) self.final_observation = None self.final_info = None def reset(self, seed=None, options=None): if ((self.final_observation is None) or ((options is not None) and options.get('force', False))): ...
class FireAfterLifeLoss(gym.Wrapper): def __init__(self, env): super().__init__(env) unwrapped = env.unwrapped action_meanings = unwrapped.get_action_meanings() assert (action_meanings[1] == 'FIRE') assert (len(action_meanings) >= 3) self.ale = unwrapped.ale ...
class NoopStart(gym.Wrapper): def __init__(self, env, noop_max): super().__init__(env) self.noop_max = noop_max def reset(self, seed=None, options=None): (obs, reset_info) = self.env.reset(seed=seed, options=options) noops = (self.env.unwrapped.np_random.integers(1, (self.noo...
@torch.no_grad() def make_grid(tensor, nrow, padding, pad_value=0): nmaps = tensor.size(0) xmaps = min(nrow, nmaps) ymaps = int(math.ceil((float(nmaps) / xmaps))) (height, width) = (int((tensor.size(2) + padding[0])), int((tensor.size(3) + padding[1]))) num_channels = tensor.size(1) grid = ten...
def to_image(tensor): from PIL import Image tensor = tensor.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8) if (tensor.shape[2] == 1): tensor = tensor.squeeze(2) return Image.fromarray(tensor.numpy()).convert('RGB')
def download_file_from_google_drive(id, destination): URL = 'https://docs.google.com/uc?export=download' session = requests.Session() response = session.get(URL, params={'id': id}, stream=True) token = get_confirm_token(response) if token: params = {'id': id, 'confirm': token} resp...
def get_confirm_token(response): for (key, value) in response.cookies.items(): if key.startswith('download_warning'): return value return None
def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, 'wb') as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: f.write(chunk)
def download_pretrained_model(): destination = os.path.join(PRETRAINED_MODEL_DIR, 'default_model.zip') if (not os.path.isdir(PRETRAINED_MODEL_DIR)): os.mkdir(PRETRAINED_MODEL_DIR) download_file_from_google_drive(FILE_ID, destination) with zipfile.ZipFile(destination, 'r') as zip_ref: z...
def add_arguments(parser): 'Helper function to fill the parser object.\n\n Args:\n parser: Parser object\n Returns:\n None\n ' parser.add_argument('-m', '--model', help='which model?', default='NoisyGRUSeq2SeqWithFeatures', type=str) parser.add_argument('-i', '--input_pipeline', def...
def create_hparams(flags): 'Create training hparams.' hparams = tf.contrib.training.HParams(model=flags.model, input_pipeline=flags.input_pipeline, input_sequence_key=flags.input_sequence_key, output_sequence_key=flags.output_sequence_key, cell_size=flags.cell_size, emb_size=flags.emb_size, save_dir=flags.sav...
def sequence2embedding(model, hparams, seq_list): 'Helper Function to run a forwards path up to the bottneck layer (ENCODER).\n Encodes a list of sequences into the molecular descriptor.\n\n Args:\n model: The translation model instance to use.\n hparams: Hyperparameter object.\n seq_li...
def embedding2sequence(model, hparams, embedding, num_top=1, maximum_iterations=1000): 'Helper Function to run a forwards path from thebottneck layer to\n output (DECODER).\n\n Args:\n model: The translation model instance to use.\n hparams: Hyperparameter object.\n embedding: Array wit...
class InferenceModel(object): 'Class that handles the inference of a trained model.' def __init__(self, model_dir=_default_model_dir, use_gpu=True, batch_size=256, gpu_mem_frac=0.1, beam_width=10, num_top=1, maximum_iterations=1000, cpu_threads=5, emb_activation=None): 'Constructor for the inference ...
class InferenceServer(): def __init__(self, model_dir=_default_model_dir, num_servers=1, port_frontend='5559', port_backend='5560', batch_size=256, gpu_mem_frac=0.3, beam_width=10, num_top=1, maximum_iterations=1000, use_running=False): self.model_dir = model_dir self.port_frontend = port_fronten...
class InputPipeline(): 'Base input pipeline class. Iterates through tf-record file to produce inputs\n for training the translation model.\n\n Atributes:\n mode: The mode the model is supposed to run (e.g. Train).\n batch_size: Number of samples per batch.\n buffer_size: Number of sampl...
class InputPipelineWithFeatures(InputPipeline): 'Input pipeline class with addtional molecular feature output. Iterates through tf-record\n file to produce inputs for training the translation model.\n\n Atributes:\n mode: The mode the model is supposed to run (e.g. Train).\n batch_size: Number...
class InputPipelineInferEncode(): 'Class that creates a python generator for list of sequnces. Used to feed\n sequnces to the encoing part during inference time.\n\n Atributes:\n seq_list: List with sequnces to iterate over.\n batch_size: Number of samples to output per iterator call.\n ...
class InputPipelineInferDecode(): 'Class that creates a python generator for arrays of embeddings (molecular descriptor).\n Used to feed embeddings to the decoding part during inference time.\n\n Atributes:\n embedding: Array with embeddings (molecular descriptors) (n_samples x n_features).\n ...
def build_models(hparams, modes=['TRAIN', 'EVAL', 'ENCODE']): 'Helper function to build a translation model for one or many different modes.\n\n Args:\n hparams: Hyperparameters defined in file or flags.\n modes: The mode the model is supposed to run (e.g. Train, EVAL, ENCODE, DECODE).\n C...
def create_model(mode, model_creator, input_pipeline_creator, hparams): 'Helper function to build a translation model for a certain mode.\n\n Args:cpu_threads\n mode: The mode the model is supposed to run(e.g. Train, EVAL, ENCODE, DECODE).\n model_creator: Type of model class (e.g. NoisyGRUSeq2Se...
def add_arguments(parser): 'Helper function to fill the parser object.\n\n Args:\n parser: Parser object\n Returns:\n None\n ' parser.add_argument('-i', '--input', help='input file. Either .smi or .csv file.', type=str) parser.add_argument('-o', '--output', help='output .csv file wi...
def read_input(file): 'Function that read teh provided file into a pandas dataframe.\n Args:\n file: File to read.\n Returns:\n pandas dataframe\n Raises:\n ValueError: If file is not a .smi or .csv file.\n ' if file.endswith('.csv'): sml_df = pd.read_csv(file) eli...
def main(unused_argv): 'Main function that extracts the contineous data-driven descriptors for a file of SMILES.' if FLAGS.gpu: os.environ['CUDA_VISIBLE_DEVICES'] = str(FLAGS.device) model_dir = FLAGS.model_dir file = FLAGS.input df = read_input(file) if FLAGS.preprocess: print...
def main_wrapper(): global FLAGS PARSER = argparse.ArgumentParser() add_arguments(PARSER) (FLAGS, UNPARSED) = PARSER.parse_known_args() tf.app.run(main=main, argv=([sys.argv[0]] + UNPARSED))
def train_loop(train_model, eval_model, encoder_model, hparams): 'Main training loop function for training and evaluating.\n Args:\n train_model: The model used for training.\n eval_model: The model used evaluating the translation accuracy.\n encoder_model: The model used for evaluating th...
def main(unused_argv): 'Main function that trains and evaluats the translation model' hparams = create_hparams(FLAGS) os.environ['CUDA_VISIBLE_DEVICES'] = str(hparams.device) (train_model, eval_model, encode_model) = build_models(hparams) train_loop(train_model, eval_model, encode_model, hparams)
def add_arguments(parser): 'Helper function to fill the parser object.\n\n Args:\n parser: Parser object\n Returns:\n None\n ' parser.add_argument('--model_dir', default=_default_model_dir, type=str) parser.add_argument('--use_gpu', dest='gpu', action='store_true') parser.set_de...
def main(unused_argv): 'Main function to test the performance of the translation model to extract\n meaningfull features for a QSAR modelling' if FLAGS.gpu: os.environ['CUDA_VISIBLE_DEVICES'] = str(FLAGS.device) print('use gpu {}'.format(str(FLAGS.device))) else: os.environ['CUD...
class MyDistributedDataParallel(LightningDistributedDataParallel): def scatter(self, inputs, kwargs, device_ids): kwargs['batch_idx'] = inputs[1] kwargs = (kwargs,) inputs = ((inputs[0].to(torch.device('cuda:{}'.format(device_ids[0]))),),) return (inputs, kwargs)
class MyDDP(DDPPlugin): def configure_ddp(self): self.model = MyDistributedDataParallel(self.model, device_ids=self.determine_ddp_device_ids(), find_unused_parameters=True)
class GeometricGraphDataset(Dataset): def __init__(self, n_min=12, n_max=20, samples_per_epoch=100000, **kwargs): super().__init__() self.n_min = n_min self.n_max = n_max self.samples_per_epoch = samples_per_epoch def __len__(self): return self.samples_per_epoch ...
class RegularGraphDataset(Dataset): def __init__(self, n_min=12, n_max=20, samples_per_epoch=100000, **kwargs): super().__init__() self.n_min = n_min self.n_max = n_max self.samples_per_epoch = samples_per_epoch def __len__(self): return self.samples_per_epoch de...
class BarabasiAlbertGraphDataset(Dataset): def __init__(self, n_min=12, n_max=20, m_min=1, m_max=5, samples_per_epoch=100000, **kwargs): super().__init__() self.n_min = n_min self.n_max = n_max self.m_min = m_min self.m_max = m_max self.samples_per_epoch = samples_...
class BinomialGraphDataset(Dataset): def __init__(self, n_min=12, n_max=20, p_min=0.4, p_max=0.6, samples_per_epoch=100000, pyg=False, **kwargs): super().__init__() self.n_min = n_min self.n_max = n_max self.p_min = p_min self.p_max = p_max self.samples_per_epoch =...
class RandomGraphDataset(Dataset): def __init__(self, n_min=12, n_max=20, samples_per_epoch=100000, **kwargs): super().__init__() self.n_min = n_min self.n_max = n_max self.samples_per_epoch = samples_per_epoch self.graph_generator = GraphGenerator() def __len__(self)...
class PyGRandomGraphDataset(RandomGraphDataset): def __getitem__(self, idx): n = np.random.randint(low=self.n_min, high=self.n_max) g = self.graph_generator(n) g = from_networkx(g) if (g.pos is not None): del g.pos return g
class DenseGraphBatch(Data): def __init__(self, node_features, edge_features, mask, **kwargs): self.node_features = node_features self.edge_features = edge_features self.mask = mask for (key, item) in kwargs.items(): setattr(self, key, item) @classmethod def f...
class DenseGraphDataLoader(torch.utils.data.DataLoader): def __init__(self, dataset, batch_size=1, shuffle=False, labels=False, **kwargs): super().__init__(dataset, batch_size, shuffle, collate_fn=(lambda data_list: DenseGraphBatch.from_sparse_graph_list(data_list, labels)), **kwargs)
class GraphDataModule(pl.LightningDataModule): def __init__(self, graph_family, graph_kwargs=None, samples_per_epoch=100000, batch_size=32, distributed_sampler=True, num_workers=1): super().__init__() if (graph_kwargs is None): graph_kwargs = {} self.graph_family = graph_famil...
def binomial_ego_graph(n, p): g = ego_graph(binomial_graph(n, p), 0) g = nx.convert_node_labels_to_integers(g, first_label=0) return g
class GraphGenerator(object): def __init__(self): self.graph_params = {'binominal': {'func': binomial_graph, 'kwargs_float_ranges': {'p': (0.2, 0.6)}}, '"binominal_ego": {\n "func": binomial_ego_graph,\n "kwargs_float_ranges": {\n "p": (0.2, 0.6)\n ...
class EvalRandomGraphDataset(Dataset): def __init__(self, n, pyg=False): self.n = n self.pyg = pyg self.graph_params = {'binominal': {'func': binomial_graph, 'kwargs': {'p': (0.25, 0.35, 0.5)}}, 'newman_watts_strogatz': {'func': newman_watts_strogatz_graph, 'kwargs': {'k': (2, 2, 5, 5), '...
class EvalRandomBinomialGraphDataset(Dataset): def __init__(self, n_min, n_max, p_min, p_max, num_samples, pyg=False): self.n_min = n_min self.n_max = n_max self.p_min = p_min self.p_max = p_max self.num_samples = num_samples self.pyg = pyg (self.graphs, se...
def add_arguments(parser): 'Helper function to fill the parser object.\n\n Args:\n parser: Parser object\n Returns:\n parser: Updated parser object\n ' parser.add_argument('--test', dest='test', action='store_true') parser.add_argument('-i', '--id', type=int, default=0) parser.a...
def main(hparams): if (not os.path.isdir((hparams.save_dir + '/run{}/'.format(hparams.id)))): print('Creating directory') os.mkdir((hparams.save_dir + '/run{}/'.format(hparams.id))) print('Starting Run {}'.format(hparams.id)) checkpoint_callback = ModelCheckpoint(dirpath=(hparams.save_dir ...
class PLGraphAE(pl.LightningModule): def __init__(self, hparams, critic): super().__init__() self.save_hyperparameters(hparams) self.graph_ae = GraphAE(hparams) self.critic = critic(hparams) def forward(self, graph, training): (graph_pred, perm, mu, logvar) = self.gra...
class NetworkConfig(object): scale = 100 max_step = (1000 * scale) initial_learning_rate = 0.0001 learning_rate_decay_rate = 0.96 learning_rate_decay_step = (5 * scale) moving_average_decay = 0.9999 entropy_weight = 0.1 save_step = (10 * scale) max_to_keep = 1000 Conv2D_out = 1...
class Config(NetworkConfig): version = 'TE_v2' project_name = 'CFR-RL' method = 'actor_critic' model_type = 'Conv' topology_file = 'Abilene' traffic_file = 'TM' test_traffic_file = 'TM2' tm_history = 1 max_moves = 10 baseline = 'avg'
def get_config(FLAGS): config = Config for (k, v) in FLAGS.__flags.items(): if hasattr(config, k): setattr(config, k, v.value) return config
class Topology(object): def __init__(self, config, data_dir='./data/'): self.topology_file = (data_dir + config.topology_file) self.shortest_paths_file = (self.topology_file + '_shortest_paths') self.DG = nx.DiGraph() self.load_topology() self.calculate_paths() def lo...
class Traffic(object): def __init__(self, config, num_nodes, data_dir='./data/', is_training=False): if is_training: self.traffic_file = ((data_dir + config.topology_file) + config.traffic_file) else: self.traffic_file = ((data_dir + config.topology_file) + config.test_tra...
class Environment(object): def __init__(self, config, is_training=False): self.data_dir = './data/' self.topology = Topology(config, self.data_dir) self.traffic = Traffic(config, self.topology.num_nodes, self.data_dir, is_training=is_training) self.traffic_matrices = ((((self.traf...
def sim(config, network, game): for tm_idx in game.tm_indexes: state = game.get_state(tm_idx) if (config.method == 'actor_critic'): policy = network.actor_predict(np.expand_dims(state, 0)).numpy()[0] elif (config.method == 'pure_policy'): policy = network.policy_pre...
def main(_): tf.config.experimental.set_visible_devices([], 'GPU') tf.get_logger().setLevel('INFO') config = (get_config(FLAGS) or FLAGS) env = Environment(config, is_training=False) game = CFRRL_Game(config, env) network = Network(config, game.state_dims, game.action_dim, game.max_moves) ...
def central_agent(config, game, model_weights_queues, experience_queues): network = Network(config, game.state_dims, game.action_dim, game.max_moves, master=True) network.save_hyperparams(config) start_step = network.restore_ckpt() for step in tqdm(range(start_step, config.max_step), ncols=70, initial...