code
stringlengths
189
49.4k
apis
list
extract_api
stringlengths
107
64.3k
import fastai from neptune.new.integrations.fastai import NeptuneCallback from fastai.vision.all import * import neptune.new as neptune run = neptune.init( project="common/fastai-integration", api_token="<PASSWORD>", tags="basic" ) path = untar_data(URLs.MNIST_TINY) dls = ImageDataLoaders.from_csv(path) # Log all training phases of the learner learn = cnn_learner(dls, resnet18, cbs=[NeptuneCallback(run=run, base_namespace="experiment")]) learn.fit_one_cycle(2) learn.fit_one_cycle(1) run.stop()
[ "neptune.new.integrations.fastai.NeptuneCallback", "neptune.new.init" ]
[((143, 234), 'neptune.new.init', 'neptune.init', ([], {'project': '"""common/fastai-integration"""', 'api_token': '"""<PASSWORD>"""', 'tags': '"""basic"""'}), "(project='common/fastai-integration', api_token='<PASSWORD>',\n tags='basic')\n", (155, 234), True, 'import neptune.new as neptune\n'), ((393, 446), 'neptune.new.integrations.fastai.NeptuneCallback', 'NeptuneCallback', ([], {'run': 'run', 'base_namespace': '"""experiment"""'}), "(run=run, base_namespace='experiment')\n", (408, 446), False, 'from neptune.new.integrations.fastai import NeptuneCallback\n')]
import neptune from tensorflow.keras.callbacks import BaseLogger class NeptuneMonitor(BaseLogger): def __init__(self, name, api_token, prj_name, params: tuple = None): assert api_token is not None assert prj_name is not None super(BaseLogger, self).__init__() self.my_name = name self.stateful_metrics = set(['loss'] or []) neptune.init( api_token=api_token, project_qualified_name=prj_name) self.experiment = neptune.create_experiment(name=self.my_name, params=params) self.log_neptune = True def on_epoch_end(self, epoch, logs={}): #acc = logs['acc'] loss = logs['loss'] if self.log_neptune: self.experiment.append_tag(self.my_name) #self.experiment.send_metric('acc', acc) self.experiment.send_metric('loss', loss) #self.experiment.send_metric('epoch', epoch) def on_train_end(self, logs={}): if self.log_neptune: self.experiment.stop()
[ "neptune.create_experiment", "neptune.init" ]
[((379, 445), 'neptune.init', 'neptune.init', ([], {'api_token': 'api_token', 'project_qualified_name': 'prj_name'}), '(api_token=api_token, project_qualified_name=prj_name)\n', (391, 445), False, 'import neptune\n'), ((497, 556), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': 'self.my_name', 'params': 'params'}), '(name=self.my_name, params=params)\n', (522, 556), False, 'import neptune\n')]
'''Train DCENet with PyTorch''' # from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import os import json import neptune import argparse import numpy as np from loader import * from utils.plots import * from utils.utils import * from utils.collision import * from utils.datainfo import DataInfo from utils.ranking import gauss_rank from models import DCENet from loss import DCENetLoss def main(): # ================= Arguments ================ # parser = argparse.ArgumentParser(description='PyTorch Knowledge Distillation') parser.add_argument('--gpu', type=str, default="4", help='gpu id') parser.add_argument('--config', type=str, default="config", help='.json') args = parser.parse_args() # ================= Device Setup ================ # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # ================= Config Load ================ # with open('config/' + args.config) as config_file: config = json.load(config_file) # ================= Neptune Setup ================ # if config['neptune']: neptune.init('seongjulee/DCENet', api_token=config["neptune_token"]) # username/project-name, api_token=token from neptune neptune.create_experiment(name='EXP', params=config) # name=project name (anything is ok), params=parameter list (json format) neptune.append_tag(args.config) # neptune tag (str or string list) # ================= Model Setup ================ # model = nn.DataParallel(DCENet(config)).to(device) if len(args.gpu.split(',')) > 1 else DCENet(config).to(device) # ================= Loss Function ================ # criterion = DCENetLoss(config) # ================= Optimizer Setup ================ # optimizer = optim.Adam(model.parameters(), lr=config['lr'], betas=(0.9, 0.999), eps=1e-8, weight_decay=1e-6, amsgrad=False) # ================= Data Loader ================ # datalist = DataInfo() train_datalist = datalist.train_merged print('Train data list', train_datalist) test_datalist = datalist.train_biwi print('Test data list', test_datalist) np.random.seed(10) offsets, traj_data, occupancy = load_data(config, train_datalist, datatype="train") trainval_split = np.random.rand(len(offsets)) < config['split'] train_x = offsets[trainval_split, :config['obs_seq'] - 1, 4:6] train_occu = occupancy[trainval_split, :config['obs_seq'] - 1, ..., :config['enviro_pdim'][-1]] train_y = offsets[trainval_split, config['obs_seq'] - 1:, 4:6] train_y_occu = occupancy[trainval_split, config['obs_seq'] - 1:, ..., :config['enviro_pdim'][-1]] val_x = offsets[~trainval_split, :config['obs_seq'] - 1, 4:6] val_occu = occupancy[~trainval_split, :config['obs_seq'] - 1, ..., :config['enviro_pdim'][-1]] val_y = offsets[~trainval_split, config['obs_seq'] - 1:, 4:6] val_y_occu = occupancy[~trainval_split, config['obs_seq'] - 1:, ..., :config['enviro_pdim'][-1]] print("%.0f trajectories for training\n %.0f trajectories for valiadation" %(train_x.shape[0], val_x.shape[0])) test_offsets, test_trajs, test_occupancy = load_data(config, test_datalist, datatype="test") test_x = test_offsets[:, :config['obs_seq'] - 1, 4:6] test_occu = test_occupancy[:, :config['obs_seq'] - 1, ..., :config['enviro_pdim'][-1]] last_obs_test = test_offsets[:, config['obs_seq'] - 2, 2:4] y_truth = test_offsets[:, config['obs_seq'] - 1:, :4] xy_truth = test_offsets[:, :, :4] print('test_trajs', test_trajs.shape) print("%.0f trajectories for testing" % (test_x.shape[0])) train_dataset = TrajDataset(x=train_x, x_occu=train_occu, y=train_y, y_occu=train_y_occu, mode='train') train_loader = DataLoader(dataset=train_dataset, batch_size=config["batch_size"], shuffle=True, num_workers=4) val_dataset = TrajDataset(x=val_x, x_occu=val_occu, y=val_y, y_occu=val_y_occu, mode='val') val_loader = DataLoader(dataset=val_dataset, batch_size=config["batch_size"], shuffle=False, num_workers=4) # test_dataset = TrajDataset(x=test_x, x_occu=test_occu, y=y_truth, y_occu=None, mode='test') # test_loader = DataLoader(dataset=test_dataset, batch_size=config["batch_size"], shuffle=False, num_workers=4) # ================= Training Loop ================ # early_stopping = EarlyStopping(patience=config['patience'], verbose=True, filename=args.config.split('/')[-1].replace('.json', '.pth')) for epoch in range(config['max_epochs']): train_one_epoch(config, epoch, device, model, optimizer, criterion, train_loader) val_loss = evaluate(config, device, model, optimizer, criterion, val_loader) early_stopping(val_loss, model) if early_stopping.early_stop: print("Early stopping") break # ================= Test ================ # model.load_state_dict(torch.load(os.path.join('checkpoints', args.config.split('/')[-1].replace('.json', '.pth')))) model.eval() with torch.no_grad(): test_x, test_occu = input2tensor(test_x, test_occu, device) x_latent = model.encoder_x(test_x, test_occu) predictions = [] for i, x_ in enumerate(x_latent): last_pos = last_obs_test[i] x_ = x_.view(1, -1) for i in range(config['num_pred']): y_p = model.decoder(x_, train=False) y_p_ = np.concatenate(([last_pos], np.squeeze(y_p.cpu().numpy())), axis=0) y_p_sum = np.cumsum(y_p_, axis=0) predictions.append(y_p_sum[1:, :]) predictions = np.reshape(predictions, [-1, config['num_pred'], config['pred_seq'], 2]) print('Predicting done!') print(predictions.shape) plot_pred(xy_truth, predictions) # Get the errors for ADE, DEF, Hausdorff distance, speed deviation, heading error print("\nEvaluation results @top%.0f" % config['num_pred']) errors = get_errors(y_truth, predictions) check_collision(y_truth) ## Get the first time prediction by g ranked_prediction = [] for prediction in predictions: ranks = gauss_rank(prediction) ranked_prediction.append(prediction[np.argmax(ranks)]) ranked_prediction = np.reshape(ranked_prediction, [-1, 1, config['pred_seq'], 2]) print("\nEvaluation results for most-likely predictions") ranked_errors = get_errors(y_truth, ranked_prediction) # Function for one epoch training def train_one_epoch(config, epoch, device, model, optimizer, criterion, loader): print('\nEpoch: %d' % epoch) model.train() train_total, train_loss = 0, 0 for batch_idx, (x, x_occu, y, y_occu) in enumerate(loader): x, x_occu, y, y_occu = x.to(device), x_occu.to(device), y.to(device), y_occu.to(device) optimizer.zero_grad() y_pred, mu, log_var = model(x, x_occu, y, y_occu, train=True) loss = criterion(mu, log_var, y_pred, y) loss.backward() optimizer.step() # train_ade += ade * x.size(0) # train_fde += fde * x.size(0) train_total += x.size(0) train_loss += loss.item() * x.size(0) if config['neptune']: # neptune.log_metric('train_batch_ADE', ade) # neptune.log_metric('train_batch_FDE', fde) neptune.log_metric('train_batch_Loss', loss.item()) # progress_bar(batch_idx, len(loader), 'Lr: %.4e | Loss: %.3f | ADE[m]: %.3f | FDE[m]: %.3f' # % (get_lr(optimizer), train_loss / train_total, train_ade / train_total, train_fde / train_total)) progress_bar(batch_idx, len(loader), 'Lr: %.4e | Loss: %.3f' % (get_lr(optimizer), train_loss / train_total)) # Function for validation @torch.no_grad() def evaluate(config, device, model, optimizer, criterion, loader): model.eval() # eval_ade, eval_fde, eval_total = 0, 0, 0 eval_total, eval_loss = 0, 0 for batch_idx, (x, x_occu, y, y_occu) in enumerate(loader): x, x_occu, y, y_occu = x.to(device), x_occu.to(device), y.to(device), y_occu.to(device) y_pred, mu, log_var = model(x, x_occu, y, y_occu, train=True) loss = criterion(mu, log_var, y_pred, y) eval_total += x.size(0) eval_loss += loss.item() * x.size(0) progress_bar(batch_idx, len(loader), 'Lr: %.4e | Loss: %.3f' % (get_lr(optimizer), eval_loss / eval_total)) # progress_bar(batch_idx, len(loader), 'Lr: %.4e | ADE[m]: %.3f | FDE[m]: %.3f' # % (get_lr(optimizer), eval_ade / eval_total, eval_fde / eval_total)) if config['neptune']: neptune.log_metric('val_Loss', eval_loss / eval_total) # neptune.log_metric('{}_ADE'.format(loader.dataset.mode), eval_ade / eval_total) # neptune.log_metric('{}_FDE'.format(loader.dataset.mode), eval_fde / eval_total) return eval_loss / eval_total if __name__ == "__main__": main()
[ "neptune.init", "neptune.log_metric", "neptune.create_experiment", "neptune.append_tag" ]
[((7920, 7935), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7933, 7935), False, 'import torch\n'), ((564, 633), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch Knowledge Distillation"""'}), "(description='PyTorch Knowledge Distillation')\n", (587, 633), False, 'import argparse\n'), ((1884, 1902), 'loss.DCENetLoss', 'DCENetLoss', (['config'], {}), '(config)\n', (1894, 1902), False, 'from loss import DCENetLoss\n'), ((2162, 2172), 'utils.datainfo.DataInfo', 'DataInfo', ([], {}), '()\n', (2170, 2172), False, 'from utils.datainfo import DataInfo\n'), ((2350, 2368), 'numpy.random.seed', 'np.random.seed', (['(10)'], {}), '(10)\n', (2364, 2368), True, 'import numpy as np\n'), ((3954, 4054), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_dataset', 'batch_size': "config['batch_size']", 'shuffle': '(True)', 'num_workers': '(4)'}), "(dataset=train_dataset, batch_size=config['batch_size'], shuffle=\n True, num_workers=4)\n", (3964, 4054), False, 'from torch.utils.data import DataLoader\n'), ((4164, 4263), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'val_dataset', 'batch_size': "config['batch_size']", 'shuffle': '(False)', 'num_workers': '(4)'}), "(dataset=val_dataset, batch_size=config['batch_size'], shuffle=\n False, num_workers=4)\n", (4174, 4263), False, 'from torch.utils.data import DataLoader\n'), ((5818, 5890), 'numpy.reshape', 'np.reshape', (['predictions', "[-1, config['num_pred'], config['pred_seq'], 2]"], {}), "(predictions, [-1, config['num_pred'], config['pred_seq'], 2])\n", (5828, 5890), True, 'import numpy as np\n'), ((6444, 6505), 'numpy.reshape', 'np.reshape', (['ranked_prediction', "[-1, 1, config['pred_seq'], 2]"], {}), "(ranked_prediction, [-1, 1, config['pred_seq'], 2])\n", (6454, 6505), True, 'import numpy as np\n'), ((1177, 1199), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (1186, 1199), False, 'import json\n'), ((1292, 1360), 'neptune.init', 'neptune.init', (['"""seongjulee/DCENet"""'], {'api_token': "config['neptune_token']"}), "('seongjulee/DCENet', api_token=config['neptune_token'])\n", (1304, 1360), False, 'import neptune\n'), ((1425, 1477), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""EXP"""', 'params': 'config'}), "(name='EXP', params=config)\n", (1450, 1477), False, 'import neptune\n'), ((1561, 1592), 'neptune.append_tag', 'neptune.append_tag', (['args.config'], {}), '(args.config)\n', (1579, 1592), False, 'import neptune\n'), ((5228, 5243), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5241, 5243), False, 'import torch\n'), ((6334, 6356), 'utils.ranking.gauss_rank', 'gauss_rank', (['prediction'], {}), '(prediction)\n', (6344, 6356), False, 'from utils.ranking import gauss_rank\n'), ((8786, 8840), 'neptune.log_metric', 'neptune.log_metric', (['"""val_Loss"""', '(eval_loss / eval_total)'], {}), "('val_Loss', eval_loss / eval_total)\n", (8804, 8840), False, 'import neptune\n'), ((1011, 1036), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1034, 1036), False, 'import torch\n'), ((1780, 1794), 'models.DCENet', 'DCENet', (['config'], {}), '(config)\n', (1786, 1794), False, 'from models import DCENet\n'), ((5724, 5747), 'numpy.cumsum', 'np.cumsum', (['y_p_'], {'axis': '(0)'}), '(y_p_, axis=0)\n', (5733, 5747), True, 'import numpy as np\n'), ((6401, 6417), 'numpy.argmax', 'np.argmax', (['ranks'], {}), '(ranks)\n', (6410, 6417), True, 'import numpy as np\n'), ((1716, 1730), 'models.DCENet', 'DCENet', (['config'], {}), '(config)\n', (1722, 1730), False, 'from models import DCENet\n')]
import gym, torch, random, copy import torch.nn as nn import torch.optim as optim import numpy as np import torch.nn.functional as F import neptune.new as neptune # initialize policy & value network class PolicyNetwork(nn.Module): def __init__(self, beta): super().__init__() self.model = nn.Sequential(nn.Linear(111, 400), nn.ReLU(), nn.Linear(400, 300), nn.ReLU(), nn.Linear(300, 8)) self.beta = beta def forward(self, x): if not isinstance(x, torch.Tensor): x = torch.from_numpy(x).float() return torch.tanh(self.model(x)) def explore(self, x): if not isinstance(x, torch.Tensor): x = torch.from_numpy(x).float() return self.forward(x) + self.beta * torch.randn(8) class ValueNetwork(nn.Module): def __init__(self): super().__init__() self.model = nn.Sequential(nn.Linear(119, 400), nn.ReLU(), nn.Linear(400, 300), nn.ReLU(), nn.Linear(300, 1)) def forward(self, x): return self.model(x) class Buffer(): def __init__(self, max_size, mini_batch): self.buffer = [] self.max_size = max_size self.batch_size = mini_batch def add(self, x): self.buffer.append(x) if len(self.buffer) > self.max_size: del self.buffer[0] def mini_batch(self): return random.sample(self.buffer, self.batch_size) # This is messy def extract(x): f_tensor = [] for i in range(5): list = [e[i] for e in x] if isinstance(list[0], np.ndarray): list = [torch.from_numpy(a).float() for a in list] if i != 2 and i!=4: tensor = torch.stack(tuple(b for b in list)) elif i == 4: tensor = torch.Tensor(list).float().unsqueeze(1) else: tensor = torch.unsqueeze(torch.tensor(list).float(), 1) f_tensor.append(tensor) return f_tensor[0], f_tensor[1], f_tensor[2], f_tensor[3], f_tensor[4] class TrainingLoop(): def __init__(self, policy_net, value_net, buffer, value_optim, policy_optim, episodes = 1000, gamma = 0.99, loss_fn = nn.MSELoss(), env=gym.make('Ant-v2'), k = 2, min_buffer_size = 1000, tau = 0.0005): self.policy_net = policy_net self.value_net = value_net self.target_policy = copy.deepcopy(self.policy_net) self.target_value = copy.deepcopy(self.value_net) self.buffer = buffer self.value_optim = value_optim self.policy_optim = policy_optim self.episodes = episodes self.gamma = gamma self.loss_fn = loss_fn self.extract_fn = extract self.episode_reward = 0 self.env = env self.k = k self.run = neptune.init(project = "jaltermain/DDPGAntv-2") self.initial_obs = None self.val_losses = [] self.pol_losses = [] self.min_buffer_size = min_buffer_size self.done = False self.steps = 0 self.tau = tau def interact(self): action = (self.policy_net.explore(self.initial_obs)).detach() obs, reward, done, _ = self.env.step(action.numpy()) # make sure the done flag is not time out self.episode_reward += reward self.buffer.add((self.initial_obs, action, reward, obs, done)) # (s, a, r, s') self.initial_obs = obs self.done = done def get_batch(self): samples = self.buffer.mini_batch() return self.extract_fn(samples) def train_value(self): initial_states, actions, rewards, states, finished = self.get_batch() q_model = value(torch.cat((initial_states, actions), 1)) q_bellman = rewards + self.gamma * self.target_value(torch.cat((states, self.target_policy(states)),1)) * (1-finished) loss_value = self.loss_fn(q_model, q_bellman.detach()) self.val_losses.append(loss_value.detach()) # run['train/value_loss'].log(loss_value) loss_value.backward() # print([i.grad for i in target_value.parameters()]) self.value_optim.step() self.value_optim.zero_grad() self.policy_optim.zero_grad() def train_policy(self): initial_states, actions, rewards, states, finished = self.get_batch() loss_policy = -(self.value_net(torch.cat((initial_states, self.policy_net.explore(initial_states)),1)).mean()) self.pol_losses.append(loss_policy.detach()) # run['train/policy_loss'].log(loss_policy) loss_policy.backward() self.policy_optim.step() self.value_optim.zero_grad() self.policy_optim.zero_grad() def polyak_averaging(self): params1 = self.value_net.named_parameters() params2 = self.target_value.named_parameters() dict_params2 = dict(params2) for name1, param1 in params1: if name1 in dict_params2: dict_params2[name1].data.copy_(self.tau*param1.data + (1-self.tau)*dict_params2[name1].data) if self.steps % self.k == 0: params1 = self.policy_net.named_parameters() params2 = self.target_policy.named_parameters() dict_params2 = dict(params2) for name1, param1 in params1: if name1 in dict_params2: dict_params2[name1].data.copy_(self.tau*param1.data + (1-self.tau)*dict_params2[name1].data) def init_log(self): network_hyperparams = {'Optimizer': 'Adam','Value-learning_rate': 0.0001, 'Policy-learning_rate': 0.0001, 'loss_fn_value': 'MSE'} self.run["network_hyperparameters"] = network_hyperparams network_sizes = {'ValueNet_size': '(119,400,300,1)', 'PolicyNet_size': '(111,400,300,8)'} self.run["network_sizes"] = network_sizes buffer_params = {'buffer_maxsize': self.buffer.max_size, 'batch_size': self.buffer.batch_size, 'min_size_train': self.min_buffer_size} self.run['buffer_parameters'] = buffer_params policy_params = {'exploration_noise': policy.beta, 'policy_smoothing': policy.beta} self.run['policy_parameters'] = policy_params environment_params = {'gamma': self.gamma, 'env_name': 'Ant-v2', 'episodes': self.episodes} self.run['environment_parameters'] = environment_params self.run['environment_parameters'] = environment_params def log(self): self.run['train/episode_reward'].log(self.episode_reward) if not self.val_losses: self.run['train/mean_episodic_value_loss'].log(0) self.run['train/mean_episodic_policy_loss'].log(0) else: mean_val_loss = sum(self.val_losses) / len(self.val_losses) mean_pol_loss = sum(self.pol_losses) / len(self.pol_losses) self.run['train/mean_episodic_value_loss'].log(mean_val_loss) self.run['train/mean_episodic_policy_loss'].log(mean_pol_loss) def evaluation_loop(self): self.episode_reward = 0 self.done = False self.initial_obs = self.env.reset() while not self.done: action = (self.policy_net(self.initial_obs)).detach() obs, reward, done, _ = self.env.step(action.numpy()) # make sure the done flag is not time out self.episode_reward += reward self.initial_obs = obs self.done = done self.run['validation/episode_reward'].log(self.episode_reward) def training_loop(self): self.init_log() for e in range(self.episodes): self.episode_reward = 0 self.done = False self.val_losses, self.pol_losses = [], [] self.initial_obs = self.env.reset() while not self.done: self.interact() if len(self.buffer.buffer) > self.min_buffer_size: self.train_value() if self.steps % self.k == 0: self.train_policy() self.polyak_averaging() self.steps += 1 self.log() self.evaluation_loop() self.run.stop() policy = PolicyNetwork(0.1) value = ValueNetwork() buffer = Buffer(15000, 128) value_optim = optim.Adam(value.parameters(), lr = 0.0001) policy_optim = optim.Adam(policy.parameters(), lr = 0.0001) training_loop = TrainingLoop(policy, value, buffer, value_optim, policy_optim) training_loop.training_loop()
[ "neptune.new.init" ]
[((1496, 1539), 'random.sample', 'random.sample', (['self.buffer', 'self.batch_size'], {}), '(self.buffer, self.batch_size)\n', (1509, 1539), False, 'import gym, torch, random, copy\n'), ((2259, 2271), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2269, 2271), True, 'import torch.nn as nn\n'), ((2277, 2295), 'gym.make', 'gym.make', (['"""Ant-v2"""'], {}), "('Ant-v2')\n", (2285, 2295), False, 'import gym, torch, random, copy\n'), ((2444, 2474), 'copy.deepcopy', 'copy.deepcopy', (['self.policy_net'], {}), '(self.policy_net)\n', (2457, 2474), False, 'import gym, torch, random, copy\n'), ((2503, 2532), 'copy.deepcopy', 'copy.deepcopy', (['self.value_net'], {}), '(self.value_net)\n', (2516, 2532), False, 'import gym, torch, random, copy\n'), ((2860, 2905), 'neptune.new.init', 'neptune.init', ([], {'project': '"""jaltermain/DDPGAntv-2"""'}), "(project='jaltermain/DDPGAntv-2')\n", (2872, 2905), True, 'import neptune.new as neptune\n'), ((325, 344), 'torch.nn.Linear', 'nn.Linear', (['(111)', '(400)'], {}), '(111, 400)\n', (334, 344), True, 'import torch.nn as nn\n'), ((346, 355), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (353, 355), True, 'import torch.nn as nn\n'), ((393, 412), 'torch.nn.Linear', 'nn.Linear', (['(400)', '(300)'], {}), '(400, 300)\n', (402, 412), True, 'import torch.nn as nn\n'), ((414, 423), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (421, 423), True, 'import torch.nn as nn\n'), ((461, 478), 'torch.nn.Linear', 'nn.Linear', (['(300)', '(8)'], {}), '(300, 8)\n', (470, 478), True, 'import torch.nn as nn\n'), ((954, 973), 'torch.nn.Linear', 'nn.Linear', (['(119)', '(400)'], {}), '(119, 400)\n', (963, 973), True, 'import torch.nn as nn\n'), ((975, 984), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (982, 984), True, 'import torch.nn as nn\n'), ((1022, 1041), 'torch.nn.Linear', 'nn.Linear', (['(400)', '(300)'], {}), '(400, 300)\n', (1031, 1041), True, 'import torch.nn as nn\n'), ((1043, 1052), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1050, 1052), True, 'import torch.nn as nn\n'), ((1090, 1107), 'torch.nn.Linear', 'nn.Linear', (['(300)', '(1)'], {}), '(300, 1)\n', (1099, 1107), True, 'import torch.nn as nn\n'), ((3735, 3774), 'torch.cat', 'torch.cat', (['(initial_states, actions)', '(1)'], {}), '((initial_states, actions), 1)\n', (3744, 3774), False, 'import gym, torch, random, copy\n'), ((820, 834), 'torch.randn', 'torch.randn', (['(8)'], {}), '(8)\n', (831, 834), False, 'import gym, torch, random, copy\n'), ((591, 610), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (607, 610), False, 'import gym, torch, random, copy\n'), ((747, 766), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (763, 766), False, 'import gym, torch, random, copy\n'), ((1714, 1733), 'torch.from_numpy', 'torch.from_numpy', (['a'], {}), '(a)\n', (1730, 1733), False, 'import gym, torch, random, copy\n'), ((1975, 1993), 'torch.tensor', 'torch.tensor', (['list'], {}), '(list)\n', (1987, 1993), False, 'import gym, torch, random, copy\n'), ((1884, 1902), 'torch.Tensor', 'torch.Tensor', (['list'], {}), '(list)\n', (1896, 1902), False, 'import gym, torch, random, copy\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=redefined-outer-name import os import random import string import threading import uuid from random import randint import pytest import neptune.new.sync from neptune.new.constants import OFFLINE_DIRECTORY from neptune.new.exceptions import ProjectNotFound from neptune.new.internal.backends.api_model import Project from neptune.new.internal.container_type import ContainerType from neptune.new.internal.containers.disk_queue import DiskQueue from neptune.new.internal.operation import Operation from neptune.new.internal.utils.sync_offset_file import SyncOffsetFile from neptune.new.sync import ( ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status, ) def a_run(): return ApiRun( str(uuid.uuid4()), "RUN-{}".format(randint(42, 12342)), "org", "proj", False ) def a_project(): return ApiRun( str(uuid.uuid4()), "".join((random.choice(string.ascii_letters).upper() for _ in range(3))), "org", "proj", False, ) def generate_get_run_impl(registered_experiments): def get_run_impl(run_id): """This function will return run as well as projects. Will be cleaned in ModelRegistry""" for exp in registered_experiments: if run_id in (str(exp.id), get_qualified_name(exp)): return exp return get_run_impl def prepare_projects(path): unsync_project = a_project() sync_project = a_project() registered_projects = (unsync_project, sync_project) execution_id = "exec-0" for project in registered_projects: project_path = path / "async" / str(project.id) / execution_id project_path.mkdir(parents=True) queue = DiskQueue( project_path, lambda x: x, lambda x: x, threading.RLock(), ContainerType.PROJECT, ) queue.put("op-proj-0") queue.put("op-proj-1") SyncOffsetFile( path / "async" / str(unsync_project.id) / execution_id / "last_ack_version" ).write(1) SyncOffsetFile( path / "async" / str(unsync_project.id) / execution_id / "last_put_version" ).write(2) SyncOffsetFile( path / "async" / str(sync_project.id) / execution_id / "last_ack_version" ).write(2) SyncOffsetFile( path / "async" / str(sync_project.id) / execution_id / "last_put_version" ).write(2) return unsync_project, sync_project, generate_get_run_impl(registered_projects) def prepare_runs(path): unsync_exp = a_run() sync_exp = a_run() registered_runs = (unsync_exp, sync_exp) execution_id = "exec-0" for exp in registered_runs: exp_path = path / "async" / str(exp.id) / execution_id exp_path.mkdir(parents=True) queue = DiskQueue( exp_path, lambda x: x, lambda x: x, threading.RLock(), ContainerType.RUN ) queue.put("op-0") queue.put("op-1") SyncOffsetFile( path / "async" / str(unsync_exp.id) / execution_id / "last_ack_version" ).write(1) SyncOffsetFile( path / "async" / str(unsync_exp.id) / execution_id / "last_put_version" ).write(2) SyncOffsetFile( path / "async" / str(sync_exp.id) / execution_id / "last_ack_version" ).write(2) SyncOffsetFile( path / "async" / str(sync_exp.id) / execution_id / "last_put_version" ).write(2) return unsync_exp, sync_exp, generate_get_run_impl(registered_runs) def prepare_offline_run(path): offline_exp_uuid = str(uuid.uuid4()) offline_exp_path = path / OFFLINE_DIRECTORY / offline_exp_uuid offline_exp_path.mkdir(parents=True) queue = DiskQueue( offline_exp_path, lambda x: x, lambda x: x, threading.RLock(), ContainerType.RUN ) queue.put("op-0") queue.put("op-1") SyncOffsetFile( path / OFFLINE_DIRECTORY / offline_exp_uuid / "last_put_version" ).write(2) return offline_exp_uuid def test_list_projects(tmp_path, mocker, capsys): """TODO: we're mentioning projects as runs, will be improved with ModelRegistry""" # given unsync_proj, sync_proj, get_exp_impl = prepare_projects(tmp_path) offline_exp_uuid = prepare_offline_run(tmp_path) # and mocker.patch.object(neptune.new.sync, "get_run", get_exp_impl) mocker.patch.object(Operation, "from_dict") # when synchronization_status(tmp_path) # then captured = capsys.readouterr() assert captured.err == "" assert ( "Synchronized runs:\n- {}".format(get_qualified_name(sync_proj)) in captured.out ) assert ( "Unsynchronized runs:\n- {}".format(get_qualified_name(unsync_proj)) in captured.out ) assert ( "Unsynchronized offline runs:\n- offline/{}".format(offline_exp_uuid) in captured.out ) def test_list_runs(tmp_path, mocker, capsys): # given unsync_exp, sync_exp, get_run_impl = prepare_runs(tmp_path) offline_exp_uuid = prepare_offline_run(tmp_path) # and mocker.patch.object(neptune.new.sync, "get_run", get_run_impl) mocker.patch.object(Operation, "from_dict") # when synchronization_status(tmp_path) # then captured = capsys.readouterr() assert captured.err == "" assert ( "Synchronized runs:\n- {}".format(get_qualified_name(sync_exp)) in captured.out ) assert ( "Unsynchronized runs:\n- {}".format(get_qualified_name(unsync_exp)) in captured.out ) assert ( "Unsynchronized offline runs:\n- offline/{}".format(offline_exp_uuid) in captured.out ) def test_list_runs_when_no_run(tmp_path, capsys): (tmp_path / "async").mkdir() # when with pytest.raises(SystemExit): synchronization_status(tmp_path) # then captured = capsys.readouterr() assert captured.err == "" assert "There are no Neptune runs" in captured.out def test_sync_all_runs(tmp_path, mocker, capsys): # given unsync_proj, sync_proj, _ = prepare_projects(tmp_path) unsync_exp, sync_exp, _ = prepare_runs(tmp_path) get_run_impl = generate_get_run_impl((unsync_proj, sync_proj, unsync_exp, sync_exp)) offline_exp_uuid = prepare_offline_run(tmp_path) registered_offline_run = a_run() # and mocker.patch.object(neptune.new.sync, "get_run", get_run_impl) mocker.patch.object(neptune.new.sync, "backend") mocker.patch.object(neptune.new.sync.backend, "execute_operations") mocker.patch.object( neptune.new.sync.backend, "get_project", lambda _: Project(str(uuid.uuid4()), "project", "workspace"), ) mocker.patch.object( neptune.new.sync, "register_offline_run", lambda project, container_type: (registered_offline_run, True), ) mocker.patch.object(Operation, "from_dict", lambda x: x) neptune.new.sync.backend.execute_operations.return_value = (1, []) # when sync_all_runs(tmp_path, "foo") # then captured = capsys.readouterr() assert captured.err == "" assert ( "Offline run {} registered as {}".format( offline_exp_uuid, get_qualified_name(registered_offline_run) ) ) in captured.out assert "Synchronising {}".format(get_qualified_name(unsync_exp)) in captured.out assert "Synchronising {}".format(get_qualified_name(unsync_proj)) in captured.out assert ( "Synchronization of run {} completed.".format(get_qualified_name(unsync_exp)) in captured.out ) assert ( "Synchronization of project {} completed.".format( get_qualified_name(unsync_proj) ) in captured.out ) assert "Synchronising {}".format(get_qualified_name(sync_exp)) not in captured.out assert "Synchronising {}".format(get_qualified_name(sync_proj)) not in captured.out # and # pylint: disable=no-member neptune.new.sync.backend.execute_operations.has_calls( [ mocker.call(unsync_exp.id, ContainerType.RUN, ["op-1"]), mocker.call(registered_offline_run.id, ContainerType.RUN, ["op-1"]), mocker.call(unsync_proj.id, ContainerType.PROJECT, ["op-proj-1"]), ], any_order=True, ) def test_sync_selected_runs(tmp_path, mocker, capsys): # given unsync_exp, sync_exp, get_run_impl = prepare_runs(tmp_path) offline_exp_uuid = prepare_offline_run(tmp_path) registered_offline_exp = a_run() def get_run_impl_(run_id: str): if run_id in ( str(registered_offline_exp.id), get_qualified_name(registered_offline_exp), ): return registered_offline_exp else: return get_run_impl(run_id) # and mocker.patch.object(neptune.new.sync, "get_run", get_run_impl_) mocker.patch.object(neptune.new.sync, "backend") mocker.patch.object(neptune.new.sync.backend, "execute_operations") mocker.patch.object( neptune.new.sync.backend, "get_project", lambda _: Project(str(uuid.uuid4()), "project", "workspace"), ) mocker.patch.object( neptune.new.sync, "register_offline_run", lambda project, container_type: (registered_offline_exp, True), ) mocker.patch.object(Operation, "from_dict", lambda x: x) neptune.new.sync.backend.execute_operations.return_value = (2, []) # when sync_selected_runs( tmp_path, "some-name", [get_qualified_name(sync_exp), "offline/" + offline_exp_uuid], ) # then captured = capsys.readouterr() assert captured.err == "" assert "Synchronising {}".format(get_qualified_name(sync_exp)) in captured.out assert ( "Synchronization of run {} completed.".format(get_qualified_name(sync_exp)) in captured.out ) assert ( "Synchronising {}".format(get_qualified_name(registered_offline_exp)) in captured.out ) assert ( "Synchronization of run {} completed.".format( get_qualified_name(registered_offline_exp) ) in captured.out ) assert "Synchronising {}".format(get_qualified_name(unsync_exp)) not in captured.out # and # pylint: disable=no-member neptune.new.sync.backend.execute_operations.assert_called_with( registered_offline_exp.id, ContainerType.RUN, operations=["op-0", "op-1"] ) def test_get_project_no_name_set(mocker): # given mocker.patch.object(os, "getenv") os.getenv.return_value = None # expect assert get_project(None) is None def test_get_project_project_not_found(mocker): # given mocker.patch.object(neptune.new.sync, "backend") mocker.patch.object(neptune.new.sync.backend, "get_project") neptune.new.sync.backend.get_project.side_effect = ProjectNotFound("foo") # expect assert get_project("foo") is None def test_sync_non_existent_run(tmp_path, mocker, capsys): # given mocker.patch.object(neptune.new.sync, "get_project") mocker.patch.object(neptune.new.sync, "get_run") neptune.new.sync.get_run.return_value = a_run() # when sync_selected_runs(tmp_path, "foo", ["bar"]) # then captured = capsys.readouterr() assert "Warning: Run 'bar' does not exist in location" in captured.err
[ "neptune.new.exceptions.ProjectNotFound", "neptune.new.sync.get_project", "neptune.new.sync.sync_all_runs", "neptune.new.internal.utils.sync_offset_file.SyncOffsetFile", "neptune.new.sync.get_qualified_name", "neptune.new.sync.sync_selected_runs", "neptune.new.sync.synchronization_status" ]
[((5024, 5056), 'neptune.new.sync.synchronization_status', 'synchronization_status', (['tmp_path'], {}), '(tmp_path)\n', (5046, 5056), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((5802, 5834), 'neptune.new.sync.synchronization_status', 'synchronization_status', (['tmp_path'], {}), '(tmp_path)\n', (5824, 5834), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((7589, 7619), 'neptune.new.sync.sync_all_runs', 'sync_all_runs', (['tmp_path', '"""foo"""'], {}), "(tmp_path, 'foo')\n", (7602, 7619), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((11448, 11470), 'neptune.new.exceptions.ProjectNotFound', 'ProjectNotFound', (['"""foo"""'], {}), "('foo')\n", (11463, 11470), False, 'from neptune.new.exceptions import ProjectNotFound\n'), ((11773, 11817), 'neptune.new.sync.sync_selected_runs', 'sync_selected_runs', (['tmp_path', '"""foo"""', "['bar']"], {}), "(tmp_path, 'foo', ['bar'])\n", (11791, 11817), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((4186, 4198), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (4196, 4198), False, 'import uuid\n'), ((4384, 4401), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (4399, 4401), False, 'import threading\n'), ((6364, 6389), 'pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (6377, 6389), False, 'import pytest\n'), ((6399, 6431), 'neptune.new.sync.synchronization_status', 'synchronization_status', (['tmp_path'], {}), '(tmp_path)\n', (6421, 6431), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((11187, 11204), 'neptune.new.sync.get_project', 'get_project', (['None'], {}), '(None)\n', (11198, 11204), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((11496, 11514), 'neptune.new.sync.get_project', 'get_project', (['"""foo"""'], {}), "('foo')\n", (11507, 11514), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((1388, 1400), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1398, 1400), False, 'import uuid\n'), ((1419, 1437), 'random.randint', 'randint', (['(42)', '(12342)'], {}), '(42, 12342)\n', (1426, 1437), False, 'from random import randint\n'), ((1517, 1529), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1527, 1529), False, 'import uuid\n'), ((2455, 2472), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (2470, 2472), False, 'import threading\n'), ((3496, 3513), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (3511, 3513), False, 'import threading\n'), ((4475, 4560), 'neptune.new.internal.utils.sync_offset_file.SyncOffsetFile', 'SyncOffsetFile', (["(path / OFFLINE_DIRECTORY / offline_exp_uuid / 'last_put_version')"], {}), "(path / OFFLINE_DIRECTORY / offline_exp_uuid / 'last_put_version'\n )\n", (4489, 4560), False, 'from neptune.new.internal.utils.sync_offset_file import SyncOffsetFile\n'), ((5189, 5218), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['sync_proj'], {}), '(sync_proj)\n', (5207, 5218), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((5299, 5330), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['unsync_proj'], {}), '(unsync_proj)\n', (5317, 5330), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((5967, 5995), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['sync_exp'], {}), '(sync_exp)\n', (5985, 5995), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((6076, 6106), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['unsync_exp'], {}), '(unsync_exp)\n', (6094, 6106), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((7790, 7832), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['registered_offline_run'], {}), '(registered_offline_run)\n', (7808, 7832), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((7902, 7932), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['unsync_exp'], {}), '(unsync_exp)\n', (7920, 7932), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((7987, 8018), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['unsync_proj'], {}), '(unsync_proj)\n', (8005, 8018), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((8103, 8133), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['unsync_exp'], {}), '(unsync_exp)\n', (8121, 8133), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((8249, 8280), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['unsync_proj'], {}), '(unsync_proj)\n', (8267, 8280), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((8358, 8386), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['sync_exp'], {}), '(sync_exp)\n', (8376, 8386), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((8445, 8474), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['sync_proj'], {}), '(sync_proj)\n', (8463, 8474), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((10107, 10135), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['sync_exp'], {}), '(sync_exp)\n', (10125, 10135), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((10289, 10317), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['sync_exp'], {}), '(sync_exp)\n', (10307, 10317), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((10402, 10430), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['sync_exp'], {}), '(sync_exp)\n', (10420, 10430), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((10509, 10551), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['registered_offline_exp'], {}), '(registered_offline_exp)\n', (10527, 10551), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((10663, 10705), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['registered_offline_exp'], {}), '(registered_offline_exp)\n', (10681, 10705), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((10783, 10813), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['unsync_exp'], {}), '(unsync_exp)\n', (10801, 10813), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((9217, 9259), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['registered_offline_exp'], {}), '(registered_offline_exp)\n', (9235, 9259), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((1929, 1952), 'neptune.new.sync.get_qualified_name', 'get_qualified_name', (['exp'], {}), '(exp)\n', (1947, 1952), False, 'from neptune.new.sync import ApiRun, get_project, get_qualified_name, sync_all_runs, sync_selected_runs, synchronization_status\n'), ((7234, 7246), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (7244, 7246), False, 'import uuid\n'), ((9684, 9696), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (9694, 9696), False, 'import uuid\n'), ((1549, 1584), 'random.choice', 'random.choice', (['string.ascii_letters'], {}), '(string.ascii_letters)\n', (1562, 1584), False, 'import random\n')]
import neptune # The init() function called this way assumes that # NEPTUNE_API_TOKEN environment variable is defined. neptune.init('zackpashkin/sandbox') PARAMS = {'decay_factor' : 0.5, 'n_iterations' : 117} neptune.create_experiment(name='minimal_example',params=PARAMS) # log some metrics for i in range(100): neptune.log_metric('loss', 0.95**i) neptune.log_metric('AUC', 0.96)
[ "neptune.create_experiment", "neptune.init", "neptune.log_metric" ]
[((121, 156), 'neptune.init', 'neptune.init', (['"""zackpashkin/sandbox"""'], {}), "('zackpashkin/sandbox')\n", (133, 156), False, 'import neptune\n'), ((223, 287), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""minimal_example"""', 'params': 'PARAMS'}), "(name='minimal_example', params=PARAMS)\n", (248, 287), False, 'import neptune\n'), ((370, 401), 'neptune.log_metric', 'neptune.log_metric', (['"""AUC"""', '(0.96)'], {}), "('AUC', 0.96)\n", (388, 401), False, 'import neptune\n'), ((333, 370), 'neptune.log_metric', 'neptune.log_metric', (['"""loss"""', '(0.95 ** i)'], {}), "('loss', 0.95 ** i)\n", (351, 370), False, 'import neptune\n')]
import requests import pytest from neptune.neptune_api import NeptuneService from neptune.tests.conftest import get_server_addr @pytest.mark.fpgas(1) def test_coco(request): """ Check the coco service from Neptune with a known image Args: request (fixture): get the cmdline options """ server_addr = get_server_addr(request.config) # create Neptune service and start it service = NeptuneService(server_addr, 'coco') service.start() # submit job to service post_data = { 'url': 'http://farm1.staticflickr.com/26/50531313_4422f0787e_z.jpg', 'dtype': 'uint8' } r = requests.post('%s/serve/coco' % server_addr, post_data) assert r.status_code == 200, r.text response = r.json() assert type(response) is dict # for this known image, validate the expected response for i, j in zip(response['resized_shape'], [149, 224, 3]): assert i == j assert 'img' in response assert response['url'] == post_data['url'] assert len(response['boxes']) == 2 tolerance = 5 for i, j in zip(response['boxes'][0], [85, 18, 149, 118, "giraffe"]): if isinstance(j, int): assert j - tolerance <= i <= j + tolerance else: assert i == j for i, j in zip(response['boxes'][1], [21, 90, 65, 148, "zebra"]): if isinstance(j, int): assert j - tolerance <= i <= j + tolerance else: assert i == j service.stop()
[ "neptune.neptune_api.NeptuneService", "neptune.tests.conftest.get_server_addr" ]
[((131, 151), 'pytest.mark.fpgas', 'pytest.mark.fpgas', (['(1)'], {}), '(1)\n', (148, 151), False, 'import pytest\n'), ((331, 362), 'neptune.tests.conftest.get_server_addr', 'get_server_addr', (['request.config'], {}), '(request.config)\n', (346, 362), False, 'from neptune.tests.conftest import get_server_addr\n'), ((420, 455), 'neptune.neptune_api.NeptuneService', 'NeptuneService', (['server_addr', '"""coco"""'], {}), "(server_addr, 'coco')\n", (434, 455), False, 'from neptune.neptune_api import NeptuneService\n'), ((639, 694), 'requests.post', 'requests.post', (["('%s/serve/coco' % server_addr)", 'post_data'], {}), "('%s/serve/coco' % server_addr, post_data)\n", (652, 694), False, 'import requests\n')]
""" Script by <NAME>, November 2020 Used to finetune models trained on pathology images (pre-chunked) on External Images """ import numpy as np import tables import pickle import neptune from neptunecontrib.monitoring.keras import NeptuneMonitor import collections from sklearn.utils import class_weight import cv2 from scipy import ndimage, misc from tensorflow.keras.models import load_model import os import random from keras.models import Model from keras.layers import Dense, Conv2D, Flatten, LSTM, Activation, Masking, Dropout, GlobalAveragePooling2D import tensorflow as tf import numpy as np from keras.optimizers import RMSprop from keras import backend as k from sklearn.preprocessing import normalize from keras.utils import np_utils from keras import regularizers from keras.applications.inception_v3 import InceptionV3 from keras.preprocessing import image from keras import backend as K from keras.callbacks import CSVLogger from keras.optimizers import * from keras import losses from keras.preprocessing.image import ImageDataGenerator from keras.applications.inception_v3 import preprocess_input import keras from keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.optimizers import SGD from keras.callbacks import ModelCheckpoint #Set up GPU to use for fine tuning os.environ["CUDA_VISIBLE_DEVICES"]="2" #Set up Neptune API to use for tracking training progress neptune_api_key = "Neptune API Key" neptune.init(api_token = neptune_api_key, project_qualified_name='yashaektefaie/benignmodel') def flatten_dict(d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten_dict(v, new_key, sep=sep).items()) else: items.append((new_key, v)) #print(dict(items)) return dict(items) #Identify and open HDF5 file containing data to finetune with hdf5_path = "/home/ye12/benign_model/benigntumorHDF5.hdf5" hdf5_file = tables.open_file(hdf5_path, mode='r') csv_logger = CSVLogger('benign_model_log.tsv', append=True, separator='\t') # Identify and open model to fine tune path_to_model = "model to finetune" model = load_model(path_to_model, compile=True) #Unfreeze specific layers of model to finetune for layer in model.layers[249:]: layer.trainable=True # Recompile model with low learning rate and SGD optimizer foor finetuning lr = 0.00001 model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss="binary_crossentropy",metrics=['accuracy']) #Regular Batch Generating Function, used to load data unmodified def imageLoader(img, labels, batch_size, validation=0): datasetLength = labels.shape[0] while True: batch_start = 0 batch_end = batch_size while batch_start < datasetLength: limit = min(batch_end, datasetLength) X = img[batch_start:limit] if validation: new_X = [] for i in X: i = cv2.resize(cv2.resize(i, (50, 50)), (224,224)) new_X.append(preprocess_input(i)) Y = np.array([[np.float32(i)] for i in labels[batch_start:limit]]) yield (np.array(new_X),Y) else: yield (X, labels[batch_start:limit]) batch_start += batch_size batch_end += batch_size #Modified Batch Generating Function, used to load a proportion of External Data interspersed with training data to protect against catastrophic forgetting def imageLoader_modified(batch_size): datasetLength = hdf5_file.root.exttest_labels.shape[0]*0.40 swap = 0 while True: batch_start = 0 batch_end = batch_size while batch_start < datasetLength: limit = min(batch_end, datasetLength) if swap%5 == 0: X = hdf5_file.root.train_img_modified[batch_start:limit] Y = hdf5_file.root.train_labels_modified[batch_start:limit] else: if swap%2 == 0: X = hdf5_file.root.exttest_img[batch_start:limit] Y = hdf5_file.root.exttest_labels[batch_start:limit] else: X = hdf5_file.root.exttest_img[batch_start+100000:limit+100000] Y = hdf5_file.root.exttest_labels[batch_start+100000:limit+100000] new_X = [] for i in X: i = cv2.resize(cv2.resize(i, (50, 50)), (224,224)) new_X.append(preprocess_input(i)) yield (np.array(new_X),Y) swap += 1 batch_start += batch_size batch_end += batch_size #Batch Size and Neptune Experiment Setup batch_size = 32 train_settings = {'epochs': 50, 'batch_size': batch_size} neptune_kwargs={} exp = neptune.create_experiment(params = flatten_dict({'compile_options': compile_kwargs, 'train_settings': {'learning_rate':lr, **train_settings}}), **neptune_kwargs) #Setup Checkpoint to save best model iteration checkpoint = ModelCheckpoint("Model Checkpoint Name", monitor='val_loss', verbose=1, save_best_only=True, mode='auto', period=1) #Start FineTuning The Model early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto') hist = model.fit( x=imageLoader_modified(batch_size), steps_per_epoch=hdf5_file.root.exttest_img.shape[0]*0.4 // batch_size, epochs=50, validation_data=imageLoader(hdf5_file.root.val_img,hdf5_file.root.val_labels,batch_size, 1), validation_steps=hdf5_file.root.val_img.shape[0] // batch_size, callbacks=[early_stopping, csv_logger, NeptuneMonitor(exp), checkpoint]) model.save('Final Model Name')
[ "neptune.init" ]
[((1446, 1542), 'neptune.init', 'neptune.init', ([], {'api_token': 'neptune_api_key', 'project_qualified_name': '"""yashaektefaie/benignmodel"""'}), "(api_token=neptune_api_key, project_qualified_name=\n 'yashaektefaie/benignmodel')\n", (1458, 1542), False, 'import neptune\n'), ((2046, 2083), 'tables.open_file', 'tables.open_file', (['hdf5_path'], {'mode': '"""r"""'}), "(hdf5_path, mode='r')\n", (2062, 2083), False, 'import tables\n'), ((2099, 2161), 'keras.callbacks.CSVLogger', 'CSVLogger', (['"""benign_model_log.tsv"""'], {'append': '(True)', 'separator': '"""\t"""'}), "('benign_model_log.tsv', append=True, separator='\\t')\n", (2108, 2161), False, 'from keras.callbacks import CSVLogger\n'), ((2246, 2285), 'tensorflow.keras.models.load_model', 'load_model', (['path_to_model'], {'compile': '(True)'}), '(path_to_model, compile=True)\n', (2256, 2285), False, 'from tensorflow.keras.models import load_model\n'), ((5214, 5333), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['"""Model Checkpoint Name"""'], {'monitor': '"""val_loss"""', 'verbose': '(1)', 'save_best_only': '(True)', 'mode': '"""auto"""', 'period': '(1)'}), "('Model Checkpoint Name', monitor='val_loss', verbose=1,\n save_best_only=True, mode='auto', period=1)\n", (5229, 5333), False, 'from keras.callbacks import ModelCheckpoint\n'), ((5380, 5486), 'tensorflow.keras.callbacks.EarlyStopping', 'tf.keras.callbacks.EarlyStopping', ([], {'monitor': '"""val_loss"""', 'min_delta': '(0)', 'patience': '(5)', 'verbose': '(0)', 'mode': '"""auto"""'}), "(monitor='val_loss', min_delta=0, patience=\n 5, verbose=0, mode='auto')\n", (5412, 5486), True, 'import tensorflow as tf\n'), ((2505, 2533), 'tensorflow.keras.optimizers.SGD', 'SGD', ([], {'lr': '(0.0001)', 'momentum': '(0.9)'}), '(lr=0.0001, momentum=0.9)\n', (2508, 2533), False, 'from tensorflow.keras.optimizers import SGD\n'), ((5841, 5860), 'neptunecontrib.monitoring.keras.NeptuneMonitor', 'NeptuneMonitor', (['exp'], {}), '(exp)\n', (5855, 5860), False, 'from neptunecontrib.monitoring.keras import NeptuneMonitor\n'), ((4503, 4526), 'cv2.resize', 'cv2.resize', (['i', '(50, 50)'], {}), '(i, (50, 50))\n', (4513, 4526), False, 'import cv2\n'), ((4568, 4587), 'keras.applications.inception_v3.preprocess_input', 'preprocess_input', (['i'], {}), '(i)\n', (4584, 4587), False, 'from keras.applications.inception_v3 import preprocess_input\n'), ((4608, 4623), 'numpy.array', 'np.array', (['new_X'], {}), '(new_X)\n', (4616, 4623), True, 'import numpy as np\n'), ((3063, 3086), 'cv2.resize', 'cv2.resize', (['i', '(50, 50)'], {}), '(i, (50, 50))\n', (3073, 3086), False, 'import cv2\n'), ((3132, 3151), 'keras.applications.inception_v3.preprocess_input', 'preprocess_input', (['i'], {}), '(i)\n', (3148, 3151), False, 'from keras.applications.inception_v3 import preprocess_input\n'), ((3260, 3275), 'numpy.array', 'np.array', (['new_X'], {}), '(new_X)\n', (3268, 3275), True, 'import numpy as np\n'), ((3184, 3197), 'numpy.float32', 'np.float32', (['i'], {}), '(i)\n', (3194, 3197), True, 'import numpy as np\n')]
import warnings from typing import Callable, Sequence, Union import joblib import neptune.new as neptune import neptune.new.integrations.optuna as optuna_utils import optuna import pandas as pd from optuna.samplers import TPESampler from optuna.study import Study from optuna.trial import FrozenTrial, Trial from sklearn.metrics import mean_absolute_error from xgboost import XGBRegressor warnings.filterwarnings("ignore") class BayesianOptimizer: def __init__( self, objective_function: Callable[[Trial], Union[float, Sequence[float]]] ): self.objective_function = objective_function def bulid_study( self, trials: FrozenTrial, name: str, liar: bool = False, verbose: bool = True, ): if liar: run = neptune.init(project="ds-wook/predict-meals") neptune_callback = optuna_utils.NeptuneCallback( run, plots_update_freq=1, log_plot_slice=False, log_plot_contour=False ) sampler = TPESampler( seed=42, constant_liar=True, multivariate=True, group=True, n_startup_trials=20, ) study = optuna.create_study( study_name=name, direction="minimize", sampler=sampler ) study.optimize( self.objective_function, n_trials=trials, callbacks=[neptune_callback] ) run.stop() else: run = neptune.init(project="ds-wook/predict-meals") neptune_callback = optuna_utils.NeptuneCallback( run, plots_update_freq=1, log_plot_slice=False, log_plot_contour=False ) sampler = TPESampler(seed=42) study = optuna.create_study( study_name=name, direction="minimize", sampler=sampler ) study.optimize( self.objective_function, n_trials=trials, callbacks=[neptune_callback] ) run.stop() if verbose: self.display_study_statistics(study) return study @staticmethod def display_study_statistics(study: Study): print("Best trial:") trial = study.best_trial print(" Value: ", trial.value) print(" Params: ") for key, value in trial.params.items(): print(f" '{key}': {value},") @staticmethod def xgb_lunch_save_params(study: Study, params_name: str): params = study.best_trial.params params["random_state"] = 42 params["n_estimators"] = 10000 params["learning_rate"] = 0.02 params["eval_metric"] = "mae" joblib.dump(params, "../../parameters/" + params_name) @staticmethod def xgb_dinner_save_params(study: Study, params_name: str): params = study.best_trial.params params["random_state"] = 42 params["n_estimators"] = 10000 params["eval_metric"] = "mae" joblib.dump(params, "../../parameters/" + params_name) def xgb_lunch_objective( trial: FrozenTrial, x_train: pd.DataFrame, y_train: pd.DataFrame, x_valid: pd.DataFrame, y_valid: pd.DataFrame, verbose: Union[int, bool], ) -> float: param = { "lambda": trial.suggest_loguniform("lambda", 1e-03, 1e-01), "subsample": trial.suggest_float("subsample", 0.5, 1), "max_depth": trial.suggest_int("max_depth", 3, 20), "min_child_weight": trial.suggest_int("min_child_weight", 1, 300), "random_state": 42, "learning_rate": 0.02, "n_estimators": 10000, "eval_metric": "mae", } model = XGBRegressor(**param) model.fit( x_train, y_train, eval_set=[(x_train, y_train), (x_valid, y_valid)], early_stopping_rounds=100, verbose=verbose, ) preds = model.predict(x_valid) mae = mean_absolute_error(y_valid, preds) return mae def xgb_dinner_objective( trial: FrozenTrial, x_train: pd.DataFrame, y_train: pd.DataFrame, x_valid: pd.DataFrame, y_valid: pd.DataFrame, verbose: Union[int, bool], ) -> float: param = { "colsample_bytree": trial.suggest_float("colsample_bytree", 0.5, 1), "subsample": trial.suggest_float("subsample", 0.5, 1), "learning_rate": trial.suggest_float("learning_rate", 1e-02, 1e-01), "n_estimators": 10000, "max_depth": trial.suggest_int("max_depth", 3, 20), "random_state": 42, "eval_metric": "mae", "min_child_weight": trial.suggest_int("min_child_weight", 1, 300), } model = XGBRegressor(**param) model.fit( x_train, y_train, eval_set=[(x_train, y_train), (x_valid, y_valid)], early_stopping_rounds=100, verbose=verbose, ) preds = model.predict(x_valid) mae = mean_absolute_error(y_valid, preds) return mae
[ "neptune.new.init", "neptune.new.integrations.optuna.NeptuneCallback" ]
[((391, 424), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (414, 424), False, 'import warnings\n'), ((3692, 3713), 'xgboost.XGBRegressor', 'XGBRegressor', ([], {}), '(**param)\n', (3704, 3713), False, 'from xgboost import XGBRegressor\n'), ((3936, 3971), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['y_valid', 'preds'], {}), '(y_valid, preds)\n', (3955, 3971), False, 'from sklearn.metrics import mean_absolute_error\n'), ((4665, 4686), 'xgboost.XGBRegressor', 'XGBRegressor', ([], {}), '(**param)\n', (4677, 4686), False, 'from xgboost import XGBRegressor\n'), ((4907, 4942), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['y_valid', 'preds'], {}), '(y_valid, preds)\n', (4926, 4942), False, 'from sklearn.metrics import mean_absolute_error\n'), ((2717, 2771), 'joblib.dump', 'joblib.dump', (['params', "('../../parameters/' + params_name)"], {}), "(params, '../../parameters/' + params_name)\n", (2728, 2771), False, 'import joblib\n'), ((3017, 3071), 'joblib.dump', 'joblib.dump', (['params', "('../../parameters/' + params_name)"], {}), "(params, '../../parameters/' + params_name)\n", (3028, 3071), False, 'import joblib\n'), ((797, 842), 'neptune.new.init', 'neptune.init', ([], {'project': '"""ds-wook/predict-meals"""'}), "(project='ds-wook/predict-meals')\n", (809, 842), True, 'import neptune.new as neptune\n'), ((874, 978), 'neptune.new.integrations.optuna.NeptuneCallback', 'optuna_utils.NeptuneCallback', (['run'], {'plots_update_freq': '(1)', 'log_plot_slice': '(False)', 'log_plot_contour': '(False)'}), '(run, plots_update_freq=1, log_plot_slice=False,\n log_plot_contour=False)\n', (902, 978), True, 'import neptune.new.integrations.optuna as optuna_utils\n'), ((1027, 1122), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(42)', 'constant_liar': '(True)', 'multivariate': '(True)', 'group': '(True)', 'n_startup_trials': '(20)'}), '(seed=42, constant_liar=True, multivariate=True, group=True,\n n_startup_trials=20)\n', (1037, 1122), False, 'from optuna.samplers import TPESampler\n'), ((1234, 1309), 'optuna.create_study', 'optuna.create_study', ([], {'study_name': 'name', 'direction': '"""minimize"""', 'sampler': 'sampler'}), "(study_name=name, direction='minimize', sampler=sampler)\n", (1253, 1309), False, 'import optuna\n'), ((1525, 1570), 'neptune.new.init', 'neptune.init', ([], {'project': '"""ds-wook/predict-meals"""'}), "(project='ds-wook/predict-meals')\n", (1537, 1570), True, 'import neptune.new as neptune\n'), ((1602, 1706), 'neptune.new.integrations.optuna.NeptuneCallback', 'optuna_utils.NeptuneCallback', (['run'], {'plots_update_freq': '(1)', 'log_plot_slice': '(False)', 'log_plot_contour': '(False)'}), '(run, plots_update_freq=1, log_plot_slice=False,\n log_plot_contour=False)\n', (1630, 1706), True, 'import neptune.new.integrations.optuna as optuna_utils\n'), ((1755, 1774), 'optuna.samplers.TPESampler', 'TPESampler', ([], {'seed': '(42)'}), '(seed=42)\n', (1765, 1774), False, 'from optuna.samplers import TPESampler\n'), ((1795, 1870), 'optuna.create_study', 'optuna.create_study', ([], {'study_name': 'name', 'direction': '"""minimize"""', 'sampler': 'sampler'}), "(study_name=name, direction='minimize', sampler=sampler)\n", (1814, 1870), False, 'import optuna\n')]
import neptune def _update_keys(d, prefix): keys = list(d.keys()) for k in keys: d['{}_{}'.format(prefix, k)] = d.pop(k) class NeptuneWriter: def __init__(self, proj_name): self.project = neptune.init(proj_name) self.has_started = False def start(self, args, **kwargs): self.experiment = self.project.create_experiment( name=args['experiment_name'], params=args, **kwargs) self.has_started = True def fin(self): if self.has_started: # will finish when all data has been sent self.experiment.stop() self.has_started = False def write(self, data, step): if self.has_started: for k in data.keys(): self.experiment.log_metric(k, step, data[k]) else: print('Warning: Writing to dead writer - call .start({}) first') def id(self): return self.experiment.id
[ "neptune.init" ]
[((220, 243), 'neptune.init', 'neptune.init', (['proj_name'], {}), '(proj_name)\n', (232, 243), False, 'import neptune\n')]
import neptune.new as neptune import os import torch.nn as nn import torch import torch.nn.functional as F from torch.optim import SGD, Adam from torch.utils.data import DataLoader, random_split from torch.optim.lr_scheduler import CyclicLR import torch.multiprocessing as mp import numpy as np import random import math import sys sys.path.append("..") # adds higher directory to python modules path from LoaderPACK.Unet_leaky import Unet_leaky, Unet_leaky_lstm from LoaderPACK.Loader import shuffle_5min from LoaderPACK.trainer import net_train from LoaderPACK.Accuarcy_finder import Accuarcy_find from LoaderPACK.Accuarcy_upload import Accuarcy_upload from multiprocessing import Process try: mp.set_start_method('spawn') except RuntimeError: pass def net_SGD(device, fl, it, train_path, val_path): token = os.getenv('Neptune_api') run = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, ) net_name = "network_SGD" batch_size = 10 n_samples = 17 # the defualt amount of samples minus 1 train_load_file = shuffle_5min(path = train_path, series_dict = 'train_series_length.pickle', size = (195, 22, 2060000), device = device, length = n_samples) train_loader = torch.utils.data.DataLoader(train_load_file, batch_size=batch_size, shuffle=True, num_workers=0) val_load_file = shuffle_5min(path = val_path, series_dict = 'val_series_length.pickle', size = (28, 22, 549200), device = device, seed = 42) val_loader = torch.utils.data.DataLoader(val_load_file, batch_size=batch_size, shuffle=False, num_workers=0, drop_last=True) nEpoch = 100 base_lr = 0.216 # where we start the learning rate (min point) max_lr = 0.268 # where the learning rate is at the max point weight_decay = 0 step_size_up = (n_samples/batch_size)*5 model = Unet_leaky_lstm(n_channels=1, batch_size=batch_size, \ device=device).to(device) optimizer = SGD(model.parameters(), lr=base_lr) lossFunc = nn.CrossEntropyLoss(weight = torch.tensor([1., 5.]).to(device), reduction = "mean") scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr, step_size_up=step_size_up, cycle_momentum=True, base_momentum=0.8, max_momentum=0.9) smooth = 0.05 params = {"optimizer":"SGD", "batch_size":batch_size, "optimizer_learning_rate": base_lr, "loss_function":"CrossEntropyLoss", "loss_function_weights":[1, 5], "loss_function_reduction":"mean", "model":"Unet_leaky_lstm", "scheduler":"CyclicLR", "scheduler_base_lr":base_lr, "scheduler_max_lr":max_lr, "scheduler_cycle_momentum":True, "base_momentum":0.8, "max_momentum":0.9, "scheduler_step_size_up":step_size_up, "smooting_loss":smooth} run[f"{net_name}/parameters"] = params net_train(device = device, fl = fl, it = it, net_name = net_name, model = model, optimizer = optimizer, lossFunc = lossFunc, nEpoch = nEpoch, smooth = smooth, train_loader = train_loader, val_loader = val_loader, run = run, path = "C:/Users/Marc/Desktop/network/", scheduler = scheduler) def net_ADAM(device, fl, it, train_path, val_path): token = os.getenv('Neptune_api') run = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, ) net_name = "network_ADAM" batch_size = 10 n_samples = 11141 - 1 # the defualt amount of samples minus 1 train_load_file = shuffle_5min(path = train_path, series_dict = 'train_series_length.pickle', size = (195, 22, 2060000), device = device, length = n_samples) train_loader = torch.utils.data.DataLoader(train_load_file, batch_size=batch_size, shuffle=True, num_workers=0, drop_last=True) val_load_file = shuffle_5min(path = val_path, series_dict = 'val_series_length.pickle', size = (28, 22, 549200), device = device, seed = 42) val_loader = torch.utils.data.DataLoader(val_load_file, batch_size=batch_size, shuffle=False, num_workers=0, drop_last=True) nEpoch = 100 base_lr = 0.0089 # where we start the learning rate (min point) max_lr = 0.013 # where the learning rate is at the max point weight_decay = 0.0001 step_size_up = (n_samples/batch_size)*5 model = Unet_leaky_lstm(n_channels=1, batch_size=batch_size, \ device=device).to(device) # model = Unet_leaky(n_channels=1, n_classes=2).to(device) optimizer = Adam(model.parameters(), lr=0.004, weight_decay=weight_decay) lossFunc = nn.CrossEntropyLoss(weight = torch.tensor([1., 5.]).to(device), reduction = "mean") scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr, step_size_up=step_size_up, cycle_momentum=False) # step_size_up is set so the learning rate is updated linearly smooth = 0.05 params = {"optimizer":"ADAM", "batch_size":batch_size, "optimizer_learning_rate": base_lr, "optimizer_weight_decay": weight_decay, "loss_function":"CrossEntropyLoss", "loss_function_weights":[1, 5], "loss_function_reduction":"mean", "model":"Unet_leaky_lstm", "scheduler":"CyclicLR", "scheduler_base_lr":base_lr, "scheduler_max_lr":max_lr, "scheduler_cycle_momentum":False, "scheduler_step_size_up":step_size_up, "smooting_loss":smooth} run[f"{net_name}/parameters"] = params net_train(device = device, fl = fl, it = it, net_name = net_name, model = model, optimizer = optimizer, lossFunc = lossFunc, nEpoch = nEpoch, smooth = smooth, train_loader = train_loader, val_loader = val_loader, run = run, path = "/home/tyson/network/", #"C:/Users/Marc/Desktop/network/", scheduler = scheduler) def net_starter(nets, device, fl, it, train_path, val_path): for net in nets: pr1 = mp.Process(target=net, args = (device, fl, it, train_path, val_path,)) pr1.start() pr1.join() if __name__ == '__main__': device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) if device == "cpu": fl = torch.FloatTensor it = torch.LongTensor else: fl = torch.cuda.FloatTensor it = torch.cuda.LongTensor core = torch.cuda.device_count() networks = [net_SGD] # cuda_dict = dict() # cuda_dict[core] = networks for i in range(core): cuda_dict[i] = [] for i in range(len(networks)): cuda_dict[i % core].append(networks[i]) # i % core #"/home/tyson/model_data/train_model_data" # "C:/Users/Marc/Desktop/model_data/train_model_data" # train_path = "/home/tyson/data_cutoff/train_model_data" # val_path = "/home/tyson/data_cutoff/val_model_data" train_path = r"C:\Users\Marc\Desktop\data\train_model_data" val_path = r"C:\Users\Marc\Desktop\data\val_model_data" pres = [] for i in range(core): pres.append(mp.Process(target=net_starter, args = (cuda_dict.get(i), f"cuda:{i}", fl, it, train_path, val_path,))) for process in pres: process.start() for process in pres: process.join()
[ "neptune.new.init" ]
[((333, 354), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (348, 354), False, 'import sys\n'), ((703, 731), 'torch.multiprocessing.set_start_method', 'mp.set_start_method', (['"""spawn"""'], {}), "('spawn')\n", (722, 731), True, 'import torch.multiprocessing as mp\n'), ((828, 852), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (837, 852), False, 'import os\n'), ((863, 928), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token'}), "(project='NTLAB/artifact-rej-scalp', api_token=token)\n", (875, 928), True, 'import neptune.new as neptune\n'), ((1085, 1218), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'train_path', 'series_dict': '"""train_series_length.pickle"""', 'size': '(195, 22, 2060000)', 'device': 'device', 'length': 'n_samples'}), "(path=train_path, series_dict='train_series_length.pickle',\n size=(195, 22, 2060000), device=device, length=n_samples)\n", (1097, 1218), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((1386, 1487), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(train_load_file, batch_size=batch_size, shuffle\n =True, num_workers=0)\n', (1413, 1487), False, 'import torch\n'), ((1645, 1764), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'val_path', 'series_dict': '"""val_series_length.pickle"""', 'size': '(28, 22, 549200)', 'device': 'device', 'seed': '(42)'}), "(path=val_path, series_dict='val_series_length.pickle', size=(\n 28, 22, 549200), device=device, seed=42)\n", (1657, 1764), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((1921, 2037), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_load_file'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(0)', 'drop_last': '(True)'}), '(val_load_file, batch_size=batch_size, shuffle=\n False, num_workers=0, drop_last=True)\n', (1948, 2037), False, 'import torch\n'), ((2755, 2896), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': 'base_lr', 'max_lr': 'max_lr', 'step_size_up': 'step_size_up', 'cycle_momentum': '(True)', 'base_momentum': '(0.8)', 'max_momentum': '(0.9)'}), '(optimizer, base_lr=base_lr, max_lr=max_lr, step_size_up=\n step_size_up, cycle_momentum=True, base_momentum=0.8, max_momentum=0.9)\n', (2763, 2896), False, 'from torch.optim.lr_scheduler import CyclicLR\n'), ((3616, 3888), 'LoaderPACK.trainer.net_train', 'net_train', ([], {'device': 'device', 'fl': 'fl', 'it': 'it', 'net_name': 'net_name', 'model': 'model', 'optimizer': 'optimizer', 'lossFunc': 'lossFunc', 'nEpoch': 'nEpoch', 'smooth': 'smooth', 'train_loader': 'train_loader', 'val_loader': 'val_loader', 'run': 'run', 'path': '"""C:/Users/Marc/Desktop/network/"""', 'scheduler': 'scheduler'}), "(device=device, fl=fl, it=it, net_name=net_name, model=model,\n optimizer=optimizer, lossFunc=lossFunc, nEpoch=nEpoch, smooth=smooth,\n train_loader=train_loader, val_loader=val_loader, run=run, path=\n 'C:/Users/Marc/Desktop/network/', scheduler=scheduler)\n", (3625, 3888), False, 'from LoaderPACK.trainer import net_train\n'), ((4139, 4163), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (4148, 4163), False, 'import os\n'), ((4174, 4239), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token'}), "(project='NTLAB/artifact-rej-scalp', api_token=token)\n", (4186, 4239), True, 'import neptune.new as neptune\n'), ((4404, 4537), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'train_path', 'series_dict': '"""train_series_length.pickle"""', 'size': '(195, 22, 2060000)', 'device': 'device', 'length': 'n_samples'}), "(path=train_path, series_dict='train_series_length.pickle',\n size=(195, 22, 2060000), device=device, length=n_samples)\n", (4416, 4537), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((4705, 4822), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)', 'drop_last': '(True)'}), '(train_load_file, batch_size=batch_size, shuffle\n =True, num_workers=0, drop_last=True)\n', (4732, 4822), False, 'import torch\n'), ((5027, 5146), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'val_path', 'series_dict': '"""val_series_length.pickle"""', 'size': '(28, 22, 549200)', 'device': 'device', 'seed': '(42)'}), "(path=val_path, series_dict='val_series_length.pickle', size=(\n 28, 22, 549200), device=device, seed=42)\n", (5039, 5146), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((5303, 5419), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_load_file'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(0)', 'drop_last': '(True)'}), '(val_load_file, batch_size=batch_size, shuffle=\n False, num_workers=0, drop_last=True)\n', (5330, 5419), False, 'import torch\n'), ((6231, 6336), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': 'base_lr', 'max_lr': 'max_lr', 'step_size_up': 'step_size_up', 'cycle_momentum': '(False)'}), '(optimizer, base_lr=base_lr, max_lr=max_lr, step_size_up=\n step_size_up, cycle_momentum=False)\n', (6239, 6336), False, 'from torch.optim.lr_scheduler import CyclicLR\n'), ((7100, 7362), 'LoaderPACK.trainer.net_train', 'net_train', ([], {'device': 'device', 'fl': 'fl', 'it': 'it', 'net_name': 'net_name', 'model': 'model', 'optimizer': 'optimizer', 'lossFunc': 'lossFunc', 'nEpoch': 'nEpoch', 'smooth': 'smooth', 'train_loader': 'train_loader', 'val_loader': 'val_loader', 'run': 'run', 'path': '"""/home/tyson/network/"""', 'scheduler': 'scheduler'}), "(device=device, fl=fl, it=it, net_name=net_name, model=model,\n optimizer=optimizer, lossFunc=lossFunc, nEpoch=nEpoch, smooth=smooth,\n train_loader=train_loader, val_loader=val_loader, run=run, path=\n '/home/tyson/network/', scheduler=scheduler)\n", (7109, 7362), False, 'from LoaderPACK.trainer import net_train\n'), ((8186, 8211), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (8209, 8211), False, 'import torch\n'), ((7680, 7747), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'net', 'args': '(device, fl, it, train_path, val_path)'}), '(target=net, args=(device, fl, it, train_path, val_path))\n', (7690, 7747), True, 'import torch.multiprocessing as mp\n'), ((2442, 2509), 'LoaderPACK.Unet_leaky.Unet_leaky_lstm', 'Unet_leaky_lstm', ([], {'n_channels': '(1)', 'batch_size': 'batch_size', 'device': 'device'}), '(n_channels=1, batch_size=batch_size, device=device)\n', (2457, 2509), False, 'from LoaderPACK.Unet_leaky import Unet_leaky, Unet_leaky_lstm\n'), ((5830, 5897), 'LoaderPACK.Unet_leaky.Unet_leaky_lstm', 'Unet_leaky_lstm', ([], {'n_channels': '(1)', 'batch_size': 'batch_size', 'device': 'device'}), '(n_channels=1, batch_size=batch_size, device=device)\n', (5845, 5897), False, 'from LoaderPACK.Unet_leaky import Unet_leaky, Unet_leaky_lstm\n'), ((7951, 7976), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7974, 7976), False, 'import torch\n'), ((2648, 2672), 'torch.tensor', 'torch.tensor', (['[1.0, 5.0]'], {}), '([1.0, 5.0])\n', (2660, 2672), False, 'import torch\n'), ((6124, 6148), 'torch.tensor', 'torch.tensor', (['[1.0, 5.0]'], {}), '([1.0, 5.0])\n', (6136, 6148), False, 'import torch\n')]
# -*- coding: utf-8 -*- # # Copyright (c) 2017, deepsense.io # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import json import os import sys from neptune.generated.swagger_client import (InputPath, QueuedRemoteExperimentParams, StringParam) from neptune.internal.cli.commands.command_names import CommandNames from neptune.internal.cli.commands.enqueue_utils import EnqueueUtils from neptune.internal.cli.commands.executing.execution_paths import ExecutionPaths from neptune.internal.cli.commands.neptune_command import NeptuneCommand from neptune.internal.cli.commands.parsers.root_parser import NeptuneRootCommandParser from neptune.internal.cli.commands.utils.pip_requirements_utils import create_string_param from neptune.internal.cli.experiments.experiment_creator import ExperimentsCreator from neptune.internal.cli.storage.populate_storage_utils import (CopyProgressBar, collect_files) from neptune.internal.cli.storage.upload_storage_utils import upload_to_storage from neptune.internal.common import NeptuneException from neptune.internal.common.config.job_config import ConfigKeys from neptune.internal.common.config.neptune_config import NeptuneConfig, load_global_config, load_local_config from neptune.internal.common.models.rich_project import ProjectResolver from neptune.internal.common.parsers.command_parsing_utils import (compose_string_command) from neptune.internal.common.parsers.common_parameters_configurator import \ CommonParametersConfigurator from neptune.internal.common.utils.git import send_git_info_if_present class NeptuneRun(NeptuneCommand): def __init__(self, config, local_storage, api_service, tracked_parameter_parser, web_browser, project, neptune_exec_factory, name, environment=None, inputs=None): super(NeptuneRun, self).__init__(name, config, api_service) self._tracked_parameter_parser = tracked_parameter_parser self._rest_api_url = self.config.rest_url self.logger.debug("Rest API url: %s", self._rest_api_url) self.project = project self.enqueue_utils = EnqueueUtils(config, api_service, web_browser) self._neptune_exec_factory = neptune_exec_factory self._local_storage = local_storage self._command_parser = NeptuneRootCommandParser() self.environment = environment self.inputs = inputs or [] self.current_command = None self.experiment_ids = [] self.tracked_params = None self.experiment_config = None self._experiments_creator = ExperimentsCreator(enqueue_utils=self.enqueue_utils, project=self.project) def prepare(self, args): self.experiment_config = self._create_run_parameters(args) self.tracked_params = \ self.enqueue_utils.parse_experiment_arguments(self.experiment_config, self._tracked_parameter_parser) self.config.parameters = self.experiment_config.parameters # pylint:disable=arguments-differ def run(self, args): try: self._ensure_executable_exists() self.prepare(args) result = self._create_experiments(args) self.experiment_ids = result.experiment_ids if args.known_args.snapshot: custom_execution_paths = self._make_code_snapshot(result.short_id) print(self._snapshot_info_message(snapshot_path=custom_execution_paths.sources_location)) else: custom_execution_paths = None self._close_experiment_creation_message() self._configure_experiments(self.experiment_ids) self.exit_code = self._exec_experiments( experiment_ids=self.experiment_ids, debug=args.known_args.debug, custom_execution_paths=custom_execution_paths) except: self.exit_code = self.UNKNOWN_EXCEPTION_EXIT_CODE raise def _create_experiments(self, args): return self._experiments_creator.create( experiment_config=self.experiment_config, enqueue_command=self._enqueue_command(args.raw_args), notebook_absolute_path=self._get_notebook_absolute_path(), tracked_params=self.tracked_params, parameters=self.config.parameters, remote_params=self._get_remote_params() ) def _configure_experiments(self, experiment_ids): self.api_service.add_experiments_backups(experiment_ids=experiment_ids, globs=list(self.config.backup)) self._upload_sources(experiment_ids) send_git_info_if_present(self.api_service, experiment_ids) for experiment_id in experiment_ids: self.api_service.mark_experiment_waiting(experiment_id) @classmethod def _create_run_parameters(cls, args): if getattr(args.known_args, 'executable', None): print(u"Using --executable is deprecated. Pass the executable as a positional parameter.") profile = getattr(args.known_args, ConfigKeys.PROFILE, CommonParametersConfigurator.DEFAULT_PROFILE) return NeptuneConfig( commandline_args=args, local_config=load_local_config(args.known_args.config), global_config=load_global_config(profile), cli_parameters=(args.known_args.parameter or []) ) def _ensure_executable_exists(self): if self.config.executable is None: raise NeptuneException(self.config.NO_EXECUTABLE_MESSAGE) def _upload_sources(self, experiment_ids): files_list, data_size, empty_dir_list = collect_files(exclude=self.config.exclude) empty_dir_list = [(x, y.replace("./", "", 1)) for x, y in empty_dir_list] copy_progress_bar = CopyProgressBar(data_size, u"Sending sources to server") experiment_id = experiment_ids[0] upload_to_storage(files_list=files_list, dir_list=empty_dir_list, upload_api_fun=self.api_service.upload_experiment_source, upload_tarstream_api_fun=self.api_service.upload_experiment_source_as_tarstream, callback=copy_progress_bar.update, experiment_id=experiment_id) copy_progress_bar.finalize() self.api_service.finalize_experiment_upload( experiment_id=experiment_id, target_experiment_ids=experiment_ids ) def abort(self): try: if self.current_command is not None: self.current_command.abort() finally: if self.experiment_ids: print(u'Marking experiments as aborted...') # TODO group abort self.api_service.mark_experiment_aborted(self.experiment_ids, with_retries=False) @staticmethod def _close_experiment_creation_message(): # Until this call, we can print formatted lines, like this: # > # > Experiment enqueued, id: ... # > sys.stdout.write(u'\n') @staticmethod def _confirmation_message(experiment_id): return (u'>\n' u'> Started experiment execution, id: {experiment_id}\n' u'>\n').format(experiment_id=experiment_id) @staticmethod def _snapshot_info_message(snapshot_path): return (u"> Source code and output are located in: {}\n" u">").format(snapshot_path) def _make_code_snapshot(self, short_id): code_snapshot = self._local_storage.experiments_directory.copy_to_subdir( src=os.getcwd(), dst_subdir_name=short_id) return ExecutionPaths(sources_location=code_snapshot.absolute_path) def _exec_experiments(self, experiment_ids, debug, custom_execution_paths): exit_codes = [ self._exec_experiment( experiment_id=experiment_id, print_confirmation=len(experiment_ids) > 1, debug=debug, custom_execution_paths=custom_execution_paths) for experiment_id in experiment_ids ] return self._combined_exit_code(exit_codes) def _exec_experiment(self, experiment_id, print_confirmation=False, debug=False, custom_execution_paths=None): if print_confirmation: print(self._confirmation_message(experiment_id)) exec_args_list = [CommandNames.EXEC, experiment_id] CommonParametersConfigurator.append_debug_param(exec_args_list, debug) args = self._command_parser.get_arguments(exec_args_list) self.current_command = self._neptune_exec_factory.create( experiment_id=experiment_id, environment=self.environment, custom_execution_paths=custom_execution_paths ) self.current_command.run(args) return self.current_command.exit_code @staticmethod def _enqueue_command(raw_args): return compose_string_command(raw_args=[u'neptune'] + raw_args) def _get_notebook_absolute_path(self): return None def _get_remote_params(self): return None @staticmethod def _combined_exit_code(exit_codes): non_zero_exit_codes = [c for c in exit_codes if c != 0] return (non_zero_exit_codes + [0])[0] class NeptuneRunWorker(NeptuneRun): def __init__(self, config, local_storage, api_service, tracked_parameter_parser, inputs, environment, worker, web_browser, project, experiment_executor_factory): super(NeptuneRunWorker, self).__init__(config=config, local_storage=local_storage, api_service=api_service, tracked_parameter_parser=tracked_parameter_parser, environment=environment, web_browser=web_browser, project=project, inputs=inputs, neptune_exec_factory=None, name=CommandNames.SEND) self._rest_api_url = self.config.rest_url self.logger.debug("Rest API url: %s", self._rest_api_url) self.worker = worker self.experiment_executor_factory = experiment_executor_factory def run(self, args): self._ensure_executable_exists() self.prepare(args) self.experiment_ids = self._create_experiments(args).experiment_ids self._close_experiment_creation_message() self._configure_experiments(self.experiment_ids) def _get_remote_params(self): inputs = self._get_inputs() string_params = self._get_string_params() token = self._get_token() return QueuedRemoteExperimentParams(inputs=inputs, environment=self.environment, worker_type=self.worker, string_params=string_params, token=json.dumps(token, sort_keys=True)) def _get_string_params(self): string_params = [] ml_framework = self.config.ml_framework log_channels = self.config.log_channels pip_requirements_file = self.config.pip_requirements_file for log_channel in log_channels: string_params.append(StringParam(name=CommonParametersConfigurator.LOG_CHANNEL, value=str(log_channel))) if ml_framework: string_params.append(StringParam(name=ConfigKeys.ML_FRAMEWORK, value=ml_framework)) if pip_requirements_file: string_params.append(create_string_param(pip_requirements_file)) return string_params def _get_token(self): offline_token = self.experiment_executor_factory.offline_token_storage_service.load() keycloak_api_service = self.experiment_executor_factory.keycloak_api_service return keycloak_api_service.request_token_refresh(offline_token.refresh_token).raw def _get_inputs(self): inputs = [] for entry in self.inputs: split_list = entry.split(':', 1) destination = split_list[1] if len(split_list) == 2 else '' inputs.append(InputPath(source=split_list[0], destination=destination)) return inputs class NeptuneRunFactory(object): def __init__(self, api_service, config, local_storage, tracked_parameter_parser, web_browser, experiment_executor_factory): self.api_service = api_service self.config = config self.local_storage = local_storage self.tracked_parameter_parser = tracked_parameter_parser self.web_browser = web_browser self.experiment_executor_factory = experiment_executor_factory def create(self, is_local, neptune_exec_factory, environment=None, worker=None, inputs=None): web_browser = self.web_browser project = ProjectResolver.resolve( api_service=self.api_service, organization_name=self.config.organization_name, project_name=self.config.project_name) if is_local: return NeptuneRun( config=self.config, local_storage=self.local_storage, api_service=self.api_service, tracked_parameter_parser=self.tracked_parameter_parser, environment=environment, web_browser=web_browser, neptune_exec_factory=neptune_exec_factory, project=project, name=CommandNames.RUN ) else: return NeptuneRunWorker( config=self.config, local_storage=self.local_storage, api_service=self.api_service, tracked_parameter_parser=self.tracked_parameter_parser, inputs=inputs, environment=environment, worker=worker, web_browser=web_browser, project=project, experiment_executor_factory=self.experiment_executor_factory )
[ "neptune.internal.cli.storage.upload_storage_utils.upload_to_storage", "neptune.internal.cli.commands.enqueue_utils.EnqueueUtils", "neptune.internal.common.config.neptune_config.load_global_config", "neptune.internal.cli.storage.populate_storage_utils.CopyProgressBar", "neptune.internal.common.NeptuneExcept...
[((2775, 2821), 'neptune.internal.cli.commands.enqueue_utils.EnqueueUtils', 'EnqueueUtils', (['config', 'api_service', 'web_browser'], {}), '(config, api_service, web_browser)\n', (2787, 2821), False, 'from neptune.internal.cli.commands.enqueue_utils import EnqueueUtils\n'), ((2957, 2983), 'neptune.internal.cli.commands.parsers.root_parser.NeptuneRootCommandParser', 'NeptuneRootCommandParser', ([], {}), '()\n', (2981, 2983), False, 'from neptune.internal.cli.commands.parsers.root_parser import NeptuneRootCommandParser\n'), ((3238, 3312), 'neptune.internal.cli.experiments.experiment_creator.ExperimentsCreator', 'ExperimentsCreator', ([], {'enqueue_utils': 'self.enqueue_utils', 'project': 'self.project'}), '(enqueue_utils=self.enqueue_utils, project=self.project)\n', (3256, 3312), False, 'from neptune.internal.cli.experiments.experiment_creator import ExperimentsCreator\n'), ((5214, 5272), 'neptune.internal.common.utils.git.send_git_info_if_present', 'send_git_info_if_present', (['self.api_service', 'experiment_ids'], {}), '(self.api_service, experiment_ids)\n', (5238, 5272), False, 'from neptune.internal.common.utils.git import send_git_info_if_present\n'), ((6280, 6322), 'neptune.internal.cli.storage.populate_storage_utils.collect_files', 'collect_files', ([], {'exclude': 'self.config.exclude'}), '(exclude=self.config.exclude)\n', (6293, 6322), False, 'from neptune.internal.cli.storage.populate_storage_utils import CopyProgressBar, collect_files\n'), ((6434, 6490), 'neptune.internal.cli.storage.populate_storage_utils.CopyProgressBar', 'CopyProgressBar', (['data_size', 'u"""Sending sources to server"""'], {}), "(data_size, u'Sending sources to server')\n", (6449, 6490), False, 'from neptune.internal.cli.storage.populate_storage_utils import CopyProgressBar, collect_files\n'), ((6542, 6828), 'neptune.internal.cli.storage.upload_storage_utils.upload_to_storage', 'upload_to_storage', ([], {'files_list': 'files_list', 'dir_list': 'empty_dir_list', 'upload_api_fun': 'self.api_service.upload_experiment_source', 'upload_tarstream_api_fun': 'self.api_service.upload_experiment_source_as_tarstream', 'callback': 'copy_progress_bar.update', 'experiment_id': 'experiment_id'}), '(files_list=files_list, dir_list=empty_dir_list,\n upload_api_fun=self.api_service.upload_experiment_source,\n upload_tarstream_api_fun=self.api_service.\n upload_experiment_source_as_tarstream, callback=copy_progress_bar.\n update, experiment_id=experiment_id)\n', (6559, 6828), False, 'from neptune.internal.cli.storage.upload_storage_utils import upload_to_storage\n'), ((7713, 7736), 'sys.stdout.write', 'sys.stdout.write', (['u"""\n"""'], {}), "(u'\\n')\n", (7729, 7736), False, 'import sys\n'), ((8331, 8391), 'neptune.internal.cli.commands.executing.execution_paths.ExecutionPaths', 'ExecutionPaths', ([], {'sources_location': 'code_snapshot.absolute_path'}), '(sources_location=code_snapshot.absolute_path)\n', (8345, 8391), False, 'from neptune.internal.cli.commands.executing.execution_paths import ExecutionPaths\n'), ((9084, 9154), 'neptune.internal.common.parsers.common_parameters_configurator.CommonParametersConfigurator.append_debug_param', 'CommonParametersConfigurator.append_debug_param', (['exec_args_list', 'debug'], {}), '(exec_args_list, debug)\n', (9131, 9154), False, 'from neptune.internal.common.parsers.common_parameters_configurator import CommonParametersConfigurator\n'), ((9596, 9652), 'neptune.internal.common.parsers.command_parsing_utils.compose_string_command', 'compose_string_command', ([], {'raw_args': "([u'neptune'] + raw_args)"}), "(raw_args=[u'neptune'] + raw_args)\n", (9618, 9652), False, 'from neptune.internal.common.parsers.command_parsing_utils import compose_string_command\n'), ((13691, 13837), 'neptune.internal.common.models.rich_project.ProjectResolver.resolve', 'ProjectResolver.resolve', ([], {'api_service': 'self.api_service', 'organization_name': 'self.config.organization_name', 'project_name': 'self.config.project_name'}), '(api_service=self.api_service, organization_name=\n self.config.organization_name, project_name=self.config.project_name)\n', (13714, 13837), False, 'from neptune.internal.common.models.rich_project import ProjectResolver\n'), ((6132, 6183), 'neptune.internal.common.NeptuneException', 'NeptuneException', (['self.config.NO_EXECUTABLE_MESSAGE'], {}), '(self.config.NO_EXECUTABLE_MESSAGE)\n', (6148, 6183), False, 'from neptune.internal.common import NeptuneException\n'), ((5860, 5901), 'neptune.internal.common.config.neptune_config.load_local_config', 'load_local_config', (['args.known_args.config'], {}), '(args.known_args.config)\n', (5877, 5901), False, 'from neptune.internal.common.config.neptune_config import NeptuneConfig, load_global_config, load_local_config\n'), ((5929, 5956), 'neptune.internal.common.config.neptune_config.load_global_config', 'load_global_config', (['profile'], {}), '(profile)\n', (5947, 5956), False, 'from neptune.internal.common.config.neptune_config import NeptuneConfig, load_global_config, load_local_config\n'), ((8277, 8288), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8286, 8288), False, 'import os\n'), ((11783, 11816), 'json.dumps', 'json.dumps', (['token'], {'sort_keys': '(True)'}), '(token, sort_keys=True)\n', (11793, 11816), False, 'import json\n'), ((12260, 12321), 'neptune.generated.swagger_client.StringParam', 'StringParam', ([], {'name': 'ConfigKeys.ML_FRAMEWORK', 'value': 'ml_framework'}), '(name=ConfigKeys.ML_FRAMEWORK, value=ml_framework)\n', (12271, 12321), False, 'from neptune.generated.swagger_client import InputPath, QueuedRemoteExperimentParams, StringParam\n'), ((12390, 12432), 'neptune.internal.cli.commands.utils.pip_requirements_utils.create_string_param', 'create_string_param', (['pip_requirements_file'], {}), '(pip_requirements_file)\n', (12409, 12432), False, 'from neptune.internal.cli.commands.utils.pip_requirements_utils import create_string_param\n'), ((12986, 13042), 'neptune.generated.swagger_client.InputPath', 'InputPath', ([], {'source': 'split_list[0]', 'destination': 'destination'}), '(source=split_list[0], destination=destination)\n', (12995, 13042), False, 'from neptune.generated.swagger_client import InputPath, QueuedRemoteExperimentParams, StringParam\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import uuid from datetime import datetime from typing import List, Dict, Optional, Union from neptune.new.exceptions import MetadataInconsistency, InternalClientError from neptune.new.internal.backends.api_model import LeaderboardEntry, AttributeWithProperties, AttributeType from neptune.new.internal.backends.hosted_neptune_backend import HostedNeptuneBackend from neptune.new.internal.utils.paths import join_paths, parse_path class RunsTableEntry: def __init__(self, backend: HostedNeptuneBackend, _id: uuid.UUID, attributes: List[AttributeWithProperties]): self._backend = backend self._id = _id self._attributes = attributes def __getitem__(self, path: str) -> 'LeaderboardHandler': return LeaderboardHandler(self, path) def get_attribute_type(self, path: str) -> AttributeType: for attr in self._attributes: if attr.path == path: return attr.type raise ValueError("Could not find {} attribute".format(path)) def _get_key_name(self, path, prefix): key_name = path[len(prefix):] return key_name[1:] if len(key_name) > 0 and key_name[0] is '/' else key_name def get_attributes_from_path(self, path: str): path_attributes = {} prefix = path for attr in self._attributes: if attr.path.startswith(prefix): key_name = self._get_key_name(attr.path, prefix) if '/' in key_name: split = key_name.split('/') if split[0] not in path_attributes: path_attributes[split[0]] = self.get_attributes_from_path(f'{prefix}/{split[0]}') else: try: path_attributes[key_name] = self.get_attribute_value(attr.path) except MetadataInconsistency as e: path_attributes[key_name] = e return path_attributes def get_attribute_value(self, path: str): for attr in self._attributes: if attr.path == path: _type = attr.type if _type == AttributeType.RUN_STATE: return attr.properties.value if _type == AttributeType.BOOL or _type == AttributeType.INT or _type == AttributeType.FLOAT or _type == AttributeType.STRING or _type == AttributeType.DATETIME: return attr.properties.value if _type == AttributeType.FLOAT_SERIES or _type == AttributeType.STRING_SERIES: return attr.properties.last if _type == AttributeType.IMAGE_SERIES: raise MetadataInconsistency("Cannot get value for image series.") if _type == AttributeType.FILE: raise MetadataInconsistency("Cannot get value for file attribute. Use download() instead.") if _type == AttributeType.FILE_SET: raise MetadataInconsistency("Cannot get value for file set attribute. Use download() instead.") if _type == AttributeType.STRING_SET: return set(attr.properties.values) if _type == AttributeType.GIT_REF: return attr.properties.commit.commitId if _type == AttributeType.NOTEBOOK_REF: return attr.properties.notebookName raise InternalClientError("Unsupported attribute type {}".format(_type)) raise ValueError("Could not find {} attribute".format(path)) def download_file_attribute(self, path: str, destination: Optional[str]): for attr in self._attributes: if attr.path == path: _type = attr.type if _type == AttributeType.FILE: self._backend.download_file(self._id, parse_path(path), destination) return raise MetadataInconsistency("Cannot download file from attribute of type {}".format(_type)) raise ValueError("Could not find {} attribute".format(path)) def download_file_set_attribute(self, path: str, destination: Optional[str]): for attr in self._attributes: if attr.path == path: _type = attr.type if _type == AttributeType.FILE_SET: self._backend.download_file_set(self._id, parse_path(path), destination) return raise MetadataInconsistency("Cannot download ZIP archive from attribute of type {}".format(_type)) raise ValueError("Could not find {} attribute".format(path)) class LeaderboardHandler: def __init__(self, run: RunsTableEntry, path: str): self._run = run self._path = path def __getitem__(self, path: str) -> 'LeaderboardHandler': return LeaderboardHandler(self._run, join_paths(self._path, path)) def get(self): return self._run.get_attribute_value(self._path) def get_path(self): return self._run.get_attributes_from_path(self._path) def download(self, destination: Optional[str]): attr_type = self._run.get_attribute_type(self._path) if attr_type == AttributeType.FILE: return self._run.download_file_attribute(self._path, destination) elif attr_type == AttributeType.FILE_SET: return self._run.download_file_set_attribute(self._path, destination) raise MetadataInconsistency("Cannot download file from attribute of type {}".format(attr_type)) class RunsTable: def __init__(self, backend: HostedNeptuneBackend, entries: List[LeaderboardEntry]): self._backend = backend self._entries = entries def to_runs(self) -> List[RunsTableEntry]: return [RunsTableEntry(self._backend, e.id, e.attributes) for e in self._entries] def to_pandas(self): # pylint:disable=import-outside-toplevel import pandas as pd def make_attribute_value(attribute: AttributeWithProperties) -> Optional[Union[str, float, datetime]]: _type = attribute.type _properties = attribute.properties if _type == AttributeType.RUN_STATE: return _properties.value if _type == AttributeType.FLOAT or _type == AttributeType.STRING or _type == AttributeType.DATETIME: return _properties.value if _type == AttributeType.FLOAT_SERIES or _type == AttributeType.STRING_SERIES: return _properties.last if _type == AttributeType.IMAGE_SERIES: return None if _type == AttributeType.FILE or _type == AttributeType.FILE_SET: return None if _type == AttributeType.STRING_SET: return ",".join(_properties.values) if _type == AttributeType.GIT_REF: return _properties.commit.commitId if _type == AttributeType.NOTEBOOK_REF: return _properties.notebookName raise InternalClientError("Unsupported attribute type {}".format(_type)) def make_row(entry: LeaderboardEntry) -> Dict[str, Optional[Union[str, float, datetime]]]: row: Dict[str, Union[str, float, datetime]] = dict() for attr in entry.attributes: value = make_attribute_value(attr) if value is not None: row[attr.path] = value return row def sort_key(attr): domain = attr.split('/')[0] if domain == 'sys': return 0, attr if domain == 'monitoring': return 2, attr return 1, attr rows = dict((n, make_row(entry)) for (n, entry) in enumerate(self._entries)) df = pd.DataFrame.from_dict(data=rows, orient='index') df = df.reindex(sorted(df.columns, key=sort_key), axis='columns') return df
[ "neptune.new.exceptions.MetadataInconsistency", "neptune.new.internal.utils.paths.join_paths", "neptune.new.internal.utils.paths.parse_path" ]
[((8356, 8405), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', ([], {'data': 'rows', 'orient': '"""index"""'}), "(data=rows, orient='index')\n", (8378, 8405), True, 'import pandas as pd\n'), ((5444, 5472), 'neptune.new.internal.utils.paths.join_paths', 'join_paths', (['self._path', 'path'], {}), '(self._path, path)\n', (5454, 5472), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((3253, 3312), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot get value for image series."""'], {}), "('Cannot get value for image series.')\n", (3274, 3312), False, 'from neptune.new.exceptions import MetadataInconsistency, InternalClientError\n'), ((3387, 3477), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot get value for file attribute. Use download() instead."""'], {}), "(\n 'Cannot get value for file attribute. Use download() instead.')\n", (3408, 3477), False, 'from neptune.new.exceptions import MetadataInconsistency, InternalClientError\n'), ((3551, 3645), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot get value for file set attribute. Use download() instead."""'], {}), "(\n 'Cannot get value for file set attribute. Use download() instead.')\n", (3572, 3645), False, 'from neptune.new.exceptions import MetadataInconsistency, InternalClientError\n'), ((4421, 4437), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['path'], {}), '(path)\n', (4431, 4437), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((4959, 4975), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['path'], {}), '(path)\n', (4969, 4975), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n')]
"""Implements Neptune Logger.""" from abc import ABC from typing import TYPE_CHECKING, List from torchflare.callbacks.callback import Callbacks from torchflare.callbacks.states import CallbackOrder from torchflare.utils.imports_check import module_available _AVAILABLE = module_available("neptune") if _AVAILABLE: import neptune.new as neptune else: neptune = None if TYPE_CHECKING: from torchflare.experiments.experiment import Experiment class NeptuneLogger(Callbacks, ABC): """Callback to log your metrics and loss values to Neptune to track your experiments. For more information about Neptune take a look at [Neptune](https://neptune.ai/) Args: project_dir: The qualified name of a project in a form of namespace/project_name params: The hyperparameters for your model and experiment as a dictionary experiment_name: The name of the experiment api_token: User’s API token tags: List of strings. Examples: .. code-block:: from torchflare.callbacks import NeptuneLogger params = {"bs": 16, "lr": 0.3} logger = NeptuneLogger( project_dir="username/Experiments", params=params, experiment_name="Experiment_10", tags=["Experiment", "fold_0"], api_token="your_secret_api_token", ) """ def __init__( self, project_dir: str, api_token: str, params: dict = None, experiment_name: str = None, tags: List[str] = None, ): """Constructor for NeptuneLogger Class.""" super(NeptuneLogger, self).__init__(order=CallbackOrder.LOGGING) self.project_dir = project_dir self.api_token = api_token self.params = params self.tags = tags self.experiment_name = experiment_name self.experiment = None def on_experiment_start(self, experiment: "Experiment"): """Start of experiment.""" self.experiment = neptune.init( project=self.project_dir, api_token=self.api_token, tags=self.tags, name=self.experiment_name, ) self.experiment["params"] = self.params def _log_metrics(self, name, value, epoch): self.experiment[name].log(value=value, step=epoch) def on_epoch_end(self, experiment: "Experiment"): """Method to log metrics and values at the end of very epoch.""" for key, value in experiment.exp_logs.items(): if key != experiment.epoch_key: epoch = experiment.exp_logs[experiment.epoch_key] self._log_metrics(name=key, value=value, epoch=epoch) def on_experiment_end(self, experiment: "Experiment"): """Method to end experiment after training is done.""" self.experiment.stop() self.experiment = None
[ "neptune.new.init" ]
[((273, 300), 'torchflare.utils.imports_check.module_available', 'module_available', (['"""neptune"""'], {}), "('neptune')\n", (289, 300), False, 'from torchflare.utils.imports_check import module_available\n'), ((2068, 2180), 'neptune.new.init', 'neptune.init', ([], {'project': 'self.project_dir', 'api_token': 'self.api_token', 'tags': 'self.tags', 'name': 'self.experiment_name'}), '(project=self.project_dir, api_token=self.api_token, tags=self.\n tags, name=self.experiment_name)\n', (2080, 2180), True, 'import neptune.new as neptune\n')]
#!/usr/bin/env python # The MIT License (MIT) # Copyright (c) 2020 <NAME> # Paper: "Self-Supervised Relational Reasoning for Representation Learning", <NAME> & <NAME>, NeurIPS 2020 # GitHub: https://github.com/mpatacchiola/self-supervised-relational-reasoning # # Implementation of a standard neural network (no self-supervised components). # This is used as baseline (upper bound) and during linear-evaluation and fine-tuning. import math import time from torch.optim import SGD, Adam import torch.nn.functional as F from torch import nn import torch import torchvision.datasets as dset import torchvision.transforms as transforms import tqdm import numpy as np from utils import AverageMeter import neptune class StandardModel(torch.nn.Module): def __init__(self, feature_extractor, num_classes, tot_epochs=200): super(StandardModel, self).__init__() self.num_classes = num_classes self.tot_epochs = tot_epochs self.feature_extractor = feature_extractor feature_size = feature_extractor.feature_size self.classifier = nn.Linear(feature_size, num_classes) self.ce = torch.nn.CrossEntropyLoss() self.optimizer = SGD([{"params": self.feature_extractor.parameters(), "lr": 0.1, "momentum": 0.9}, {"params": self.classifier.parameters(), "lr": 0.1, "momentum": 0.9}]) self.optimizer_lineval = Adam([{"params": self.classifier.parameters(), "lr": 0.001}]) self.optimizer_finetune = Adam([{"params": self.feature_extractor.parameters(), "lr": 0.001, "weight_decay": 1e-5}, {"params": self.classifier.parameters(), "lr": 0.0001, "weight_decay": 1e-5}]) neptune.init(f'valeriobiscione/TestProject') neptune.create_experiment(tags=['viewpoint-inv']) def forward(self, x, detach=False): if(detach): out = self.feature_extractor(x).detach() else: out = self.feature_extractor(x) out = self.classifier(out) return out def train(self, epoch, train_loader): start_time = time.time() self.feature_extractor.train() self.classifier.train() start = time.time() if(epoch==int(self.tot_epochs*0.5) or epoch==int(self.tot_epochs*0.75)): for i_g, g in enumerate(self.optimizer.param_groups): g["lr"] *= 0.1 #divide by 10 print("Group[" + str(i_g) + "] learning rate: " + str(g["lr"])) loss_meter = AverageMeter() accuracy_meter = AverageMeter() print(torch.rand(1)) for i, (data, target) in enumerate(train_loader): if torch.cuda.is_available(): data, target = data.cuda(), target.cuda() self.optimizer.zero_grad() output = self.forward(data) loss = self.ce(output, target) loss_meter.update(loss.item(), len(target)) loss.backward() self.optimizer.step() pred = output.argmax(-1) correct = pred.eq(target.view_as(pred)).cpu().sum() accuracy = (100.0 * correct / float(len(target))) accuracy_meter.update(accuracy.item(), len(target)) if i % 5 == 0: neptune.send_metric("accuracy", accuracy) if i % 100 == 0: print(f"time elapsed 100 iter: {time.time()-start}") start = time.time() elapsed_time = time.time() - start_time print("Epoch [" + str(epoch) + "]" + "[" + str(time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) + "]" + " loss: " + str(loss_meter.avg) + "; acc: " + str(accuracy_meter.avg) + "%") return loss_meter.avg, accuracy_meter.avg def linear_evaluation(self, epoch, train_loader): self.feature_extractor.eval() self.classifier.train() minibatch_iter = tqdm.tqdm(train_loader, desc=f"(Epoch {epoch}) Minibatch") loss_meter = AverageMeter() accuracy_meter = AverageMeter() for data, target in minibatch_iter: if torch.cuda.is_available(): data, target = data.cuda(), target.cuda() self.optimizer_lineval.zero_grad() output = self.forward(data, detach=True) loss = self.ce(output, target) loss_meter.update(loss.item(), len(target)) loss.backward() self.optimizer_lineval.step() pred = output.argmax(-1) correct = pred.eq(target.view_as(pred)).cpu().sum() accuracy = (100.0 * correct / float(len(target))) accuracy_meter.update(accuracy.item(), len(target)) minibatch_iter.set_postfix({"loss": loss_meter.avg, "acc": accuracy_meter.avg}) return loss_meter.avg, accuracy_meter.avg def finetune(self, epoch, train_loader): self.feature_extractor.train() self.classifier.train() if(epoch==int(self.tot_epochs*0.5) or epoch==int(self.tot_epochs*0.75)): for i_g, g in enumerate(self.optimizer_finetune.param_groups): g["lr"] *= 0.1 #divide by 10 print("Group[" + str(i_g) + "] learning rate: " + str(g["lr"])) minibatch_iter = tqdm.tqdm(train_loader, desc=f"(Epoch {epoch}) Minibatch") loss_meter = AverageMeter() accuracy_meter = AverageMeter() for data, target in minibatch_iter: if torch.cuda.is_available(): data, target = data.cuda(), target.cuda() self.optimizer_finetune.zero_grad() output = self.forward(data) loss = self.ce(output, target) loss_meter.update(loss.item(), len(target)) loss.backward() self.optimizer_finetune.step() pred = output.argmax(-1) correct = pred.eq(target.view_as(pred)).cpu().sum() accuracy = (100.0 * correct / float(len(target))) accuracy_meter.update(accuracy.item(), len(target)) minibatch_iter.set_postfix({"loss": loss_meter.avg, "acc": accuracy_meter.avg}) return loss_meter.avg, accuracy_meter.avg def test(self, test_loader): self.feature_extractor.eval() self.classifier.eval() loss_meter = AverageMeter() accuracy_meter = AverageMeter() with torch.no_grad(): for data, target in test_loader: if torch.cuda.is_available(): data, target = data.cuda(), target.cuda() output = self.forward(data) loss = self.ce(output, target) loss_meter.update(loss.item(), len(target)) pred = output.argmax(-1) correct = pred.eq(target.view_as(pred)).cpu().sum() accuracy = (100.0 * correct / float(len(target))) accuracy_meter.update(accuracy.item(), len(target)) return loss_meter.avg, accuracy_meter.avg def return_embeddings(self, data_loader, portion=0.5): self.feature_extractor.eval() embeddings_list = [] target_list = [] with torch.no_grad(): for i, (data, target) in enumerate(data_loader): if torch.cuda.is_available(): data, target = data.cuda(), target.cuda() features = self.feature_extractor(data) embeddings_list.append(features) target_list.append(target) if(i>=int(len(data_loader)*portion)): break return torch.cat(embeddings_list, dim=0).cpu().detach().numpy(), torch.cat(target_list, dim=0).cpu().detach().numpy() def save(self, file_path="./checkpoint.dat"): state_dict = self.classifier.state_dict() feature_extractor_state_dict = self.feature_extractor.state_dict() optimizer_state_dict = self.optimizer.state_dict() optimizer_lineval_state_dict = self.optimizer_lineval.state_dict() optimizer_finetune_state_dict = self.optimizer_finetune.state_dict() torch.save({"classifier": state_dict, "backbone": feature_extractor_state_dict, "optimizer": optimizer_state_dict, "optimizer_lineval": optimizer_lineval_state_dict, "optimizer_finetune": optimizer_finetune_state_dict}, file_path) def load(self, file_path): checkpoint = torch.load(file_path) self.classifier.load_state_dict(checkpoint["classifier"]) self.feature_extractor.load_state_dict(checkpoint["backbone"]) self.optimizer.load_state_dict(checkpoint["optimizer"]) self.optimizer_lineval.load_state_dict(checkpoint["optimizer_lineval"]) self.optimizer_finetune.load_state_dict(checkpoint["optimizer_finetune"])
[ "neptune.send_metric", "neptune.create_experiment", "neptune.init" ]
[((1075, 1111), 'torch.nn.Linear', 'nn.Linear', (['feature_size', 'num_classes'], {}), '(feature_size, num_classes)\n', (1084, 1111), False, 'from torch import nn\n'), ((1130, 1157), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (1155, 1157), False, 'import torch\n'), ((1713, 1757), 'neptune.init', 'neptune.init', (['f"""valeriobiscione/TestProject"""'], {}), "(f'valeriobiscione/TestProject')\n", (1725, 1757), False, 'import neptune\n'), ((1766, 1815), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'tags': "['viewpoint-inv']"}), "(tags=['viewpoint-inv'])\n", (1791, 1815), False, 'import neptune\n'), ((2086, 2097), 'time.time', 'time.time', ([], {}), '()\n', (2095, 2097), False, 'import time\n'), ((2185, 2196), 'time.time', 'time.time', ([], {}), '()\n', (2194, 2196), False, 'import time\n'), ((2490, 2504), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2502, 2504), False, 'from utils import AverageMeter\n'), ((2530, 2544), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2542, 2544), False, 'from utils import AverageMeter\n'), ((3895, 3953), 'tqdm.tqdm', 'tqdm.tqdm', (['train_loader'], {'desc': 'f"""(Epoch {epoch}) Minibatch"""'}), "(train_loader, desc=f'(Epoch {epoch}) Minibatch')\n", (3904, 3953), False, 'import tqdm\n'), ((3975, 3989), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (3987, 3989), False, 'from utils import AverageMeter\n'), ((4015, 4029), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (4027, 4029), False, 'from utils import AverageMeter\n'), ((5221, 5279), 'tqdm.tqdm', 'tqdm.tqdm', (['train_loader'], {'desc': 'f"""(Epoch {epoch}) Minibatch"""'}), "(train_loader, desc=f'(Epoch {epoch}) Minibatch')\n", (5230, 5279), False, 'import tqdm\n'), ((5301, 5315), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (5313, 5315), False, 'from utils import AverageMeter\n'), ((5341, 5355), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (5353, 5355), False, 'from utils import AverageMeter\n'), ((6244, 6258), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6256, 6258), False, 'from utils import AverageMeter\n'), ((6284, 6298), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6296, 6298), False, 'from utils import AverageMeter\n'), ((7980, 8222), 'torch.save', 'torch.save', (["{'classifier': state_dict, 'backbone': feature_extractor_state_dict,\n 'optimizer': optimizer_state_dict, 'optimizer_lineval':\n optimizer_lineval_state_dict, 'optimizer_finetune':\n optimizer_finetune_state_dict}", 'file_path'], {}), "({'classifier': state_dict, 'backbone':\n feature_extractor_state_dict, 'optimizer': optimizer_state_dict,\n 'optimizer_lineval': optimizer_lineval_state_dict, 'optimizer_finetune':\n optimizer_finetune_state_dict}, file_path)\n", (7990, 8222), False, 'import torch\n'), ((8374, 8395), 'torch.load', 'torch.load', (['file_path'], {}), '(file_path)\n', (8384, 8395), False, 'import torch\n'), ((2559, 2572), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (2569, 2572), False, 'import torch\n'), ((2648, 2673), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2671, 2673), False, 'import torch\n'), ((3428, 3439), 'time.time', 'time.time', ([], {}), '()\n', (3437, 3439), False, 'import time\n'), ((4089, 4114), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4112, 4114), False, 'import torch\n'), ((5415, 5440), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5438, 5440), False, 'import torch\n'), ((6312, 6327), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6325, 6327), False, 'import torch\n'), ((7077, 7092), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7090, 7092), False, 'import torch\n'), ((3228, 3269), 'neptune.send_metric', 'neptune.send_metric', (['"""accuracy"""', 'accuracy'], {}), "('accuracy', accuracy)\n", (3247, 3269), False, 'import neptune\n'), ((3392, 3403), 'time.time', 'time.time', ([], {}), '()\n', (3401, 3403), False, 'import time\n'), ((6393, 6418), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6416, 6418), False, 'import torch\n'), ((7174, 7199), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7197, 7199), False, 'import torch\n'), ((3347, 3358), 'time.time', 'time.time', ([], {}), '()\n', (3356, 3358), False, 'import time\n'), ((7466, 7499), 'torch.cat', 'torch.cat', (['embeddings_list'], {'dim': '(0)'}), '(embeddings_list, dim=0)\n', (7475, 7499), False, 'import torch\n'), ((7524, 7553), 'torch.cat', 'torch.cat', (['target_list'], {'dim': '(0)'}), '(target_list, dim=0)\n', (7533, 7553), False, 'import torch\n'), ((3550, 3575), 'time.gmtime', 'time.gmtime', (['elapsed_time'], {}), '(elapsed_time)\n', (3561, 3575), False, 'import time\n')]
# -*- coding: utf-8 -*- # # Copyright (c) 2017, deepsense.io # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from future.builtins import input from future.utils import raise_from import base64 import json import socketserver import sys from threading import Thread from flask import Flask, request from neptune.internal.cli.commands.command_names import CommandNames from neptune.internal.cli.commands.framework import Command from neptune.internal.cli.commands.neptune_command import NeptuneCommand from neptune.internal.common import NeptuneException, NeptuneInternalException from neptune.internal.common.api.api_service_factory import create_services from neptune.internal.common.exceptions.keycloak_exceptions import KeycloakException from neptune.internal.common.threads.neptune_future import NeptuneFuture class NeptuneLogout(Command): name = u'logout' LOGGED_OUT_MESSAGE = u'You have been successfully logged out.' def __init__(self, token_storage): self.token_storage = token_storage def run(self, *_): if self.token_storage.contains_token(): self.token_storage.clear() print(self.LOGGED_OUT_MESSAGE) class NeptuneManualLogin(Command): name = u'manual login' def __init__(self, config, auth_code_url, keycloak_service, token_storage, api_service, webbrowser): self.config = config self.auth_code_url = auth_code_url self.keycloak_service = keycloak_service self.token_storage = token_storage self.api_service = api_service self.webbrowser = webbrowser def run(self, *_): print(u'Please follow {} to obtain authentication token.\n'.format(self.auth_code_url)) self.webbrowser.open(self.auth_code_url) user_input = input(u'Authentication token: ') authorization_code, redirect_uri = extract_fields(decode_token(user_input)) offline_token = self.keycloak_service.request_offline_token( authorization_code=authorization_code, redirect_uri=redirect_uri) self.token_storage.save(offline_token) services = create_services(self.token_storage) services.api_service.user_logged_to_cli() print(u'Login successful.') class NeptuneApiToken(NeptuneCommand): name = u'api key' def __init__(self, config, api_service): super(NeptuneApiToken, self).__init__(CommandNames.API_TOKEN, config, api_service=api_service) def run(self, *_): print(self.api_service.get_api_token()) class NeptuneLocalLogin(NeptuneCommand): name = u'local login' def __init__(self, config, keycloak_api_service, offline_token_storage_service, api_service, webbrowser): super(NeptuneLocalLogin, self).__init__(CommandNames.LOGIN, config, api_service=None) self._keycloak_api_service = keycloak_api_service self._offline_token_storage_service = offline_token_storage_service self._aborted = False self._stock_server_bind = socketserver.TCPServer.server_bind self.api_service = api_service self.webbrowser = webbrowser def run(self, args): webserver_port_future, authorization_code_future = self._start_webserver( self._keycloak_api_service.get_local_login_redirect_url() ) webserver_port = webserver_port_future.wait() url = self._keycloak_api_service.get_request_authorization_code_url( redirect_uri=self._webserver_url(webserver_port)) # Open webbrowser in the seperate thread to avoid freeze in Firefox. t = Thread(target=self.webbrowser.open, args=(url,)) t.daemon = True t.start() print("Waiting for authentication, press Ctrl+C to abort...") authorization_code = self._wait_for_authorization_code(authorization_code_future) try: offline_token = self._request_offline_token( authorization_code=authorization_code, redirect_uri=self._webserver_url(webserver_port) ) except KeycloakException as e: print(e.message) sys.exit(1) self._offline_token_storage_service.save(offline_token) services = create_services(self._offline_token_storage_service) # Performs operations needed to be run for a new user on his first login. # TODO Consider moving this API call to Keycloak. services.api_service.login() services.api_service.user_logged_to_cli() print('Login successful.') def abort(self): self._aborted = True def _start_webserver(self, login_redirect_address): app = Flask(__name__) webserver_port_future = self._intercept_server_port() authorization_code_future = NeptuneFuture() app.add_url_rule( rule='/', endpoint='_authorization_code_request_handler', view_func=self._authorization_code_request_handler(authorization_code_future, login_redirect_address) ) webserver_port = Thread(target=app.run, kwargs={"port": 0}) webserver_port.setDaemon(True) webserver_port.start() return webserver_port_future, authorization_code_future def _wait_for_authorization_code(self, authorization_code_future): while not self._aborted: authorization_code = authorization_code_future.wait(timeout=1) if authorization_code: return authorization_code def _request_offline_token(self, authorization_code, redirect_uri): offline_token = self._keycloak_api_service.request_offline_token( authorization_code=authorization_code, redirect_uri=redirect_uri ) return offline_token def _authorization_code_request_handler(self, authorization_code_future, login_redirect_address): def handler(): authorization_code_future.set(request.args['code']) request.environ.get('werkzeug.server.shutdown')() return '<script type="text/javascript">' \ 'window.location.href = "{frontend_address}";' \ '</script>'.format(frontend_address=login_redirect_address) return handler def _intercept_server_port(self): websocket_port_future = NeptuneFuture() def _server_bind_wrapper(tcp_server): return_value = self._stock_server_bind(tcp_server) websocket_port_future.set(tcp_server.socket.getsockname()[1]) socketserver.TCPServer.server_bind = self._stock_server_bind return return_value socketserver.TCPServer.server_bind = _server_bind_wrapper return websocket_port_future def _webserver_url(self, webserver_port): return 'http://localhost:{}'.format(webserver_port) def decode_token(string): try: raw_message = base64.b64decode(string) return json.loads(raw_message.decode('UTF-8')) except: raise NeptuneException('Invalid authentication token.') def extract_fields(message): try: redirect_uri = message['redirect_uri'] authorization_code = message['code'] except KeyError as error: raise_from(NeptuneInternalException('Invalid JSON received from frontend.'), error) return authorization_code, redirect_uri
[ "neptune.internal.common.api.api_service_factory.create_services", "neptune.internal.common.threads.neptune_future.NeptuneFuture", "neptune.internal.common.NeptuneInternalException", "neptune.internal.common.NeptuneException" ]
[((2326, 2358), 'future.builtins.input', 'input', (['u"""Authentication token: """'], {}), "(u'Authentication token: ')\n", (2331, 2358), False, 'from future.builtins import input\n'), ((2672, 2707), 'neptune.internal.common.api.api_service_factory.create_services', 'create_services', (['self.token_storage'], {}), '(self.token_storage)\n', (2687, 2707), False, 'from neptune.internal.common.api.api_service_factory import create_services\n'), ((4153, 4201), 'threading.Thread', 'Thread', ([], {'target': 'self.webbrowser.open', 'args': '(url,)'}), '(target=self.webbrowser.open, args=(url,))\n', (4159, 4201), False, 'from threading import Thread\n'), ((4788, 4840), 'neptune.internal.common.api.api_service_factory.create_services', 'create_services', (['self._offline_token_storage_service'], {}), '(self._offline_token_storage_service)\n', (4803, 4840), False, 'from neptune.internal.common.api.api_service_factory import create_services\n'), ((5228, 5243), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (5233, 5243), False, 'from flask import Flask, request\n'), ((5343, 5358), 'neptune.internal.common.threads.neptune_future.NeptuneFuture', 'NeptuneFuture', ([], {}), '()\n', (5356, 5358), False, 'from neptune.internal.common.threads.neptune_future import NeptuneFuture\n'), ((5618, 5660), 'threading.Thread', 'Thread', ([], {'target': 'app.run', 'kwargs': "{'port': 0}"}), "(target=app.run, kwargs={'port': 0})\n", (5624, 5660), False, 'from threading import Thread\n'), ((6878, 6893), 'neptune.internal.common.threads.neptune_future.NeptuneFuture', 'NeptuneFuture', ([], {}), '()\n', (6891, 6893), False, 'from neptune.internal.common.threads.neptune_future import NeptuneFuture\n'), ((7454, 7478), 'base64.b64decode', 'base64.b64decode', (['string'], {}), '(string)\n', (7470, 7478), False, 'import base64\n'), ((7560, 7609), 'neptune.internal.common.NeptuneException', 'NeptuneException', (['"""Invalid authentication token."""'], {}), "('Invalid authentication token.')\n", (7576, 7609), False, 'from neptune.internal.common import NeptuneException, NeptuneInternalException\n'), ((4691, 4702), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4699, 4702), False, 'import sys\n'), ((6530, 6577), 'flask.request.environ.get', 'request.environ.get', (['"""werkzeug.server.shutdown"""'], {}), "('werkzeug.server.shutdown')\n", (6549, 6577), False, 'from flask import Flask, request\n'), ((7791, 7855), 'neptune.internal.common.NeptuneInternalException', 'NeptuneInternalException', (['"""Invalid JSON received from frontend."""'], {}), "('Invalid JSON received from frontend.')\n", (7815, 7855), False, 'from neptune.internal.common import NeptuneException, NeptuneInternalException\n')]
import neptune # The init() function called this way assumes that # NEPTUNE_API_TOKEN environment variable is defined. neptune.init('vanducng/sandbox') neptune.create_experiment(name='minimal_example') # log some metrics for i in range(100): neptune.log_metric('loss', 0.95**i) neptune.log_metric('AUC', 0.96)
[ "neptune.create_experiment", "neptune.init", "neptune.log_metric" ]
[((121, 153), 'neptune.init', 'neptune.init', (['"""vanducng/sandbox"""'], {}), "('vanducng/sandbox')\n", (133, 153), False, 'import neptune\n'), ((154, 203), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""minimal_example"""'}), "(name='minimal_example')\n", (179, 203), False, 'import neptune\n'), ((287, 318), 'neptune.log_metric', 'neptune.log_metric', (['"""AUC"""', '(0.96)'], {}), "('AUC', 0.96)\n", (305, 318), False, 'import neptune\n'), ((250, 287), 'neptune.log_metric', 'neptune.log_metric', (['"""loss"""', '(0.95 ** i)'], {}), "('loss', 0.95 ** i)\n", (268, 287), False, 'import neptune\n')]
import sys from dataclasses import asdict from pathlib import Path from pprint import pprint from typing import Optional import click import matplotlib.pyplot as plt import neptune import torch import torchaudio from click import Context from torch.nn.functional import mse_loss from tqdm import trange, tqdm from reformer_tts.config import Config from reformer_tts.dataset.convert import PhonemeSequenceCreator from reformer_tts.dataset.download import download_speech_videos_and_transcripts from reformer_tts.dataset.preprocess import preprocess_data from reformer_tts.dataset.visualize import plot_spectrogram, plot_attention_matrix from reformer_tts.squeeze_wave.modules import SqueezeWave from reformer_tts.training.train import train_tts as train_tts_function from reformer_tts.training.train import train_vocoder as train_vocoder_function from reformer_tts.training.wrappers import LitSqueezeWave, LitReformerTTS @click.group() @click.option("-c", "--config", envvar="REFORMER_TTS_CONFIG", default=None) @click.pass_context def cli(ctx: Context, config): ctx.ensure_object(dict) if config is None: ctx.obj["CONFIG"] = Config() # use default values else: ctx.obj["CONFIG"] = Config.from_yaml_file(config) @cli.command() @click.option("-r", "--resume", type=str, default=None, help="Path to checkpoint to resume") @click.pass_context def train_tts(ctx: Context, resume: Optional[str]): config = ctx.obj["CONFIG"] if resume is not None: resume = Path(resume) train_tts_function(config, resume) @cli.command() @click.option("-r", "--resume", type=str, default=None, help="Path to checkpoint to resume") @click.pass_context def train_vocoder(ctx: Context, resume: str): config = ctx.obj["CONFIG"] if resume is not None: resume = Path(resume) train_vocoder_function(config, resume) @cli.command() @click.pass_context def download(ctx: Context): config = ctx.obj["CONFIG"] download_speech_videos_and_transcripts( url=config.dataset.source_url, transcript_directory=config.dataset.structure.transcript_directory, video_directory=config.dataset.structure.video_directory ) @cli.command() @click.pass_context def preprocess(ctx: Context): config = ctx.obj["CONFIG"] preprocess_data( trump_speaker_names=config.dataset.trump_speaker_names, transcript_directory=config.transcript_directory, merged_transcript_csv_path=config.merged_transcript_csv_path, audio_directory=config.audio_directory, video_directory=config.video_directory, spectrogram_dir=config.mel_directory, nltk_data_directory=config.nltk_data_directory, audio_format=config.dataset.audio_format, mel_format=config.dataset.mel_format, use_tacotron2_spectrograms=config.dataset.use_tacotron2_spectrograms ) @cli.command() @click.option("-r", "--reformer-checkpoint", type=str, required=True, help="Path to reformer checkpoint") @click.option("-s", "--squeeze-wave-checkpoint", type=str, required=True, help="Path to squeezewave checkpoint") @click.option("-o", "--output-dir", type=str, required=True, help="Path where outputs will be saved") @click.option("-m", "--max-samples", type=int, default=None, help="Maximum number of total generated samples") @click.pass_context def predict_samples( ctx: Context, reformer_checkpoint: str, squeeze_wave_checkpoint: str, output_dir: str, max_samples: Optional[int] ): """ Generates predictions on the test_set portion of text-to-spectrogram dataset. Provided config must be compatible with both reformer and squeezewave (keys and values in config structure must be the same as the ones used during their training) """ config = ctx.obj["CONFIG"] output_dir = Path(output_dir) output_dir.mkdir(exist_ok=True, parents=True) if torch.cuda.is_available(): torch.set_default_tensor_type(torch.cuda.FloatTensor) device = torch.device('cuda') on_gpu = True else: device = torch.device('cpu') on_gpu = False reformer = LitReformerTTS.load_from_checkpoint(reformer_checkpoint, config=config) reformer = reformer.eval() squeeze_wave = LitSqueezeWave.load_from_checkpoint( squeeze_wave_checkpoint, config=config, on_gpu=on_gpu ) squeeze_wave = SqueezeWave.remove_norms(squeeze_wave.model) squeeze_wave = squeeze_wave.eval() results = list() reformer.prepare_data() if len(reformer.test_set) == 0: dataset = reformer.val_set else: dataset = reformer.test_set if max_samples is None: max_samples = len(dataset) with torch.no_grad(): # todo: use ReformerTTS.infer for test_sample_idx in trange(max_samples, desc="predicting"): sample = dataset[test_sample_idx] phonemes_in = sample['phonemes'].unsqueeze(0).to(device=device) spectrogram_in = sample['spectrogram'].unsqueeze(0).to(device=device) # todo: we shouldn't pass target spectrogram into reformer: spectrogram_out, stop_out = reformer(phonemes_in, spectrogram_in[:, :-1, :]) mse = mse_loss(spectrogram_out, spectrogram_in[:, 1:, :]) cutoff: int = stop_out.argmax() spectrogram_out: torch.Tensor = spectrogram_out.transpose(1, 2) spectrogram_out = spectrogram_out[:, :, :cutoff] audio_out = squeeze_wave.infer(spectrogram_out) results.append({ "spectrogram": spectrogram_out.cpu(), "spectrogram_mse": float(mse.cpu().numpy()), "audio": audio_out.cpu(), "idx": sample["idx"], }) best_mse = min(results, key=lambda r: r["spectrogram_mse"])["spectrogram_mse"] worst_mse = max(results, key=lambda r: r["spectrogram_mse"])["spectrogram_mse"] mean_mse = sum(r["spectrogram_mse"] for r in results) / float(len(results)) print(f"{best_mse=:.4f}, {worst_mse=:.4f}, {mean_mse=:.4f}") for result in tqdm(results, desc="saving"): filename = f"pred-{result['idx']}-idx_{result['spectrogram_mse']:.4f}-mse" spectrogram_path = output_dir / f"{filename}.png" plot_spectrogram(result["spectrogram"], scale=False) plt.savefig(str(spectrogram_path)) plt.close() audio_path = output_dir / f"{filename}.wav" torchaudio.save( str(audio_path), result["audio"], config.dataset.audio_format.sampling_rate ) print(f"Results saved to {output_dir.resolve()}") @cli.command() @click.option("-r", "--reformer-checkpoint", type=str, required=True, help="Path to reformer checkpoint") @click.option("-s", "--squeeze-wave-checkpoint", type=str, required=True, help="Path to squeezewave checkpoint") @click.option("-o", "--output-dir", type=str, required=True, help="Path where outputs will be saved") @click.option("-S", "--strategy", type=str, default="concat", help="Strategy for TTS inference ('concat' or 'replace')") @click.pass_context def predict_from_text( ctx: Context, reformer_checkpoint: str, squeeze_wave_checkpoint: str, output_dir: str, strategy: str, ): config: Config = ctx.obj["CONFIG"] # todo: refactor - most of this is the same as in predict_samples output_dir = Path(output_dir) output_dir.mkdir(exist_ok=True, parents=True) if torch.cuda.is_available(): torch.set_default_tensor_type(torch.cuda.FloatTensor) on_gpu = True device = torch.device('cuda') else: on_gpu = False device = torch.device('cpu') reformer = LitReformerTTS.load_from_checkpoint(reformer_checkpoint, config=config) reformer = reformer.eval() squeeze_wave = LitSqueezeWave.load_from_checkpoint( squeeze_wave_checkpoint, config=config, on_gpu=on_gpu ) squeeze_wave = SqueezeWave.remove_norms(squeeze_wave.model) squeeze_wave = squeeze_wave.eval() phonemizer = PhonemeSequenceCreator(config.nltk_data_directory) phoneme_encoder = reformer.get_phoneme_encoder() print("Type a sentence and press enter to convert it to speech:") with torch.no_grad(): for idx, line in enumerate(sys.stdin): phonemes = phonemizer.phonemize(line) print(f"Predicting from {phonemes=}...") phonemes = " ".join(phonemes) phonemes = phoneme_encoder(phonemes).unsqueeze(0).to(device=device) stop_at_stop_token = config.experiment.tts_training.stop_loss_weight != 0. spectrogram, stop = reformer.model.infer( phonemes, combine_strategy=strategy, verbose=True, stop_at_stop_token=stop_at_stop_token, ) spectrogram = spectrogram[:, :, :stop.item()] audio_out = squeeze_wave.infer(spectrogram) spectrogram_path = output_dir / f"pred-stdin-{idx}.png" plot_spectrogram(spectrogram.cpu(), scale=False) plt.savefig(str(spectrogram_path)) plt.close() audio_path = output_dir / f"pred-{strategy}-stdin-{idx}.wav" torchaudio.save( str(audio_path), audio_out.cpu(), config.dataset.audio_format.sampling_rate ) print(f"Output saved to {audio_path.resolve()}") @cli.command() @click.option("-s", "--squeeze-wave-checkpoint", type=str, required=True, help="Path to squeezewave checkpoint") @click.option("-o", "--output-dir", type=str, required=True, help="Path where outputs will be saved") @click.pass_context def predict_from_mel(ctx: Context, squeeze_wave_checkpoint: str, output_dir: str): config: Config = ctx.obj["CONFIG"] output_dir = Path(output_dir) output_dir.mkdir(exist_ok=True, parents=True) on_gpu = torch.cuda.is_available() squeeze_wave = LitSqueezeWave.load_from_checkpoint( squeeze_wave_checkpoint, config=config, on_gpu=False ) squeeze_wave = SqueezeWave.remove_norms(squeeze_wave.model) squeeze_wave = squeeze_wave.eval() trump_spec = torch.load('data/preprocessed-tacotron2/mel/speech00_0000.pt') lj_spec = torch.load('data/lj-speech-tacotron2/mel/LJ001-0001.pt') prefix = str(Path(squeeze_wave_checkpoint).name) for spec, suffix in zip([trump_spec, lj_spec], ["trump", "lj"]): audio = squeeze_wave.infer(spec) audio_path = output_dir / f"{prefix}-{suffix}.wav" torchaudio.save( str(audio_path), audio.cpu(), sample_rate=config.dataset.audio_format.sampling_rate ) print(f"Results saved to {output_dir}") @cli.command() @click.option("-r", "--reformer-checkpoint", type=str, required=True, help="Path to reformer checkpoint") @click.option("-o", "--output-dir", type=str, required=True, help="Path where outputs will be saved") @click.pass_context def visualize_attention(ctx, reformer_checkpoint, output_dir): config: Config = ctx.obj["CONFIG"] output_dir = Path(output_dir) output_dir.mkdir(exist_ok=True, parents=True) if torch.cuda.is_available(): torch.set_default_tensor_type(torch.cuda.FloatTensor) on_gpu = True device = torch.device('cuda') else: on_gpu = False device = torch.device('cpu') reformer = LitReformerTTS.load_from_checkpoint( reformer_checkpoint, config=config, on_gpu=on_gpu, ) reformer = reformer.eval() reformer.prepare_data() batch = next(iter(reformer.val_dataloader())) batch = {key: batch[key].to(device=device) for key in batch} with torch.no_grad(): _, _, _, _, _, attention_matrices = reformer( batch['phonemes'], batch['spectrogram'], batch['stop_tokens'], batch["loss_mask"], use_transform=False, ) attention_matrices = reformer.trim_attention_matrices( attention_matrices, batch["stop_tokens"], ) attention_matrices = [ [matrix.cpu() for matrix in matrices] for matrices in attention_matrices ] for i, matrices in enumerate(attention_matrices): for j, matrix in enumerate(matrices): plot_attention_matrix(matrix) plt.savefig(output_dir / f"{i}_{j}.png") @cli.command() @click.pass_context def show_config(ctx: Context): config = ctx.obj["CONFIG"] pprint(asdict(config)) @cli.command() @click.option("-o", "--output", type=str, required=True, help="Path where config will be saved") @click.pass_context def save_config(ctx: Context, output): """ Save all config variables (defaults + overrides from config file) """ config = ctx.obj["CONFIG"] config.to_yaml_file(output) print(f"Config saved to {output}") @cli.command() @click.argument('idx', type=str) def remove_image_logs(idx): """ Remove all image logs from experiment""" proj = neptune.init("reformer-tts/reformer-tts") exp = proj.get_experiments(idx)[0] logs = exp.get_channels() for name, channel in logs.items(): if channel.channelType == 'image': exp.reset_log(name) exp.set_property('cleaned_image_logs', True) if __name__ == "__main__": cli(obj={})
[ "neptune.init" ]
[((925, 938), 'click.group', 'click.group', ([], {}), '()\n', (936, 938), False, 'import click\n'), ((940, 1014), 'click.option', 'click.option', (['"""-c"""', '"""--config"""'], {'envvar': '"""REFORMER_TTS_CONFIG"""', 'default': 'None'}), "('-c', '--config', envvar='REFORMER_TTS_CONFIG', default=None)\n", (952, 1014), False, 'import click\n'), ((1262, 1358), 'click.option', 'click.option', (['"""-r"""', '"""--resume"""'], {'type': 'str', 'default': 'None', 'help': '"""Path to checkpoint to resume"""'}), "('-r', '--resume', type=str, default=None, help=\n 'Path to checkpoint to resume')\n", (1274, 1358), False, 'import click\n'), ((1571, 1667), 'click.option', 'click.option', (['"""-r"""', '"""--resume"""'], {'type': 'str', 'default': 'None', 'help': '"""Path to checkpoint to resume"""'}), "('-r', '--resume', type=str, default=None, help=\n 'Path to checkpoint to resume')\n", (1583, 1667), False, 'import click\n'), ((2892, 3001), 'click.option', 'click.option', (['"""-r"""', '"""--reformer-checkpoint"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path to reformer checkpoint"""'}), "('-r', '--reformer-checkpoint', type=str, required=True, help=\n 'Path to reformer checkpoint')\n", (2904, 3001), False, 'import click\n'), ((2998, 3113), 'click.option', 'click.option', (['"""-s"""', '"""--squeeze-wave-checkpoint"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path to squeezewave checkpoint"""'}), "('-s', '--squeeze-wave-checkpoint', type=str, required=True,\n help='Path to squeezewave checkpoint')\n", (3010, 3113), False, 'import click\n'), ((3111, 3216), 'click.option', 'click.option', (['"""-o"""', '"""--output-dir"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path where outputs will be saved"""'}), "('-o', '--output-dir', type=str, required=True, help=\n 'Path where outputs will be saved')\n", (3123, 3216), False, 'import click\n'), ((3213, 3327), 'click.option', 'click.option', (['"""-m"""', '"""--max-samples"""'], {'type': 'int', 'default': 'None', 'help': '"""Maximum number of total generated samples"""'}), "('-m', '--max-samples', type=int, default=None, help=\n 'Maximum number of total generated samples')\n", (3225, 3327), False, 'import click\n'), ((6751, 6860), 'click.option', 'click.option', (['"""-r"""', '"""--reformer-checkpoint"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path to reformer checkpoint"""'}), "('-r', '--reformer-checkpoint', type=str, required=True, help=\n 'Path to reformer checkpoint')\n", (6763, 6860), False, 'import click\n'), ((6857, 6972), 'click.option', 'click.option', (['"""-s"""', '"""--squeeze-wave-checkpoint"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path to squeezewave checkpoint"""'}), "('-s', '--squeeze-wave-checkpoint', type=str, required=True,\n help='Path to squeezewave checkpoint')\n", (6869, 6972), False, 'import click\n'), ((6970, 7075), 'click.option', 'click.option', (['"""-o"""', '"""--output-dir"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path where outputs will be saved"""'}), "('-o', '--output-dir', type=str, required=True, help=\n 'Path where outputs will be saved')\n", (6982, 7075), False, 'import click\n'), ((7072, 7196), 'click.option', 'click.option', (['"""-S"""', '"""--strategy"""'], {'type': 'str', 'default': '"""concat"""', 'help': '"""Strategy for TTS inference (\'concat\' or \'replace\')"""'}), '(\'-S\', \'--strategy\', type=str, default=\'concat\', help=\n "Strategy for TTS inference (\'concat\' or \'replace\')")\n', (7084, 7196), False, 'import click\n'), ((9600, 9715), 'click.option', 'click.option', (['"""-s"""', '"""--squeeze-wave-checkpoint"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path to squeezewave checkpoint"""'}), "('-s', '--squeeze-wave-checkpoint', type=str, required=True,\n help='Path to squeezewave checkpoint')\n", (9612, 9715), False, 'import click\n'), ((9713, 9818), 'click.option', 'click.option', (['"""-o"""', '"""--output-dir"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path where outputs will be saved"""'}), "('-o', '--output-dir', type=str, required=True, help=\n 'Path where outputs will be saved')\n", (9725, 9818), False, 'import click\n'), ((10875, 10984), 'click.option', 'click.option', (['"""-r"""', '"""--reformer-checkpoint"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path to reformer checkpoint"""'}), "('-r', '--reformer-checkpoint', type=str, required=True, help=\n 'Path to reformer checkpoint')\n", (10887, 10984), False, 'import click\n'), ((10981, 11086), 'click.option', 'click.option', (['"""-o"""', '"""--output-dir"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path where outputs will be saved"""'}), "('-o', '--output-dir', type=str, required=True, help=\n 'Path where outputs will be saved')\n", (10993, 11086), False, 'import click\n'), ((12680, 12780), 'click.option', 'click.option', (['"""-o"""', '"""--output"""'], {'type': 'str', 'required': '(True)', 'help': '"""Path where config will be saved"""'}), "('-o', '--output', type=str, required=True, help=\n 'Path where config will be saved')\n", (12692, 12780), False, 'import click\n'), ((13033, 13064), 'click.argument', 'click.argument', (['"""idx"""'], {'type': 'str'}), "('idx', type=str)\n", (13047, 13064), False, 'import click\n'), ((1518, 1552), 'reformer_tts.training.train.train_tts', 'train_tts_function', (['config', 'resume'], {}), '(config, resume)\n', (1536, 1552), True, 'from reformer_tts.training.train import train_tts as train_tts_function\n'), ((1821, 1859), 'reformer_tts.training.train.train_vocoder', 'train_vocoder_function', (['config', 'resume'], {}), '(config, resume)\n', (1843, 1859), True, 'from reformer_tts.training.train import train_vocoder as train_vocoder_function\n'), ((1960, 2163), 'reformer_tts.dataset.download.download_speech_videos_and_transcripts', 'download_speech_videos_and_transcripts', ([], {'url': 'config.dataset.source_url', 'transcript_directory': 'config.dataset.structure.transcript_directory', 'video_directory': 'config.dataset.structure.video_directory'}), '(url=config.dataset.source_url,\n transcript_directory=config.dataset.structure.transcript_directory,\n video_directory=config.dataset.structure.video_directory)\n', (1998, 2163), False, 'from reformer_tts.dataset.download import download_speech_videos_and_transcripts\n'), ((2288, 2817), 'reformer_tts.dataset.preprocess.preprocess_data', 'preprocess_data', ([], {'trump_speaker_names': 'config.dataset.trump_speaker_names', 'transcript_directory': 'config.transcript_directory', 'merged_transcript_csv_path': 'config.merged_transcript_csv_path', 'audio_directory': 'config.audio_directory', 'video_directory': 'config.video_directory', 'spectrogram_dir': 'config.mel_directory', 'nltk_data_directory': 'config.nltk_data_directory', 'audio_format': 'config.dataset.audio_format', 'mel_format': 'config.dataset.mel_format', 'use_tacotron2_spectrograms': 'config.dataset.use_tacotron2_spectrograms'}), '(trump_speaker_names=config.dataset.trump_speaker_names,\n transcript_directory=config.transcript_directory,\n merged_transcript_csv_path=config.merged_transcript_csv_path,\n audio_directory=config.audio_directory, video_directory=config.\n video_directory, spectrogram_dir=config.mel_directory,\n nltk_data_directory=config.nltk_data_directory, audio_format=config.\n dataset.audio_format, mel_format=config.dataset.mel_format,\n use_tacotron2_spectrograms=config.dataset.use_tacotron2_spectrograms)\n', (2303, 2817), False, 'from reformer_tts.dataset.preprocess import preprocess_data\n'), ((3841, 3857), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (3845, 3857), False, 'from pathlib import Path\n'), ((3916, 3941), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3939, 3941), False, 'import torch\n'), ((4151, 4222), 'reformer_tts.training.wrappers.LitReformerTTS.load_from_checkpoint', 'LitReformerTTS.load_from_checkpoint', (['reformer_checkpoint'], {'config': 'config'}), '(reformer_checkpoint, config=config)\n', (4186, 4222), False, 'from reformer_tts.training.wrappers import LitSqueezeWave, LitReformerTTS\n'), ((4273, 4367), 'reformer_tts.training.wrappers.LitSqueezeWave.load_from_checkpoint', 'LitSqueezeWave.load_from_checkpoint', (['squeeze_wave_checkpoint'], {'config': 'config', 'on_gpu': 'on_gpu'}), '(squeeze_wave_checkpoint, config=config,\n on_gpu=on_gpu)\n', (4308, 4367), False, 'from reformer_tts.training.wrappers import LitSqueezeWave, LitReformerTTS\n'), ((4413, 4457), 'reformer_tts.squeeze_wave.modules.SqueezeWave.remove_norms', 'SqueezeWave.remove_norms', (['squeeze_wave.model'], {}), '(squeeze_wave.model)\n', (4437, 4457), False, 'from reformer_tts.squeeze_wave.modules import SqueezeWave\n'), ((7507, 7523), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (7511, 7523), False, 'from pathlib import Path\n'), ((7582, 7607), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7605, 7607), False, 'import torch\n'), ((7817, 7888), 'reformer_tts.training.wrappers.LitReformerTTS.load_from_checkpoint', 'LitReformerTTS.load_from_checkpoint', (['reformer_checkpoint'], {'config': 'config'}), '(reformer_checkpoint, config=config)\n', (7852, 7888), False, 'from reformer_tts.training.wrappers import LitSqueezeWave, LitReformerTTS\n'), ((7940, 8034), 'reformer_tts.training.wrappers.LitSqueezeWave.load_from_checkpoint', 'LitSqueezeWave.load_from_checkpoint', (['squeeze_wave_checkpoint'], {'config': 'config', 'on_gpu': 'on_gpu'}), '(squeeze_wave_checkpoint, config=config,\n on_gpu=on_gpu)\n', (7975, 8034), False, 'from reformer_tts.training.wrappers import LitSqueezeWave, LitReformerTTS\n'), ((8080, 8124), 'reformer_tts.squeeze_wave.modules.SqueezeWave.remove_norms', 'SqueezeWave.remove_norms', (['squeeze_wave.model'], {}), '(squeeze_wave.model)\n', (8104, 8124), False, 'from reformer_tts.squeeze_wave.modules import SqueezeWave\n'), ((8182, 8232), 'reformer_tts.dataset.convert.PhonemeSequenceCreator', 'PhonemeSequenceCreator', (['config.nltk_data_directory'], {}), '(config.nltk_data_directory)\n', (8204, 8232), False, 'from reformer_tts.dataset.convert import PhonemeSequenceCreator\n'), ((9974, 9990), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (9978, 9990), False, 'from pathlib import Path\n'), ((10055, 10080), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (10078, 10080), False, 'import torch\n'), ((10100, 10193), 'reformer_tts.training.wrappers.LitSqueezeWave.load_from_checkpoint', 'LitSqueezeWave.load_from_checkpoint', (['squeeze_wave_checkpoint'], {'config': 'config', 'on_gpu': '(False)'}), '(squeeze_wave_checkpoint, config=config,\n on_gpu=False)\n', (10135, 10193), False, 'from reformer_tts.training.wrappers import LitSqueezeWave, LitReformerTTS\n'), ((10223, 10267), 'reformer_tts.squeeze_wave.modules.SqueezeWave.remove_norms', 'SqueezeWave.remove_norms', (['squeeze_wave.model'], {}), '(squeeze_wave.model)\n', (10247, 10267), False, 'from reformer_tts.squeeze_wave.modules import SqueezeWave\n'), ((10325, 10387), 'torch.load', 'torch.load', (['"""data/preprocessed-tacotron2/mel/speech00_0000.pt"""'], {}), "('data/preprocessed-tacotron2/mel/speech00_0000.pt')\n", (10335, 10387), False, 'import torch\n'), ((10402, 10458), 'torch.load', 'torch.load', (['"""data/lj-speech-tacotron2/mel/LJ001-0001.pt"""'], {}), "('data/lj-speech-tacotron2/mel/LJ001-0001.pt')\n", (10412, 10458), False, 'import torch\n'), ((11221, 11237), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (11225, 11237), False, 'from pathlib import Path\n'), ((11295, 11320), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (11318, 11320), False, 'import torch\n'), ((11529, 11619), 'reformer_tts.training.wrappers.LitReformerTTS.load_from_checkpoint', 'LitReformerTTS.load_from_checkpoint', (['reformer_checkpoint'], {'config': 'config', 'on_gpu': 'on_gpu'}), '(reformer_checkpoint, config=config,\n on_gpu=on_gpu)\n', (11564, 11619), False, 'from reformer_tts.training.wrappers import LitSqueezeWave, LitReformerTTS\n'), ((13153, 13194), 'neptune.init', 'neptune.init', (['"""reformer-tts/reformer-tts"""'], {}), "('reformer-tts/reformer-tts')\n", (13165, 13194), False, 'import neptune\n'), ((1145, 1153), 'reformer_tts.config.Config', 'Config', ([], {}), '()\n', (1151, 1153), False, 'from reformer_tts.config import Config\n'), ((1214, 1243), 'reformer_tts.config.Config.from_yaml_file', 'Config.from_yaml_file', (['config'], {}), '(config)\n', (1235, 1243), False, 'from reformer_tts.config import Config\n'), ((1501, 1513), 'pathlib.Path', 'Path', (['resume'], {}), '(resume)\n', (1505, 1513), False, 'from pathlib import Path\n'), ((1804, 1816), 'pathlib.Path', 'Path', (['resume'], {}), '(resume)\n', (1808, 1816), False, 'from pathlib import Path\n'), ((3951, 4004), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.cuda.FloatTensor'], {}), '(torch.cuda.FloatTensor)\n', (3980, 4004), False, 'import torch\n'), ((4022, 4042), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (4034, 4042), False, 'import torch\n'), ((4092, 4111), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (4104, 4111), False, 'import torch\n'), ((4739, 4754), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4752, 4754), False, 'import torch\n'), ((4825, 4863), 'tqdm.trange', 'trange', (['max_samples'], {'desc': '"""predicting"""'}), "(max_samples, desc='predicting')\n", (4831, 4863), False, 'from tqdm import trange, tqdm\n'), ((6135, 6163), 'tqdm.tqdm', 'tqdm', (['results'], {'desc': '"""saving"""'}), "(results, desc='saving')\n", (6139, 6163), False, 'from tqdm import trange, tqdm\n'), ((7617, 7670), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.cuda.FloatTensor'], {}), '(torch.cuda.FloatTensor)\n', (7646, 7670), False, 'import torch\n'), ((7710, 7730), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (7722, 7730), False, 'import torch\n'), ((7781, 7800), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (7793, 7800), False, 'import torch\n'), ((8366, 8381), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8379, 8381), False, 'import torch\n'), ((11330, 11383), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.cuda.FloatTensor'], {}), '(torch.cuda.FloatTensor)\n', (11359, 11383), False, 'import torch\n'), ((11423, 11443), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (11435, 11443), False, 'import torch\n'), ((11494, 11513), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (11506, 11513), False, 'import torch\n'), ((11830, 11845), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11843, 11845), False, 'import torch\n'), ((12646, 12660), 'dataclasses.asdict', 'asdict', (['config'], {}), '(config)\n', (12652, 12660), False, 'from dataclasses import asdict\n'), ((5250, 5301), 'torch.nn.functional.mse_loss', 'mse_loss', (['spectrogram_out', 'spectrogram_in[:, 1:, :]'], {}), '(spectrogram_out, spectrogram_in[:, 1:, :])\n', (5258, 5301), False, 'from torch.nn.functional import mse_loss\n'), ((6327, 6379), 'reformer_tts.dataset.visualize.plot_spectrogram', 'plot_spectrogram', (["result['spectrogram']"], {'scale': '(False)'}), "(result['spectrogram'], scale=False)\n", (6343, 6379), False, 'from reformer_tts.dataset.visualize import plot_spectrogram, plot_attention_matrix\n'), ((6439, 6450), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6448, 6450), True, 'import matplotlib.pyplot as plt\n'), ((9268, 9279), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9277, 9279), True, 'import matplotlib.pyplot as plt\n'), ((10477, 10506), 'pathlib.Path', 'Path', (['squeeze_wave_checkpoint'], {}), '(squeeze_wave_checkpoint)\n', (10481, 10506), False, 'from pathlib import Path\n'), ((12453, 12482), 'reformer_tts.dataset.visualize.plot_attention_matrix', 'plot_attention_matrix', (['matrix'], {}), '(matrix)\n', (12474, 12482), False, 'from reformer_tts.dataset.visualize import plot_spectrogram, plot_attention_matrix\n'), ((12495, 12535), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(output_dir / f'{i}_{j}.png')"], {}), "(output_dir / f'{i}_{j}.png')\n", (12506, 12535), True, 'import matplotlib.pyplot as plt\n')]
import itertools import json import logging import os import tempfile from typing import List, Any, Dict, Tuple import gin import numpy as np import pandas as pd from experiments.src.gin import get_default_experiment_name, parse_gin_str from experiments.src.training.training_utils import get_metric_cls GridResultDict = Dict[frozenset, Dict[int, Dict[str, float]]] def get_grid_results_dict() -> GridResultDict: grid_results_dict = create_grid_results_dict() study_name = get_default_experiment_name() if gin.query_parameter('train.use_neptune'): fetch_grid_results_dict_from_neptune(grid_results_dict, study_name) else: fetch_grid_results_dict_from_local(grid_results_dict, study_name) return grid_results_dict def create_grid_results_dict() -> GridResultDict: seeds = get_params_dict()['data.split_seed'] hps_dict = get_hps_dict() hps_product_list = _get_params_product_list(hps_dict) return {frozenset(hps.items()): {seed: None for seed in seeds} for hps in hps_product_list} # neptune def fetch_grid_results_dict_from_neptune(results_dict: GridResultDict, study_name: str) -> None: import neptune user_name = gin.query_parameter('neptune.user_name') project_name = gin.query_parameter('neptune.project_name') project = neptune.init(f'{user_name}/{project_name}') df = download_dataframe_from_neptune(project, study_name) hps_names = list(get_hps_dict().keys()) for idx, row in df.iterrows(): hps = dict(row[hps_names]) seed = int(row['data.split_seed']) results = download_results_from_neptune(project, row['id'], 'results.json') results_dict[frozenset(hps.items())][seed] = results def download_dataframe_from_neptune(neptune_project, name: str) -> pd.DataFrame: df = neptune_project.get_leaderboard(state='succeeded', tag=name) params_dict = get_params_dict() df.rename(columns={f'parameter_{p}': p for p in params_dict.keys()}, inplace=True) df = df[['id', 'name'] + list(params_dict.keys())] for param_name, param_value in params_dict.items(): dtype = type(param_value[0]) df[param_name] = df[param_name].astype(dtype) if dtype != int else df[param_name].astype(float).astype(int) return df def download_results_from_neptune(neptune_project, id: str, artifact_name: str) -> Dict[str, float]: try: with tempfile.TemporaryDirectory() as tmp: experiment = neptune_project.get_experiments(id=id)[0] experiment.download_artifact(artifact_name, tmp) return load_results_from_local(os.path.join(tmp, artifact_name)) except Exception as e: raise RuntimeError(f'Downloading artifacts failed on {id}. Exception: {e}') # local def fetch_grid_results_dict_from_local(grid_results_dict: GridResultDict, study_name: str) -> None: root_path = gin.query_parameter('optuna.root_path') save_path = os.path.join(root_path, study_name) hps_names = set(get_hps_dict().keys()) for path in os.listdir(save_path): trial_path = os.path.join(save_path, path) if os.path.isdir(trial_path): experiment_path = os.path.join(trial_path, study_name) gin_path = os.path.join(experiment_path, "gin-config-essential.txt") with open(gin_path, 'r') as fp: gin_str = fp.read() gin_dict = parse_gin_str(gin_str) hps = {k: v for k, v in gin_dict.items() if k in hps_names} seed = gin_dict['data.split_seed'] results = load_results_from_local(os.path.join(experiment_path, 'results.json')) grid_results_dict[frozenset(hps.items())][seed] = results def load_results_from_local(output_path: str) -> Dict[str, float]: return json.load(open(output_path, 'r'))[0] # results check def check_grid_results_dict(grid_results_dict: GridResultDict) -> None: any_missing_result = False for params, results in grid_results_dict.items(): for seed, result in results.items(): if result is None: any_missing_result = True logging.error(f'Results for seed: {seed} and hps: {dict(params)} are missing') assert not any_missing_result # helper methods def get_params_dict() -> Dict[str, Any]: params_dict: dict = gin.query_parameter('optuna.params') return {k: v.__deepcopy__(None) if isinstance(v, gin.config.ConfigurableReference) else v for k, v in params_dict.items()} def get_hps_dict() -> Dict[str, Any]: params_dict = get_params_dict() return {k: v for k, v in params_dict.items() if k != 'data.split_seed'} def _get_params_product_list(params_dict: Dict[str, Any]) -> List[dict]: params_dict = {k: list(map(lambda x: (k, x), v)) for k, v in params_dict.items()} return [dict(params) for params in itertools.product(*params_dict.values())] # compute results def compute_result(grid_results_dict: GridResultDict) -> Tuple[frozenset, Dict[str, float], str]: metric_cls = get_metric_cls() metric_name = metric_cls.__name__.lower() agg_fn = min if metric_cls.direction == 'minimize' else max valid_metric = f'valid_{metric_name}' test_metric = f'test_{metric_name}' results = [(params, average_dictionary(results)) for params, results in grid_results_dict.items()] results = [x for x in results if not np.isnan(x[1][valid_metric])] assert len(results) > 0, "'results' contains only nan!" params, result = agg_fn(results, key=lambda x: x[1][valid_metric]) return params, result, test_metric def average_dictionary(dictionary: Dict[int, Dict[str, float]]) -> Dict[str, float]: values = list(dictionary.values())[0].keys() agg = {v: [dictionary[seed][v] for seed in dictionary.keys()] for v in values} mean = {k: np.mean(lst) for k, lst in agg.items()} std = {f'{k}_std': np.std(lst) for k, lst in agg.items()} return {**mean, **std} def print_result(params: frozenset, result: Dict[str, float], test_metric: str) -> None: print(f'Best params: {dict(params)}') for key in sorted(key for key in result.keys() if not key.endswith('_std')): print(f'\t{key}: {rounded_mean_std(result, key)}') print(f'Result: {rounded_mean_std(result, test_metric)}') def rounded_mean_std(result: Dict[str, float], key: str) -> str: return f'{round(result[key], 3)} \u00B1 {round(result[f"{key}_std"], 3)}'
[ "neptune.init" ]
[((486, 515), 'experiments.src.gin.get_default_experiment_name', 'get_default_experiment_name', ([], {}), '()\n', (513, 515), False, 'from experiments.src.gin import get_default_experiment_name, parse_gin_str\n'), ((523, 563), 'gin.query_parameter', 'gin.query_parameter', (['"""train.use_neptune"""'], {}), "('train.use_neptune')\n", (542, 563), False, 'import gin\n'), ((1184, 1224), 'gin.query_parameter', 'gin.query_parameter', (['"""neptune.user_name"""'], {}), "('neptune.user_name')\n", (1203, 1224), False, 'import gin\n'), ((1244, 1287), 'gin.query_parameter', 'gin.query_parameter', (['"""neptune.project_name"""'], {}), "('neptune.project_name')\n", (1263, 1287), False, 'import gin\n'), ((1302, 1345), 'neptune.init', 'neptune.init', (['f"""{user_name}/{project_name}"""'], {}), "(f'{user_name}/{project_name}')\n", (1314, 1345), False, 'import neptune\n'), ((2875, 2914), 'gin.query_parameter', 'gin.query_parameter', (['"""optuna.root_path"""'], {}), "('optuna.root_path')\n", (2894, 2914), False, 'import gin\n'), ((2931, 2966), 'os.path.join', 'os.path.join', (['root_path', 'study_name'], {}), '(root_path, study_name)\n', (2943, 2966), False, 'import os\n'), ((3027, 3048), 'os.listdir', 'os.listdir', (['save_path'], {}), '(save_path)\n', (3037, 3048), False, 'import os\n'), ((4321, 4357), 'gin.query_parameter', 'gin.query_parameter', (['"""optuna.params"""'], {}), "('optuna.params')\n", (4340, 4357), False, 'import gin\n'), ((5027, 5043), 'experiments.src.training.training_utils.get_metric_cls', 'get_metric_cls', ([], {}), '()\n', (5041, 5043), False, 'from experiments.src.training.training_utils import get_metric_cls\n'), ((3071, 3100), 'os.path.join', 'os.path.join', (['save_path', 'path'], {}), '(save_path, path)\n', (3083, 3100), False, 'import os\n'), ((3112, 3137), 'os.path.isdir', 'os.path.isdir', (['trial_path'], {}), '(trial_path)\n', (3125, 3137), False, 'import os\n'), ((5814, 5826), 'numpy.mean', 'np.mean', (['lst'], {}), '(lst)\n', (5821, 5826), True, 'import numpy as np\n'), ((5877, 5888), 'numpy.std', 'np.std', (['lst'], {}), '(lst)\n', (5883, 5888), True, 'import numpy as np\n'), ((2394, 2423), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2421, 2423), False, 'import tempfile\n'), ((3169, 3205), 'os.path.join', 'os.path.join', (['trial_path', 'study_name'], {}), '(trial_path, study_name)\n', (3181, 3205), False, 'import os\n'), ((3229, 3286), 'os.path.join', 'os.path.join', (['experiment_path', '"""gin-config-essential.txt"""'], {}), "(experiment_path, 'gin-config-essential.txt')\n", (3241, 3286), False, 'import os\n'), ((3390, 3412), 'experiments.src.gin.parse_gin_str', 'parse_gin_str', (['gin_str'], {}), '(gin_str)\n', (3403, 3412), False, 'from experiments.src.gin import get_default_experiment_name, parse_gin_str\n'), ((2603, 2635), 'os.path.join', 'os.path.join', (['tmp', 'artifact_name'], {}), '(tmp, artifact_name)\n', (2615, 2635), False, 'import os\n'), ((3579, 3624), 'os.path.join', 'os.path.join', (['experiment_path', '"""results.json"""'], {}), "(experiment_path, 'results.json')\n", (3591, 3624), False, 'import os\n'), ((5380, 5408), 'numpy.isnan', 'np.isnan', (['x[1][valid_metric]'], {}), '(x[1][valid_metric])\n', (5388, 5408), True, 'import numpy as np\n')]
# # Copyright (c) 2022, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from unittest.mock import MagicMock import pytest from neptune.new.exceptions import ProjectNotFound from neptune.new.sync.utils import get_project @pytest.fixture(name="backend") def backend_fixture(): return MagicMock() def test_get_project_no_name_set(mocker, backend): # given mocker.patch.object(os, "getenv") os.getenv.return_value = None # expect assert get_project(None, backend=backend) is None def test_get_project_project_not_found(backend): # given backend.get_project.side_effect = ProjectNotFound("foo") # expect assert get_project("foo", backend=backend) is None
[ "neptune.new.exceptions.ProjectNotFound", "neptune.new.sync.utils.get_project" ]
[((760, 790), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""backend"""'}), "(name='backend')\n", (774, 790), False, 'import pytest\n'), ((825, 836), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (834, 836), False, 'from unittest.mock import MagicMock\n'), ((1143, 1165), 'neptune.new.exceptions.ProjectNotFound', 'ProjectNotFound', (['"""foo"""'], {}), "('foo')\n", (1158, 1165), False, 'from neptune.new.exceptions import ProjectNotFound\n'), ((999, 1033), 'neptune.new.sync.utils.get_project', 'get_project', (['None'], {'backend': 'backend'}), '(None, backend=backend)\n', (1010, 1033), False, 'from neptune.new.sync.utils import get_project\n'), ((1191, 1226), 'neptune.new.sync.utils.get_project', 'get_project', (['"""foo"""'], {'backend': 'backend'}), "('foo', backend=backend)\n", (1202, 1226), False, 'from neptune.new.sync.utils import get_project\n')]
import logging import os as os import tempfile import datetime as dt from matplotlib import pyplot as plt import neptune as npt from neptunecontrib import api as npta from neptunecontrib import hpo as npth from neptunecontrib.monitoring import optuna as nmo from neptunecontrib.monitoring import keras as nmk class ExperimentManager(object): def __init__(self, log, project_name, experiment_name, experiment_params, experiment_tags): logging.getLogger('neptune').setLevel(logging.ERROR) self.log = log self.project = None self.experiment = None self._optuna_callback = None self._keras_callback = None self._experiment_name = None if self.log: self.project=npt.set_project( project_qualified_name=project_name) self.experiment = npt.create_experiment( name=experiment_name, params=experiment_params) for tag in experiment_tags: self.experiment.append_tags(tag) @property def experiment_name(self): if self._experiment_name is None: if self.log and self.experiment: self._experiment_name = self.experiment.id else: self._experiment_name = ExperimentManager.get_fake_name() return self._experiment_name @property def optuna_callback(self): if self.log and self._optuna_callback is None: self._optuna_callback = nmo.NeptuneCallback( experiment=self.experiment) return self._optuna_callback @property def keras_callback(self): if self.log and self._keras_callback is None: self._keras_callback = nmk.NeptuneCallback( experiment=self.experiment) return self._keras_callback @staticmethod def get_fake_name(): return str(int(dt.datetime.now().timestamp())) def get_experiment_id(self): if self.log and self.experiment: return self.experiment.id else: return None def add_experiment_tags(self, tag): if self.log and self.experiment: self.experiment.append_tags(tag) print('[Tag] {0}'.format(tag)) def set_experiment_property(self, key, value): if self.log and self.experiment: self.experiment.set_property( key=key, value=value) print('[Property] {0}: {1}'.format(key, value)) def log_data_to_neptune(self, data, name, log_index=False, log_to_table=True, log_to_artifact=True): if self.log and self.experiment: if name is None: name = ExperimentManager.get_fake_name() if log_to_table: npta.log_table( name='{0}.csv'.format(name), table=data, experiment=self.experiment) if log_to_artifact: file_path = os.path.join( tempfile.gettempdir(), '{0}.csv'.format(name)) data.to_csv(file_path, index=log_index) self.experiment.log_artifact( file_path, 'data/{0}.csv'.format(name)) def log_chart_to_neptune(self, figure, name, log_to_artifact=True): if self.log and self.experiment: if name is None: name = ExperimentManager.get_fake_name() if log_to_artifact: file_path = os.path.join( tempfile.gettempdir(), '{0}.jpg'.format(name)) figure.savefig( fname=file_path, dpi=96, format='jpg', quality=90, bbox_inches='tight') self.experiment.log_artifact( file_path, 'charts/{0}.jpg'.format(name))
[ "neptune.create_experiment", "neptune.set_project" ]
[((745, 797), 'neptune.set_project', 'npt.set_project', ([], {'project_qualified_name': 'project_name'}), '(project_qualified_name=project_name)\n', (760, 797), True, 'import neptune as npt\n'), ((846, 915), 'neptune.create_experiment', 'npt.create_experiment', ([], {'name': 'experiment_name', 'params': 'experiment_params'}), '(name=experiment_name, params=experiment_params)\n', (867, 915), True, 'import neptune as npt\n'), ((1502, 1549), 'neptunecontrib.monitoring.optuna.NeptuneCallback', 'nmo.NeptuneCallback', ([], {'experiment': 'self.experiment'}), '(experiment=self.experiment)\n', (1521, 1549), True, 'from neptunecontrib.monitoring import optuna as nmo\n'), ((1747, 1794), 'neptunecontrib.monitoring.keras.NeptuneCallback', 'nmk.NeptuneCallback', ([], {'experiment': 'self.experiment'}), '(experiment=self.experiment)\n', (1766, 1794), True, 'from neptunecontrib.monitoring import keras as nmk\n'), ((452, 480), 'logging.getLogger', 'logging.getLogger', (['"""neptune"""'], {}), "('neptune')\n", (469, 480), False, 'import logging\n'), ((3079, 3100), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (3098, 3100), False, 'import tempfile\n'), ((3625, 3646), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (3644, 3646), False, 'import tempfile\n'), ((1920, 1937), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (1935, 1937), True, 'import datetime as dt\n')]
import random import neptune import numpy as np import tensorflow as tf import neptune_tensorboard as neptune_tb from absl import flags from absl import app from data_processor import read_data from tensorflow.keras import callbacks, Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization from tensorflow.keras.optimizers import Adam flags.DEFINE_string('mode', 'train', 'In which mode should the program be run train/eval') flags.DEFINE_float('dropout', 0.2, 'Set dropout') flags.DEFINE_float('learning_rate', 0.0001, 'Set learning rate') flags.DEFINE_string('activation', 'relu', 'Set activation method') flags.DEFINE_string('data_dir', '../data/uniform_200k_time_delta/', 'Relative path to the data folder') flags.DEFINE_integer('epochs', 1, 'Number of epochs') flags.DEFINE_integer('lstm_filters', 1, 'Number of LSTM layers') flags.DEFINE_integer('lstm_filter', 256, 'Number of units in lstm') flags.DEFINE_integer('dense_filters', 1, 'Number of Dense layers') flags.DEFINE_integer('dense_filter', 256, 'Number of units in dense layer') FLAGS = flags.FLAGS RUN_NAME = 'run_{}'.format(random.getrandbits(64)) EXPERIMENT_LOG_DIR = 'logs/{}'.format(RUN_NAME) def input_fn(trainingset_path): x_train, y_train = read_data(trainingset_path, 'train') x_eval, y_eval = read_data(trainingset_path, 'eval') x_train = np.reshape(x_train.values, (-1, x_train.shape[1], 1)) y_train = np.reshape(y_train.values, (-1, 1)) x_eval = np.reshape(x_eval.values, (-1, x_eval.shape[1], 1)) y_eval = np.reshape(y_eval.values, (-1, 1)) return x_train, y_train, x_eval, y_eval def create_lstm(hparams): model = Sequential() model.add(BatchNormalization()) for _ in range(hparams['lstm_filters']): model.add(LSTM(hparams['lstm_filter'], return_sequences=True)) model.add(LSTM(hparams['lstm_filter'])) for _ in range(hparams['dense_filters']): model.add(Dense(hparams['dense_filter'], activation='relu')) model.add(Dropout(hparams['dropout'])) model.add(BatchNormalization()) return model def divide(x): ret = np.empty([len(x), 20, 2]) for i, row in enumerate(x): for j in range(1, len(row)): j -= 1 if (j - 1) % 2: ret[i][(j - 1) // 2][0] = row[j + 1] else: ret[i][(j - 1) // 2][1] = row[j + 1] return ret def train(hparams): neptune.init(project_qualified_name='kowson/OLN') with neptune.create_experiment(name="Recurrent neural network", params=hparams, tags=["CuDNNLSTM", hparams['data_dir'], "data_v2", "mse"]): x_train, y_train, x_eval, y_eval = input_fn(hparams['data_dir']) x_train_divided = divide(x_train) x_eval_divided = divide(x_eval) model = create_lstm(hparams) opt = Adam(lr=hparams["learning_rate"], decay=1e-3 / 200) model.compile(loss=tf.keras.losses.MeanSquaredError(), optimizer=opt) tbCallBack = callbacks.TensorBoard(log_dir=EXPERIMENT_LOG_DIR) checkpoint_path = EXPERIMENT_LOG_DIR cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, save_freq=11*100, verbose=1) history_callback = model.fit( x_train, y_train, validation_data=(x_eval, y_eval), epochs=hparams["num_epochs"], batch_size=hparams["batch_size"], callbacks=[tbCallBack, cp_callback], verbose=2) def create_experiment(): neptune_tb.integrate_with_tensorflow() hyper_params = { 'data_dir': FLAGS.data_dir, 'shuffle': False, 'num_threads': 1, 'batch_size': 16384, 'initializer': 'uniform_unit_scaling', 'lstm_filters': FLAGS.lstm_filters, 'lstm_filter': FLAGS.lstm_filter, 'dense_filters': FLAGS.dense_filters, 'dense_filter': FLAGS.dense_filter, 'dropout': FLAGS.dropout, 'learning_rate': FLAGS.learning_rate, 'activation': 'relu', 'num_epochs': FLAGS.epochs, } print('--- Starting trial ---') train(hyper_params) def main(argv): if FLAGS.mode == 'train': create_experiment() elif FLAGS.mode == 'eval': pass if __name__ == '__main__': app.run(main)
[ "neptune.create_experiment", "neptune.init" ]
[((369, 463), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""mode"""', '"""train"""', '"""In which mode should the program be run train/eval"""'], {}), "('mode', 'train',\n 'In which mode should the program be run train/eval')\n", (388, 463), False, 'from absl import flags\n'), ((460, 509), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""dropout"""', '(0.2)', '"""Set dropout"""'], {}), "('dropout', 0.2, 'Set dropout')\n", (478, 509), False, 'from absl import flags\n'), ((510, 574), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""learning_rate"""', '(0.0001)', '"""Set learning rate"""'], {}), "('learning_rate', 0.0001, 'Set learning rate')\n", (528, 574), False, 'from absl import flags\n'), ((575, 641), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""activation"""', '"""relu"""', '"""Set activation method"""'], {}), "('activation', 'relu', 'Set activation method')\n", (594, 641), False, 'from absl import flags\n'), ((642, 749), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""data_dir"""', '"""../data/uniform_200k_time_delta/"""', '"""Relative path to the data folder"""'], {}), "('data_dir', '../data/uniform_200k_time_delta/',\n 'Relative path to the data folder')\n", (661, 749), False, 'from absl import flags\n'), ((746, 799), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""epochs"""', '(1)', '"""Number of epochs"""'], {}), "('epochs', 1, 'Number of epochs')\n", (766, 799), False, 'from absl import flags\n'), ((800, 864), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""lstm_filters"""', '(1)', '"""Number of LSTM layers"""'], {}), "('lstm_filters', 1, 'Number of LSTM layers')\n", (820, 864), False, 'from absl import flags\n'), ((865, 932), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""lstm_filter"""', '(256)', '"""Number of units in lstm"""'], {}), "('lstm_filter', 256, 'Number of units in lstm')\n", (885, 932), False, 'from absl import flags\n'), ((933, 999), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""dense_filters"""', '(1)', '"""Number of Dense layers"""'], {}), "('dense_filters', 1, 'Number of Dense layers')\n", (953, 999), False, 'from absl import flags\n'), ((1000, 1075), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""dense_filter"""', '(256)', '"""Number of units in dense layer"""'], {}), "('dense_filter', 256, 'Number of units in dense layer')\n", (1020, 1075), False, 'from absl import flags\n'), ((1124, 1146), 'random.getrandbits', 'random.getrandbits', (['(64)'], {}), '(64)\n', (1142, 1146), False, 'import random\n'), ((1252, 1288), 'data_processor.read_data', 'read_data', (['trainingset_path', '"""train"""'], {}), "(trainingset_path, 'train')\n", (1261, 1288), False, 'from data_processor import read_data\n'), ((1310, 1345), 'data_processor.read_data', 'read_data', (['trainingset_path', '"""eval"""'], {}), "(trainingset_path, 'eval')\n", (1319, 1345), False, 'from data_processor import read_data\n'), ((1360, 1413), 'numpy.reshape', 'np.reshape', (['x_train.values', '(-1, x_train.shape[1], 1)'], {}), '(x_train.values, (-1, x_train.shape[1], 1))\n', (1370, 1413), True, 'import numpy as np\n'), ((1428, 1463), 'numpy.reshape', 'np.reshape', (['y_train.values', '(-1, 1)'], {}), '(y_train.values, (-1, 1))\n', (1438, 1463), True, 'import numpy as np\n'), ((1477, 1528), 'numpy.reshape', 'np.reshape', (['x_eval.values', '(-1, x_eval.shape[1], 1)'], {}), '(x_eval.values, (-1, x_eval.shape[1], 1))\n', (1487, 1528), True, 'import numpy as np\n'), ((1542, 1576), 'numpy.reshape', 'np.reshape', (['y_eval.values', '(-1, 1)'], {}), '(y_eval.values, (-1, 1))\n', (1552, 1576), True, 'import numpy as np\n'), ((1661, 1673), 'tensorflow.keras.Sequential', 'Sequential', ([], {}), '()\n', (1671, 1673), False, 'from tensorflow.keras import callbacks, Sequential\n'), ((2433, 2482), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""kowson/OLN"""'}), "(project_qualified_name='kowson/OLN')\n", (2445, 2482), False, 'import neptune\n'), ((3724, 3762), 'neptune_tensorboard.integrate_with_tensorflow', 'neptune_tb.integrate_with_tensorflow', ([], {}), '()\n', (3760, 3762), True, 'import neptune_tensorboard as neptune_tb\n'), ((4542, 4555), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (4549, 4555), False, 'from absl import app\n'), ((1688, 1708), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1706, 1708), False, 'from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization\n'), ((1845, 1873), 'tensorflow.keras.layers.LSTM', 'LSTM', (["hparams['lstm_filter']"], {}), "(hparams['lstm_filter'])\n", (1849, 1873), False, 'from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization\n'), ((2492, 2629), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""Recurrent neural network"""', 'params': 'hparams', 'tags': "['CuDNNLSTM', hparams['data_dir'], 'data_v2', 'mse']"}), "(name='Recurrent neural network', params=hparams,\n tags=['CuDNNLSTM', hparams['data_dir'], 'data_v2', 'mse'])\n", (2517, 2629), False, 'import neptune\n'), ((2912, 2964), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': "hparams['learning_rate']", 'decay': '(0.001 / 200)'}), "(lr=hparams['learning_rate'], decay=0.001 / 200)\n", (2916, 2964), False, 'from tensorflow.keras.optimizers import Adam\n'), ((3083, 3132), 'tensorflow.keras.callbacks.TensorBoard', 'callbacks.TensorBoard', ([], {'log_dir': 'EXPERIMENT_LOG_DIR'}), '(log_dir=EXPERIMENT_LOG_DIR)\n', (3104, 3132), False, 'from tensorflow.keras import callbacks, Sequential\n'), ((3201, 3296), 'tensorflow.keras.callbacks.ModelCheckpoint', 'tf.keras.callbacks.ModelCheckpoint', ([], {'filepath': 'checkpoint_path', 'save_freq': '(11 * 100)', 'verbose': '(1)'}), '(filepath=checkpoint_path, save_freq=11 *\n 100, verbose=1)\n', (3235, 3296), True, 'import tensorflow as tf\n'), ((1778, 1829), 'tensorflow.keras.layers.LSTM', 'LSTM', (["hparams['lstm_filter']"], {'return_sequences': '(True)'}), "(hparams['lstm_filter'], return_sequences=True)\n", (1782, 1829), False, 'from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization\n'), ((1940, 1989), 'tensorflow.keras.layers.Dense', 'Dense', (["hparams['dense_filter']"], {'activation': '"""relu"""'}), "(hparams['dense_filter'], activation='relu')\n", (1945, 1989), False, 'from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization\n'), ((2009, 2036), 'tensorflow.keras.layers.Dropout', 'Dropout', (["hparams['dropout']"], {}), "(hparams['dropout'])\n", (2016, 2036), False, 'from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization\n'), ((2056, 2076), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (2074, 2076), False, 'from tensorflow.keras.layers import LSTM, Dense, Dropout, BatchNormalization\n'), ((3010, 3044), 'tensorflow.keras.losses.MeanSquaredError', 'tf.keras.losses.MeanSquaredError', ([], {}), '()\n', (3042, 3044), True, 'import tensorflow as tf\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import atexit import threading import time import traceback import uuid from contextlib import AbstractContextManager from datetime import datetime from typing import Dict, Any, Union, List, Optional import click from neptune.new.attributes.atoms.datetime import Datetime as DatetimeAttr from neptune.new.attributes.atoms.run_state import RunState as RunStateAttr from neptune.new.attributes.atoms.file import File as FileAttr from neptune.new.attributes.atoms.float import Float as FloatAttr from neptune.new.attributes.atoms.git_ref import GitRef as GitRefAttr from neptune.new.attributes.atoms.string import String as StringAttr from neptune.new.attributes.attribute import Attribute from neptune.new.attributes.file_set import FileSet as FileSetAttr from neptune.new.attributes.series.float_series import FloatSeries as FloatSeriesAttr from neptune.new.attributes.series.file_series import FileSeries as ImageSeriesAttr from neptune.new.attributes.series.string_series import StringSeries as StringSeriesAttr from neptune.new.attributes.sets.string_set import StringSet as StringSetAttr from neptune.new.exceptions import MetadataInconsistency from neptune.new.handler import Handler from neptune.new.internal.backends.api_model import AttributeType from neptune.new.internal.backends.neptune_backend import NeptuneBackend from neptune.new.internal.background_job import BackgroundJob from neptune.new.internal.run_structure import RunStructure from neptune.new.internal.operation import DeleteAttribute from neptune.new.internal.operation_processors.operation_processor import OperationProcessor from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like from neptune.new.internal.utils.paths import parse_path from neptune.new.internal.value_to_attribute_visitor import ValueToAttributeVisitor from neptune.new.types import Boolean, Integer from neptune.new.types.atoms.datetime import Datetime from neptune.new.types.atoms.float import Float from neptune.new.types.atoms.string import String from neptune.new.types.value import Value from neptune.exceptions import UNIX_STYLES class Run(AbstractContextManager): last_run = None # "static" instance of recently created Run def __init__( self, _uuid: uuid.UUID, backend: NeptuneBackend, op_processor: OperationProcessor, background_job: BackgroundJob ): self._uuid = _uuid self._backend = backend self._op_processor = op_processor self._bg_job = background_job self._structure = RunStructure[Attribute]() self._lock = threading.RLock() self._started = False Run.last_run = self def __exit__(self, exc_type, exc_val, exc_tb): traceback.print_exception(exc_type, exc_val, exc_tb) self.stop() def __getitem__(self, path: str) -> 'Handler': return Handler(self, path) def __setitem__(self, key: str, value) -> None: self.__getitem__(key).assign(value) def __delitem__(self, path) -> None: self.pop(path) def assign(self, value, wait: bool = False) -> None: self[""].assign(value, wait) def ping(self): self._backend.ping_run(self._uuid) def start(self): atexit.register(self._shutdown_hook) self._op_processor.start() self._bg_job.start(self) self._started = True def stop(self, seconds: Optional[Union[float, int]] = None): verify_type("seconds", seconds, (float, int, type(None))) if not self._started: return self._started = False ts = time.time() self._bg_job.stop() self._bg_job.join(seconds) with self._lock: sec_left = None if seconds is None else seconds - (time.time() - ts) self._op_processor.stop(sec_left) def get_structure(self) -> Dict[str, Any]: return self._structure.get_structure() def print_structure(self) -> None: self._print_structure_impl(self.get_structure(), indent=0) def _print_structure_impl(self, struct: dict, indent: int) -> None: for key in sorted(struct.keys()): click.echo(" " * indent, nl=False) if isinstance(struct[key], dict): click.echo("{blue}'{key}'{end}:".format( blue=UNIX_STYLES['blue'], key=key, end=UNIX_STYLES['end'])) self._print_structure_impl(struct[key], indent=indent+1) else: click.echo("{blue}'{key}'{end}: {type}".format( blue=UNIX_STYLES['blue'], key=key, end=UNIX_STYLES['end'], type=type(struct[key]).__name__)) def define(self, path: str, value: Union[Value, int, float, str, datetime], wait: bool = False ) -> Attribute: if isinstance(value, Value): pass elif is_bool(value): value = Boolean(value) elif is_int(value): value = Integer(value) elif is_float(value): value = Float(value) elif is_string(value): value = String(value) elif isinstance(value, datetime): value = Datetime(value) elif is_float_like(value): value = Float(float(value)) elif is_string_like(value): value = String(str(value)) else: raise TypeError("Value of unsupported type {}".format(type(value))) parsed_path = parse_path(path) with self._lock: old_attr = self._structure.get(parsed_path) if old_attr: raise MetadataInconsistency("Attribute {} is already defined".format(path)) attr = ValueToAttributeVisitor(self, parsed_path).visit(value) attr.assign(value, wait) self._structure.set(parsed_path, attr) return attr def get_attribute(self, path: str) -> Optional[Attribute]: with self._lock: return self._structure.get(parse_path(path)) def set_attribute(self, path: str, attribute: Attribute) -> Optional[Attribute]: with self._lock: return self._structure.set(parse_path(path), attribute) def exists(self, path: str) -> bool: verify_type("path", path, str) return self.get_attribute(path) is not None def pop(self, path: str, wait: bool = False): verify_type("path", path, str) with self._lock: parsed_path = parse_path(path) self._op_processor.enqueue_operation(DeleteAttribute(parsed_path), wait) self._structure.pop(parsed_path) def lock(self) -> threading.RLock: return self._lock def wait(self, disk_only=False): with self._lock: if disk_only: self._op_processor.flush() else: self._op_processor.wait() def sync(self, wait: bool = True): with self._lock: if wait: self._op_processor.wait() attributes = self._backend.get_attributes(self._uuid) self._structure.clear() for attribute in attributes: self._define_attribute(parse_path(attribute.path), attribute.type) def _define_attribute(self, _path: List[str], _type: AttributeType): if _type == AttributeType.FLOAT: self._structure.set(_path, FloatAttr(self, _path)) if _type == AttributeType.STRING: self._structure.set(_path, StringAttr(self, _path)) if _type == AttributeType.DATETIME: self._structure.set(_path, DatetimeAttr(self, _path)) if _type == AttributeType.FILE: self._structure.set(_path, FileAttr(self, _path)) if _type == AttributeType.FILE_SET: self._structure.set(_path, FileSetAttr(self, _path)) if _type == AttributeType.FLOAT_SERIES: self._structure.set(_path, FloatSeriesAttr(self, _path)) if _type == AttributeType.STRING_SERIES: self._structure.set(_path, StringSeriesAttr(self, _path)) if _type == AttributeType.IMAGE_SERIES: self._structure.set(_path, ImageSeriesAttr(self, _path)) if _type == AttributeType.STRING_SET: self._structure.set(_path, StringSetAttr(self, _path)) if _type == AttributeType.GIT_REF: self._structure.set(_path, GitRefAttr(self, _path)) if _type == AttributeType.RUN_STATE: self._structure.set(_path, RunStateAttr(self, _path)) def _shutdown_hook(self): self.stop()
[ "neptune.new.internal.utils.is_float_like", "neptune.new.types.atoms.float.Float", "neptune.new.internal.utils.is_string_like", "neptune.new.internal.utils.is_int", "neptune.new.attributes.atoms.file.File", "neptune.new.attributes.atoms.datetime.Datetime", "neptune.new.types.Boolean", "neptune.new.int...
[((3256, 3273), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (3271, 3273), False, 'import threading\n'), ((3393, 3445), 'traceback.print_exception', 'traceback.print_exception', (['exc_type', 'exc_val', 'exc_tb'], {}), '(exc_type, exc_val, exc_tb)\n', (3418, 3445), False, 'import traceback\n'), ((3533, 3552), 'neptune.new.handler.Handler', 'Handler', (['self', 'path'], {}), '(self, path)\n', (3540, 3552), False, 'from neptune.new.handler import Handler\n'), ((3904, 3940), 'atexit.register', 'atexit.register', (['self._shutdown_hook'], {}), '(self._shutdown_hook)\n', (3919, 3940), False, 'import atexit\n'), ((4262, 4273), 'time.time', 'time.time', ([], {}), '()\n', (4271, 4273), False, 'import time\n'), ((6236, 6252), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['path'], {}), '(path)\n', (6246, 6252), False, 'from neptune.new.internal.utils.paths import parse_path\n'), ((7014, 7044), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""path"""', 'path', 'str'], {}), "('path', path, str)\n", (7025, 7044), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n'), ((7156, 7186), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""path"""', 'path', 'str'], {}), "('path', path, str)\n", (7167, 7186), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n'), ((4818, 4855), 'click.echo', 'click.echo', (["(' ' * indent)"], {'nl': '(False)'}), "(' ' * indent, nl=False)\n", (4828, 4855), False, 'import click\n'), ((5650, 5664), 'neptune.new.internal.utils.is_bool', 'is_bool', (['value'], {}), '(value)\n', (5657, 5664), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n'), ((7238, 7254), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['path'], {}), '(path)\n', (7248, 7254), False, 'from neptune.new.internal.utils.paths import parse_path\n'), ((5686, 5700), 'neptune.new.types.Boolean', 'Boolean', (['value'], {}), '(value)\n', (5693, 5700), False, 'from neptune.new.types import Boolean, Integer\n'), ((5714, 5727), 'neptune.new.internal.utils.is_int', 'is_int', (['value'], {}), '(value)\n', (5720, 5727), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n'), ((6767, 6783), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['path'], {}), '(path)\n', (6777, 6783), False, 'from neptune.new.internal.utils.paths import parse_path\n'), ((6935, 6951), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['path'], {}), '(path)\n', (6945, 6951), False, 'from neptune.new.internal.utils.paths import parse_path\n'), ((7304, 7332), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (['parsed_path'], {}), '(parsed_path)\n', (7319, 7332), False, 'from neptune.new.internal.operation import DeleteAttribute\n'), ((8151, 8173), 'neptune.new.attributes.atoms.float.Float', 'FloatAttr', (['self', '_path'], {}), '(self, _path)\n', (8160, 8173), True, 'from neptune.new.attributes.atoms.float import Float as FloatAttr\n'), ((8256, 8279), 'neptune.new.attributes.atoms.string.String', 'StringAttr', (['self', '_path'], {}), '(self, _path)\n', (8266, 8279), True, 'from neptune.new.attributes.atoms.string import String as StringAttr\n'), ((8364, 8389), 'neptune.new.attributes.atoms.datetime.Datetime', 'DatetimeAttr', (['self', '_path'], {}), '(self, _path)\n', (8376, 8389), True, 'from neptune.new.attributes.atoms.datetime import Datetime as DatetimeAttr\n'), ((8470, 8491), 'neptune.new.attributes.atoms.file.File', 'FileAttr', (['self', '_path'], {}), '(self, _path)\n', (8478, 8491), True, 'from neptune.new.attributes.atoms.file import File as FileAttr\n'), ((8576, 8600), 'neptune.new.attributes.file_set.FileSet', 'FileSetAttr', (['self', '_path'], {}), '(self, _path)\n', (8587, 8600), True, 'from neptune.new.attributes.file_set import FileSet as FileSetAttr\n'), ((8689, 8717), 'neptune.new.attributes.series.float_series.FloatSeries', 'FloatSeriesAttr', (['self', '_path'], {}), '(self, _path)\n', (8704, 8717), True, 'from neptune.new.attributes.series.float_series import FloatSeries as FloatSeriesAttr\n'), ((8807, 8836), 'neptune.new.attributes.series.string_series.StringSeries', 'StringSeriesAttr', (['self', '_path'], {}), '(self, _path)\n', (8823, 8836), True, 'from neptune.new.attributes.series.string_series import StringSeries as StringSeriesAttr\n'), ((8925, 8953), 'neptune.new.attributes.series.file_series.FileSeries', 'ImageSeriesAttr', (['self', '_path'], {}), '(self, _path)\n', (8940, 8953), True, 'from neptune.new.attributes.series.file_series import FileSeries as ImageSeriesAttr\n'), ((9040, 9066), 'neptune.new.attributes.sets.string_set.StringSet', 'StringSetAttr', (['self', '_path'], {}), '(self, _path)\n', (9053, 9066), True, 'from neptune.new.attributes.sets.string_set import StringSet as StringSetAttr\n'), ((9150, 9173), 'neptune.new.attributes.atoms.git_ref.GitRef', 'GitRefAttr', (['self', '_path'], {}), '(self, _path)\n', (9160, 9173), True, 'from neptune.new.attributes.atoms.git_ref import GitRef as GitRefAttr\n'), ((9259, 9284), 'neptune.new.attributes.atoms.run_state.RunState', 'RunStateAttr', (['self', '_path'], {}), '(self, _path)\n', (9271, 9284), True, 'from neptune.new.attributes.atoms.run_state import RunState as RunStateAttr\n'), ((5749, 5763), 'neptune.new.types.Integer', 'Integer', (['value'], {}), '(value)\n', (5756, 5763), False, 'from neptune.new.types import Boolean, Integer\n'), ((5777, 5792), 'neptune.new.internal.utils.is_float', 'is_float', (['value'], {}), '(value)\n', (5785, 5792), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n'), ((6471, 6513), 'neptune.new.internal.value_to_attribute_visitor.ValueToAttributeVisitor', 'ValueToAttributeVisitor', (['self', 'parsed_path'], {}), '(self, parsed_path)\n', (6494, 6513), False, 'from neptune.new.internal.value_to_attribute_visitor import ValueToAttributeVisitor\n'), ((7953, 7979), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['attribute.path'], {}), '(attribute.path)\n', (7963, 7979), False, 'from neptune.new.internal.utils.paths import parse_path\n'), ((4425, 4436), 'time.time', 'time.time', ([], {}), '()\n', (4434, 4436), False, 'import time\n'), ((5814, 5826), 'neptune.new.types.atoms.float.Float', 'Float', (['value'], {}), '(value)\n', (5819, 5826), False, 'from neptune.new.types.atoms.float import Float\n'), ((5840, 5856), 'neptune.new.internal.utils.is_string', 'is_string', (['value'], {}), '(value)\n', (5849, 5856), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n'), ((5878, 5891), 'neptune.new.types.atoms.string.String', 'String', (['value'], {}), '(value)\n', (5884, 5891), False, 'from neptune.new.types.atoms.string import String\n'), ((5954, 5969), 'neptune.new.types.atoms.datetime.Datetime', 'Datetime', (['value'], {}), '(value)\n', (5962, 5969), False, 'from neptune.new.types.atoms.datetime import Datetime\n'), ((5983, 6003), 'neptune.new.internal.utils.is_float_like', 'is_float_like', (['value'], {}), '(value)\n', (5996, 6003), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n'), ((6058, 6079), 'neptune.new.internal.utils.is_string_like', 'is_string_like', (['value'], {}), '(value)\n', (6072, 6079), False, 'from neptune.new.internal.utils import is_bool, is_int, verify_type, is_float, is_string, is_float_like, is_string_like\n')]
import neptune from config import EnvConfig import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import pickle comet_cfg = EnvConfig() session = neptune.Session(api_token=comet_cfg.neptune_token) project = session.get_project(project_qualified_name=comet_cfg.neptune_project_name) experiments = project.get_experiments(state='succeeded') print(experiments) #params = [] #lyap_inter = [] lyap_intra_large = [] #neg_intra = [] for exp in experiments: print(exp.id) # properties = exp.get_properties() # # model_update = properties['target_model_update'] # mem_len = properties['memory_limit'] # alpha = properties['learning_rate'] # lyap_inter.append(exp.get_numeric_channels_values('lyap_exp_inter_ins_0','lyap_exp_inter_ins_1','lyap_exp_inter_ins_2').to_numpy()[0][1:]) lyap_intra = exp.get_numeric_channels_values('lyap_exp_intra_ins_0','lyap_exp_intra_ins_1','lyap_exp_intra_ins_2').to_numpy()[:,1:] # neg_intra.append(sum(sum(lyap_intra<0))/600) lyap_intra_large.append(lyap_intra) # print(lyap) # params.append([model_update, mem_len, alpha]) #params = np.array(params).astype(np.float) #lyap_inter = np.min(np.array(lyap_inter).astype(np.float), axis=1) #lyap_intra = np.array(lyap_intra).astype(np.float) with open('dumps/lyap_intra.p','wb') as f: pickle.dump(lyap_intra_large,f)
[ "neptune.Session" ]
[((182, 193), 'config.EnvConfig', 'EnvConfig', ([], {}), '()\n', (191, 193), False, 'from config import EnvConfig\n'), ((204, 254), 'neptune.Session', 'neptune.Session', ([], {'api_token': 'comet_cfg.neptune_token'}), '(api_token=comet_cfg.neptune_token)\n', (219, 254), False, 'import neptune\n'), ((1362, 1394), 'pickle.dump', 'pickle.dump', (['lyap_intra_large', 'f'], {}), '(lyap_intra_large, f)\n', (1373, 1394), False, 'import pickle\n')]
# importing neptune import neptune # File data version from neptunecontrib.versioning.data import log_data_version # File Loader from data_loader import data_loader # Hyperparameter Tuner from hyperparameter_optimizer import create_objective # Model from model.lightgbm_0.model import learning # set UserName/ExperimentName neptune.init('toroi/HousePrice') # set Train/Test file path TRAIN_FILEPATH = '/data/train.csv' TEST_FILEPATH = '/data/test.csv' TARGET_LIST = ["SalePrice"] with neptune.create_experiment(): log_data_version(TRAIN_FILEPATH) log_data_version(TEST_FILEPATH) training_data, training_target = data_loader(TRAIN_FILEPATH, TARGET_LIST) test_data, _ = data_loader(TEST_FILEPATH) neptune.create_experiment('HousePrice') neptune_callback = optuna_utils.NeptuneCallback() objective = lambda trial : create_objective(trial, learning, training_data, training_target, metric, validation_size=0.25) study = optuna.create_study(direction='maximize') study.optimize(objective, n_trials=100, callbacks=[neptune_callback]) optuna_utils.log_study(study)
[ "neptune.create_experiment", "neptune.init" ]
[((325, 357), 'neptune.init', 'neptune.init', (['"""toroi/HousePrice"""'], {}), "('toroi/HousePrice')\n", (337, 357), False, 'import neptune\n'), ((623, 663), 'data_loader.data_loader', 'data_loader', (['TRAIN_FILEPATH', 'TARGET_LIST'], {}), '(TRAIN_FILEPATH, TARGET_LIST)\n', (634, 663), False, 'from data_loader import data_loader\n'), ((679, 705), 'data_loader.data_loader', 'data_loader', (['TEST_FILEPATH'], {}), '(TEST_FILEPATH)\n', (690, 705), False, 'from data_loader import data_loader\n'), ((707, 746), 'neptune.create_experiment', 'neptune.create_experiment', (['"""HousePrice"""'], {}), "('HousePrice')\n", (732, 746), False, 'import neptune\n'), ((487, 514), 'neptune.create_experiment', 'neptune.create_experiment', ([], {}), '()\n', (512, 514), False, 'import neptune\n'), ((520, 552), 'neptunecontrib.versioning.data.log_data_version', 'log_data_version', (['TRAIN_FILEPATH'], {}), '(TRAIN_FILEPATH)\n', (536, 552), False, 'from neptunecontrib.versioning.data import log_data_version\n'), ((557, 588), 'neptunecontrib.versioning.data.log_data_version', 'log_data_version', (['TEST_FILEPATH'], {}), '(TEST_FILEPATH)\n', (573, 588), False, 'from neptunecontrib.versioning.data import log_data_version\n'), ((825, 924), 'hyperparameter_optimizer.create_objective', 'create_objective', (['trial', 'learning', 'training_data', 'training_target', 'metric'], {'validation_size': '(0.25)'}), '(trial, learning, training_data, training_target, metric,\n validation_size=0.25)\n', (841, 924), False, 'from hyperparameter_optimizer import create_objective\n')]
from functools import partial import os from datetime import datetime, timedelta import numpy as np import torch from PIL import Image import neptune from torch.autograd import Variable from torch.optim.lr_scheduler import ExponentialLR from tempfile import TemporaryDirectory from steppy.base import Step, IdentityOperation from steppy.adapter import Adapter, E from toolkit.pytorch_transformers.utils import Averager, persist_torch_model from toolkit.pytorch_transformers.validation import score_model from .utils import get_logger, sigmoid, softmax, make_apply_transformer, read_masks, get_list_of_image_predictions from .metrics import intersection_over_union, intersection_over_union_thresholds from .postprocessing import crop_image, resize_image, binarize logger = get_logger() Y_COLUMN = 'file_path_mask' ORIGINAL_SIZE = (101, 101) THRESHOLD = 0.5 class Callback: def __init__(self): self.epoch_id = None self.batch_id = None self.model = None self.optimizer = None self.loss_function = None self.output_names = None self.validation_datagen = None self.lr_scheduler = None def set_params(self, transformer, validation_datagen, *args, **kwargs): self.model = transformer.model self.optimizer = transformer.optimizer self.loss_function = transformer.loss_function self.output_names = transformer.output_names self.validation_datagen = validation_datagen self.transformer = transformer def on_train_begin(self, *args, **kwargs): self.epoch_id = 0 self.batch_id = 0 def on_train_end(self, *args, **kwargs): pass def on_epoch_begin(self, *args, **kwargs): pass def on_epoch_end(self, *args, **kwargs): self.epoch_id += 1 def training_break(self, *args, **kwargs): return False def on_batch_begin(self, *args, **kwargs): pass def on_batch_end(self, *args, **kwargs): self.batch_id += 1 def get_validation_loss(self): if self.epoch_id not in self.transformer.validation_loss.keys(): self.transformer.validation_loss[self.epoch_id] = score_model(self.model, self.loss_function, self.validation_datagen) return self.transformer.validation_loss[self.epoch_id] class CallbackList: def __init__(self, callbacks=None): if callbacks is None: self.callbacks = [] elif isinstance(callbacks, Callback): self.callbacks = [callbacks] else: self.callbacks = callbacks def __len__(self): return len(self.callbacks) def set_params(self, *args, **kwargs): for callback in self.callbacks: callback.set_params(*args, **kwargs) def on_train_begin(self, *args, **kwargs): for callback in self.callbacks: callback.on_train_begin(*args, **kwargs) def on_train_end(self, *args, **kwargs): for callback in self.callbacks: callback.on_train_end(*args, **kwargs) def on_epoch_begin(self, *args, **kwargs): for callback in self.callbacks: callback.on_epoch_begin(*args, **kwargs) def on_epoch_end(self, *args, **kwargs): for callback in self.callbacks: callback.on_epoch_end(*args, **kwargs) def training_break(self, *args, **kwargs): callback_out = [callback.training_break(*args, **kwargs) for callback in self.callbacks] return any(callback_out) def on_batch_begin(self, *args, **kwargs): for callback in self.callbacks: callback.on_batch_begin(*args, **kwargs) def on_batch_end(self, *args, **kwargs): for callback in self.callbacks: callback.on_batch_end(*args, **kwargs) class TrainingMonitor(Callback): def __init__(self, epoch_every=None, batch_every=None): super().__init__() self.epoch_loss_averagers = {} if epoch_every == 0: self.epoch_every = False else: self.epoch_every = epoch_every if batch_every == 0: self.batch_every = False else: self.batch_every = batch_every def on_train_begin(self, *args, **kwargs): self.epoch_loss_averagers = {} self.epoch_id = 0 self.batch_id = 0 def on_epoch_end(self, *args, **kwargs): for name, averager in self.epoch_loss_averagers.items(): epoch_avg_loss = averager.value averager.reset() if self.epoch_every and ((self.epoch_id % self.epoch_every) == 0): logger.info('epoch {0} {1}: {2:.5f}'.format(self.epoch_id, name, epoch_avg_loss)) self.epoch_id += 1 def on_batch_end(self, metrics, *args, **kwargs): for name, loss in metrics.items(): loss = loss.data.cpu().numpy()[0] if name in self.epoch_loss_averagers.keys(): self.epoch_loss_averagers[name].send(loss) else: self.epoch_loss_averagers[name] = Averager() self.epoch_loss_averagers[name].send(loss) if self.batch_every and ((self.batch_id % self.batch_every) == 0): logger.info('epoch {0} batch {1} {2}: {3:.5f}'.format(self.epoch_id, self.batch_id, name, loss)) self.batch_id += 1 class ExponentialLRScheduler(Callback): def __init__(self, gamma, epoch_every=1, batch_every=None): super().__init__() self.gamma = gamma if epoch_every == 0: self.epoch_every = False else: self.epoch_every = epoch_every if batch_every == 0: self.batch_every = False else: self.batch_every = batch_every def set_params(self, transformer, validation_datagen, *args, **kwargs): self.validation_datagen = validation_datagen self.model = transformer.model self.optimizer = transformer.optimizer self.loss_function = transformer.loss_function self.lr_scheduler = ExponentialLR(self.optimizer, self.gamma, last_epoch=-1) def on_train_begin(self, *args, **kwargs): self.epoch_id = 0 self.batch_id = 0 logger.info('initial lr: {0}'.format(self.optimizer.state_dict()['param_groups'][0]['initial_lr'])) def on_epoch_end(self, *args, **kwargs): if self.epoch_every and (((self.epoch_id + 1) % self.epoch_every) == 0): self.lr_scheduler.step() logger.info('epoch {0} current lr: {1}'.format(self.epoch_id + 1, self.optimizer.state_dict()['param_groups'][0]['lr'])) self.epoch_id += 1 def on_batch_end(self, *args, **kwargs): if self.batch_every and ((self.batch_id % self.batch_every) == 0): self.lr_scheduler.step() logger.info('epoch {0} batch {1} current lr: {2}'.format( self.epoch_id + 1, self.batch_id + 1, self.optimizer.state_dict()['param_groups'][0]['lr'])) self.batch_id += 1 class ExperimentTiming(Callback): def __init__(self, epoch_every=None, batch_every=None): super().__init__() if epoch_every == 0: self.epoch_every = False else: self.epoch_every = epoch_every if batch_every == 0: self.batch_every = False else: self.batch_every = batch_every self.batch_start = None self.epoch_start = None self.current_sum = None self.current_mean = None def on_train_begin(self, *args, **kwargs): self.epoch_id = 0 self.batch_id = 0 logger.info('starting training...') def on_train_end(self, *args, **kwargs): logger.info('training finished') def on_epoch_begin(self, *args, **kwargs): if self.epoch_id > 0: epoch_time = datetime.now() - self.epoch_start if self.epoch_every: if (self.epoch_id % self.epoch_every) == 0: logger.info('epoch {0} time {1}'.format(self.epoch_id - 1, str(epoch_time)[:-7])) self.epoch_start = datetime.now() self.current_sum = timedelta() self.current_mean = timedelta() logger.info('epoch {0} ...'.format(self.epoch_id)) def on_batch_begin(self, *args, **kwargs): if self.batch_id > 0: current_delta = datetime.now() - self.batch_start self.current_sum += current_delta self.current_mean = self.current_sum / self.batch_id if self.batch_every: if self.batch_id > 0 and (((self.batch_id - 1) % self.batch_every) == 0): logger.info('epoch {0} average batch time: {1}'.format(self.epoch_id, str(self.current_mean)[:-5])) if self.batch_every: if self.batch_id == 0 or self.batch_id % self.batch_every == 0: logger.info('epoch {0} batch {1} ...'.format(self.epoch_id, self.batch_id)) self.batch_start = datetime.now() class NeptuneMonitor(Callback): def __init__(self, image_nr, image_resize, model_name): super().__init__() self.model_name = model_name self.ctx = neptune.Context() self.epoch_loss_averager = Averager() self.image_nr = image_nr self.image_resize = image_resize def on_train_begin(self, *args, **kwargs): self.epoch_loss_averagers = {} self.epoch_id = 0 self.batch_id = 0 def on_batch_end(self, metrics, *args, **kwargs): for name, loss in metrics.items(): loss = loss.data.cpu().numpy()[0] if name in self.epoch_loss_averagers.keys(): self.epoch_loss_averagers[name].send(loss) else: self.epoch_loss_averagers[name] = Averager() self.epoch_loss_averagers[name].send(loss) self.ctx.channel_send('{} batch {} loss'.format(self.model_name, name), x=self.batch_id, y=loss) self.batch_id += 1 def on_epoch_end(self, *args, **kwargs): self._send_numeric_channels() self.epoch_id += 1 def _send_numeric_channels(self, *args, **kwargs): for name, averager in self.epoch_loss_averagers.items(): epoch_avg_loss = averager.value averager.reset() self.ctx.channel_send('{} epoch {} loss'.format(self.model_name, name), x=self.epoch_id, y=epoch_avg_loss) self.model.eval() val_loss = self.get_validation_loss() self.model.train() for name, loss in val_loss.items(): loss = loss.data.cpu().numpy()[0] self.ctx.channel_send('{} epoch_val {} loss'.format(self.model_name, name), x=self.epoch_id, y=loss) class ValidationMonitor(Callback): def __init__(self, data_dir, loader_mode, epoch_every=None, batch_every=None): super().__init__() if epoch_every == 0: self.epoch_every = False else: self.epoch_every = epoch_every if batch_every == 0: self.batch_every = False else: self.batch_every = batch_every self.data_dir = data_dir self.validation_pipeline = postprocessing_pipeline_simplified self.loader_mode = loader_mode self.meta_valid = None self.y_true = None self.activation_func = None def set_params(self, transformer, validation_datagen, meta_valid=None, *args, **kwargs): self.model = transformer.model self.optimizer = transformer.optimizer self.loss_function = transformer.loss_function self.output_names = transformer.output_names self.validation_datagen = validation_datagen self.meta_valid = meta_valid self.y_true = read_masks(self.meta_valid[Y_COLUMN].values) self.activation_func = transformer.activation_func self.transformer = transformer def get_validation_loss(self): return self._get_validation_loss() def on_epoch_end(self, *args, **kwargs): if self.epoch_every and ((self.epoch_id % self.epoch_every) == 0): self.model.eval() val_loss = self.get_validation_loss() self.model.train() for name, loss in val_loss.items(): loss = loss.data.cpu().numpy()[0] logger.info('epoch {0} validation {1}: {2:.5f}'.format(self.epoch_id, name, loss)) self.epoch_id += 1 def _get_validation_loss(self): output, epoch_loss = self._transform() y_pred = self._generate_prediction(output) logger.info('Calculating IOU and IOUT Scores') iou_score = intersection_over_union(self.y_true, y_pred) iout_score = intersection_over_union_thresholds(self.y_true, y_pred) logger.info('IOU score on validation is {}'.format(iou_score)) logger.info('IOUT score on validation is {}'.format(iout_score)) if not self.transformer.validation_loss: self.transformer.validation_loss = {} self.transformer.validation_loss.setdefault(self.epoch_id, {'sum': epoch_loss, 'iou': Variable(torch.Tensor([iou_score])), 'iout': Variable(torch.Tensor([iout_score]))}) return self.transformer.validation_loss[self.epoch_id] def _transform(self): self.model.eval() batch_gen, steps = self.validation_datagen partial_batch_losses = [] outputs = {} for batch_id, data in enumerate(batch_gen): X = data[0] targets_tensors = data[1:] if torch.cuda.is_available(): X = Variable(X, volatile=True).cuda() targets_var = [] for target_tensor in targets_tensors: targets_var.append(Variable(target_tensor, volatile=True).cuda()) else: X = Variable(X, volatile=True) targets_var = [] for target_tensor in targets_tensors: targets_var.append(Variable(target_tensor, volatile=True)) outputs_batch = self.model(X) if len(self.output_names) == 1: for (name, loss_function_one, weight), target in zip(self.loss_function, targets_var): loss_sum = loss_function_one(outputs_batch, target) * weight outputs.setdefault(self.output_names[0], []).append(outputs_batch.data.cpu().numpy()) else: batch_losses = [] for (name, loss_function_one, weight), output, target in zip(self.loss_function, outputs_batch, targets_var): loss = loss_function_one(output, target) * weight batch_losses.append(loss) partial_batch_losses.setdefault(name, []).append(loss) output_ = output.data.cpu().numpy() outputs.setdefault(name, []).append(output_) loss_sum = sum(batch_losses) partial_batch_losses.append(loss_sum) if batch_id == steps: break self.model.train() average_losses = sum(partial_batch_losses) / steps outputs = {'{}_prediction'.format(name): get_list_of_image_predictions(outputs_) for name, outputs_ in outputs.items()} for name, prediction in outputs.items(): if self.activation_func == 'softmax': outputs[name] = [softmax(single_prediction, axis=0) for single_prediction in prediction] elif self.activation_func == 'sigmoid': outputs[name] = [sigmoid(np.squeeze(mask)) for mask in prediction] else: raise Exception('Only softmax and sigmoid activations are allowed') return outputs, average_losses def _generate_prediction(self, outputs): data = {'callback_input': {'meta': self.meta_valid, 'meta_valid': None, }, 'unet_output': {**outputs} } with TemporaryDirectory() as cache_dirpath: pipeline = self.validation_pipeline(cache_dirpath, self.loader_mode) output = pipeline.transform(data) y_pred = output['y_pred'] return y_pred class ModelCheckpoint(Callback): def __init__(self, filepath, metric_name='sum', epoch_every=1, minimize=True): self.filepath = filepath self.minimize = minimize self.best_score = None if epoch_every == 0: self.epoch_every = False else: self.epoch_every = epoch_every self.metric_name = metric_name def on_train_begin(self, *args, **kwargs): self.epoch_id = 0 self.batch_id = 0 os.makedirs(os.path.dirname(self.filepath), exist_ok=True) def on_epoch_end(self, *args, **kwargs): if self.epoch_every and ((self.epoch_id % self.epoch_every) == 0): self.model.eval() val_loss = self.get_validation_loss() loss_sum = val_loss[self.metric_name] loss_sum = loss_sum.data.cpu().numpy()[0] self.model.train() if self.best_score is None: self.best_score = loss_sum if (self.minimize and loss_sum < self.best_score) or (not self.minimize and loss_sum > self.best_score) or ( self.epoch_id == 0): self.best_score = loss_sum persist_torch_model(self.model, self.filepath) logger.info('epoch {0} model saved to {1}'.format(self.epoch_id, self.filepath)) self.epoch_id += 1 class EarlyStopping(Callback): def __init__(self, metric_name='sum', patience=1000, minimize=True): super().__init__() self.patience = patience self.minimize = minimize self.best_score = None self.epoch_since_best = 0 self._training_break = False self.metric_name = metric_name def training_break(self, *args, **kwargs): return self._training_break def on_epoch_end(self, *args, **kwargs): self.model.eval() val_loss = self.get_validation_loss() loss_sum = val_loss[self.metric_name] loss_sum = loss_sum.data.cpu().numpy()[0] self.model.train() if not self.best_score: self.best_score = loss_sum if (self.minimize and loss_sum < self.best_score) or (not self.minimize and loss_sum > self.best_score): self.best_score = loss_sum self.epoch_since_best = 0 else: self.epoch_since_best += 1 if self.epoch_since_best > self.patience: self._training_break = True self.epoch_id += 1 def postprocessing_pipeline_simplified(cache_dirpath, loader_mode): if loader_mode == 'resize_and_pad': size_adjustment_function = partial(crop_image, target_size=ORIGINAL_SIZE) elif loader_mode == 'resize': size_adjustment_function = partial(resize_image, target_size=ORIGINAL_SIZE) else: raise NotImplementedError mask_resize = Step(name='mask_resize', transformer=make_apply_transformer(size_adjustment_function, output_name='resized_images', apply_on=['images']), input_data=['unet_output'], adapter=Adapter({'images': E('unet_output', 'mask_prediction'), }), experiment_directory=cache_dirpath) binarizer = Step(name='binarizer', transformer=make_apply_transformer( partial(binarize, threshold=THRESHOLD), output_name='binarized_images', apply_on=['images']), input_steps=[mask_resize], adapter=Adapter({'images': E(mask_resize.name, 'resized_images'), }), experiment_directory=cache_dirpath) output = Step(name='output', transformer=IdentityOperation(), input_steps=[binarizer], adapter=Adapter({'y_pred': E(binarizer.name, 'binarized_images'), }), experiment_directory=cache_dirpath) return output
[ "neptune.Context" ]
[((6126, 6182), 'torch.optim.lr_scheduler.ExponentialLR', 'ExponentialLR', (['self.optimizer', 'self.gamma'], {'last_epoch': '(-1)'}), '(self.optimizer, self.gamma, last_epoch=-1)\n', (6139, 6182), False, 'from torch.optim.lr_scheduler import ExponentialLR\n'), ((8226, 8240), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8238, 8240), False, 'from datetime import datetime, timedelta\n'), ((8268, 8279), 'datetime.timedelta', 'timedelta', ([], {}), '()\n', (8277, 8279), False, 'from datetime import datetime, timedelta\n'), ((8308, 8319), 'datetime.timedelta', 'timedelta', ([], {}), '()\n', (8317, 8319), False, 'from datetime import datetime, timedelta\n'), ((9085, 9099), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (9097, 9099), False, 'from datetime import datetime, timedelta\n'), ((9277, 9294), 'neptune.Context', 'neptune.Context', ([], {}), '()\n', (9292, 9294), False, 'import neptune\n'), ((9330, 9340), 'toolkit.pytorch_transformers.utils.Averager', 'Averager', ([], {}), '()\n', (9338, 9340), False, 'from toolkit.pytorch_transformers.utils import Averager, persist_torch_model\n'), ((19165, 19211), 'functools.partial', 'partial', (['crop_image'], {'target_size': 'ORIGINAL_SIZE'}), '(crop_image, target_size=ORIGINAL_SIZE)\n', (19172, 19211), False, 'from functools import partial\n'), ((2187, 2255), 'toolkit.pytorch_transformers.validation.score_model', 'score_model', (['self.model', 'self.loss_function', 'self.validation_datagen'], {}), '(self.model, self.loss_function, self.validation_datagen)\n', (2198, 2255), False, 'from toolkit.pytorch_transformers.validation import score_model\n'), ((13774, 13799), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (13797, 13799), False, 'import torch\n'), ((16337, 16357), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (16355, 16357), False, 'from tempfile import TemporaryDirectory\n'), ((17058, 17088), 'os.path.dirname', 'os.path.dirname', (['self.filepath'], {}), '(self.filepath)\n', (17073, 17088), False, 'import os\n'), ((19281, 19329), 'functools.partial', 'partial', (['resize_image'], {'target_size': 'ORIGINAL_SIZE'}), '(resize_image, target_size=ORIGINAL_SIZE)\n', (19288, 19329), False, 'from functools import partial\n'), ((20475, 20494), 'steppy.base.IdentityOperation', 'IdentityOperation', ([], {}), '()\n', (20492, 20494), False, 'from steppy.base import Step, IdentityOperation\n'), ((5127, 5137), 'toolkit.pytorch_transformers.utils.Averager', 'Averager', ([], {}), '()\n', (5135, 5137), False, 'from toolkit.pytorch_transformers.utils import Averager, persist_torch_model\n'), ((7970, 7984), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (7982, 7984), False, 'from datetime import datetime, timedelta\n'), ((8485, 8499), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8497, 8499), False, 'from datetime import datetime, timedelta\n'), ((9883, 9893), 'toolkit.pytorch_transformers.utils.Averager', 'Averager', ([], {}), '()\n', (9891, 9893), False, 'from toolkit.pytorch_transformers.utils import Averager, persist_torch_model\n'), ((14066, 14092), 'torch.autograd.Variable', 'Variable', (['X'], {'volatile': '(True)'}), '(X, volatile=True)\n', (14074, 14092), False, 'from torch.autograd import Variable\n'), ((17748, 17794), 'toolkit.pytorch_transformers.utils.persist_torch_model', 'persist_torch_model', (['self.model', 'self.filepath'], {}), '(self.model, self.filepath)\n', (17767, 17794), False, 'from toolkit.pytorch_transformers.utils import Averager, persist_torch_model\n'), ((20033, 20071), 'functools.partial', 'partial', (['binarize'], {'threshold': 'THRESHOLD'}), '(binarize, threshold=THRESHOLD)\n', (20040, 20071), False, 'from functools import partial\n'), ((13278, 13303), 'torch.Tensor', 'torch.Tensor', (['[iou_score]'], {}), '([iou_score])\n', (13290, 13303), False, 'import torch\n'), ((13391, 13417), 'torch.Tensor', 'torch.Tensor', (['[iout_score]'], {}), '([iout_score])\n', (13403, 13417), False, 'import torch\n'), ((19771, 19806), 'steppy.adapter.E', 'E', (['"""unet_output"""', '"""mask_prediction"""'], {}), "('unet_output', 'mask_prediction')\n", (19772, 19806), False, 'from steppy.adapter import Adapter, E\n'), ((20273, 20310), 'steppy.adapter.E', 'E', (['mask_resize.name', '"""resized_images"""'], {}), "(mask_resize.name, 'resized_images')\n", (20274, 20310), False, 'from steppy.adapter import Adapter, E\n'), ((20584, 20621), 'steppy.adapter.E', 'E', (['binarizer.name', '"""binarized_images"""'], {}), "(binarizer.name, 'binarized_images')\n", (20585, 20621), False, 'from steppy.adapter import Adapter, E\n'), ((13821, 13847), 'torch.autograd.Variable', 'Variable', (['X'], {'volatile': '(True)'}), '(X, volatile=True)\n', (13829, 13847), False, 'from torch.autograd import Variable\n'), ((14219, 14257), 'torch.autograd.Variable', 'Variable', (['target_tensor'], {'volatile': '(True)'}), '(target_tensor, volatile=True)\n', (14227, 14257), False, 'from torch.autograd import Variable\n'), ((15880, 15896), 'numpy.squeeze', 'np.squeeze', (['mask'], {}), '(mask)\n', (15890, 15896), True, 'import numpy as np\n'), ((13981, 14019), 'torch.autograd.Variable', 'Variable', (['target_tensor'], {'volatile': '(True)'}), '(target_tensor, volatile=True)\n', (13989, 14019), False, 'from torch.autograd import Variable\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from faker import Faker import boto3 import pytest from neptune.management.internal.utils import normalize_project_name from neptune.management import create_project, add_project_member import neptune.new as neptune from e2e_tests.utils import a_project_name, Environment fake = Faker() @pytest.fixture(scope="session") def environment(): workspace = os.getenv("WORKSPACE_NAME") admin_token = os.getenv("ADMIN_NEPTUNE_API_TOKEN") user = os.getenv("USER_USERNAME") project_name, project_key = a_project_name(project_slug=fake.slug()) project_identifier = normalize_project_name(name=project_name, workspace=workspace) created_project_identifier = create_project( name=project_name, key=project_key, visibility="priv", workspace=workspace, api_token=admin_token, ) add_project_member( name=created_project_identifier, username=user, # pylint: disable=no-member role="contributor", api_token=admin_token, ) yield Environment( workspace=workspace, project=project_identifier, user_token=os.getenv("NEPTUNE_API_TOKEN"), admin_token=admin_token, admin=os.getenv("ADMIN_USERNAME"), user=user, ) @pytest.fixture(scope="session") def container(request, environment): if request.param == "project": project = neptune.init_project(name=environment.project) yield project project.stop() if request.param == "run": exp = neptune.init_run(project=environment.project) yield exp exp.stop() @pytest.fixture(scope="session") def bucket(environment): bucket_name = os.environ.get("BUCKET_NAME") s3_client = boto3.resource("s3") s3_bucket = s3_client.Bucket(bucket_name) yield bucket_name, s3_client s3_bucket.objects.filter(Prefix=environment.project).delete()
[ "neptune.new.init_project", "neptune.management.create_project", "neptune.management.add_project_member", "neptune.management.internal.utils.normalize_project_name", "neptune.new.init_run" ]
[((889, 896), 'faker.Faker', 'Faker', ([], {}), '()\n', (894, 896), False, 'from faker import Faker\n'), ((900, 931), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (914, 931), False, 'import pytest\n'), ((1878, 1909), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1892, 1909), False, 'import pytest\n'), ((2224, 2255), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (2238, 2255), False, 'import pytest\n'), ((967, 994), 'os.getenv', 'os.getenv', (['"""WORKSPACE_NAME"""'], {}), "('WORKSPACE_NAME')\n", (976, 994), False, 'import os\n'), ((1013, 1049), 'os.getenv', 'os.getenv', (['"""ADMIN_NEPTUNE_API_TOKEN"""'], {}), "('ADMIN_NEPTUNE_API_TOKEN')\n", (1022, 1049), False, 'import os\n'), ((1061, 1087), 'os.getenv', 'os.getenv', (['"""USER_USERNAME"""'], {}), "('USER_USERNAME')\n", (1070, 1087), False, 'import os\n'), ((1187, 1249), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'project_name', 'workspace': 'workspace'}), '(name=project_name, workspace=workspace)\n', (1209, 1249), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((1283, 1400), 'neptune.management.create_project', 'create_project', ([], {'name': 'project_name', 'key': 'project_key', 'visibility': '"""priv"""', 'workspace': 'workspace', 'api_token': 'admin_token'}), "(name=project_name, key=project_key, visibility='priv',\n workspace=workspace, api_token=admin_token)\n", (1297, 1400), False, 'from neptune.management import create_project, add_project_member\n'), ((1449, 1563), 'neptune.management.add_project_member', 'add_project_member', ([], {'name': 'created_project_identifier', 'username': 'user', 'role': '"""contributor"""', 'api_token': 'admin_token'}), "(name=created_project_identifier, username=user, role=\n 'contributor', api_token=admin_token)\n", (1467, 1563), False, 'from neptune.management import create_project, add_project_member\n'), ((2299, 2328), 'os.environ.get', 'os.environ.get', (['"""BUCKET_NAME"""'], {}), "('BUCKET_NAME')\n", (2313, 2328), False, 'import os\n'), ((2346, 2366), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (2360, 2366), False, 'import boto3\n'), ((2000, 2046), 'neptune.new.init_project', 'neptune.init_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2020, 2046), True, 'import neptune.new as neptune\n'), ((2138, 2183), 'neptune.new.init_run', 'neptune.init_run', ([], {'project': 'environment.project'}), '(project=environment.project)\n', (2154, 2183), True, 'import neptune.new as neptune\n'), ((1742, 1772), 'os.getenv', 'os.getenv', (['"""NEPTUNE_API_TOKEN"""'], {}), "('NEPTUNE_API_TOKEN')\n", (1751, 1772), False, 'import os\n'), ((1821, 1848), 'os.getenv', 'os.getenv', (['"""ADMIN_USERNAME"""'], {}), "('ADMIN_USERNAME')\n", (1830, 1848), False, 'import os\n')]
import neptune.new as neptune import os from GTApack.GTA_hotloader import GTA_hotloader from GTApack.GTA_Unet import GTA_Unet from GTApack.GTA_tester import GTA_tester from torchvision import datasets, transforms from torch.optim import SGD, Adam from torch.optim.lr_scheduler import (ReduceLROnPlateau, CyclicLR, CosineAnnealingLR) from torch.utils.data import DataLoader, random_split import torch.nn.functional as F import torch.nn as nn import torch import numpy as np import time from neptune.new.types import File import matplotlib.pyplot as plt device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) # Set up the datasets np.random.seed(42) val_set, train_set = torch.utils.data.random_split( np.random.randint(low = 1, high = 4962, size = 800), [80, 720], generator=torch.Generator().manual_seed(42)) test_val_set = np.random.randint(low = 1, high = 856, size = 200) valload = GTA_hotloader(path = "C:/Users/Marc/Desktop/Billeder/train/", width = 400, height = 300, ind = val_set, device = device) trainload = GTA_hotloader(path = "C:/Users/Marc/Desktop/Billeder/train/", width = 400, height = 300, ind = train_set, device = device) testload = GTA_hotloader(path = "C:/Users/Marc/Desktop/Billeder/test-val/", width = 400, height = 300, ind = test_val_set, device = device) batch_size = 1 # Set up the dataloaders: valloader = torch.utils.data.DataLoader(valload, batch_size=batch_size, shuffle=True, num_workers=0) trainloader = torch.utils.data.DataLoader(trainload, batch_size=batch_size, shuffle=True, num_workers=0) testloader = torch.utils.data.DataLoader(testload, batch_size=batch_size, shuffle=True, num_workers=0) token = os.getenv('Neptune_api') run = neptune.init( project="Deep-Learning-test/Deep-Learning-Test", api_token=token, ) nEpoch = 61 # Network with reduce #params = {"optimizer":"SGD", "optimizer_momentum": 0.9, # "optimizer_learning_rate": 1, "loss_function":"MSEloss", # "model":"GTA_Unet", "scheduler":"ReduceLROnPlateau", # "scheduler_patience":3, "scheduler_threshold":0.01} # #run[f"network_reduce/parameters"] = params # #lossFunc = nn.MSELoss() #model = GTA_Unet(n_channels = 3, n_classes = 9).to(device) # #optimizer = SGD(model.parameters(), lr=1, momentum=0.9) #scheduler = ReduceLROnPlateau(optimizer, 'min', patience=3, threshold=0.01) # #valid_loss, train_loss = [], [] # #avg_train_loss, avg_valid_loss = [], [] # # #for iEpoch in range(nEpoch): # print(f"Training epoch {iEpoch}") # # run[f"network_reduce/learning_rate"].log(optimizer.param_groups[0]['lr']) # # for img, lab in trainloader: # y_pred = model(img) # model.zero_grad() # loss = lossFunc(y_pred, lab) # loss.backward() # optimizer.step() # train_loss.append(loss.item()) # # avg_train_loss.append(w := (np.mean(np.array(train_loss)))) # run[f"network_reduce/train_loss"].log(w) # train_loss = [] # # for img, lab in valloader: # y_pred = model(img) # loss = lossFunc(y_pred, lab) # valid_loss.append(loss.item()) # # avg_valid_loss.append(w := (np.mean(np.array(valid_loss)))) # run[f"network_reduce/validation_loss"].log(w) # # val_acc_per_pic = np.mean(GTA_tester(model, valloader, p = False)) # run[f"network_reduce/validation_mean_acc"].log(val_acc_per_pic) # # scheduler.step(w) # # valid_loss = [] # #torch.save(model.state_dict(), "C:/Users/Marc/Desktop/Billeder/params/thefinaltwo/network_reduce.pt") #run[f"network_reduce/network_weights"].upload(File("C:/Users/Marc/Desktop/Billeder/params/thefinaltwo/network_reduce.pt")) # # #test_acc_per_pic = GTA_tester(model, testloader) # #print(np.mean(test_acc_per_pic)) # #run[f"network_reduce/test_accuracy_per_pic"].log(test_acc_per_pic) #run[f"network_reduce/mean_test_accuracy"].log(np.mean(test_acc_per_pic)) # Network with cycl params = {"optimizer":"SGD", "optimizer_momentum": 0.9, "optimizer_learning_rate": 0.001, "loss_function":"MSEloss", "model":"GTA_Unet", "scheduler":"CyclicLR", "scheduler_base_lr":0.001, "scheduler_max_lr":1.15, "scheduler_step_size_up":10} run[f"network_cycl/parameters"] = params lossFunc = nn.MSELoss() model = GTA_Unet(n_channels = 3, n_classes = 9).to(device) optimizer = SGD(model.parameters(), lr=0.001, momentum=0.9) scheduler = CyclicLR(optimizer, base_lr=0.001, max_lr=1.15, step_size_up=10) valid_loss, train_loss = [], [] avg_train_loss, avg_valid_loss = [], [] for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_cycl/learning_rate"].log(optimizer.param_groups[0]['lr']) for img, lab in trainloader: y_pred = model(img) model.zero_grad() loss = lossFunc(y_pred, lab) loss.backward() optimizer.step() train_loss.append(loss.item()) avg_train_loss.append(w := (np.mean(np.array(train_loss)))) run[f"network_cycl/train_loss"].log(w) train_loss = [] for img, lab in valloader: y_pred = model(img) loss = lossFunc(y_pred, lab) valid_loss.append(loss.item()) val_acc_per_pic = np.mean(GTA_tester(model, valloader, p = False)) run[f"network_cycl/validation_mean_acc"].log(val_acc_per_pic) avg_valid_loss.append(w := (np.mean(np.array(valid_loss)))) run[f"network_cycl/validation_loss"].log(w) valid_loss = [] scheduler.step() torch.save(model.state_dict(), "C:/Users/Marc/Desktop/Billeder/params/thefinaltwo/network_cycl.pt") run[f"network_cycl/network_weights"].upload(File("C:/Users/Marc/Desktop/Billeder/params/thefinaltwo/network_cycl.pt")) test_acc_per_pic = GTA_tester(model, testloader) print(np.mean(test_acc_per_pic)) run[f"network_cycl/test_accuracy_per_pic"].log(test_acc_per_pic) run[f"network_cycl/mean_test_accuracy"].log(np.mean(test_acc_per_pic)) run.stop()
[ "neptune.new.init", "neptune.new.types.File" ]
[((701, 719), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (715, 719), True, 'import numpy as np\n'), ((983, 1027), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(856)', 'size': '(200)'}), '(low=1, high=856, size=200)\n', (1000, 1027), True, 'import numpy as np\n'), ((1047, 1161), 'GTApack.GTA_hotloader.GTA_hotloader', 'GTA_hotloader', ([], {'path': '"""C:/Users/Marc/Desktop/Billeder/train/"""', 'width': '(400)', 'height': '(300)', 'ind': 'val_set', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/Billeder/train/', width=400,\n height=300, ind=val_set, device=device)\n", (1060, 1161), False, 'from GTApack.GTA_hotloader import GTA_hotloader\n'), ((1229, 1345), 'GTApack.GTA_hotloader.GTA_hotloader', 'GTA_hotloader', ([], {'path': '"""C:/Users/Marc/Desktop/Billeder/train/"""', 'width': '(400)', 'height': '(300)', 'ind': 'train_set', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/Billeder/train/', width=400,\n height=300, ind=train_set, device=device)\n", (1242, 1345), False, 'from GTApack.GTA_hotloader import GTA_hotloader\n'), ((1412, 1534), 'GTApack.GTA_hotloader.GTA_hotloader', 'GTA_hotloader', ([], {'path': '"""C:/Users/Marc/Desktop/Billeder/test-val/"""', 'width': '(400)', 'height': '(300)', 'ind': 'test_val_set', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/Billeder/test-val/', width=400,\n height=300, ind=test_val_set, device=device)\n", (1425, 1534), False, 'from GTApack.GTA_hotloader import GTA_hotloader\n'), ((1644, 1736), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['valload'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(valload, batch_size=batch_size, shuffle=True,\n num_workers=0)\n', (1671, 1736), False, 'import torch\n'), ((1874, 1968), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainload'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(trainload, batch_size=batch_size, shuffle=True,\n num_workers=0)\n', (1901, 1968), False, 'import torch\n'), ((2105, 2198), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['testload'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(testload, batch_size=batch_size, shuffle=True,\n num_workers=0)\n', (2132, 2198), False, 'import torch\n'), ((2331, 2355), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (2340, 2355), False, 'import os\n'), ((2363, 2441), 'neptune.new.init', 'neptune.init', ([], {'project': '"""Deep-Learning-test/Deep-Learning-Test"""', 'api_token': 'token'}), "(project='Deep-Learning-test/Deep-Learning-Test', api_token=token)\n", (2375, 2441), True, 'import neptune.new as neptune\n'), ((4873, 4885), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (4883, 4885), True, 'import torch.nn as nn\n'), ((5018, 5082), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.001)', 'max_lr': '(1.15)', 'step_size_up': '(10)'}), '(optimizer, base_lr=0.001, max_lr=1.15, step_size_up=10)\n', (5026, 5082), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau, CyclicLR, CosineAnnealingLR\n'), ((6314, 6343), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'testloader'], {}), '(model, testloader)\n', (6324, 6343), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((802, 847), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(4962)', 'size': '(800)'}), '(low=1, high=4962, size=800)\n', (819, 847), True, 'import numpy as np\n'), ((6219, 6292), 'neptune.new.types.File', 'File', (['"""C:/Users/Marc/Desktop/Billeder/params/thefinaltwo/network_cycl.pt"""'], {}), "('C:/Users/Marc/Desktop/Billeder/params/thefinaltwo/network_cycl.pt')\n", (6223, 6292), False, 'from neptune.new.types import File\n'), ((6350, 6375), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (6357, 6375), True, 'import numpy as np\n'), ((6487, 6512), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (6494, 6512), True, 'import numpy as np\n'), ((625, 650), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (648, 650), False, 'import torch\n'), ((4894, 4929), 'GTApack.GTA_Unet.GTA_Unet', 'GTA_Unet', ([], {'n_channels': '(3)', 'n_classes': '(9)'}), '(n_channels=3, n_classes=9)\n', (4902, 4929), False, 'from GTApack.GTA_Unet import GTA_Unet\n'), ((5811, 5848), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'valloader'], {'p': '(False)'}), '(model, valloader, p=False)\n', (5821, 5848), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((932, 949), 'torch.Generator', 'torch.Generator', ([], {}), '()\n', (947, 949), False, 'import torch\n'), ((5557, 5577), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (5565, 5577), True, 'import numpy as np\n'), ((5959, 5979), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (5967, 5979), True, 'import numpy as np\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __all__ = [ "NeptuneCallback", ] import json import subprocess import warnings from io import BytesIO import matplotlib.pyplot as plt import xgboost as xgb from matplotlib import image from neptune_xgboost import __version__ try: # neptune-client=0.9.0+ package structure import neptune.new as neptune from neptune.new.internal.utils import verify_type from neptune.new.internal.utils.compatibility import expect_not_an_experiment except ImportError: # neptune-client>=1.0.0 package structure import neptune from neptune.internal.utils import verify_type from neptune.internal.utils.compatibility import expect_not_an_experiment INTEGRATION_VERSION_KEY = "source_code/integrations/neptune-xgboost" class NeptuneCallback(xgb.callback.TrainingCallback): """Neptune callback for logging metadata during XGBoost model training. See guide with examples in the `Neptune-XGBoost docs`_. This callback logs metrics, all parameters, learning rate, pickled model, visualizations. If early stopping is activated "best_score" and "best_iteration" is also logged. All metadata are collected under the common namespace that you can specify. See: ``base_namespace`` argument (defaults to "training"). Metrics are logged for every dataset in the ``evals`` list and for every metric specified. For example with ``evals = [(dtrain, "train"), (dval, "valid")]`` and ``"eval_metric": ["mae", "rmse"]``, 4 metrics are created:: "train/mae" "train/rmse" "valid/mae" "valid/rmse" Visualizations are feature importances and trees. Callback works with ``xgboost.train()`` and ``xgboost.cv()`` functions, and with the sklearn API ``model.fit()``. Note: This callback works with ``xgboost>=1.3.0``. This release introduced new style Python callback API. Note: You can use public ``api_token="<PASSWORD>"`` and set ``project="common/xgboost-integration"`` for testing without registration. Args: run (:obj:`neptune.new.run.Run`): Neptune run object. A run in Neptune is a representation of all metadata that you log to Neptune. Learn more in `run docs`_. base_namespace(:obj:`str`, optional): Defaults to "training". Root namespace. All metadata will be logged inside. log_model (bool): Defaults to True. Log model as pickled file at the end of training. log_importance (bool): Defaults to True. Log feature importance charts at the end of training. max_num_features (int): Defaults to None. Max number of top features on the importance charts. Works only if ``log_importance`` is set to ``True``. If None, all features will be displayed. See `xgboost.plot_importance`_ for details. log_tree (list): Defaults to None. Indices of the target trees to log as charts. This requires graphviz to work. Learn about setup in the `Neptune-XGBoost installation`_ docs. See `xgboost.to_graphviz`_ for details. tree_figsize (int): Defaults to 30, Control size of the visualized tree image. Increase this in case you work with large trees. Works only if ``log_tree`` is list. Examples: For more examples visit `example scripts`_. Full script that does model training and logging of the metadata:: import neptune.new as neptune import xgboost as xgb from neptune.new.integrations.xgboost import NeptuneCallback from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split # Create run run = neptune.init( project="common/xgboost-integration", api_token="<PASSWORD>", name="xgb-train", tags=["xgb-integration", "train"] ) # Create neptune callback neptune_callback = NeptuneCallback(run=run, log_tree=[0, 1, 2, 3]) # Prepare data X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123) dtrain = xgb.DMatrix(X_train, label=y_train) dval = xgb.DMatrix(X_test, label=y_test) # Define parameters model_params = { "eta": 0.7, "gamma": 0.001, "max_depth": 9, "objective": "reg:squarederror", "eval_metric": ["mae", "rmse"] } evals = [(dtrain, "train"), (dval, "valid")] num_round = 57 # Train the model and log metadata to the run in Neptune xgb.train( params=model_params, dtrain=dtrain, num_boost_round=num_round, evals=evals, callbacks=[ neptune_callback, xgb.callback.LearningRateScheduler(lambda epoch: 0.99**epoch), xgb.callback.EarlyStopping(rounds=30) ], ) .. _Neptune-XGBoost docs: https://docs.neptune.ai/integrations-and-supported-tools/model-training/xgboost _Neptune-XGBoost installation: https://docs.neptune.ai/integrations-and-supported-tools/model-training/xgboost#install-requirements _run docs: https://docs.neptune.ai/api-reference/run _xgboost.plot_importance: https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.plot_importance _xgboost.to_graphviz: https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.to_graphviz _example scripts: https://github.com/neptune-ai/examples/tree/main/integrations-and-supported-tools/xgboost/scripts """ def __init__(self, run, base_namespace="training", log_model=True, log_importance=True, max_num_features=None, log_tree=None, tree_figsize=30): expect_not_an_experiment(run) verify_type("run", run, neptune.Run) verify_type("base_namespace", base_namespace, str) log_model is not None and verify_type("log_model", log_model, bool) log_importance is not None and verify_type("log_importance", log_importance, bool) max_num_features is not None and verify_type("max_num_features", max_num_features, int) log_tree is not None and verify_type("log_tree", log_tree, list) verify_type("tree_figsize", tree_figsize, int) self.run = run[base_namespace] self.log_model = log_model self.log_importance = log_importance self.max_num_features = max_num_features self.log_tree = log_tree self.cv = False self.tree_figsize = tree_figsize if self.log_tree: try: subprocess.call(["dot", "-V"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except OSError: self.log_tree = None message = "Graphviz executables not found, so trees will not be logged. " \ "Make sure the Graphviz executables are on your systems' PATH" warnings.warn(message) run[INTEGRATION_VERSION_KEY] = __version__ def before_training(self, model): if hasattr(model, "cvfolds"): self.cv = True return model def after_training(self, model): # model structure is different for "cv" and "train" functions that you use to train xgb model if self.cv: for i, fold in enumerate(model.cvfolds): self.run[f"fold_{i}/booster_config"] = json.loads(fold.bst.save_config()) else: self.run["booster_config"] = json.loads(model.save_config()) if "best_score" in model.attributes().keys(): self.run["early_stopping/best_score"] = model.attributes()["best_score"] if "best_iteration" in model.attributes().keys(): self.run["early_stopping/best_iteration"] = model.attributes()["best_iteration"] self._log_importance(model) self._log_trees(model) self._log_model(model) return model def _log_importance(self, model): if self.log_importance: # for "cv" log importance chart per fold if self.cv: for i, fold in enumerate(model.cvfolds): importance = xgb.plot_importance(fold.bst, max_num_features=self.max_num_features) self.run[f"fold_{i}/plots/importance"].upload(neptune.types.File.as_image(importance.figure)) plt.close("all") else: importance = xgb.plot_importance(model, max_num_features=self.max_num_features) self.run["plots/importance"].upload(neptune.types.File.as_image(importance.figure)) plt.close("all") def _log_trees(self, model): if self.log_tree is not None: # for "cv" log trees for each cv fold (different model is trained on each fold) if self.cv: for i, fold in enumerate(model.cvfolds): trees = [] for j in self.log_tree: tree = xgb.to_graphviz(fold.bst, num_trees=j) _, ax = plt.subplots(1, 1, figsize=(self.tree_figsize, self.tree_figsize)) s = BytesIO() s.write(tree.pipe(format="png")) s.seek(0) ax.imshow(image.imread(s)) ax.axis("off") trees.append(neptune.types.File.as_image(ax.figure)) self.run[f"fold_{i}/plots/trees"] = neptune.types.FileSeries(trees) plt.close("all") else: trees = [] for j in self.log_tree: tree = xgb.to_graphviz(model, num_trees=j) _, ax = plt.subplots(1, 1, figsize=(self.tree_figsize, self.tree_figsize)) s = BytesIO() s.write(tree.pipe(format="png")) s.seek(0) ax.imshow(image.imread(s)) ax.axis("off") trees.append(neptune.types.File.as_image(ax.figure)) self.run["plots/trees"] = neptune.types.FileSeries(trees) plt.close("all") def _log_model(self, model): if self.log_model: # for "cv" log model per fold if self.cv: for i, fold in enumerate(model.cvfolds): self.run[f"fold_{i}/pickled_model"].upload(neptune.types.File.as_pickle(fold.bst)) else: self.run["pickled_model"].upload(neptune.types.File.as_pickle(model)) def before_iteration(self, model, epoch: int, evals_log) -> bool: # False to indicate training should not stop. return False def after_iteration(self, model, epoch: int, evals_log) -> bool: self.run["epoch"].log(epoch) self._log_metrics(evals_log) self._log_learning_rate(model) return False def _log_metrics(self, evals_log): for stage, metrics_dict in evals_log.items(): for metric_name, metric_values in evals_log[stage].items(): if self.cv: mean, std = metric_values[-1] self.run[stage][metric_name]["mean"].log(mean) self.run[stage][metric_name]["std"].log(std) else: self.run[stage][metric_name].log(metric_values[-1]) def _log_learning_rate(self, model): if self.cv: config = json.loads(model.cvfolds[0].bst.save_config()) else: config = json.loads(model.save_config()) lr = None updater = config["learner"]["gradient_booster"]["updater"] updater_types = ['grow_colmaker', 'grow_histmaker', 'grow_local_histmaker', 'grow_quantile_histmaker', 'grow_gpu_hist', 'sync', 'refresh', 'prune'] for updater_type in updater_types: if updater_type in updater: lr = updater[updater_type]["train_param"]["learning_rate"] break if lr is not None: self.run["learning_rate"].log(float(lr))
[ "neptune.internal.utils.verify_type", "neptune.internal.utils.compatibility.expect_not_an_experiment", "neptune.types.FileSeries", "neptune.types.File.as_pickle", "neptune.types.File.as_image" ]
[((6737, 6766), 'neptune.internal.utils.compatibility.expect_not_an_experiment', 'expect_not_an_experiment', (['run'], {}), '(run)\n', (6761, 6766), False, 'from neptune.internal.utils.compatibility import expect_not_an_experiment\n'), ((6775, 6811), 'neptune.internal.utils.verify_type', 'verify_type', (['"""run"""', 'run', 'neptune.Run'], {}), "('run', run, neptune.Run)\n", (6786, 6811), False, 'from neptune.internal.utils import verify_type\n'), ((6820, 6870), 'neptune.internal.utils.verify_type', 'verify_type', (['"""base_namespace"""', 'base_namespace', 'str'], {}), "('base_namespace', base_namespace, str)\n", (6831, 6870), False, 'from neptune.internal.utils import verify_type\n'), ((7215, 7261), 'neptune.internal.utils.verify_type', 'verify_type', (['"""tree_figsize"""', 'tree_figsize', 'int'], {}), "('tree_figsize', tree_figsize, int)\n", (7226, 7261), False, 'from neptune.internal.utils import verify_type\n'), ((6905, 6946), 'neptune.internal.utils.verify_type', 'verify_type', (['"""log_model"""', 'log_model', 'bool'], {}), "('log_model', log_model, bool)\n", (6916, 6946), False, 'from neptune.internal.utils import verify_type\n'), ((6986, 7037), 'neptune.internal.utils.verify_type', 'verify_type', (['"""log_importance"""', 'log_importance', 'bool'], {}), "('log_importance', log_importance, bool)\n", (6997, 7037), False, 'from neptune.internal.utils import verify_type\n'), ((7079, 7133), 'neptune.internal.utils.verify_type', 'verify_type', (['"""max_num_features"""', 'max_num_features', 'int'], {}), "('max_num_features', max_num_features, int)\n", (7090, 7133), False, 'from neptune.internal.utils import verify_type\n'), ((7167, 7206), 'neptune.internal.utils.verify_type', 'verify_type', (['"""log_tree"""', 'log_tree', 'list'], {}), "('log_tree', log_tree, list)\n", (7178, 7206), False, 'from neptune.internal.utils import verify_type\n'), ((7589, 7678), 'subprocess.call', 'subprocess.call', (["['dot', '-V']"], {'stdout': 'subprocess.DEVNULL', 'stderr': 'subprocess.DEVNULL'}), "(['dot', '-V'], stdout=subprocess.DEVNULL, stderr=subprocess\n .DEVNULL)\n", (7604, 7678), False, 'import subprocess\n'), ((9390, 9406), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (9399, 9406), True, 'import matplotlib.pyplot as plt\n'), ((9454, 9520), 'xgboost.plot_importance', 'xgb.plot_importance', (['model'], {'max_num_features': 'self.max_num_features'}), '(model, max_num_features=self.max_num_features)\n', (9473, 9520), True, 'import xgboost as xgb\n'), ((9637, 9653), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (9646, 9653), True, 'import matplotlib.pyplot as plt\n'), ((11121, 11152), 'neptune.types.FileSeries', 'neptune.types.FileSeries', (['trees'], {}), '(trees)\n', (11145, 11152), False, 'import neptune\n'), ((11169, 11185), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (11178, 11185), True, 'import matplotlib.pyplot as plt\n'), ((7936, 7958), 'warnings.warn', 'warnings.warn', (['message'], {}), '(message)\n', (7949, 7958), False, 'import warnings\n'), ((9190, 9259), 'xgboost.plot_importance', 'xgb.plot_importance', (['fold.bst'], {'max_num_features': 'self.max_num_features'}), '(fold.bst, max_num_features=self.max_num_features)\n', (9209, 9259), True, 'import xgboost as xgb\n'), ((9573, 9619), 'neptune.types.File.as_image', 'neptune.types.File.as_image', (['importance.figure'], {}), '(importance.figure)\n', (9600, 9619), False, 'import neptune\n'), ((10495, 10526), 'neptune.types.FileSeries', 'neptune.types.FileSeries', (['trees'], {}), '(trees)\n', (10519, 10526), False, 'import neptune\n'), ((10547, 10563), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (10556, 10563), True, 'import matplotlib.pyplot as plt\n'), ((10676, 10711), 'xgboost.to_graphviz', 'xgb.to_graphviz', (['model'], {'num_trees': 'j'}), '(model, num_trees=j)\n', (10691, 10711), True, 'import xgboost as xgb\n'), ((10740, 10806), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(self.tree_figsize, self.tree_figsize)'}), '(1, 1, figsize=(self.tree_figsize, self.tree_figsize))\n', (10752, 10806), True, 'import matplotlib.pyplot as plt\n'), ((10831, 10840), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (10838, 10840), False, 'from io import BytesIO\n'), ((11540, 11575), 'neptune.types.File.as_pickle', 'neptune.types.File.as_pickle', (['model'], {}), '(model)\n', (11568, 11575), False, 'import neptune\n'), ((9326, 9372), 'neptune.types.File.as_image', 'neptune.types.File.as_image', (['importance.figure'], {}), '(importance.figure)\n', (9353, 9372), False, 'import neptune\n'), ((10005, 10043), 'xgboost.to_graphviz', 'xgb.to_graphviz', (['fold.bst'], {'num_trees': 'j'}), '(fold.bst, num_trees=j)\n', (10020, 10043), True, 'import xgboost as xgb\n'), ((10076, 10142), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(self.tree_figsize, self.tree_figsize)'}), '(1, 1, figsize=(self.tree_figsize, self.tree_figsize))\n', (10088, 10142), True, 'import matplotlib.pyplot as plt\n'), ((10171, 10180), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (10178, 10180), False, 'from io import BytesIO\n'), ((10954, 10969), 'matplotlib.image.imread', 'image.imread', (['s'], {}), '(s)\n', (10966, 10969), False, 'from matplotlib import image\n'), ((11039, 11077), 'neptune.types.File.as_image', 'neptune.types.File.as_image', (['ax.figure'], {}), '(ax.figure)\n', (11066, 11077), False, 'import neptune\n'), ((11433, 11471), 'neptune.types.File.as_pickle', 'neptune.types.File.as_pickle', (['fold.bst'], {}), '(fold.bst)\n', (11461, 11471), False, 'import neptune\n'), ((10306, 10321), 'matplotlib.image.imread', 'image.imread', (['s'], {}), '(s)\n', (10318, 10321), False, 'from matplotlib import image\n'), ((10399, 10437), 'neptune.types.File.as_image', 'neptune.types.File.as_image', (['ax.figure'], {}), '(ax.figure)\n', (10426, 10437), False, 'import neptune\n')]
#!/usr/bin/env python # coding: utf-8 # In[1]: #hide get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') # In[2]: # default_exp core # In[3]: #export from nbdev.export import check_re,read_nb from pathlib import Path import re import os import platform # # module name here # # > API details. # ## Code cells # In[4]: #export _re_blank_code = re.compile(r""" # Matches any line with #export or #exports without any module name: ^ # beginning of line (since re.MULTILINE is passed) \s* # any number of whitespace \#\s* # # then any number of whitespace code # export or exports \s* # any number of whitespace $ # end of line (since re.MULTILINE is passed) """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) _re_mod_code = re.compile(r""" # Matches any line with #export or #exports with a module name and catches it in group 1: ^ # beginning of line (since re.MULTILINE is passed) \s* # any number of whitespace \#\s* # # then any number of whitespace code # export or exports \s* # any number of whitespace (\S+) # catch a group with any non-whitespace chars \s* # any number of whitespace $ # end of line (since re.MULTILINE is passed) """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) # In[5]: #export def is_code(cell, default="main.py"): "Check if `cell` is to be exported and returns the name of the module to export it if provided" if check_re(cell, _re_blank_code): return default tst = check_re(cell, _re_mod_code) return os.path.sep.join(tst.groups()[0].split('.')).replace("\\",".") if tst else None # In[6]: #export from collections import defaultdict def get_codes(fn:str,default:str = "main.py") -> dict: nb = read_nb(fn) module_to_code = defaultdict(str) module_to_code[default] = "" for cell in nb["cells"]: code = is_code(cell,default) if code: module_to_code[code] += cell["source"] return dict(module_to_code) # ## Properties # ### OS information # In[7]: #export def get_metadata() -> dict: data = { "os":os.name, "system":platform.system(), "release":platform.release(), "python_version":platform.python_version() } return data # In[8]: get_metadata() # ### Modules information # In[2]: get_ipython().system('echo coucou') # In[3]: from pipreqs.pipreqs import init # In[5]: from docopt import docopt # In[7]: subprocess.check_output(["pipreqs","./","--force"]) # In[9]: #export def create_requirements(fn): # Convert the notebook to a python file os.system(f"jupyter nbconvert --to=python {fn}") # Create the requirements file os.system("pipreqs ./ --force") # ### Properties cells # In[10]: #export _re_blank_property = re.compile(r""" # Matches any line with #export or #exports without any module name: ^ # beginning of line (since re.MULTILINE is passed) \s* # any number of whitespace \#\s* # # then any number of whitespace property # export or exports \s* # any number of whitespace $ # end of line (since re.MULTILINE is passed) """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) _re_obj_def = re.compile(r""" # Catches any 0-indented object definition (bla = thing) with its name in group 1 ^ # Beginning of a line (since re.MULTILINE is passed) ([^=\s]*) # Catching group with any character except a whitespace or an equal sign \s*= # Any number of whitespace followed by an = """, re.MULTILINE | re.VERBOSE) # In[11]: #export def is_property(cell): "Check if `cell` is to be exported and returns the name of the module to export it if provided" if check_re(cell, _re_blank_property): return True else: return False def add_cell_to_properties(cell: dict,properties: dict,globs:dict): """Adds all variables in the cell to the properties""" objs = _re_obj_def.findall(cell["source"]) objs = {obj : globs[obj] for obj in objs} properties.update(objs) # In[12]: #export def files_in_properties(properties:dict): """Returns the list of files from properties""" files = [] for key,val in properties.items(): if isinstance(val,Path) and val.is_file(): files.append(str(val)) return files # In[13]: #export def get_properties_from_cells(fn: str,globs:dict,return_files:bool = True,): """Gets the properties from all #property cells""" nb = read_nb(fn) properties = {} for cell in nb["cells"]: if is_property(cell): add_cell_to_properties(cell,properties,globs=globs) files = files_in_properties(properties) return properties,files # ## Wrapper # In[41]: #export from contextlib import contextmanager from neptune.projects import Project from neptune.experiments import Experiment @contextmanager def fast_experiment(project: Project,nb_name:str,globs:dict,return_files: bool = True, default:str = "main.py",**kwargs) -> Experiment: # First we get the code cells codes = get_codes(nb_name,default=default) # We write them in separate files for fn,code in codes.items(): with open(fn,"w") as file: file.write(code) codes = list(codes.keys()) # We get the properties properties,files = get_properties_from_cells(nb_name,globs=globs,return_files=return_files) metadata = get_metadata() properties.update(metadata) properties["nb_name"] = nb_name # We convert the dict keys to string for k,v in properties.items(): properties[k] = str(v) exp = project.create_experiment(params=properties,upload_source_files=codes,**kwargs) # We create the requirements file and send it create_requirements(nb_name) exp.send_artifact("requirements.txt") for fn in files: exp.send_artifact(fn) yield exp exp.stop() # We remove the code files for fn in codes: os.remove(fn) os.remove("requirements.txt") # In[8]: #code print("Coucou") # In[9]: nb_name = "00_core.ipynb" # In[11]: # Neptune login from neptune.sessions import Session from fast_neptune.core import fast_experiment import getpass api_token = getpass.getpass("Please enter your NeptuneML API token : ") session = Session(api_token=api_token) project = session.get_project(project_qualified_name='danywin/fast-neptune') # In[13]: globs = globals() # In[ ]: with fast_experiment(project,nb_name,globs) as exp: pass
[ "neptune.sessions.Session" ]
[((412, 817), 're.compile', 're.compile', (['"""\n# Matches any line with #export or #exports without any module name:\n^ # beginning of line (since re.MULTILINE is passed)\n\\\\s* # any number of whitespace\n\\\\#\\\\s* # # then any number of whitespace\ncode # export or exports\n\\\\s* # any number of whitespace\n$ # end of line (since re.MULTILINE is passed)\n"""', '(re.IGNORECASE | re.MULTILINE | re.VERBOSE)'], {}), '(\n """\n# Matches any line with #export or #exports without any module name:\n^ # beginning of line (since re.MULTILINE is passed)\n\\\\s* # any number of whitespace\n\\\\#\\\\s* # # then any number of whitespace\ncode # export or exports\n\\\\s* # any number of whitespace\n$ # end of line (since re.MULTILINE is passed)\n"""\n , re.IGNORECASE | re.MULTILINE | re.VERBOSE)\n', (422, 817), False, 'import re\n'), ((821, 1342), 're.compile', 're.compile', (['"""\n# Matches any line with #export or #exports with a module name and catches it in group 1:\n^ # beginning of line (since re.MULTILINE is passed)\n\\\\s* # any number of whitespace\n\\\\#\\\\s* # # then any number of whitespace\ncode # export or exports\n\\\\s* # any number of whitespace\n(\\\\S+) # catch a group with any non-whitespace chars\n\\\\s* # any number of whitespace\n$ # end of line (since re.MULTILINE is passed)\n"""', '(re.IGNORECASE | re.MULTILINE | re.VERBOSE)'], {}), '(\n """\n# Matches any line with #export or #exports with a module name and catches it in group 1:\n^ # beginning of line (since re.MULTILINE is passed)\n\\\\s* # any number of whitespace\n\\\\#\\\\s* # # then any number of whitespace\ncode # export or exports\n\\\\s* # any number of whitespace\n(\\\\S+) # catch a group with any non-whitespace chars\n\\\\s* # any number of whitespace\n$ # end of line (since re.MULTILINE is passed)\n"""\n , re.IGNORECASE | re.MULTILINE | re.VERBOSE)\n', (831, 1342), False, 'import re\n'), ((2884, 3293), 're.compile', 're.compile', (['"""\n# Matches any line with #export or #exports without any module name:\n^ # beginning of line (since re.MULTILINE is passed)\n\\\\s* # any number of whitespace\n\\\\#\\\\s* # # then any number of whitespace\nproperty # export or exports\n\\\\s* # any number of whitespace\n$ # end of line (since re.MULTILINE is passed)\n"""', '(re.IGNORECASE | re.MULTILINE | re.VERBOSE)'], {}), '(\n """\n# Matches any line with #export or #exports without any module name:\n^ # beginning of line (since re.MULTILINE is passed)\n\\\\s* # any number of whitespace\n\\\\#\\\\s* # # then any number of whitespace\nproperty # export or exports\n\\\\s* # any number of whitespace\n$ # end of line (since re.MULTILINE is passed)\n"""\n , re.IGNORECASE | re.MULTILINE | re.VERBOSE)\n', (2894, 3293), False, 'import re\n'), ((3296, 3639), 're.compile', 're.compile', (['"""\n# Catches any 0-indented object definition (bla = thing) with its name in group 1\n^ # Beginning of a line (since re.MULTILINE is passed)\n([^=\\\\s]*) # Catching group with any character except a whitespace or an equal sign\n\\\\s*= # Any number of whitespace followed by an =\n"""', '(re.MULTILINE | re.VERBOSE)'], {}), '(\n """\n# Catches any 0-indented object definition (bla = thing) with its name in group 1\n^ # Beginning of a line (since re.MULTILINE is passed)\n([^=\\\\s]*) # Catching group with any character except a whitespace or an equal sign\n\\\\s*= # Any number of whitespace followed by an =\n"""\n , re.MULTILINE | re.VERBOSE)\n', (3306, 3639), False, 'import re\n'), ((6399, 6458), 'getpass.getpass', 'getpass.getpass', (['"""Please enter your NeptuneML API token : """'], {}), "('Please enter your NeptuneML API token : ')\n", (6414, 6458), False, 'import getpass\n'), ((6469, 6497), 'neptune.sessions.Session', 'Session', ([], {'api_token': 'api_token'}), '(api_token=api_token)\n', (6476, 6497), False, 'from neptune.sessions import Session\n'), ((1494, 1524), 'nbdev.export.check_re', 'check_re', (['cell', '_re_blank_code'], {}), '(cell, _re_blank_code)\n', (1502, 1524), False, 'from nbdev.export import check_re, read_nb\n'), ((1559, 1587), 'nbdev.export.check_re', 'check_re', (['cell', '_re_mod_code'], {}), '(cell, _re_mod_code)\n', (1567, 1587), False, 'from nbdev.export import check_re, read_nb\n'), ((1801, 1812), 'nbdev.export.read_nb', 'read_nb', (['fn'], {}), '(fn)\n', (1808, 1812), False, 'from nbdev.export import check_re, read_nb\n'), ((1839, 1855), 'collections.defaultdict', 'defaultdict', (['str'], {}), '(str)\n', (1850, 1855), False, 'from collections import defaultdict\n'), ((2692, 2740), 'os.system', 'os.system', (['f"""jupyter nbconvert --to=python {fn}"""'], {}), "(f'jupyter nbconvert --to=python {fn}')\n", (2701, 2740), False, 'import os\n'), ((2785, 2816), 'os.system', 'os.system', (['"""pipreqs ./ --force"""'], {}), "('pipreqs ./ --force')\n", (2794, 2816), False, 'import os\n'), ((3781, 3815), 'nbdev.export.check_re', 'check_re', (['cell', '_re_blank_property'], {}), '(cell, _re_blank_property)\n', (3789, 3815), False, 'from nbdev.export import check_re, read_nb\n'), ((4568, 4579), 'nbdev.export.read_nb', 'read_nb', (['fn'], {}), '(fn)\n', (4575, 4579), False, 'from nbdev.export import check_re, read_nb\n'), ((6154, 6183), 'os.remove', 'os.remove', (['"""requirements.txt"""'], {}), "('requirements.txt')\n", (6163, 6183), False, 'import os\n'), ((6625, 6665), 'fast_neptune.core.fast_experiment', 'fast_experiment', (['project', 'nb_name', 'globs'], {}), '(project, nb_name, globs)\n', (6640, 6665), False, 'from fast_neptune.core import fast_experiment\n'), ((2210, 2227), 'platform.system', 'platform.system', ([], {}), '()\n', (2225, 2227), False, 'import platform\n'), ((2247, 2265), 'platform.release', 'platform.release', ([], {}), '()\n', (2263, 2265), False, 'import platform\n'), ((2292, 2317), 'platform.python_version', 'platform.python_version', ([], {}), '()\n', (2315, 2317), False, 'import platform\n'), ((6127, 6140), 'os.remove', 'os.remove', (['fn'], {}), '(fn)\n', (6136, 6140), False, 'import os\n')]
from typing import Dict import neptune.new as neptune import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn from config import NEPTUNE_API_TOKEN, NEPTUNE_PROJECT_NAME from sklearn.metrics import classification_report, f1_score from utils.summary_loss import SummaryLoss from math import ceil from models.feature_extractors.multi_frame_feature_extractor import ( MultiFrameFeatureExtractor, ) from models.model_loader import ModelLoader from models.common.simple_sequential_model import SimpleSequentialModel from models.landmarks_models.lanmdarks_sequential_model import LandmarksSequentialModel from models.head_models.head_sequential_model import HeadClassificationSequentialModel # initialize neptune logging def initialize_neptun(tags): return neptune.init( api_token=NEPTUNE_API_TOKEN, project=NEPTUNE_PROJECT_NAME, tags=tags, capture_stdout=False, capture_stderr=False, ) class GlossTranslationModel(pl.LightningModule): """Awesome model for Gloss Translation""" def __init__( self, general_parameters: Dict = None, train_parameters: Dict = None, feature_extractor_parameters: Dict = None, transformer_parameters: Dict = None, heads: Dict = None, freeze_scheduler: Dict = None, loss_function=nn.BCEWithLogitsLoss, steps_per_epoch: int = 1000 ): """ Args: general_parameters (Dict): Dict containing general parameters not parameterizing training process. [Warning] Must contain fields: - path_to_save (str) - neptune (bool) feature_extractor_parameters (Dict): Dict containing parameters regarding currently used feature extractor. [Warning] Must contain fields: - "name" (str) - "model_path" (str) - "representation_size" (int) transformer_parameters (Dict): Dict containing parameters regarding currently used transformer. [Warning] Must contain fields: - "name" (str) - "output_size" (int) - "feedforward_size" (int) - "num_encoder_layers" (int) - "num_attention_heads" (int) - "dropout_rate" (float) train_parameters (Dict): Dict containing parameters parameterizing the training process. [Warning] Must contain fields: - "num_segments" (int) - "lr" (float) - "multiply_lr_step" (float) - "warmup_steps" (float) - "classification_mode" (str) heads (Dict): Dict containg information describing structure of output heads for specific tasks (gloss/hamnosys). freeze_scheduler (Dict): Dict containing information describing feature_extractor & transformer freezing/unfreezing process. loss_function (torch.nn.Module): Loss function. """ super().__init__() if general_parameters["neptune"]: tags = [train_parameters["classification_mode"], feature_extractor_parameters["name"], transformer_parameters["name"]] self.run = initialize_neptun(tags) self.run["parameters"] = { "general_parameters": general_parameters, "train_parameters": train_parameters, "feature_extractor_parameters": feature_extractor_parameters, "transformer_parameters": transformer_parameters, "heads": heads, "freeze_scheduler": freeze_scheduler, "loss_function": loss_function } else: self.run = None # parameters self.lr = train_parameters["lr"] self.model_save_dir = general_parameters["path_to_save"] self.warmup_steps = train_parameters["warmup_steps"] self.multiply_lr_step = train_parameters["multiply_lr_step"] self.use_frames = train_parameters["use_frames"] self.use_landmarks = train_parameters["use_landmarks"] self.classification_heads = heads[train_parameters['classification_mode']] self.cls_head = nn.ModuleList() self.loss_weights = [] for value in self.classification_heads.values(): self.cls_head.append( HeadClassificationSequentialModel( classes_number=value["num_class"], representation_size=3 * value["num_class"], additional_layers=1, dropout_rate=heads["model"]["dropout_rate"] ) ) self.loss_weights.append(value["loss_weight"]) # losses self.summary_loss = SummaryLoss(loss_function, self.loss_weights) # models-parts self.model_loader = ModelLoader() representation_size = feature_extractor_parameters["representation_size"] self.adjustment_to_representatios_size = nn.LazyLinear(out_features=representation_size) if self.use_frames: self.multi_frame_feature_extractor = MultiFrameFeatureExtractor( self.model_loader.load_feature_extractor( feature_extractor_name=feature_extractor_parameters["name"], representation_size=representation_size, model_path=feature_extractor_parameters["model_path"], ) ) else: self.multi_frame_feature_extractor = None self.transformer = self.model_loader.load_transformer( transformer_name=transformer_parameters["name"], feature_extractor_parameters=feature_extractor_parameters, transformer_parameters=transformer_parameters, train_parameters=train_parameters ) self.steps_per_epoch = steps_per_epoch if freeze_scheduler is not None: self.freeze_scheduler = freeze_scheduler self.configure_freeze_scheduler() def forward(self, input, **kwargs): predictions = [] frames, landmarks = input if self.use_frames: x = self.multi_frame_feature_extractor(frames.to(self.device)) if self.use_landmarks: x_landmarks = self._prepare_landmarks_tensor(landmarks) if self.use_frames: x = torch.concat([x, x_landmarks], dim=-1) else: x = x_landmarks x = self.adjustment_to_representatios_size(x) x = self.transformer(x) for head in self.cls_head: predictions.append(head(x)) return predictions def _prepare_landmarks_tensor(self, landmarks): concatenated_landmarks = np.concatenate( [landmarks[landmarks_name] for landmarks_name in landmarks.keys()], axis=-1 ) return torch.as_tensor(concatenated_landmarks, dtype=torch.float32, device=self.device) def training_step(self, batch, batch_idx): targets, predictions, losses = self._process_batch(batch) self.scheduler.step() if self.global_step < 2: for name, child in self.named_children(): for param in child.parameters(): param.requires_grad = True if self.freeze_scheduler["freeze_mode"] == "step": self.freeze_step() if self.run: self.run["metrics/batch/training_loss"].log(losses) return {"loss": losses} def validation_step(self, batch, batch_idx): targets, predictions, losses = self._process_batch(batch) if self.run: self.run["metrics/batch/validation_loss"].log(losses) return {"val_loss": losses, "targets": targets, "predictions": predictions} def _process_batch(self, batch): frames, landmarks, targets = batch predictions = self((frames, landmarks)) losses = self.summary_loss(predictions, targets) return targets, predictions, losses def validation_epoch_end(self, out): head_names = list(self.classification_heads.keys()) # initialize empty list with list per head all_targets = [[] for name in head_names] all_predictions = [[] for name in head_names] for single_batch in out: targets, predictions = single_batch["targets"], single_batch["predictions"] # append predictions and targets for every head for nr_head, head_targets in enumerate(targets): all_targets[nr_head] += list(torch.argmax(targets[nr_head], dim=1).cpu().detach().numpy()) all_predictions[nr_head] += list(torch.argmax(predictions[nr_head], dim=1).cpu().detach().numpy()) for nr_head, targets_for_head in enumerate(all_targets): head_name = head_names[nr_head] predictions_for_head = all_predictions[nr_head] head_report = "\n".join( [ head_name, classification_report( targets_for_head, predictions_for_head, zero_division=0 ), ] ) print(head_report) f1 = f1_score(targets_for_head, predictions_for_head, average='macro', zero_division=0) if self.run: log_path = "/".join(["metrics/epoch/", head_name]) self.run[log_path].log(head_report) self.run[f'/metrics/epoch/f1/{head_name}'].log(f1) if self.trainer.global_step > 0: print("Saving model...") torch.save(self.state_dict(), self.model_save_dir) self.scheduler.step() if (self.freeze_scheduler is not None) and self.freeze_scheduler["freeze_mode"] == "epoch": self.freeze_step() def configure_optimizers(self): optimizer = torch.optim.RAdam(self.parameters(), lr=self.lr) self.scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=self.lr, div_factor=100, final_div_factor=10, pct_start=0.2, total_steps=self.trainer.max_epochs * self.steps_per_epoch + 2) return [optimizer], [self.scheduler] def optimizer_step( self, epoch, batch_idx, optimizer, optimizer_idx, optimizer_closure, on_tpu=False, using_native_amp=False, using_lbfgs=False, ): optimizer.step(closure=optimizer_closure) if self.run: self.run["params/lr"].log(optimizer.param_groups[0]["lr"]) def configure_freeze_scheduler(self): ### TO-DO check if all params are correctly set # e.g. check if all lists are the same length # check if values are bools self.freeze_scheduler["current_pattern"] = 0 self.freeze_scheduler["current_counter"] = 0 self.freeze_step() def freeze_step(self): ### TO- DO # If the `freeze_pattern_repeats` is set as an integer isntead of a list, # e.g. `freeze_pattern_repeats = 3`, it is equal to a pattern # `feature_extractor = [True, False] * freeze_pattern_repeats`, # hence it is exactly the same as: # ``` # "model_params": { # "feature_extractor": [True, False, True, False, True, False], # "transformer": [False, True,False, True, False, True], # } # ``` if self.freeze_scheduler is not None: self.freeze_update() for params_to_freeze in list(self.freeze_scheduler["model_params"].keys()): if self.freeze_scheduler["current_pattern"] >= len( self.freeze_scheduler["model_params"][params_to_freeze] ): current_pattern = True else: current_pattern = self.freeze_scheduler["model_params"][ params_to_freeze ][self.freeze_scheduler["current_pattern"]] for name, child in self.named_children(): if params_to_freeze in name: for param in child.parameters(): param.requires_grad = not current_pattern if self.freeze_scheduler["verbose"]: print( "Freeze status:", params_to_freeze, "set to", str(current_pattern), ) def freeze_update(self): if self.freeze_scheduler["current_pattern"] >= len( self.freeze_scheduler["model_params"][ list(self.freeze_scheduler["model_params"].keys())[0] ] ): return if ( self.freeze_scheduler["current_counter"] >= self.freeze_scheduler["freeze_pattern_repeats"][ self.freeze_scheduler["current_pattern"] ] ): self.freeze_scheduler["current_pattern"] += 1 self.freeze_scheduler["current_counter"] = 0 self.freeze_scheduler["current_counter"] += 1
[ "neptune.new.init" ]
[((790, 920), 'neptune.new.init', 'neptune.init', ([], {'api_token': 'NEPTUNE_API_TOKEN', 'project': 'NEPTUNE_PROJECT_NAME', 'tags': 'tags', 'capture_stdout': '(False)', 'capture_stderr': '(False)'}), '(api_token=NEPTUNE_API_TOKEN, project=NEPTUNE_PROJECT_NAME,\n tags=tags, capture_stdout=False, capture_stderr=False)\n', (802, 920), True, 'import neptune.new as neptune\n'), ((4324, 4339), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (4337, 4339), True, 'import torch.nn as nn\n'), ((4874, 4919), 'utils.summary_loss.SummaryLoss', 'SummaryLoss', (['loss_function', 'self.loss_weights'], {}), '(loss_function, self.loss_weights)\n', (4885, 4919), False, 'from utils.summary_loss import SummaryLoss\n'), ((4972, 4985), 'models.model_loader.ModelLoader', 'ModelLoader', ([], {}), '()\n', (4983, 4985), False, 'from models.model_loader import ModelLoader\n'), ((5119, 5166), 'torch.nn.LazyLinear', 'nn.LazyLinear', ([], {'out_features': 'representation_size'}), '(out_features=representation_size)\n', (5132, 5166), True, 'import torch.nn as nn\n'), ((7030, 7115), 'torch.as_tensor', 'torch.as_tensor', (['concatenated_landmarks'], {'dtype': 'torch.float32', 'device': 'self.device'}), '(concatenated_landmarks, dtype=torch.float32, device=self.device\n )\n', (7045, 7115), False, 'import torch\n'), ((10133, 10321), 'torch.optim.lr_scheduler.OneCycleLR', 'torch.optim.lr_scheduler.OneCycleLR', (['optimizer'], {'max_lr': 'self.lr', 'div_factor': '(100)', 'final_div_factor': '(10)', 'pct_start': '(0.2)', 'total_steps': '(self.trainer.max_epochs * self.steps_per_epoch + 2)'}), '(optimizer, max_lr=self.lr, div_factor=\n 100, final_div_factor=10, pct_start=0.2, total_steps=self.trainer.\n max_epochs * self.steps_per_epoch + 2)\n', (10168, 10321), False, 'import torch\n'), ((9365, 9451), 'sklearn.metrics.f1_score', 'f1_score', (['targets_for_head', 'predictions_for_head'], {'average': '"""macro"""', 'zero_division': '(0)'}), "(targets_for_head, predictions_for_head, average='macro',\n zero_division=0)\n", (9373, 9451), False, 'from sklearn.metrics import classification_report, f1_score\n'), ((4478, 4664), 'models.head_models.head_sequential_model.HeadClassificationSequentialModel', 'HeadClassificationSequentialModel', ([], {'classes_number': "value['num_class']", 'representation_size': "(3 * value['num_class'])", 'additional_layers': '(1)', 'dropout_rate': "heads['model']['dropout_rate']"}), "(classes_number=value['num_class'],\n representation_size=3 * value['num_class'], additional_layers=1,\n dropout_rate=heads['model']['dropout_rate'])\n", (4511, 4664), False, 'from models.head_models.head_sequential_model import HeadClassificationSequentialModel\n'), ((6524, 6562), 'torch.concat', 'torch.concat', (['[x, x_landmarks]'], {'dim': '(-1)'}), '([x, x_landmarks], dim=-1)\n', (6536, 6562), False, 'import torch\n'), ((9159, 9237), 'sklearn.metrics.classification_report', 'classification_report', (['targets_for_head', 'predictions_for_head'], {'zero_division': '(0)'}), '(targets_for_head, predictions_for_head, zero_division=0)\n', (9180, 9237), False, 'from sklearn.metrics import classification_report, f1_score\n'), ((8706, 8743), 'torch.argmax', 'torch.argmax', (['targets[nr_head]'], {'dim': '(1)'}), '(targets[nr_head], dim=1)\n', (8718, 8743), False, 'import torch\n'), ((8817, 8858), 'torch.argmax', 'torch.argmax', (['predictions[nr_head]'], {'dim': '(1)'}), '(predictions[nr_head], dim=1)\n', (8829, 8858), False, 'import torch\n')]
import argparse import shutil import sys import time import torch.nn.parallel import torch.optim import torch.utils.data from plot_functions_cw import * from helper_functions import * from PIL import ImageFile import neptune.new as neptune from access_keys import neptune_key run = neptune.init(project='irmavdbrandt/Interpret-rna', api_token=neptune_key, source_files=['train_premirna.py']) ImageFile.LOAD_TRUNCATED_IMAGES = True parser = argparse.ArgumentParser(description='PyTorch premiRNA Training') parser.add_argument('--arch', '-a', metavar='ARCH', default='deepmir') parser.add_argument('--whitened_layers', default='6') parser.add_argument('--act_mode', default='pool_max') parser.add_argument('-j', '--workers', default=0, type=int, metavar='N', help='number of data loading workers (default: 4)') parser.add_argument('--epochs', default=100, type=int, metavar='N', help='number of total epochs to run') parser.add_argument('--start-epoch', default=0, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('-b', '--batch-size', default=56, type=int, metavar='BS', help='mini-batch size (default: 256)') parser.add_argument('--lr', '--learning-rate', default=0.1, type=float, metavar='LR', help='initial learning rate') parser.add_argument('--concepts', type=str) parser.add_argument('--print-freq', '-p', default=10, type=int, metavar='N', help='print frequency (default: 10)') parser.add_argument('--checkpoint_name', default='', type=str, metavar='PATH', help='path to latest checkpoint ' '(default: none)') parser.add_argument("--seed", type=int, default=1234, metavar='S', help='randomization seed') parser.add_argument("--prefix", type=str, required=True, metavar='PFX', help='prefix for logging & checkpoint saving') parser.add_argument('--data', metavar='DIR', help='path to dataset') parser.add_argument('--type_training', type=str, dest='type_training', help='desired type of training (pre-training, ' 'fine-tuning, CW, evaluation') parser.add_argument('--foldn_bestmodel', type=str, default=0, help='data fold with best results during training') os.chdir(sys.path[0]) if not os.path.exists('./checkpoints'): os.mkdir('./checkpoints') def main(): global args, best_acc args = parser.parse_args() print("args", args) # define loss function criterion = nn.CrossEntropyLoss() # training initialization if (args.type_training != 'evaluate') and (args.type_training != 'get_activations'): # specifies which type of training is desired if args.type_training == "finetune" or args.type_training == "pretrain": # initialize empty model model = None # if fine-tuning, we want the weights from pre-training if args.type_training == 'finetune': if args.arch == 'deepmir_v2_bn': # change the model file to the file with the desired pre-training weights model = DeepMir_v2_BN(args, model_file='checkpoints/deepmir_v2_bn/DEEPMIR_v2_pretrain_BN_' 'checkpoint.pth.tar') elif args.arch == 'deepmir_vfinal_bn': # change the model file to the file with the desired pre-training weights # model file below is the one reported in the thesis report model = DeepMir_vfinal_BN(args, model_file='checkpoints/deepmir_vfinal_bn/DEEPMIR_vfinal_' 'BN_pretrain_checkpoint.pth.tar') else: # if pre-training, we need to initialize the model with random weights if args.arch == 'deepmir_v2_bn': model = DeepMir_v2_BN(args, model_file=None) elif args.arch == 'deepmir_vfinal_bn': model = DeepMir_vfinal_BN(args, model_file=None) # define optimizer optimizer = torch.optim.Adam(model.parameters(), args.lr) model = torch.nn.DataParallel(model) print('Model architecture: ', model) print(f'Number of model parameters: {sum([p.data.nelement() for p in model.parameters()])}') # add seeds for reproducibility torch.manual_seed(args.seed) np.random.seed(args.seed) # create path links to data directories traindir = os.path.join(args.data, 'train') test_loader = None if args.type_training == 'finetune': test_loader = create_data_loader(os.path.join(args.data, 'test'), False) # create a balanced data loader for the training set using class weights calculated on the training set train_loader = balanced_data_loader(args, traindir) # set the best accuracy so far to 0 before starting the training best_acc = 0 for epoch in range(args.start_epoch, args.start_epoch + args.epochs): train_loss, train_acc = train_baseline(train_loader, model, criterion, optimizer, epoch) # evaluate on validation set if args.type_training == 'finetune': acc, val_loss = validate(test_loader, model, criterion) else: # if pre-training without test set, evaluate on the training set acc, val_loss = validate(train_loader, model, criterion) # neptune logging metrics # Log epoch loss run[f"training/loss"].log(train_loss) # Log epoch accuracy run[f"training/acc"].log(train_acc) # Log epoch loss run[f"validation/loss"].log(val_loss) # Log epoch accuracy run[f"validation/acc"].log(acc) # remember best accuracy (or precision) and save checkpoint for this model is_best = acc > best_acc best_acc = max(acc, best_acc) save_checkpoint({ 'epoch': epoch + 1, 'arch': args.arch, 'state_dict': model.state_dict(), 'best_prec1': best_acc, 'optimizer': optimizer.state_dict(), }, is_best, args.prefix, fold_n=None) print('Best accuracy so far: ', best_acc) print('Accuracy current fold: ', acc) # stop the neptune logging run.stop() if args.type_training == "finetune": dst = './plot/' + '/' + args.arch + '/' if not os.path.exists(dst): os.mkdir(dst) # create a data loader for the test set that includes the image paths test_loader_with_path = torch.utils.data.DataLoader( ImageFolderWithPaths(os.path.join(args.data, 'test'), transforms.Compose([transforms.ToTensor(), ])), batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=False) print("Plot correlation BN layer in non-CW model") plot_correlation(dst, args, test_loader_with_path, model, args.whitened_layers) elif args.type_training == 'cw': args.prefix += '_' + '_'.join(args.whitened_layers.split(',')) train_accuracies = [] val_accuracies = [] correlations = [] # apply 5-fold cv using the training set splits in the dataset directory k_folds = 5 for fold in range(0, k_folds): print(f'now starting fold {fold}') # initialize model architecture and possibly weights model = None if args.arch == 'deepmir_v2_cw': model = DeepMir_v2_Transfer(args, [int(x) for x in args.whitened_layers.split(',')], model_file='checkpoints/deepmir_v2_bn/DEEPMIR_v2_BN_finetune_' 'checkpoint.pth.tar') elif args.arch == "deepmir_vfinal_cw": model = DeepMir_vfinal_Transfer(args, [int(x) for x in args.whitened_layers.split(',')], model_file='checkpoints/deepmir_vfinal_bn/DEEPMIR_' 'vfinal_BN_finetune_model_best.pth.tar') # define optimizer optimizer = torch.optim.Adam(model.parameters(), args.lr) model = torch.nn.DataParallel(model) print('Model architecture: ', model) print(f'Number of model parameters: {sum([p.data.nelement() for p in model.parameters()])}') # add seeds for reproducibility torch.manual_seed(args.seed) np.random.seed(args.seed) # create path links to data directories traindir = os.path.join(args.data, f'train_fold{fold}') valdir = os.path.join(args.data, f'val_fold{fold}') conceptdir_train = os.path.join(args.data, f'concept_train_fold{fold}') # create a balanced data loader for the training set using class weights calculated on the training set train_loader = balanced_data_loader(args, traindir) # initialize the concept data loader concept_loaders = [ torch.utils.data.DataLoader( datasets.ImageFolder(os.path.join(conceptdir_train, concept), transforms.Compose([ transforms.ToTensor(), ])), batch_size=args.batch_size, shuffle=True, num_workers=args.workers, pin_memory=False) for concept in args.concepts.split(',') ] # create balanced data loader for the test set using class weights calculated on the test set val_loader = create_data_loader(valdir, False) # create another data loader for the test set that includes the image paths val_loader_with_path = torch.utils.data.DataLoader( ImageFolderWithPaths(valdir, transforms.Compose([transforms.ToTensor(), ])), batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=False) # neptune parameter configuration run['config/dataset/path'] = traindir run['config/model'] = type(model).__name__ run['config/criterion'] = type(criterion).__name__ run['config/optimizer'] = type(optimizer).__name__ run['config/lr'] = args.lr run['config/batchsize'] = args.batch_size print("Start training") best_acc = 0 accuracies = [] val_losses = [] train_acc = None val_acc = None # set settings for early stopping: the model needs to run for 20 epochs before activating the function, # initialize an empty counter for the number of epochs without improvement in val loss and set the # initial val loss to infinity n_epochs_stop = 20 epochs_no_improve = 0 min_val_loss = np.Inf for epoch in range(args.start_epoch, args.start_epoch + args.epochs): # 0 used to be args.start_epoch adjust_learning_rate(args, optimizer, epoch) # train for one epoch train_acc, train_loss = train(train_loader, concept_loaders, model, criterion, optimizer, epoch) # evaluate on validation set val_acc, val_loss = validate(val_loader, model, criterion) accuracies.append(val_acc) val_losses.append(val_loss) # Neptune logging # Log fold loss run[f"training/{fold}/loss"].log(train_loss) # Log fold accuracy run[f"training/{fold}/acc"].log(train_acc) # Log fold loss run[f"validation/{fold}/loss"].log(val_loss) # Log fold accuracy run[f"validation/{fold}/acc"].log(val_acc) # remember best accuracy (or precision) and save checkpoint for this model is_best = val_acc > best_acc best_acc = max(val_acc, best_acc) # do not save models before the first 10 epochs (these models tend to not yet have learned any # concepts but do have high accuracy due to the use of pretraining weights) if epoch < args.start_epoch + 5: continue else: save_checkpoint({ 'epoch': epoch + 1, 'arch': args.arch, 'state_dict': model.state_dict(), 'best_prec1': best_acc, 'optimizer': optimizer.state_dict(), }, is_best, args.prefix, fold_n=fold) print('Best accuracy so far: ', best_acc) print('Accuracy current fold: ', val_acc) # add early stopping criteria: if the loss on the validation set has not improved over the last 10 # epochs, stop the training if val_loss < min_val_loss: epochs_no_improve = 0 min_val_loss = val_loss else: epochs_no_improve += 1 if epoch > args.start_epoch + 10 and epochs_no_improve == n_epochs_stop: print('Early stopping!') print('validation loss not decreased over 20 epochs') break else: continue train_accuracies.append(train_acc) val_accuracies.append(val_acc) print("mean accuracy on training set: ", np.mean(train_accuracies)) print("std accuracy on training set: ", np.std(train_accuracies)) print("mean accuracy on validation set: ", np.mean(val_accuracies)) print("std accuracy on validation set: ", np.std(val_accuracies)) print('Max accuracy on validation set: ', np.max(val_accuracies), 'index: ', np.argmax(val_accuracies)) print('Start evaluation for decorrelation and concept learning') concept_name = args.concepts.split(',') base_dir = './plot/' + '_'.join(concept_name) if not os.path.exists(base_dir): os.mkdir(base_dir) val_dir = os.path.join(base_dir, 'validation') if not os.path.exists(val_dir): os.mkdir(val_dir) dir_fold = os.path.join(val_dir, str(fold)) if not os.path.exists(dir_fold): os.mkdir(dir_fold) # create directory where plots will be stored dst = './plot/' + '_'.join(args.concepts.split(',')) + '/validation/' + str(fold) + '/' + args.arch \ + '/' if not os.path.exists(dst): os.mkdir(dst) # plot the correlation between the different neurons in the CW layer in a heatmap and collect the # correlation values mean_correlation = plot_correlation(dst, args, val_loader_with_path, model, args.whitened_layers) # Neptune logging: log decorrelation of trained model on fold x run[f"validation/correlation"].log(mean_correlation) correlations.append(mean_correlation) print("mean correlations on validation set: ", np.mean(correlations)) print("std correlations on validation set: ", np.std(correlations)) print('Min correlation on validation set: ', np.min(correlations), 'index: ', np.argmin(correlations)) print("Collect 50 most activated images and plot the top 10") plot_concept_top50(args, val_loader_with_path, model, args.whitened_layers, False, args.act_mode, dst) plot_top10(args.concepts.split(','), args.whitened_layers, args.type_training, dst) # stop the neptune logging run.stop() # get activations after the cw layer on the complete training and test dataset elif args.type_training == 'get_activations': # create a data loader for the training set that includes the image paths train_loader_with_path = torch.utils.data.DataLoader( ImageFolderWithPaths(os.path.join(args.data, 'train'), transforms.Compose([transforms.ToTensor(), ])), batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=False) # create a data loader for the test set that includes the image paths test_loader_with_path = torch.utils.data.DataLoader( ImageFolderWithPaths(os.path.join(args.data, 'test'), transforms.Compose([transforms.ToTensor(), ])), batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=False) model = load_deepmir_model(args, whitened_layer=args.whitened_layers, checkpoint_name=args.checkpoint_name) print("Save activation values after CW layer for training set instances") get_activations_CWlayer(args, train_loader_with_path, model, args.whitened_layers, args.type_training, 72) print("Save activation values after CW layer for test set instances") get_activations_CWlayer(args, test_loader_with_path, model, args.whitened_layers, args.type_training, 72) elif args.type_training == 'evaluate': # create path links to data directories testdir = os.path.join(args.data, 'test') conceptdir_test = os.path.join(args.data, 'concept_test') # create balanced data loader for the test set using class weights calculated on the test set test_loader = create_data_loader(testdir, False) # create another data loader for the test set that includes the image paths test_loader_with_path = torch.utils.data.DataLoader( ImageFolderWithPaths(testdir, transforms.Compose([transforms.ToTensor(), ])), batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=False) model = load_deepmir_model(args, whitened_layer=args.whitened_layers, checkpoint_name=args.checkpoint_name) print("Start testing") validate(test_loader, model, criterion) print("Start Plotting") if not os.path.exists('./plot/' + '_'.join(args.concepts.split(','))): os.mkdir('./plot/' + '_'.join(args.concepts.split(','))) plot_figures(args, model, test_loader_with_path, conceptdir_test) def create_data_loader(directory, shuffle): """ :param directory: folder (or directory) where data is stored :param shuffle: where the data should be shuffled by the loader :return: torch data loader object """ data_loader = torch.utils.data.DataLoader( datasets.ImageFolder(directory, transforms.Compose([transforms.ToTensor(), ])), batch_size=args.batch_size, shuffle=shuffle, num_workers=args.workers, pin_memory=False) return data_loader def train(train_loader, concept_loaders, model, criterion, optimizer, epoch): """ :param train_loader: data loader with training images :param concept_loaders: data loader with concept images of training set :param model: model used for training :param criterion: loss function :param optimizer: optimizer :param epoch: current training epoch :return: training script """ batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input_img, target) in enumerate(train_loader): # after 30 images, switch to evaluation mode if (i + 1) % 30 == 0: model.eval() with torch.no_grad(): # update the gradient matrix G by aligning concepts with the latent space axes for concept_index, concept_loader in enumerate(concept_loaders): # change to concept aligning mode model.module.change_mode(concept_index) for j, (X, _) in enumerate(concept_loader): X_var = torch.autograd.Variable(X) model(X_var) break model.module.update_rotation_matrix() # change to ordinary training mode model.module.change_mode(-1) # induce training again model.train() # measure data loading time data_time.update(time.time() - end) # create autograd variables of the input and target so that hooks (forward and backward) can be used # the hooks are used to track the gradient updates in layers that have hooks input_var = torch.autograd.Variable(input_img) target_var = torch.autograd.Variable(target) output = model(input_var) # compute model predictions_test # activate these lines in case of model with 1 predictions_test neuron # target_var = target_var.unsqueeze(1) # target_var = target_var.float() # ########### loss = criterion(output, target_var) # update the loss function # measure accuracy and record loss [acc] = accuracy(output.data, target, topk=(1,)) losses.update(loss.data, input_img.size(0)) top1.update(acc.item(), input_img.size(0)) # compute gradient and do loss step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print(f'Epoch: [{epoch}][{i}/{len(train_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' f'Loss {losses.val:.4f} ({losses.avg:.4f})\t' f'Accuracy {top1.val:.3f} ({top1.avg:.3f})') print(' * Accuracy {top1.avg:.3f}'.format(top1=top1)) return top1.avg, losses.avg def validate(test_loader, model, criterion): """ :param test_loader: data loader containing the test/validation set images :param model: model used for validation :param criterion: loss function :return: validation script """ batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() # switch to evaluate mode model.eval() end = time.time() # initialize empty list for storing predictions predictions = [] with torch.no_grad(): for i, (input_img, target) in enumerate(test_loader): # create autograd variables of the input and target so that hooks (forward and backward) can be used # the hooks are used to track the gradient updates in layers that have hooks input_var = torch.autograd.Variable(input_img) target_var = torch.autograd.Variable(target) output = model(input_var) # compute model predictions_test # save the predictions in case we are dealing with the test set (they are used for explainability) if (args.type_training == 'evaluate') or (args.type_training == 'activations_tree_train'): predictions.append(output.data.detach().numpy()) # activate these lines in case of model with 1 predictions_test neuron # target_var = target_var.unsqueeze(1) # target_var = target_var.float() # ########### loss = criterion(output, target_var) # update the loss function # measure accuracy and record loss [acc] = accuracy(output.data, target, topk=(1,)) losses.update(loss.data, input_img.size(0)) top1.update(acc.item(), input_img.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print(f'Test: [{i}/{len(test_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Loss {losses.val:.4f} ({losses.avg:.4f})\t' f'Accuracy {top1.val:.3f} ({top1.avg:.3f})') print(' * Accuracy {top1.avg:.3f}'.format(top1=top1)) # save the predictions in case we are dealing with the test set (they are used for explainability) if args.type_training == 'evaluate': dst = './output/predictions/' + '_'.join(args.concepts.split(',')) + '/' if not os.path.exists(dst): os.mkdir(dst) # save predictions for creating decision tree / decision rules np.save(dst + 'predictions_test', predictions) elif args.type_training == 'get_activations_train': dst = './output/predictions/' + '_'.join(args.concepts.split(',')) + '/' if not os.path.exists(dst): os.mkdir(dst) # save predictions for creating decision tree / decision rules np.save(dst + 'predictions_train', predictions) return top1.avg, losses.avg def train_baseline(train_loader, model, criterion, optimizer, epoch): """ :param train_loader: data loader with training images :param model: model used for training :param criterion: loss function :param optimizer: optimizer :param epoch: current training epoch :return: baseline training script used for pretraining and fine-tuning of deepmir model """ batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input_img, target) in enumerate(train_loader): # measure data loading time data_time.update(time.time() - end) # create autograd variables of the input and target so that hooks (forward and backward) can be used # the hooks are used to track the gradient updates in layers that have hooks input_var = torch.autograd.Variable(input_img) target_var = torch.autograd.Variable(target) output = model(input_var) # compute model predictions_test # activate these lines in case of model with 1 predictions_test neuron # target_var = target_var.unsqueeze(1) # target_var = target_var.float() # ########### loss = criterion(output, target_var) # update the loss function # measure accuracy and record loss [acc] = accuracy(output.data, target, topk=(1,)) losses.update(loss.data, input_img.size(0)) top1.update(acc.item(), input_img.size(0)) # compute gradient and do loss step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print(f'Epoch: [{epoch}][{i}/{len(train_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' f'Loss {losses.val:.4f} ({losses.avg:.4f})\t' f'Accuracy {top1.val:.3f} ({top1.avg:.3f})') return losses.avg, top1.avg def plot_figures(arguments, model, test_loader_with_path, conceptdir): """ :param arguments: arguments given by user :param model: model used for training :param test_loader_with_path: data loader with test images (including path) :param conceptdir: directory containing concept images from test set :return: visualizations (correlation matrix, highly activated images, concept pureness, etc.) of CW results """ concept_name = arguments.concepts.split(',') dst = './plot/' + '_'.join(args.concepts.split(',')) + '/' + args.arch + '/' if not os.path.exists(dst): os.mkdir(dst) # if using the ordinary model without cw, just plot the correlation matrix in the BN layer if args.arch == "deepmir_v2_cw" or args.arch == "deepmir_vfinal_cw": # TODO: add here the pretty labels for the x and y axes of the plots (with newline...) # ticklabels_xaxis = ['Large\nterminal\nloop', 'At least\n90% base\npairs and\nwobbles in\nstem', # 'Large\nasymmetric\nbulge\ninstead\nof terminal\nloop', 'Large\nasymmetric\nbulge', # 'U-G-U\nmotif', 'A-U pairs\nmotif'] ticklabels_xaxis = ['Large asymmetric bulge', 'At least 90% base\npairs and wobbles in\nstem'] # ticklabels_yaxis = ['Large terminal\nloop', 'At least 90%\nbase pairs and\nwobbles in stem', # 'Large asymmetric\nbulge instead\nof terminal loop', 'Large asymmetric\nbulge', # 'U-G-U motif', 'A-U pairs motif'] ticklabels_yaxis = ['Large\nasymmetric\nbulge', 'At least\n90% base\npairs and\nwobbles in\nstem'] print("Plot correlation in CW layer of CW model") plot_correlation(dst, args, test_loader_with_path, model, args.whitened_layers) print("Collect 50 most activated images and plot the top 10") # False is if you want the top50 concept images for the whitened layer and the assigned neuron, # otherwise you can say for which layer neuron in that layer you want the top 50 plot_concept_top50(args, test_loader_with_path, model, args.whitened_layers, False, args.act_mode, dst) plot_top10(args.concepts.split(','), args.whitened_layers, args.type_training, dst) # use below if you want to get the most activated images for another neuron (and specify which neuron) plot_concept_top50(args, test_loader_with_path, model, args.whitened_layers, 4, args.act_mode, dst) plot_concept_top50(args, test_loader_with_path, model, args.whitened_layers, 36, args.act_mode, dst) print("Plot intra- and inter-concept similarities") intra_concept_dot_product_vs_inter_concept_dot_product(args, conceptdir, args.whitened_layers, args.concepts.split(','), 'deepmir_vfinal_cw', model, ticklabels_xaxis, ticklabels_yaxis) print("Plot AUC-concept_purity") plot_auc_cw(args, conceptdir, whitened_layers=args.whitened_layers, plot_cpt=concept_name, activation_mode=args.act_mode, concept_labels=ticklabels_xaxis) print("Plot receptive field over most activated img") saliency_map_concept_cover(args, args.whitened_layers, num_concepts=len(args.concepts.split(',')), model=model) # one below is for checking the other neurons in the layer that are not aligned with concepts # nodes variable is for the highly activated neurons one wants to check # give the list of neurons from the lowest to the highest first number of the neuron index saliency_map_cover_most_activated_neuron(args, args.whitened_layers, 4, [36, 4], model) saliency_map_cover_most_activated_neuron(args, args.whitened_layers, 36, [36, 4], model) def save_checkpoint(state, is_best, prefix, checkpoint_folder='./checkpoints', fold_n=None): """ :param state: model state with weight dictionary :param is_best: boolean specifying whether model is the best based on accuracy :param prefix: name to be used for stored object :param checkpoint_folder: folder where checkpoint needs to be stored :param fold_n: current fold in k-fold cross validation :return: storage of weights (checkpoint) of model in checkpoint folder """ if args.type_training == 'pretrain' or args.type_training == 'finetune': if not os.path.exists(os.path.join(checkpoint_folder, args.arch)): os.mkdir(os.path.join(checkpoint_folder, args.arch)) filename = os.path.join(checkpoint_folder, args.arch, f'{prefix}_checkpoint.pth.tar') torch.save(state, filename) if is_best: shutil.copyfile(filename, os.path.join(checkpoint_folder, args.arch, f'{prefix}_model_best.pth.tar')) else: concept_name = '_'.join(args.concepts.split(',')) if not os.path.exists(os.path.join(checkpoint_folder, concept_name)): os.mkdir(os.path.join(checkpoint_folder, concept_name)) filename = os.path.join(checkpoint_folder, concept_name, f'{prefix}_foldn{str(fold_n)}_checkpoint.pth.tar') torch.save(state, filename) if is_best: shutil.copyfile(filename, os.path.join(checkpoint_folder, concept_name, f'{prefix}_foldn{str(fold_n)}_model_' f'best.pth.tar')) class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def adjust_learning_rate(arguments, optimizer, epoch): """ :param arguments: arguments given by user :param optimizer: optimizer :param epoch: current epoch :return: sets the learning rate to the initial LR decayed by 10 every 30 epochs """ print('old lr', arguments.lr) print('start epoch', args.start_epoch) lr = arguments.lr * (0.1 ** ((epoch - args.start_epoch) // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr print('new lr', lr) def accuracy(output, target, topk=(1,)): """ :param output: model predictions_test (prediction) :param target: target value (true) :param topk: specification for the number of additional instances that need accuracy calculation (top-k accuracy) :return: computes the precision@k for the specified values of k """ maxk = max(topk) batch_size = target.size(0) # for CrossEntropyLoss use below _, pred = output.topk(maxk, 1, True, True) # in case of 1 predictions_test node and BCEloss use below # pred = (predictions_test > 0.5).float() pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res def make_weights_for_balanced_classes(images, n_classes): """ :param images: images of dataset :param n_classes: number of classes in dataset :return: class weight for training data loader """ count = [0] * n_classes for item in images: count[item[1]] += 1 weight_per_class = [0.] * n_classes N = float(sum(count)) for i in range(n_classes): weight_per_class[i] = N / float(count[i]) weight = [0] * len(images) for idx, val in enumerate(images): weight[idx] = weight_per_class[val[1]] return weight def get_class_weights(images, n_classes): """ :param images: images of dataset :param n_classes: number of classes in dataset :return: class weights for test data loader """ count = [0] * n_classes for item in images: count[item[1]] += 1 weight_per_class = [0.] * n_classes N = float(sum(count)) for i in range(n_classes): weight_per_class[i] = N / (2 * float(count[i])) return weight_per_class def balanced_data_loader(arguments, dataset_dir): """ :param arguments: arguments given in training/evaluation initialization :param dataset_dir: directory where dataset is stored :return: data loader that uses balanced class weights to balance the data that is fed to the model """ dataset = datasets.ImageFolder(dataset_dir, transforms.Compose([transforms.ToTensor(), ])) # For unbalanced dataset we create a weighted sampler weights = make_weights_for_balanced_classes(dataset.imgs, len(dataset.classes)) weights = torch.DoubleTensor(weights) sampler = torch.utils.data.sampler.WeightedRandomSampler(weights, len(weights)) loader = torch.utils.data.DataLoader(dataset, batch_size=arguments.batch_size, shuffle=False, sampler=sampler, num_workers=arguments.workers, pin_memory=False) return loader if __name__ == '__main__': main()
[ "neptune.new.init" ]
[((283, 396), 'neptune.new.init', 'neptune.init', ([], {'project': '"""irmavdbrandt/Interpret-rna"""', 'api_token': 'neptune_key', 'source_files': "['train_premirna.py']"}), "(project='irmavdbrandt/Interpret-rna', api_token=neptune_key,\n source_files=['train_premirna.py'])\n", (295, 396), True, 'import neptune.new as neptune\n'), ((481, 545), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch premiRNA Training"""'}), "(description='PyTorch premiRNA Training')\n", (504, 545), False, 'import argparse\n'), ((20554, 20565), 'time.time', 'time.time', ([], {}), '()\n', (20563, 20565), False, 'import time\n'), ((23407, 23418), 'time.time', 'time.time', ([], {}), '()\n', (23416, 23418), False, 'import time\n'), ((26571, 26582), 'time.time', 'time.time', ([], {}), '()\n', (26580, 26582), False, 'import time\n'), ((22535, 22546), 'time.time', 'time.time', ([], {}), '()\n', (22544, 22546), False, 'import time\n'), ((27772, 27783), 'time.time', 'time.time', ([], {}), '()\n', (27781, 27783), False, 'import time\n'), ((24854, 24865), 'time.time', 'time.time', ([], {}), '()\n', (24863, 24865), False, 'import time\n'), ((21465, 21476), 'time.time', 'time.time', ([], {}), '()\n', (21474, 21476), False, 'import time\n'), ((22502, 22513), 'time.time', 'time.time', ([], {}), '()\n', (22511, 22513), False, 'import time\n'), ((26704, 26715), 'time.time', 'time.time', ([], {}), '()\n', (26713, 26715), False, 'import time\n'), ((27739, 27750), 'time.time', 'time.time', ([], {}), '()\n', (27748, 27750), False, 'import time\n'), ((24817, 24828), 'time.time', 'time.time', ([], {}), '()\n', (24826, 24828), False, 'import time\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import pathlib import shutil import tempfile import unittest from pathlib import Path from neptune.new.exceptions import ( NeptuneLocalStorageAccessException, NeptuneUnsupportedArtifactFunctionalityException, ) from neptune.new.internal.artifacts.drivers.local import LocalArtifactDriver from neptune.new.internal.artifacts.types import ( ArtifactDriversMap, ArtifactFileData, ArtifactFileType, ) from tests.neptune.new.internal.artifacts.utils import md5 class TestLocalArtifactDrivers(unittest.TestCase): test_dir = None def setUp(self): self.test_sources_dir = Path(str(tempfile.mktemp())) self.test_dir = Path(str(tempfile.mktemp())) test_source_data = ( Path(__file__).parents[5] / "data" / "local_artifact_drivers_data" ) test_data = self.test_dir / "data" # copy source data to temp dir (to prevent e.g. inter-fs symlinks) shutil.copytree(test_source_data, self.test_sources_dir) # create files to track shutil.copytree(self.test_sources_dir / "files_to_track", test_data) # symbolic and hard link files # `link_to` is new in python 3.8 # (test_source_data / 'file_to_link.txt').link_to(test_data / 'hardlinked_file.txt') os.link( src=str(self.test_sources_dir / "file_to_link.txt"), dst=str(test_data / "hardlinked_file.txt"), ) (test_data / "symlinked_file.txt").symlink_to( self.test_sources_dir / "file_to_link.txt" ) # symlink dir - content of this file won't be discovered (test_data / "symlinked_dir").symlink_to( self.test_sources_dir / "dir_to_link", target_is_directory=True ) def tearDown(self) -> None: # clean tmp directories shutil.rmtree(self.test_dir, ignore_errors=True) shutil.rmtree(self.test_sources_dir, ignore_errors=True) def test_match_by_path(self): self.assertEqual( ArtifactDriversMap.match_path("file:///path/to/"), LocalArtifactDriver ) self.assertEqual( ArtifactDriversMap.match_path("/path/to/"), LocalArtifactDriver ) def test_match_by_type(self): self.assertEqual(ArtifactDriversMap.match_type("Local"), LocalArtifactDriver) def test_file_download(self): path = (self.test_dir / "data/file1.txt").as_posix() artifact_file = ArtifactFileData( file_path="data/file1.txt", file_hash="??", type="??", metadata={"file_path": f"file://{path}"}, ) with tempfile.TemporaryDirectory() as temporary: downloaded_file = Path(temporary) / "downloaded_file.ext" LocalArtifactDriver.download_file( destination=downloaded_file, file_definition=artifact_file ) self.assertTrue(Path(downloaded_file).is_symlink()) self.assertEqual("ad62f265e5b1a2dc51f531e44e748aa0", md5(downloaded_file)) def test_non_existing_file_download(self): path = "/wrong/path" artifact_file = ArtifactFileData( file_path=path, file_hash="??", type="??", metadata={"file_path": path} ) with self.assertRaises( NeptuneLocalStorageAccessException ), tempfile.TemporaryDirectory() as temporary: local_destination = Path(temporary) LocalArtifactDriver.download_file( destination=local_destination, file_definition=artifact_file ) def test_single_retrieval(self): files = LocalArtifactDriver.get_tracked_files( str(self.test_dir / "data/file1.txt") ) self.assertEqual(1, len(files)) self.assertIsInstance(files[0], ArtifactFileData) self.assertEqual(ArtifactFileType.LOCAL.value, files[0].type) self.assertEqual("d2c24d65e1d3870f4cf2dbbd8c994b4977a7c384", files[0].file_hash) self.assertEqual("file1.txt", files[0].file_path) self.assertEqual(21, files[0].size) self.assertEqual({"file_path", "last_modified"}, files[0].metadata.keys()) self.assertEqual( f"file://{(self.test_dir.resolve() / 'data/file1.txt').as_posix()}", files[0].metadata["file_path"], ) self.assertIsInstance(files[0].metadata["last_modified"], str) def test_multiple_retrieval(self): files = LocalArtifactDriver.get_tracked_files(str(self.test_dir / "data")) files = sorted(files, key=lambda file: file.file_path) self.assertEqual(4, len(files)) self.assertEqual("file1.txt", files[0].file_path) self.assertEqual("d2c24d65e1d3870f4cf2dbbd8c994b4977a7c384", files[0].file_hash) self.assertEqual(21, files[0].size) self.assertEqual( f"file://{(self.test_dir.resolve() / 'data/file1.txt').as_posix()}", files[0].metadata["file_path"], ) self.assertEqual("hardlinked_file.txt", files[1].file_path) self.assertEqual("da3e6ddfa171e1ab5564609caa1dbbea9871886e", files[1].file_hash) self.assertEqual(44, files[1].size) self.assertEqual( f"file://{(self.test_dir.resolve() / 'data/hardlinked_file.txt').as_posix()}", files[1].metadata["file_path"], ) self.assertEqual("sub_dir/file_in_subdir.txt", files[2].file_path) self.assertEqual("98181b1a4c880a462fcfa96b92c84b8e945ac335", files[2].file_hash) self.assertEqual(24, files[2].size) self.assertEqual( f"file://{(self.test_dir.resolve() / 'data/sub_dir/file_in_subdir.txt').as_posix()}", files[2].metadata["file_path"], ) self.assertEqual("symlinked_file.txt", files[3].file_path) self.assertEqual("da3e6ddfa171e1ab5564609caa1dbbea9871886e", files[3].file_hash) self.assertEqual(44, files[3].size) self.assertEqual( f"file://{(self.test_sources_dir.resolve() / 'file_to_link.txt').as_posix()}", files[3].metadata["file_path"], ) def test_multiple_retrieval_prefix(self): files = LocalArtifactDriver.get_tracked_files( (self.test_dir / "data").as_posix(), "my/custom_path" ) files = sorted(files, key=lambda file: file.file_path) self.assertEqual(4, len(files)) self.assertEqual("my/custom_path/file1.txt", files[0].file_path) self.assertEqual("d2c24d65e1d3870f4cf2dbbd8c994b4977a7c384", files[0].file_hash) self.assertEqual(21, files[0].size) self.assertEqual( f"file://{(self.test_dir.resolve() / 'data/file1.txt').as_posix()}", files[0].metadata["file_path"], ) self.assertEqual("my/custom_path/hardlinked_file.txt", files[1].file_path) self.assertEqual("da3e6ddfa171e1ab5564609caa1dbbea9871886e", files[1].file_hash) self.assertEqual(44, files[1].size) self.assertEqual( f"file://{(self.test_dir.resolve() / 'data/hardlinked_file.txt').as_posix()}", files[1].metadata["file_path"], ) self.assertEqual( "my/custom_path/sub_dir/file_in_subdir.txt", files[2].file_path ) self.assertEqual("98181b1a4c880a462fcfa96b92c84b8e945ac335", files[2].file_hash) self.assertEqual(24, files[2].size) self.assertEqual( f"file://{(self.test_dir.resolve() / 'data/sub_dir/file_in_subdir.txt').as_posix()}", files[2].metadata["file_path"], ) self.assertEqual("my/custom_path/symlinked_file.txt", files[3].file_path) self.assertEqual("da3e6ddfa171e1ab5564609caa1dbbea9871886e", files[3].file_hash) self.assertEqual(44, files[3].size) self.assertEqual( f"file://{(self.test_sources_dir.resolve() / 'file_to_link.txt').as_posix()}", files[3].metadata["file_path"], ) def test_expand_user(self): os.environ["HOME"] = str(self.test_dir.resolve()) with open(pathlib.Path("~/tmp_test_expand_user").expanduser(), "w") as f: f.write("File to test ~ resolution") files = LocalArtifactDriver.get_tracked_files("~/tmp_test_expand_user") self.assertEqual(1, len(files)) file = files[0] self.assertEqual("tmp_test_expand_user", file.file_path) self.assertEqual("eb596bf2f5fd0461d3d0b432f805b3984786c721", file.file_hash) self.assertEqual(25, file.size) def test_wildcards_not_supported(self): with self.assertRaises(NeptuneUnsupportedArtifactFunctionalityException): LocalArtifactDriver.get_tracked_files(str(self.test_dir / "data/*.txt"))
[ "neptune.new.internal.artifacts.types.ArtifactDriversMap.match_path", "neptune.new.internal.artifacts.drivers.local.LocalArtifactDriver.download_file", "neptune.new.internal.artifacts.types.ArtifactFileData", "neptune.new.internal.artifacts.drivers.local.LocalArtifactDriver.get_tracked_files", "neptune.new....
[((1537, 1593), 'shutil.copytree', 'shutil.copytree', (['test_source_data', 'self.test_sources_dir'], {}), '(test_source_data, self.test_sources_dir)\n', (1552, 1593), False, 'import shutil\n'), ((1635, 1703), 'shutil.copytree', 'shutil.copytree', (["(self.test_sources_dir / 'files_to_track')", 'test_data'], {}), "(self.test_sources_dir / 'files_to_track', test_data)\n", (1650, 1703), False, 'import shutil\n'), ((2421, 2469), 'shutil.rmtree', 'shutil.rmtree', (['self.test_dir'], {'ignore_errors': '(True)'}), '(self.test_dir, ignore_errors=True)\n', (2434, 2469), False, 'import shutil\n'), ((2478, 2534), 'shutil.rmtree', 'shutil.rmtree', (['self.test_sources_dir'], {'ignore_errors': '(True)'}), '(self.test_sources_dir, ignore_errors=True)\n', (2491, 2534), False, 'import shutil\n'), ((3042, 3159), 'neptune.new.internal.artifacts.types.ArtifactFileData', 'ArtifactFileData', ([], {'file_path': '"""data/file1.txt"""', 'file_hash': '"""??"""', 'type': '"""??"""', 'metadata': "{'file_path': f'file://{path}'}"}), "(file_path='data/file1.txt', file_hash='??', type='??',\n metadata={'file_path': f'file://{path}'})\n", (3058, 3159), False, 'from neptune.new.internal.artifacts.types import ArtifactDriversMap, ArtifactFileData, ArtifactFileType\n'), ((3733, 3827), 'neptune.new.internal.artifacts.types.ArtifactFileData', 'ArtifactFileData', ([], {'file_path': 'path', 'file_hash': '"""??"""', 'type': '"""??"""', 'metadata': "{'file_path': path}"}), "(file_path=path, file_hash='??', type='??', metadata={\n 'file_path': path})\n", (3749, 3827), False, 'from neptune.new.internal.artifacts.types import ArtifactDriversMap, ArtifactFileData, ArtifactFileType\n'), ((8795, 8858), 'neptune.new.internal.artifacts.drivers.local.LocalArtifactDriver.get_tracked_files', 'LocalArtifactDriver.get_tracked_files', (['"""~/tmp_test_expand_user"""'], {}), "('~/tmp_test_expand_user')\n", (8832, 8858), False, 'from neptune.new.internal.artifacts.drivers.local import LocalArtifactDriver\n'), ((2608, 2657), 'neptune.new.internal.artifacts.types.ArtifactDriversMap.match_path', 'ArtifactDriversMap.match_path', (['"""file:///path/to/"""'], {}), "('file:///path/to/')\n", (2637, 2657), False, 'from neptune.new.internal.artifacts.types import ArtifactDriversMap, ArtifactFileData, ArtifactFileType\n'), ((2727, 2769), 'neptune.new.internal.artifacts.types.ArtifactDriversMap.match_path', 'ArtifactDriversMap.match_path', (['"""/path/to/"""'], {}), "('/path/to/')\n", (2756, 2769), False, 'from neptune.new.internal.artifacts.types import ArtifactDriversMap, ArtifactFileData, ArtifactFileType\n'), ((2861, 2899), 'neptune.new.internal.artifacts.types.ArtifactDriversMap.match_type', 'ArtifactDriversMap.match_type', (['"""Local"""'], {}), "('Local')\n", (2890, 2899), False, 'from neptune.new.internal.artifacts.types import ArtifactDriversMap, ArtifactFileData, ArtifactFileType\n'), ((3229, 3258), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3256, 3258), False, 'import tempfile\n'), ((3356, 3453), 'neptune.new.internal.artifacts.drivers.local.LocalArtifactDriver.download_file', 'LocalArtifactDriver.download_file', ([], {'destination': 'downloaded_file', 'file_definition': 'artifact_file'}), '(destination=downloaded_file,\n file_definition=artifact_file)\n', (3389, 3453), False, 'from neptune.new.internal.artifacts.drivers.local import LocalArtifactDriver\n'), ((3936, 3965), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3963, 3965), False, 'import tempfile\n'), ((4012, 4027), 'pathlib.Path', 'Path', (['temporary'], {}), '(temporary)\n', (4016, 4027), False, 'from pathlib import Path\n'), ((4040, 4139), 'neptune.new.internal.artifacts.drivers.local.LocalArtifactDriver.download_file', 'LocalArtifactDriver.download_file', ([], {'destination': 'local_destination', 'file_definition': 'artifact_file'}), '(destination=local_destination,\n file_definition=artifact_file)\n', (4073, 4139), False, 'from neptune.new.internal.artifacts.drivers.local import LocalArtifactDriver\n'), ((1219, 1236), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (1234, 1236), False, 'import tempfile\n'), ((1272, 1289), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (1287, 1289), False, 'import tempfile\n'), ((3303, 3318), 'pathlib.Path', 'Path', (['temporary'], {}), '(temporary)\n', (3307, 3318), False, 'from pathlib import Path\n'), ((3610, 3630), 'tests.neptune.new.internal.artifacts.utils.md5', 'md5', (['downloaded_file'], {}), '(downloaded_file)\n', (3613, 3630), False, 'from tests.neptune.new.internal.artifacts.utils import md5\n'), ((1333, 1347), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1337, 1347), False, 'from pathlib import Path\n'), ((3509, 3530), 'pathlib.Path', 'Path', (['downloaded_file'], {}), '(downloaded_file)\n', (3513, 3530), False, 'from pathlib import Path\n'), ((8665, 8703), 'pathlib.Path', 'pathlib.Path', (['"""~/tmp_test_expand_user"""'], {}), "('~/tmp_test_expand_user')\n", (8677, 8703), False, 'import pathlib\n')]
import images as images import numpy as np import pandas as pd import xgboost as xgb from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error as mse from sklearn.model_selection import train_test_split from sklearn.multioutput import MultiOutputRegressor import pickle import neptune import os token = os.getenv('NEPTUNE_API_TOKEN') upload = False if token: print('Uploading results') neptune.init(project_qualified_name='piotrt/hsqc', api_token=os.getenv('NEPTUNE_API_TOKEN')) neptune.create_experiment(name='xgboost') upload = True else: print('NEPTUNE_API_TOKEN not specified in the shell, not uploading results') data_files = images.get_data_files() print(len(data_files)) x_all = np.ndarray(shape=(len(data_files), images.target_height*images.target_width*images.channels), dtype=np.uint8) y_all = np.ndarray(shape=(len(data_files), 5), dtype=np.float32) i = 0 no_file = len(data_files) for file in data_files: print(i,'/', no_file, ' File:',str(file)) #extract data scaled down to 224x224 x_all[i] = np.array(np.ravel(images.preprocess_image(file))) #extract required output y_all[i] = np.array(images.extract_values(file)).astype(np.float32) i+=1 X = pd.DataFrame(data=x_all, index=None, columns=None) y = pd.DataFrame(data=y_all, index=None, columns=images.value_names) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, shuffle=True) xgb_reg = MultiOutputRegressor(xgb.XGBRegressor(verbosity=3, tree_method='gpu_hist', gpu_id=0)) print(xgb_reg) print(X_train.shape) print(y_train.shape) xgb_reg.fit(X_train, y_train) y_pred = xgb_reg.predict(X_test) # Predictions y_true = y_test # True values MSE = mse(y_true, y_pred) RMSE = np.sqrt(MSE) R_squared = r2_score(y_true, y_pred) if upload: neptune.log_metric("RMSE", np.round(RMSE, 2)) print("\nRMSE: ", np.round(RMSE, 2)) print() print("R-Squared: ", np.round(R_squared, 2)) actual = pd.DataFrame(data=y_true, index=None, columns=images.value_names) predicted = pd.DataFrame(data=y_pred, index=None, columns=images.pred_names) actual.to_csv('actxgboost.csv') predicted.to_csv('predxgboost.csv') pickle.dump(xgb_reg, open("xgboost.dat", "wb")) if upload: neptune.log_artifact('actxgboost.csv') neptune.log_artifact('predxgboost.csv') neptune.stop()
[ "neptune.stop", "neptune.create_experiment", "neptune.log_artifact" ]
[((330, 360), 'os.getenv', 'os.getenv', (['"""NEPTUNE_API_TOKEN"""'], {}), "('NEPTUNE_API_TOKEN')\n", (339, 360), False, 'import os\n'), ((680, 703), 'images.get_data_files', 'images.get_data_files', ([], {}), '()\n', (701, 703), True, 'import images as images\n'), ((1235, 1285), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'x_all', 'index': 'None', 'columns': 'None'}), '(data=x_all, index=None, columns=None)\n', (1247, 1285), True, 'import pandas as pd\n'), ((1290, 1354), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'y_all', 'index': 'None', 'columns': 'images.value_names'}), '(data=y_all, index=None, columns=images.value_names)\n', (1302, 1354), True, 'import pandas as pd\n'), ((1391, 1459), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(42)', 'shuffle': '(True)'}), '(X, y, test_size=0.2, random_state=42, shuffle=True)\n', (1407, 1459), False, 'from sklearn.model_selection import train_test_split\n'), ((1732, 1751), 'sklearn.metrics.mean_squared_error', 'mse', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (1735, 1751), True, 'from sklearn.metrics import mean_squared_error as mse\n'), ((1760, 1772), 'numpy.sqrt', 'np.sqrt', (['MSE'], {}), '(MSE)\n', (1767, 1772), True, 'import numpy as np\n'), ((1786, 1810), 'sklearn.metrics.r2_score', 'r2_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (1794, 1810), False, 'from sklearn.metrics import r2_score\n'), ((1976, 2041), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'y_true', 'index': 'None', 'columns': 'images.value_names'}), '(data=y_true, index=None, columns=images.value_names)\n', (1988, 2041), True, 'import pandas as pd\n'), ((2054, 2118), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'y_pred', 'index': 'None', 'columns': 'images.pred_names'}), '(data=y_pred, index=None, columns=images.pred_names)\n', (2066, 2118), True, 'import pandas as pd\n'), ((519, 560), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""xgboost"""'}), "(name='xgboost')\n", (544, 560), False, 'import neptune\n'), ((1492, 1555), 'xgboost.XGBRegressor', 'xgb.XGBRegressor', ([], {'verbosity': '(3)', 'tree_method': '"""gpu_hist"""', 'gpu_id': '(0)'}), "(verbosity=3, tree_method='gpu_hist', gpu_id=0)\n", (1508, 1555), True, 'import xgboost as xgb\n'), ((1892, 1909), 'numpy.round', 'np.round', (['RMSE', '(2)'], {}), '(RMSE, 2)\n', (1900, 1909), True, 'import numpy as np\n'), ((1942, 1964), 'numpy.round', 'np.round', (['R_squared', '(2)'], {}), '(R_squared, 2)\n', (1950, 1964), True, 'import numpy as np\n'), ((2250, 2288), 'neptune.log_artifact', 'neptune.log_artifact', (['"""actxgboost.csv"""'], {}), "('actxgboost.csv')\n", (2270, 2288), False, 'import neptune\n'), ((2293, 2332), 'neptune.log_artifact', 'neptune.log_artifact', (['"""predxgboost.csv"""'], {}), "('predxgboost.csv')\n", (2313, 2332), False, 'import neptune\n'), ((2337, 2351), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (2349, 2351), False, 'import neptune\n'), ((1854, 1871), 'numpy.round', 'np.round', (['RMSE', '(2)'], {}), '(RMSE, 2)\n', (1862, 1871), True, 'import numpy as np\n'), ((483, 513), 'os.getenv', 'os.getenv', (['"""NEPTUNE_API_TOKEN"""'], {}), "('NEPTUNE_API_TOKEN')\n", (492, 513), False, 'import os\n'), ((1088, 1117), 'images.preprocess_image', 'images.preprocess_image', (['file'], {}), '(file)\n', (1111, 1117), True, 'import images as images\n'), ((1173, 1200), 'images.extract_values', 'images.extract_values', (['file'], {}), '(file)\n', (1194, 1200), True, 'import images as images\n')]
import json import pandas as pd import lightgbm as lgb from loguru import logger from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split import neptune from neptunecontrib.monitoring.lightgbm import neptune_monitor from src.utils.read_params import read_params if __name__ == '__main__': logger.add("logs/logs_lgbm.txt", level="TRACE", rotation="10 KB") with logger.catch(): with open("params/neptune.json") as json_file: neptune_init = json.load(json_file) neptune.init( project_qualified_name=neptune_init['project_name'], api_token=neptune_init['api_token'], ) param = read_params() df = pd.read_csv("data/interim/train_scaled.csv") train_df, valid_df = train_test_split(df, test_size=0.4, random_state=42) target = 'target' features = param['features'] params = { 'objective': 'regression', 'seed': 42, 'metric': 'rmse', 'learning_rate': 0.05, 'max_bin': 800, 'num_leaves': 80, 'min_child_samples': train_df.shape[0] // 50, } tr_data = lgb.Dataset(train_df[features], label=train_df[target]) va_data = lgb.Dataset(valid_df[features], label=valid_df[target]) evals_result = {} # Record training results experiment = neptune.create_experiment( name='lgb', tags=['train'], params=params, properties={'target': target, 'features': ', '.join(features)} ) monitor = neptune_monitor() model = lgb.train( params, tr_data, num_boost_round=5000, valid_sets=[tr_data, va_data], evals_result=evals_result, early_stopping_rounds=100, verbose_eval=100, callbacks=[monitor], ) model.save_model('models/lgbm/model.txt') ax = lgb.plot_importance(model, importance_type='gain') experiment.log_image('importance', plt.gcf()) neptune.stop()
[ "neptune.stop", "neptune.init" ]
[((329, 394), 'loguru.logger.add', 'logger.add', (['"""logs/logs_lgbm.txt"""'], {'level': '"""TRACE"""', 'rotation': '"""10 KB"""'}), "('logs/logs_lgbm.txt', level='TRACE', rotation='10 KB')\n", (339, 394), False, 'from loguru import logger\n'), ((404, 418), 'loguru.logger.catch', 'logger.catch', ([], {}), '()\n', (416, 418), False, 'from loguru import logger\n'), ((531, 638), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': "neptune_init['project_name']", 'api_token': "neptune_init['api_token']"}), "(project_qualified_name=neptune_init['project_name'], api_token\n =neptune_init['api_token'])\n", (543, 638), False, 'import neptune\n'), ((686, 699), 'src.utils.read_params.read_params', 'read_params', ([], {}), '()\n', (697, 699), False, 'from src.utils.read_params import read_params\n'), ((714, 758), 'pandas.read_csv', 'pd.read_csv', (['"""data/interim/train_scaled.csv"""'], {}), "('data/interim/train_scaled.csv')\n", (725, 758), True, 'import pandas as pd\n'), ((788, 840), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df'], {'test_size': '(0.4)', 'random_state': '(42)'}), '(df, test_size=0.4, random_state=42)\n', (804, 840), False, 'from sklearn.model_selection import train_test_split\n'), ((1199, 1254), 'lightgbm.Dataset', 'lgb.Dataset', (['train_df[features]'], {'label': 'train_df[target]'}), '(train_df[features], label=train_df[target])\n', (1210, 1254), True, 'import lightgbm as lgb\n'), ((1273, 1328), 'lightgbm.Dataset', 'lgb.Dataset', (['valid_df[features]'], {'label': 'valid_df[target]'}), '(valid_df[features], label=valid_df[target])\n', (1284, 1328), True, 'import lightgbm as lgb\n'), ((1613, 1630), 'neptunecontrib.monitoring.lightgbm.neptune_monitor', 'neptune_monitor', ([], {}), '()\n', (1628, 1630), False, 'from neptunecontrib.monitoring.lightgbm import neptune_monitor\n'), ((1648, 1828), 'lightgbm.train', 'lgb.train', (['params', 'tr_data'], {'num_boost_round': '(5000)', 'valid_sets': '[tr_data, va_data]', 'evals_result': 'evals_result', 'early_stopping_rounds': '(100)', 'verbose_eval': '(100)', 'callbacks': '[monitor]'}), '(params, tr_data, num_boost_round=5000, valid_sets=[tr_data,\n va_data], evals_result=evals_result, early_stopping_rounds=100,\n verbose_eval=100, callbacks=[monitor])\n', (1657, 1828), True, 'import lightgbm as lgb\n'), ((1992, 2042), 'lightgbm.plot_importance', 'lgb.plot_importance', (['model'], {'importance_type': '"""gain"""'}), "(model, importance_type='gain')\n", (2011, 2042), True, 'import lightgbm as lgb\n'), ((2106, 2120), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (2118, 2120), False, 'import neptune\n'), ((502, 522), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (511, 522), False, 'import json\n'), ((2086, 2095), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (2093, 2095), True, 'from matplotlib import pyplot as plt\n')]
# -*- coding: utf-8 -*- import argparse import sys import time from datetime import datetime import neptune import torch import numpy as np from torch.utils.data import SequentialSampler, RandomSampler import pandas as pd sys.path.insert(0, '.') from configs import CONFIGS # noqa from src.dataset import DatasetRetriever # noqa from src.converters import CTCLabeling, AttnLabeling # noqa from src.model import Model # noqa from src.experiment import OCRExperiment # noqa from src import utils # noqa from src.predictor import Predictor # noqa from src.metrics import string_accuracy, cer, wer # noqa if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run train script.') parser.add_argument('--checkpoint_path', type=str) parser.add_argument('--experiment_name', type=str) parser.add_argument('--experiment_description', type=str) parser.add_argument('--neptune_project', type=str) parser.add_argument('--neptune_token', type=str) parser.add_argument('--data_dir', type=str) parser.add_argument('--output_dir', type=str) parser.add_argument('--dataset_name', type=str) parser.add_argument('--image_w', type=int) parser.add_argument('--image_h', type=int) parser.add_argument('--num_epochs', type=int) parser.add_argument('--bs', type=int) parser.add_argument('--num_workers', type=int) parser.add_argument('--seed', type=int, default=6955) parser.add_argument('--use_progress_bar', type=int, default=0) parser.add_argument('--FeatureExtraction', type=str) parser.add_argument('--SequenceModeling', type=str) # parser.add_argument('--Transformation', type=str, default='None') parser.add_argument('--Prediction', type=str, default='CTC') parser.add_argument('--batch_max_length', type=int, default=100) parser.add_argument('--input_channel', type=int, default=3) parser.add_argument('--output_channel', type=int, default=256) parser.add_argument('--hidden_size', type=int, default=256) parser.add_argument('--num_fiducial', type=int, default=20, help='number of fiducial points of TPS-STN') args = parser.parse_args() assert args.dataset_name in CONFIGS if args.checkpoint_path: seed = round(datetime.utcnow().timestamp()) % 10000 # warning! in resume need change seed else: seed = args.seed utils.seed_everything(seed) config = CONFIGS[args.dataset_name]( data_dir=args.data_dir, experiment_name=args.experiment_name, experiment_description=args.experiment_description, image_w=args.image_w, image_h=args.image_h, num_epochs=args.num_epochs, bs=args.bs, num_workers=args.num_workers, seed=seed, batch_max_length=args.batch_max_length, FeatureExtraction=args.FeatureExtraction, SequenceModeling=args.SequenceModeling, Prediction=args.Prediction, Transformation=args.Transformation, ) device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu') print('DEVICE:', device) print('DATASET:', args.dataset_name) if args.Prediction == 'Attn': converter = AttnLabeling(config) elif args.Prediction == 'CTC': converter = CTCLabeling(config) else: raise ValueError('Unknown type of prediction') args.num_class = len(converter.chars) args.imgH = args.image_h args.imgW = args.image_w df = pd.read_csv(f'{args.data_dir}/{args.dataset_name}/marking.csv', index_col='sample_id') train_dataset = DatasetRetriever(df[df['stage'] == 'train'], config, converter) valid_dataset = DatasetRetriever(df[df['stage'] == 'valid'], config, converter) test_dataset = DatasetRetriever(df[df['stage'] == 'test'], config, converter) def count_parameters(model): total_params = 0 for name, parameter in model.named_parameters(): if not parameter.requires_grad: continue param = parameter.numel() total_params += param print(f"Total Trainable Params: {total_params}") return total_params model = Model(args) count_parameters(model) print(model) model = model.to(device) if args.Prediction == 'Attn': criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device) elif args.Prediction == 'CTC': criterion = torch.nn.CTCLoss(zero_infinity=True).to(device) else: raise ValueError('Unknown type of prediction') optimizer = torch.optim.AdamW(model.parameters(), **config['optimizer']['params']) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=config['bs'], sampler=RandomSampler(train_dataset), pin_memory=False, drop_last=True, num_workers=config['num_workers'], collate_fn=utils.kw_collate_fn ) valid_loader = torch.utils.data.DataLoader( valid_dataset, batch_size=config['bs'], sampler=SequentialSampler(valid_dataset), pin_memory=False, drop_last=False, num_workers=config['num_workers'], collate_fn=utils.kw_collate_fn ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=config['bs'], sampler=SequentialSampler(test_dataset), pin_memory=False, drop_last=False, num_workers=config['num_workers'], collate_fn=utils.kw_collate_fn ) scheduler = torch.optim.lr_scheduler.OneCycleLR( optimizer, epochs=config['num_epochs'], steps_per_epoch=len(train_loader), **config['scheduler']['params'], ) neptune_kwargs = {} if args.neptune_project: neptune.init( project_qualified_name=args.neptune_project, api_token=args.neptune_token, ) neptune_kwargs = dict( neptune=neptune, neptune_params={ 'description': config['experiment_description'], 'params': config.params, } ) if not args.checkpoint_path: experiment = OCRExperiment( experiment_name=config['experiment_name'], model=model, optimizer=optimizer, criterion=criterion, scheduler=scheduler, device=device, base_dir=args.output_dir, best_saving={'cer': 'min', 'wer': 'min', 'acc': 'max'}, last_saving=True, low_memory=True, verbose_step=10**5, seed=seed, use_progress_bar=bool(args.use_progress_bar), **neptune_kwargs, converter=converter, config=config, ) experiment.fit(train_loader, valid_loader, config['num_epochs']) else: print('RESUMED FROM:', args.checkpoint_path) experiment = OCRExperiment.resume( checkpoint_path=args.checkpoint_path, train_loader=train_loader, valid_loader=valid_loader, n_epochs=config['num_epochs'], model=model, optimizer=optimizer, criterion=criterion, scheduler=scheduler, device=device, seed=seed, neptune=neptune_kwargs.get('neptune'), converter=converter, config=config, ) time_inference = [] for best_metric in ['best_cer', 'best_wer', 'best_acc', 'last']: experiment.load(f'{experiment.experiment_dir}/{best_metric}.pt') experiment.model.eval() predictor = Predictor(experiment.model, device) time_a = time.time() predictions = predictor.run_inference(test_loader) time_b = time.time() time_inference.append(time_b - time_a) df_pred = pd.DataFrame([{ 'id': prediction['id'], 'pred_text': converter.decode(prediction['raw_output'].argmax(1)), 'gt_text': prediction['gt_text'] } for prediction in predictions]).set_index('id') cer_metric = round(cer(df_pred['pred_text'], df_pred['gt_text']), 5) wer_metric = round(wer(df_pred['pred_text'], df_pred['gt_text']), 5) acc_metric = round(string_accuracy(df_pred['pred_text'], df_pred['gt_text']), 5) if args.neptune_project: experiment.neptune.log_metric(f'cer_test__{best_metric}', cer_metric) experiment.neptune.log_metric(f'wer_test__{best_metric}', wer_metric) experiment.neptune.log_metric(f'acc_test__{best_metric}', acc_metric) mistakes = df_pred[df_pred['pred_text'] != df_pred['gt_text']] df_pred.to_csv(f'{experiment.experiment_dir}/pred__{best_metric}.csv') if args.neptune_project: experiment.neptune.log_metric(f'mistakes__{best_metric}', mistakes.shape[0]) experiment.neptune.log_artifact(f'{experiment.experiment_dir}/pred__{best_metric}.csv') experiment._log( # noqa f'Results for {best_metric}.pt.', cer=cer_metric, wer=wer_metric, acc=acc_metric, speed_inference=len(test_dataset) / (time_b - time_a), ) if args.neptune_project: experiment.neptune.log_metric('time_inference', np.mean(time_inference)) experiment.neptune.log_metric('speed_inference', len(test_dataset) / np.mean(time_inference)) # sample / sec experiment.destroy()
[ "neptune.init" ]
[((224, 247), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""."""'], {}), "(0, '.')\n", (239, 247), False, 'import sys\n'), ((654, 710), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run train script."""'}), "(description='Run train script.')\n", (677, 710), False, 'import argparse\n'), ((2370, 2397), 'src.utils.seed_everything', 'utils.seed_everything', (['seed'], {}), '(seed)\n', (2391, 2397), False, 'from src import utils\n'), ((3471, 3562), 'pandas.read_csv', 'pd.read_csv', (['f"""{args.data_dir}/{args.dataset_name}/marking.csv"""'], {'index_col': '"""sample_id"""'}), "(f'{args.data_dir}/{args.dataset_name}/marking.csv', index_col=\n 'sample_id')\n", (3482, 3562), True, 'import pandas as pd\n'), ((3579, 3642), 'src.dataset.DatasetRetriever', 'DatasetRetriever', (["df[df['stage'] == 'train']", 'config', 'converter'], {}), "(df[df['stage'] == 'train'], config, converter)\n", (3595, 3642), False, 'from src.dataset import DatasetRetriever\n'), ((3663, 3726), 'src.dataset.DatasetRetriever', 'DatasetRetriever', (["df[df['stage'] == 'valid']", 'config', 'converter'], {}), "(df[df['stage'] == 'valid'], config, converter)\n", (3679, 3726), False, 'from src.dataset import DatasetRetriever\n'), ((3746, 3808), 'src.dataset.DatasetRetriever', 'DatasetRetriever', (["df[df['stage'] == 'test']", 'config', 'converter'], {}), "(df[df['stage'] == 'test'], config, converter)\n", (3762, 3808), False, 'from src.dataset import DatasetRetriever\n'), ((4164, 4175), 'src.model.Model', 'Model', (['args'], {}), '(args)\n', (4169, 4175), False, 'from src.model import Model\n'), ((3023, 3048), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3046, 3048), False, 'import torch\n'), ((2997, 3019), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (3009, 3019), False, 'import torch\n'), ((3054, 3073), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3066, 3073), False, 'import torch\n'), ((3199, 3219), 'src.converters.AttnLabeling', 'AttnLabeling', (['config'], {}), '(config)\n', (3211, 3219), False, 'from src.converters import CTCLabeling, AttnLabeling\n'), ((5748, 5840), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': 'args.neptune_project', 'api_token': 'args.neptune_token'}), '(project_qualified_name=args.neptune_project, api_token=args.\n neptune_token)\n', (5760, 5840), False, 'import neptune\n'), ((7608, 7643), 'src.predictor.Predictor', 'Predictor', (['experiment.model', 'device'], {}), '(experiment.model, device)\n', (7617, 7643), False, 'from src.predictor import Predictor\n'), ((7661, 7672), 'time.time', 'time.time', ([], {}), '()\n', (7670, 7672), False, 'import time\n'), ((7749, 7760), 'time.time', 'time.time', ([], {}), '()\n', (7758, 7760), False, 'import time\n'), ((3275, 3294), 'src.converters.CTCLabeling', 'CTCLabeling', (['config'], {}), '(config)\n', (3286, 3294), False, 'from src.converters import CTCLabeling, AttnLabeling\n'), ((4736, 4764), 'torch.utils.data.RandomSampler', 'RandomSampler', (['train_dataset'], {}), '(train_dataset)\n', (4749, 4764), False, 'from torch.utils.data import SequentialSampler, RandomSampler\n'), ((5024, 5056), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['valid_dataset'], {}), '(valid_dataset)\n', (5041, 5056), False, 'from torch.utils.data import SequentialSampler, RandomSampler\n'), ((5315, 5346), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['test_dataset'], {}), '(test_dataset)\n', (5332, 5346), False, 'from torch.utils.data import SequentialSampler, RandomSampler\n'), ((8088, 8133), 'src.metrics.cer', 'cer', (["df_pred['pred_text']", "df_pred['gt_text']"], {}), "(df_pred['pred_text'], df_pred['gt_text'])\n", (8091, 8133), False, 'from src.metrics import string_accuracy, cer, wer\n'), ((8165, 8210), 'src.metrics.wer', 'wer', (["df_pred['pred_text']", "df_pred['gt_text']"], {}), "(df_pred['pred_text'], df_pred['gt_text'])\n", (8168, 8210), False, 'from src.metrics import string_accuracy, cer, wer\n'), ((8242, 8299), 'src.metrics.string_accuracy', 'string_accuracy', (["df_pred['pred_text']", "df_pred['gt_text']"], {}), "(df_pred['pred_text'], df_pred['gt_text'])\n", (8257, 8299), False, 'from src.metrics import string_accuracy, cer, wer\n'), ((9285, 9308), 'numpy.mean', 'np.mean', (['time_inference'], {}), '(time_inference)\n', (9292, 9308), True, 'import numpy as np\n'), ((4306, 4347), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'ignore_index': '(0)'}), '(ignore_index=0)\n', (4331, 4347), False, 'import torch\n'), ((9387, 9410), 'numpy.mean', 'np.mean', (['time_inference'], {}), '(time_inference)\n', (9394, 9410), True, 'import numpy as np\n'), ((4414, 4450), 'torch.nn.CTCLoss', 'torch.nn.CTCLoss', ([], {'zero_infinity': '(True)'}), '(zero_infinity=True)\n', (4430, 4450), False, 'import torch\n'), ((2252, 2269), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (2267, 2269), False, 'from datetime import datetime\n')]
# -*- coding: utf-8 -*- # # Copyright (c) 2016, deepsense.io # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from future.builtins import object import os import sys import threading import warnings from PIL import Image from neptune.generated.swagger_client import ExperimentState from neptune.internal.cli.commands.utils.urls import Urls from neptune.internal.cli.exceptions.params_exceptions import ReadOnlyException from neptune.internal.cli.helpers import should_retry_api_calls from neptune.internal.client_library.background_services.services import Services from neptune.internal.client_library.job_development_api.channel import AutoIncrementType from neptune.internal.client_library.job_development_api.context_params import ContextParams from neptune.internal.client_library.job_development_api.job import Job from neptune.internal.client_library.job_development_api.key_value_properties_service import \ KeyValuePropertiesService from neptune.internal.client_library.job_development_api.metric import Metric from neptune.internal.client_library.job_development_api.tags_service import TagsService from neptune.internal.client_library.offline import (OfflineApiService, OfflineChannelValuesService, OfflineContextParams, OfflineIntegration, OfflineServices, OfflineTags, OfflineUtilitiesService) from neptune.internal.client_library.third_party_integration import ThirdPartyIntegration from neptune.internal.common.api.job_api_service import JobApiService from neptune.internal.common.api.keycloak_api_service import KeycloakApiConfig, KeycloakApiService from neptune.internal.common.api.neptune_api.handler import create_base_neptune_api_handler, \ create_base_neptune_api_handler_without_auth, create_neptune_api_handler from neptune.internal.common.api.offline_token_storage_service import OfflineTokenStorageService from neptune.internal.common.api.utilities_api_service import UtilitiesService from neptune.internal.common.local_storage.local_storage import LocalStorage from neptune.internal.common.utils.logging_utils import LogFileOpenError, OfflineNeptuneLogger, OnlineNeptuneLogger from neptune.internal.common.utils.neptune_warnings import JobDeprecationWarning, JobPropertyDeprecationWarning, \ ignore_deprecated, neptune_warn from neptune.internal.common.websockets.reconnecting_websocket_factory import ReconnectingWebsocketFactory class NeptuneContext(object): """ A Context represents a connection to Neptune Server and can be used to: .. warning:: For internal use only. Use :py:attr:`~neptune.Context` to create NeptuneContext instead. - access Experiment class to manage its lifecycle, access and modify objects connected to Experiment, - access ContextParams via params, - access and modify storage_url. """ def __init__(self, experiment, params, utilities_service): self._experiment = experiment self._params = params self._utilities_service = utilities_service @property def job(self): """ This method is deprecated and will be removed in the future release. Gets Experiment object from the Context. :return: An Experiment from the Context. """ neptune_warn("'experiment' property in 'context' object is deprecated " + "and will be removed in the future release. Please call experiment methods directly from " + "the context object (see http://docs.neptune.ml/advanced-topics/context)" , JobPropertyDeprecationWarning) return self._experiment @property @ignore_deprecated def experiment_id(self): """ Gets id of the underlying Experiment. :return: The id of the Experiment. :rtype: uuid """ return self._experiment.id @property @ignore_deprecated def state(self): """ Gets state of underlying Experiment. :return: An experiment's state. :rtype: ExperimentState """ return self._experiment.state @property @ignore_deprecated def tags(self): """ Gets the set of user-defined tags for the experiment. Tags can be used for searching and marking experiments. Accessing tags:: my_tag_exists = 'my-tag' in ctx.tags Modifying tags:: ctx.tags.append('new-tag') ctx.tags.remove('new-tag') :return: A experiment's tags. :rtype: neptune.TagsService """ return self._experiment.tags @tags.setter @ignore_deprecated def tags(self, new_tags): """ Sets user-defined tags for the experiment. Tags can be used for searching and marking experiments. Modifying tags:: ctx.tags = ['tag1', 'tag2', 'tag3'] :param new_tags: list of new experiment's tags :return: Nothing """ self._experiment.tags.set_tags(new_tags) @property @ignore_deprecated def properties(self): """ Gets the set of user-defined properties of the Experiment. Properties are additional metadata of the experiment. A property is defined as a key-value pair of two strings. Experiment’s properties can be set from the configuration file and experiment’s code or by command line parameters. Accessing properties:: print ctx.properties['my-property'] Modifying properties:: ctx.properties['property1'] = 'new-value' ctx.properties['property2'] = 'new-value' del(ctx.properties['property2']) :return: An experiment's properties. :rtype: collections.MutableMapping """ return self._experiment.properties @property def params(self): """ Gets the params of this Context. The set of user-defined variables passed to the experiment’s program. :return: The params of this Context. :rtype: neptune.ContextParams """ return self._params @params.setter def params(self, _): raise ReadOnlyException() @property def metric(self): """ Gets the metric used to compare the experiment with other experiments in the group. :return: The metric from the Context. :rtype: neptune.Metric """ return self._experiment.metric def get_neptune_config_info(self): """ Gets configuration information. :return: neptune config info. """ return self._utilities_service.get_config_info() @ignore_deprecated def integrate_with_tensorflow(self): """ Integrate Tensorflow with Neptune. """ self._experiment.integrate_with_tensorflow() @ignore_deprecated def integrate_with_keras(self): """ Integrate Keras with Neptune. """ self._experiment.integrate_with_keras() @ignore_deprecated def create_channel(self, name, channel_type, auto_increment_type=AutoIncrementType.Int): """ Creates a new channel with given name, type and optional extra parameters. Creating numeric and text channels:: numeric_channel = ctx.create_channel( name='numeric_channel', channel_type=neptune.ChannelType.NUMERIC) text_channel = ctx.create_channel( name='text_channel', channel_type=neptune.ChannelType.TEXT) numeric_channel.send(x=1, y=2.5) numeric_channel.send(x=1.5, y=5) text_channel.send(x=2.5, y='text 1') text_channel.send(x=3, y='text 2') Creating an image channel:: channel = ctx.create_channel( name='image_channel', channel_type=neptune.ChannelType.IMAGE) channel.send( x=1, y=neptune.Image( name='#1 image name', description='#1 image description', data=Image.open("/home/ubuntu/image1.jpg"))) :param name: A channel name. It must be unique in the scope of a specific experiment. :param channel_type: Type of the channel. :param auto_increment_type: Type of the x auto incrementing algorithm. :type name: unicode :type channel_type: neptune.ChannelType :type auto_increment_type: AutoIncrementType :return: Channel. :rtype: neptune.Channel """ return self._experiment.create_channel(name, channel_type, auto_increment_type) @ignore_deprecated def channel_send(self, name, x=None, y=None): """ Given values of X and Y and Name, sends a value to named Neptune channel, creating it if necessary. If the channel needs to be created, the type of the channel is determined based on type of Y value Calling ctx.channel_send( name='ch1', x=1.0, y=2.0) Is equivalent to: ch1 = ctx.create_channel( name='ch1', channel_type=neptune.ChannelType.NUMERIC) ch1.send(x=1.0, y=2.0) :param name: The name of the Neptune channel to use. If the channel does not exist yet, it is created with a type based on Y value type :param x: The value of channel value's X-coordinate. Values of the x parameter should be strictly increasing for consecutive calls. If this param is None, the last X-coordinate incremented by one will be used :param y: The value of channel value's Y-coordinate. Accepted types: float for :py:attr:`~neptune.series_type.NUMERIC`, str/unicode for :py:attr:`~neptune.series_type.TEXT`, neptune.Image for :py:attr:`~neptune.series_type.IMAGE`. :return: The channel used to send message to Neptune. :rtype: neptune.Channel """ return self._experiment.channel_send(name, x, y) @ignore_deprecated def channel_reset(self, name): """ Given a channel name, resets the channel. Calling ctx.channel_reset(name='ch1') Is equivalent to: ch1 = ctx.create_channel( name='ch1', channel_type=neptune.ChannelType.NUMERIC) ch1.reset() :param name: The name of the Neptune channel to use. """ return self._experiment.channel_reset(name) def reset(self): """ Delete all channels with their values """ return self._experiment._delete_all_channels() # pylint:disable=protected-access def delete_all_channels(self): """ Delete all channels with their values """ return self._experiment._delete_all_channels() # pylint:disable=protected-access def reset_all_channels(self): """ Remove all values from all channels """ return self._experiment._reset_all_channels() # pylint:disable=protected-access def delete_channel(self, name): """ Delete channel with a given name and all its values :param name: The name of the Neptune channel to delete. """ return self._experiment._delete_channel(name) # pylint:disable=protected-access @ignore_deprecated def register_action(self, name, handler): """ Registers a new action that calls handler with provided argument on invocation. Registering an action:: session = ... def save_model(path): return str(session.save_model(path)) ctx.register_action(name='save model', handler=save_model) :param name: Unique action name. :param handler: An one argument function that will be called on an action invocation. Handler must take one unicode or str argument and return unicode or str as the result. :type name: unicode :return: Action. :rtype: neptune.Action """ return self._experiment.register_action(name, handler) class ContextFactory(object): def __init__(self): if 'NEPTUNE_USER_PROFILE_PATH' in os.environ: self._local_storage = LocalStorage(os.environ["NEPTUNE_USER_PROFILE_PATH"]) else: self._local_storage = LocalStorage.profile() offline_execution_message = u'neptune: Executing in Offline Mode.' logfile_open_error_message = ( u"neptune: Cannot open logging file: {}.\n" u" Sent channel values will not be logged during experiment execution.\n" u" If you want to print sent channel values, you need to add following\n" u" piece of code at the top of your experiment, after call to neptune.Context function:\n" u"\n" u" import logging\n" u" logging.getLogger('experiment').addHandler(logging.StreamHandler())") def create(self, cmd_line_args=None, tags=None, properties=None, offline_parameters=None, parent_thread=threading.current_thread(), with_retries=should_retry_api_calls()): warnings.simplefilter("once", JobDeprecationWarning) warnings.simplefilter("once", JobPropertyDeprecationWarning) if 'NEPTUNE_ONLINE_CONTEXT' in os.environ: return self._create_online_context(cmd_line_args, self._local_storage, parent_thread, with_retries) else: print(self.offline_execution_message, file=sys.stderr) return self._create_offline_context(context_params=offline_parameters, context_tags=tags, context_properties=properties) @staticmethod def _create_online_context(cmd_line_args, local_storage, parent_thread, with_retries): if cmd_line_args is None: cmd_line_args = get_cmdline_arguments() OnlineNeptuneLogger.configure_python_library_logging(cmd_line_args) keycloak_api_service = KeycloakApiService(KeycloakApiConfig()) offline_token_storage_service = OfflineTokenStorageService.create( token_dirpath=local_storage.tokens_directory.absolute_path) neptune_rest_api_url = os.environ["NEPTUNE_REST_API_URL"] neptune_experiment_id = os.environ["NEPTUNE_JOB_ID"] preinit_PIL() api_service, utilities_service, tags_service, properties_service = create_online_services( Urls(neptune_rest_api_url), neptune_rest_api_url, neptune_experiment_id, offline_token_storage_service, with_retries=with_retries ) experiment_api_model = api_service.get_experiment(neptune_experiment_id) group_api_model = api_service.get_group(experiment_api_model.group_id) if experiment_api_model.group_id \ is not None else None actions = {action.id: action for action in experiment_api_model.actions} channels = experiment_api_model.channels or [] return NeptuneContext( experiment=Job(api_service=api_service, experiment_id=neptune_experiment_id, state=experiment_api_model.state, channels=channels, actions=actions, tags=tags_service, metric=create_metric(group_api_model), properties=properties_service, integration=ThirdPartyIntegration(), services=Services( neptune_experiment_id, api_service, utilities_service.get_config_info().max_form_content_size, job_actions=actions, parent_thread=parent_thread, websocket_factory=ReconnectingWebsocketFactory( local_storage=local_storage, base_address=os.environ["NEPTUNE_WS_API_URL"], experiment_id=os.environ["NEPTUNE_JOB_ID"], offline_token_storage_service=offline_token_storage_service, keycloak_api_service=keycloak_api_service)).start()), params=ContextParams.create_from(experiment_api_model), utilities_service=utilities_service) def _create_offline_context(self, context_params, context_properties=None, context_tags=None): try: OfflineNeptuneLogger.configure_python_library_logging() except LogFileOpenError as error: print(self.logfile_open_error_message.format(error.path), file=sys.stderr) context_params = context_params or {} context_params = OfflineContextParams.create_without_commandline_arguments_from(context_params) return NeptuneContext( experiment=Job(api_service=OfflineApiService(), experiment_id=None, state=ExperimentState.running, channels=[], actions={}, tags=OfflineTags.create_from(context_tags), metric=None, properties=context_properties or {}, integration=OfflineIntegration(), services=OfflineServices(OfflineChannelValuesService())), params=context_params, utilities_service=OfflineUtilitiesService()) def create_online_services(urls, rest_api_url, experiment_id, offline_token_storage_service, with_retries): """ :rtype: (neptune.internal.common.api.job_api_service.JobApiService, UtilitiesService, TagsService, KeyValuePropertiesService) """ base_api_handler_with_auth, requests_client_with_auth = \ create_base_neptune_api_handler(rest_api_url, offline_token_storage_service) base_api_handler_without_auth = create_base_neptune_api_handler_without_auth(rest_api_url) neptune_api_handler_with_auth = create_neptune_api_handler(base_api_handler_with_auth) neptune_api_handler_without_auth = create_neptune_api_handler(base_api_handler_without_auth) utilities_service = UtilitiesService( neptune_api_handler_with_auth, neptune_api_handler_without_auth ) api_service = JobApiService( urls, requests_client_with_auth, neptune_api_handler_with_auth, with_retries, utilities_service ) tags_service = TagsService(experiment_id, neptune_api_handler_with_auth) properties_service = KeyValuePropertiesService(experiment_id, neptune_api_handler_with_auth) return api_service, utilities_service, tags_service, properties_service def create_metric(group_api_model): if group_api_model is None: return None api_metric = group_api_model.metric if api_metric is not None: return Metric(channel_name=api_metric.channel_name, direction=api_metric.direction) else: return None def get_cmdline_arguments(): return sys.argv def preinit_PIL(): """ This method imports several inner-PIL modules. It's important to run it during context initialization, otherwise the modules will be imported implicitly during Image.save(), which we do as part of sending to an image channel. If during such import (which takes around 0.3 sec) this process is forked, and the child process tries to execute this method as well, it will deadlock. This is not a theoretical issue - it caused a recurring problem with PyTorch data loader. """ Image.preinit()
[ "neptune.internal.common.local_storage.local_storage.LocalStorage.profile", "neptune.internal.common.utils.neptune_warnings.neptune_warn", "neptune.internal.cli.commands.utils.urls.Urls", "neptune.internal.common.api.job_api_service.JobApiService", "neptune.internal.client_library.offline.OfflineIntegration...
[((18982, 19058), 'neptune.internal.common.api.neptune_api.handler.create_base_neptune_api_handler', 'create_base_neptune_api_handler', (['rest_api_url', 'offline_token_storage_service'], {}), '(rest_api_url, offline_token_storage_service)\n', (19013, 19058), False, 'from neptune.internal.common.api.neptune_api.handler import create_base_neptune_api_handler, create_base_neptune_api_handler_without_auth, create_neptune_api_handler\n'), ((19095, 19153), 'neptune.internal.common.api.neptune_api.handler.create_base_neptune_api_handler_without_auth', 'create_base_neptune_api_handler_without_auth', (['rest_api_url'], {}), '(rest_api_url)\n', (19139, 19153), False, 'from neptune.internal.common.api.neptune_api.handler import create_base_neptune_api_handler, create_base_neptune_api_handler_without_auth, create_neptune_api_handler\n'), ((19191, 19245), 'neptune.internal.common.api.neptune_api.handler.create_neptune_api_handler', 'create_neptune_api_handler', (['base_api_handler_with_auth'], {}), '(base_api_handler_with_auth)\n', (19217, 19245), False, 'from neptune.internal.common.api.neptune_api.handler import create_base_neptune_api_handler, create_base_neptune_api_handler_without_auth, create_neptune_api_handler\n'), ((19285, 19342), 'neptune.internal.common.api.neptune_api.handler.create_neptune_api_handler', 'create_neptune_api_handler', (['base_api_handler_without_auth'], {}), '(base_api_handler_without_auth)\n', (19311, 19342), False, 'from neptune.internal.common.api.neptune_api.handler import create_base_neptune_api_handler, create_base_neptune_api_handler_without_auth, create_neptune_api_handler\n'), ((19368, 19453), 'neptune.internal.common.api.utilities_api_service.UtilitiesService', 'UtilitiesService', (['neptune_api_handler_with_auth', 'neptune_api_handler_without_auth'], {}), '(neptune_api_handler_with_auth,\n neptune_api_handler_without_auth)\n', (19384, 19453), False, 'from neptune.internal.common.api.utilities_api_service import UtilitiesService\n'), ((19490, 19604), 'neptune.internal.common.api.job_api_service.JobApiService', 'JobApiService', (['urls', 'requests_client_with_auth', 'neptune_api_handler_with_auth', 'with_retries', 'utilities_service'], {}), '(urls, requests_client_with_auth,\n neptune_api_handler_with_auth, with_retries, utilities_service)\n', (19503, 19604), False, 'from neptune.internal.common.api.job_api_service import JobApiService\n'), ((19667, 19724), 'neptune.internal.client_library.job_development_api.tags_service.TagsService', 'TagsService', (['experiment_id', 'neptune_api_handler_with_auth'], {}), '(experiment_id, neptune_api_handler_with_auth)\n', (19678, 19724), False, 'from neptune.internal.client_library.job_development_api.tags_service import TagsService\n'), ((19750, 19821), 'neptune.internal.client_library.job_development_api.key_value_properties_service.KeyValuePropertiesService', 'KeyValuePropertiesService', (['experiment_id', 'neptune_api_handler_with_auth'], {}), '(experiment_id, neptune_api_handler_with_auth)\n', (19775, 19821), False, 'from neptune.internal.client_library.job_development_api.key_value_properties_service import KeyValuePropertiesService\n'), ((20775, 20790), 'PIL.Image.preinit', 'Image.preinit', ([], {}), '()\n', (20788, 20790), False, 'from PIL import Image\n'), ((3865, 4154), 'neptune.internal.common.utils.neptune_warnings.neptune_warn', 'neptune_warn', (['("\'experiment\' property in \'context\' object is deprecated " +\n \'and will be removed in the future release. Please call experiment methods directly from \'\n +\n \'the context object (see http://docs.neptune.ml/advanced-topics/context)\')', 'JobPropertyDeprecationWarning'], {}), '("\'experiment\' property in \'context\' object is deprecated " +\n \'and will be removed in the future release. Please call experiment methods directly from \'\n +\n \'the context object (see http://docs.neptune.ml/advanced-topics/context)\',\n JobPropertyDeprecationWarning)\n', (3877, 4154), False, 'from neptune.internal.common.utils.neptune_warnings import JobDeprecationWarning, JobPropertyDeprecationWarning, ignore_deprecated, neptune_warn\n'), ((6792, 6811), 'neptune.internal.cli.exceptions.params_exceptions.ReadOnlyException', 'ReadOnlyException', ([], {}), '()\n', (6809, 6811), False, 'from neptune.internal.cli.exceptions.params_exceptions import ReadOnlyException\n'), ((13974, 14000), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (13998, 14000), False, 'import threading\n'), ((14030, 14054), 'neptune.internal.cli.helpers.should_retry_api_calls', 'should_retry_api_calls', ([], {}), '()\n', (14052, 14054), False, 'from neptune.internal.cli.helpers import should_retry_api_calls\n'), ((14066, 14118), 'warnings.simplefilter', 'warnings.simplefilter', (['"""once"""', 'JobDeprecationWarning'], {}), "('once', JobDeprecationWarning)\n", (14087, 14118), False, 'import warnings\n'), ((14127, 14187), 'warnings.simplefilter', 'warnings.simplefilter', (['"""once"""', 'JobPropertyDeprecationWarning'], {}), "('once', JobPropertyDeprecationWarning)\n", (14148, 14187), False, 'import warnings\n'), ((14819, 14886), 'neptune.internal.common.utils.logging_utils.OnlineNeptuneLogger.configure_python_library_logging', 'OnlineNeptuneLogger.configure_python_library_logging', (['cmd_line_args'], {}), '(cmd_line_args)\n', (14871, 14886), False, 'from neptune.internal.common.utils.logging_utils import LogFileOpenError, OfflineNeptuneLogger, OnlineNeptuneLogger\n'), ((15000, 15098), 'neptune.internal.common.api.offline_token_storage_service.OfflineTokenStorageService.create', 'OfflineTokenStorageService.create', ([], {'token_dirpath': 'local_storage.tokens_directory.absolute_path'}), '(token_dirpath=local_storage.\n tokens_directory.absolute_path)\n', (15033, 15098), False, 'from neptune.internal.common.api.offline_token_storage_service import OfflineTokenStorageService\n'), ((17863, 17941), 'neptune.internal.client_library.offline.OfflineContextParams.create_without_commandline_arguments_from', 'OfflineContextParams.create_without_commandline_arguments_from', (['context_params'], {}), '(context_params)\n', (17925, 17941), False, 'from neptune.internal.client_library.offline import OfflineApiService, OfflineChannelValuesService, OfflineContextParams, OfflineIntegration, OfflineServices, OfflineTags, OfflineUtilitiesService\n'), ((20077, 20153), 'neptune.internal.client_library.job_development_api.metric.Metric', 'Metric', ([], {'channel_name': 'api_metric.channel_name', 'direction': 'api_metric.direction'}), '(channel_name=api_metric.channel_name, direction=api_metric.direction)\n', (20083, 20153), False, 'from neptune.internal.client_library.job_development_api.metric import Metric\n'), ((13078, 13131), 'neptune.internal.common.local_storage.local_storage.LocalStorage', 'LocalStorage', (["os.environ['NEPTUNE_USER_PROFILE_PATH']"], {}), "(os.environ['NEPTUNE_USER_PROFILE_PATH'])\n", (13090, 13131), False, 'from neptune.internal.common.local_storage.local_storage import LocalStorage\n'), ((13180, 13202), 'neptune.internal.common.local_storage.local_storage.LocalStorage.profile', 'LocalStorage.profile', ([], {}), '()\n', (13200, 13202), False, 'from neptune.internal.common.local_storage.local_storage import LocalStorage\n'), ((14938, 14957), 'neptune.internal.common.api.keycloak_api_service.KeycloakApiConfig', 'KeycloakApiConfig', ([], {}), '()\n', (14955, 14957), False, 'from neptune.internal.common.api.keycloak_api_service import KeycloakApiConfig, KeycloakApiService\n'), ((15371, 15397), 'neptune.internal.cli.commands.utils.urls.Urls', 'Urls', (['neptune_rest_api_url'], {}), '(neptune_rest_api_url)\n', (15375, 15397), False, 'from neptune.internal.cli.commands.utils.urls import Urls\n'), ((17606, 17661), 'neptune.internal.common.utils.logging_utils.OfflineNeptuneLogger.configure_python_library_logging', 'OfflineNeptuneLogger.configure_python_library_logging', ([], {}), '()\n', (17659, 17661), False, 'from neptune.internal.common.utils.logging_utils import LogFileOpenError, OfflineNeptuneLogger, OnlineNeptuneLogger\n'), ((17382, 17429), 'neptune.internal.client_library.job_development_api.context_params.ContextParams.create_from', 'ContextParams.create_from', (['experiment_api_model'], {}), '(experiment_api_model)\n', (17407, 17429), False, 'from neptune.internal.client_library.job_development_api.context_params import ContextParams\n'), ((18604, 18629), 'neptune.internal.client_library.offline.OfflineUtilitiesService', 'OfflineUtilitiesService', ([], {}), '()\n', (18627, 18629), False, 'from neptune.internal.client_library.offline import OfflineApiService, OfflineChannelValuesService, OfflineContextParams, OfflineIntegration, OfflineServices, OfflineTags, OfflineUtilitiesService\n'), ((16503, 16526), 'neptune.internal.client_library.third_party_integration.ThirdPartyIntegration', 'ThirdPartyIntegration', ([], {}), '()\n', (16524, 16526), False, 'from neptune.internal.client_library.third_party_integration import ThirdPartyIntegration\n'), ((18013, 18032), 'neptune.internal.client_library.offline.OfflineApiService', 'OfflineApiService', ([], {}), '()\n', (18030, 18032), False, 'from neptune.internal.client_library.offline import OfflineApiService, OfflineChannelValuesService, OfflineContextParams, OfflineIntegration, OfflineServices, OfflineTags, OfflineUtilitiesService\n'), ((18250, 18287), 'neptune.internal.client_library.offline.OfflineTags.create_from', 'OfflineTags.create_from', (['context_tags'], {}), '(context_tags)\n', (18273, 18287), False, 'from neptune.internal.client_library.offline import OfflineApiService, OfflineChannelValuesService, OfflineContextParams, OfflineIntegration, OfflineServices, OfflineTags, OfflineUtilitiesService\n'), ((18432, 18452), 'neptune.internal.client_library.offline.OfflineIntegration', 'OfflineIntegration', ([], {}), '()\n', (18450, 18452), False, 'from neptune.internal.client_library.offline import OfflineApiService, OfflineChannelValuesService, OfflineContextParams, OfflineIntegration, OfflineServices, OfflineTags, OfflineUtilitiesService\n'), ((18506, 18535), 'neptune.internal.client_library.offline.OfflineChannelValuesService', 'OfflineChannelValuesService', ([], {}), '()\n', (18533, 18535), False, 'from neptune.internal.client_library.offline import OfflineApiService, OfflineChannelValuesService, OfflineContextParams, OfflineIntegration, OfflineServices, OfflineTags, OfflineUtilitiesService\n'), ((16923, 17190), 'neptune.internal.common.websockets.reconnecting_websocket_factory.ReconnectingWebsocketFactory', 'ReconnectingWebsocketFactory', ([], {'local_storage': 'local_storage', 'base_address': "os.environ['NEPTUNE_WS_API_URL']", 'experiment_id': "os.environ['NEPTUNE_JOB_ID']", 'offline_token_storage_service': 'offline_token_storage_service', 'keycloak_api_service': 'keycloak_api_service'}), "(local_storage=local_storage, base_address=os.\n environ['NEPTUNE_WS_API_URL'], experiment_id=os.environ[\n 'NEPTUNE_JOB_ID'], offline_token_storage_service=\n offline_token_storage_service, keycloak_api_service=keycloak_api_service)\n", (16951, 17190), False, 'from neptune.internal.common.websockets.reconnecting_websocket_factory import ReconnectingWebsocketFactory\n')]
import argparse import os import os.path as osp import torch.nn.functional as F import numpy as np import torch import torch.nn as nn import torch.optim as optim import network import loss from torch.utils.data import DataLoader import lr_schedule import data_list from data_list import ImageList, split_train_test from eval import test_dev import socket import neptune from torch.autograd import Variable import random import pdb import math def entropy(p, mean=True): p = F.softmax(p) if not mean: return -torch.sum(p * torch.log(p+1e-5), 1) else: return -torch.mean(torch.sum(p * torch.log(p+1e-5), 1)) def ent(p, mean=True): if not mean: return -torch.sum(p * torch.log(p+1e-5), 1) else: return -torch.mean(torch.sum(p * torch.log(p+1e-5), 1)) def image_classification_test(loader, model, test_10crop=False): start_test = True with torch.no_grad(): if test_10crop: iter_test = [iter(loader['test'][i]) for i in range(10)] for i in range(len(loader['test'][0])): data = [iter_test[j].next() for j in range(10)] inputs = [data[j][0] for j in range(10)] labels = data[0][1] for j in range(10): inputs[j] = inputs[j].cuda() labels = labels outputs = [] for j in range(10): _, predict_out = model(inputs[j]) outputs.append(nn.Softmax(dim=1)(predict_out)) outputs = sum(outputs) if start_test: all_output = outputs.float().cpu() all_label = labels.float() start_test = False else: all_output = torch.cat((all_output, outputs.float().cpu()), 0) all_label = torch.cat((all_label, labels.float()), 0) else: iter_test = iter(loader["test"]) for i in range(len(loader['test'])): data = iter_test.next() inputs = data[0] labels = data[1] inputs = inputs.cuda() labels = labels.cuda() _, outputs = model(inputs) soft_output = F.softmax(outputs) if start_test: all_output = outputs.float().cuda() all_output_soft = soft_output.float().cuda() all_label = labels.float().cuda() start_test = False else: all_output = torch.cat((all_output, outputs.float().cuda()), 0) all_output_soft = torch.cat((all_output_soft, soft_output.float().cuda()), 0) all_label = torch.cat((all_label, labels.float()), 0).cuda() _, predict = torch.max(all_output, 1) accuracy = torch.sum(torch.squeeze(predict).float() == all_label).item() / float(all_label.size()[0]) ent_class = ent(all_output_soft) normalized = F.normalize(all_output_soft).cpu() # .cpu() mat = torch.matmul(normalized, normalized.t()) / 0.05 mask = torch.eye(mat.size(0), mat.size(0)).bool()#.cuda() mat.masked_fill_(mask, -1 / 0.05) ent_soft = entropy(mat) normalized_nosoft = F.normalize(all_output).cpu() # .cpu() mat_nosoft = torch.matmul(normalized_nosoft, normalized_nosoft.t()) / 0.05 mask = torch.eye(mat.size(0), mat.size(0)).bool() # .cuda() mat_nosoft.masked_fill_(mask, -1 / 0.05) ent_nosoft = entropy(mat_nosoft) return accuracy, ent_soft, ent_nosoft, ent_class def train(config): ## set pre-process prep_dict = {} if config["dataset"] == "visda": import preprop_visda as prep else: import pre_process as prep prep_config = config["prep"] prep_dict["source"] = prep.image_train(**config["prep"]['params']) prep_dict["target"] = prep.image_train(**config["prep"]['params']) if prep_config["test_10crop"]: prep_dict["test"] = prep.image_test_10crop(**config["prep"]['params']) else: prep_dict["test"] = prep.image_test(**config["prep"]['params']) ## prepare data dsets = {} dset_loaders = {} data_config = config["data"] train_bs = data_config["source"]["batch_size"] test_bs = data_config["test"]["batch_size"] dsets["source"], dsets["source_test"] = split_train_test(data_config["source"]["list_path"], prep_dict["source"], prep_dict["test"], return_id=False, perclass=3, random_seed=config["random_seed"]) dset_loaders["source"] = DataLoader(dsets["source"], batch_size=train_bs, \ shuffle=True, num_workers=2, drop_last=True) dsets["target"] = ImageList(open(data_config["target"]["list_path"]).readlines(), \ transform=prep_dict["target"]) dset_loaders["target"] = DataLoader(dsets["target"], batch_size=train_bs, \ shuffle=True, num_workers=2, drop_last=True) dset_loaders["source_test"] = DataLoader(dsets["source_test"], batch_size=test_bs, \ shuffle=False, num_workers=2) if prep_config["test_10crop"]: for i in range(10): dsets["test"] = [ImageList(open(data_config["test"]["list_path"]).readlines(), \ transform=prep_dict["test"][i]) for i in range(10)] dset_loaders["test"] = [DataLoader(dset, batch_size=test_bs, \ shuffle=False, num_workers=2) for dset in dsets['test']] else: dsets["test"] = ImageList(open(data_config["test"]["list_path"]).readlines(), \ transform=prep_dict["test"]) dset_loaders["test"] = DataLoader(dsets["test"], batch_size=test_bs, \ shuffle=False, num_workers=2) class_num = config["network"]["params"]["class_num"] ## set nc_ps network net_config = config["network"] base_network = net_config["name"](**net_config["params"]) base_network = base_network.cuda() ## add additional network for some methods #import pdb #pdb.set_trace() if config["loss"]["random"]: random_layer = network.RandomLayer([base_network.output_num(), class_num], config["loss"]["random_dim"]) ad_net = network.AdversarialNetwork(config["loss"]["random_dim"], 1024) else: random_layer = None ad_net = network.AdversarialNetwork(base_network.output_num() * class_num, 1024) if config["loss"]["random"]: random_layer.cuda() if config['method'] == 'DANN': ad_net = network.AdversarialNetwork(base_network.output_num(), 1024) ad_net = ad_net.cuda() parameter_list = base_network.get_parameters() + ad_net.get_parameters() ## set optimizer optimizer_config = config["optimizer"] optimizer = optimizer_config["type"](parameter_list, \ **(optimizer_config["optim_params"])) param_lr = [] for param_group in optimizer.param_groups: param_lr.append(param_group["lr"]) schedule_param = optimizer_config["lr_param"] lr_scheduler = lr_schedule.schedule_dict[optimizer_config["lr_type"]] #gpus = config['gpu'].split(',') #if len(gpus) > 1: # ad_net = nn.DataParallel(ad_net, device_ids=[int(i) for i in gpus]) # base_network = nn.DataParallel(base_network, device_ids=[int(i) for i in gpus]) ## train len_train_source = len(dset_loaders["source"]) len_train_target = len(dset_loaders["target"]) #transfer_loss_value = classifier_loss_value = total_loss_value = 0.0 best_acc = 0.0 print('start train') print(config["out_file"]) #error, dev_risk = test_dev(0, dset_loaders, config["result_path"], base_network) metric_names = {"neighborhood_density": "nd", "entropy": "ent", "source_risk": "s_risk", "dev_risk": "d_risk"} ## For s_risk, d_risk, ent, smaller is better. ## For neighborhood density, larger is better. metrics = {k: 1e5 for k in metric_names.keys()} metrics["neighborhood_density"] = 0 acc_dict = {k: 0 for k in metric_names.keys()} iter_dict = {k: 0 for k in metric_names.keys()} acc_best = 0 iter_best = 0 for i in range(config["num_iterations"]): if i % config["test_interval"] == config["test_interval"] - 1 and i >= config["start_record"]: base_network.train(False) s_risk, d_risk = test_dev(i, dset_loaders, config["result_path"], base_network) acc, nd, ent, nd_nosoft = image_classification_test(dset_loaders, \ base_network, test_10crop=prep_config["test_10crop"]) output = "Iteration {} : current selected accs".format(i) for k, v in metric_names.items(): value_rep = eval(v) if v is not "nd": ## For s_risk, d_risk, ent, smaller is better. if value_rep < metrics[k]: metrics[k] = value_rep acc_dict[k] = acc iter_dict[k] = i elif v is "nd": if value_rep > metrics[k]: metrics[k] = value_rep acc_dict[k] = acc iter_dict[k] = i output += " {} : {} ".format(k, acc_dict[k]) temp_model = nn.Sequential(base_network) if acc > acc_best: acc_best = acc iter_best = i best_model = temp_model output += "Acc best: {}".format(acc_best) print(output) log_str = "iter: {:05d}, precision: {:.5f} sim ent: {:.5f} " \ "ent_class: {:.5f} ".format(i, acc, nd.item(), ent.item()) config["out_file"].write(log_str+"\n") config["out_file"].flush() if config["neptune"]: neptune.log_metric('sim entropy', nd.item()) neptune.log_metric('sim entropy no soft', nd_nosoft.item()) neptune.log_metric('entropy', ent.item()) neptune.log_metric('accuracy', acc) neptune.log_metric('source test error', s_risk) neptune.log_metric('weighted risk', d_risk) print(log_str) loss_params = config["loss"] ## train one iter base_network.train(True) ad_net.train(True) optimizer = lr_scheduler(optimizer, i, **schedule_param) optimizer.zero_grad() if i % len_train_source == 0: iter_source = iter(dset_loaders["source"]) if i % len_train_target == 0: iter_target = iter(dset_loaders["target"]) if i % 100 ==0: print('step %d'%i) inputs_source, labels_source = iter_source.next() inputs_target, labels_target = iter_target.next() inputs_source, inputs_target, labels_source = inputs_source.cuda(), inputs_target.cuda(), labels_source.cuda() features_source, outputs_source = base_network(inputs_source) features_target, outputs_target = base_network(inputs_target) features = torch.cat((features_source, features_target), dim=0) outputs = torch.cat((outputs_source, outputs_target), dim=0) softmax_out = nn.Softmax(dim=1)(outputs) if config['method'] == 'CDAN+E': entropy = loss.Entropy(softmax_out) transfer_loss = loss.CDAN([features, softmax_out], ad_net, entropy, network.calc_coeff(i), random_layer) elif config['method'] == 'CDAN': transfer_loss = loss.CDAN([features, softmax_out], ad_net, None, None, random_layer) elif config['method'] == 'DANN': transfer_loss = loss.DANN(features, ad_net) elif config['method'] == 'DAN': transfer_loss = loss.DAN(features_source, features_target) elif config['method'] == 'JAN': transfer_loss = loss.JAN(features_source, features_target, outputs_source, outputs_target) else: raise ValueError('Method cannot be recognized.') classifier_loss = nn.CrossEntropyLoss()(outputs_source, labels_source) total_loss = loss_params["trade_off"] * transfer_loss + classifier_loss total_loss.backward() optimizer.step() return acc_dict, metrics, iter_dict, acc_best, iter_best if __name__ == "__main__": parser = argparse.ArgumentParser(description='Conditional Domain Adversarial Network') parser.add_argument('method', type=str, default='CDAN+E', choices=['CDAN', 'CDAN+E', 'DANN', 'DAN', 'JAN']) parser.add_argument('--gpu_id', type=str, nargs='?', default='0', help="device id to run") parser.add_argument('--net', type=str, default='ResNet50', choices=["ResNet18", "ResNet34", "ResNet50", "ResNet101", "ResNet152", "VGG11", "VGG13", "VGG16", "VGG19", "VGG11BN", "VGG13BN", "VGG16BN", "VGG19BN", "AlexNet"]) parser.add_argument('--dset', type=str, default='office', choices=['DomainNet','office', 'image-clef', 'visda', 'office-home'], help="The dataset or source dataset used") parser.add_argument('--s_dset_path', type=str, default='../../data/office/amazon_31_list.txt', help="The source dataset path list") parser.add_argument('--t_dset_path', type=str, default='../../data/office/webcam_10_list.txt', help="The target dataset path list") parser.add_argument('--test_interval', type=int, default=500, help="interval of two continuous test phase") parser.add_argument('--snapshot_interval', type=int, default=5000, help="interval of two continuous output model") parser.add_argument('--output_dir', type=str, default='san', help="output directory of our model (in ../snapshot directory)") parser.add_argument('--lr', type=float, default=0.001, help="learning rate") parser.add_argument('--trade_off', type=float, default=[1.0, 0.5, 0.1, 0.3, 1.5], nargs="*", help='trade off parameter') parser.add_argument('--random', type=bool, default=False, help="whether use random projection") parser.add_argument('--neptune', type=bool, default=False, help="whether use neptune") parser.add_argument('--path_neptune', type=str, default="keisaito/sandbox", help="experiment path in neptune. change if you have it") parser.add_argument('--random_seed', type=int, default=0, help="whether use random projection") parser.add_argument('--per_class', type=int, default=3, help="seed for selecting images") args = parser.parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_id #os.environ["CUDA_VISIBLE_DEVICES"] = '0,1,2,3' # train config config = {} config['method'] = args.method #config["gpu"] = args.gpu_id config["random_seed"] = args.random_seed config["num_iterations"] = 10000 config["test_interval"] = args.test_interval config["snapshot_interval"] = args.snapshot_interval config["output_for_test"] = True config["output_path"] = "snapshot/" + args.output_dir config["neptune"] = args.neptune source = args.s_dset_path.split("/")[-1] target = args.t_dset_path.split("/")[-1] output_filename = args.method + '_' + args.dset + '_%s_to_%s'%(source, target) config["result_path"] = os.path.join(config["output_path"], output_filename) print("output %s"%config["result_path"]) if not osp.exists(config["output_path"]): os.system('mkdir -p '+config["output_path"]) config["out_file"] = open(osp.join(config["output_path"], "log.txt"), "w") if not osp.exists(config["output_path"]): os.mkdir(config["output_path"]) config["prep"] = {"test_10crop":False, 'params':{"resize_size":256, "crop_size":224, 'alexnet':False}} if "AlexNet" in args.net: config["prep"]['params']['alexnet'] = True config["prep"]['params']['crop_size'] = 227 config["network"] = {"name":network.AlexNetFc, \ "params":{"use_bottleneck":True, "bottleneck_dim":256, "new_cls":True} } elif "ResNet" in args.net: config["network"] = {"name":network.ResNetFc, \ "params":{"resnet_name":args.net, "use_bottleneck":True, "bottleneck_dim":256, "new_cls":True} } elif "VGG" in args.net: config["network"] = {"name":network.VGGFc, \ "params":{"vgg_name":args.net, "use_bottleneck":True, "bottleneck_dim":256, "new_cls":True} } config["loss"] = {} config["loss"]["random"] = args.random config["loss"]["random_dim"] = 1024 config["optimizer"] = {"type":optim.SGD, "optim_params":{'lr':args.lr, "momentum":0.9, \ "weight_decay":0.0005, "nesterov":True}, "lr_type":"inv", \ "lr_param":{"lr":args.lr, "gamma":0.001, "power":0.75} } config["dataset"] = args.dset config["data"] = {"source":{"list_path":args.s_dset_path, "batch_size":36}, \ "target":{"list_path":args.t_dset_path, "batch_size":36}, \ "test":{"list_path":args.t_dset_path, "batch_size":24}} if config["dataset"] == "office": if ("amazon" in args.s_dset_path and "webcam" in args.t_dset_path) or \ ("webcam" in args.s_dset_path and "dslr" in args.t_dset_path) or \ ("webcam" in args.s_dset_path and "amazon" in args.t_dset_path) or \ ("dslr" in args.s_dset_path and "amazon" in args.t_dset_path): config["optimizer"]["lr_param"]["lr"] = 0.001 # optimal parameters elif ("amazon" in args.s_dset_path and "dslr" in args.t_dset_path) or \ ("dslr" in args.s_dset_path and "webcam" in args.t_dset_path): config["optimizer"]["lr_param"]["lr"] = 0.0003 # optimal parameters #config["optimizer"]["lr_param"]["lr"] = 0.001 # optimal parameters config["network"]["params"]["class_num"] = 31 config["start_record"] = 1000 elif config["dataset"] == "image-clef": config["optimizer"]["lr_param"]["lr"] = 0.001 # optimal parameters config["network"]["params"]["class_num"] = 12 elif config["dataset"] == "visda": config["optimizer"]["lr_param"]["lr"] = 0.001 # optimal parameters config["network"]["params"]["class_num"] = 12 config["start_record"] = 2000 #config['loss']["trade_off"] = 1.0 elif config["dataset"] == "office-home": config["optimizer"]["lr_param"]["lr"] = args.lr # optimal parameters config["optimizer"]["optim_params"]["lr"] = args.lr # optimal parameters config["network"]["params"]["class_num"] = 65 config["start_record"] = 1000 elif config["dataset"] == "DomainNet": config["optimizer"]["lr_param"]["lr"] = 0.001 # optimal parameters config["network"]["params"]["class_num"] = 126 config["start_record"] = 2000 else: raise ValueError('Dataset cannot be recognized. Please define your own dataset here.') config["out_file"].write(str(config)) config["out_file"].flush() metric_names = {"neighborhood_density": "nd", "entropy": "ent", "source_risk": "s_risk", "dev_risk": "d_risk"} all_metrics = {k: {} for k in metric_names.keys()} all_iters = {k: {} for k in metric_names.keys()} all_acc_dict = {k: {} for k in metric_names.keys()} acc_best_all = 0 iter_best_all = 0 for trade_off in args.trade_off: config["loss"]["trade_off"] = trade_off if args.neptune: import socket import neptune setting = args.s_dset_path + "_to_" + args.t_dset_path neptune.init(args.path_neptune) current_name = os.path.basename(__file__) PARAMS = {'weight': config['loss']["trade_off"], 'lr': args.lr, 'machine': socket.gethostname(), 'file': current_name, 'net': args.net, 'setting': setting, 'dataset': config["dataset"], 'method': config['method']} neptune.create_experiment(name=current_name, params=PARAMS) neptune.append_tag("setting %s file %s" % (setting, current_name)) #train(config) acc_choosen, metrics, iter_choosen, acc_best_gt, iter_best_gt = train(config) if acc_best_gt > acc_best_all: acc_best_all = acc_best_gt iter_best_all = iter_best_gt for name in metric_names.keys(): all_acc_dict[name][trade_off], \ all_metrics[name][trade_off], \ all_iters[name][trade_off] = acc_choosen[name], metrics[name], iter_choosen[name] print(all_metrics) print(all_acc_dict) for met, acc, in zip(all_metrics.keys(), all_acc_dict.keys()): dict_met = all_metrics[met] if met == 'neighborhood_density': hp_best = max(dict_met, key=dict_met.get) else: hp_best = min(dict_met, key=dict_met.get) output = "metric %s selected hp %s iteration %s, " \ "metrics value %s acc choosen %s" % (met, hp_best, all_iters[met][hp_best], dict_met[hp_best], all_acc_dict[met][hp_best]) print(output) import logging logger = logging.getLogger(__name__) logging.basicConfig(filename=config["out_file"], format="%(message)s") logger.setLevel(logging.INFO) print(output) logger.info(output)
[ "neptune.log_metric", "neptune.create_experiment", "neptune.init", "neptune.append_tag" ]
[((482, 494), 'torch.nn.functional.softmax', 'F.softmax', (['p'], {}), '(p)\n', (491, 494), True, 'import torch.nn.functional as F\n'), ((2847, 2871), 'torch.max', 'torch.max', (['all_output', '(1)'], {}), '(all_output, 1)\n', (2856, 2871), False, 'import torch\n'), ((3848, 3892), 'pre_process.image_train', 'prep.image_train', ([], {}), "(**config['prep']['params'])\n", (3864, 3892), True, 'import pre_process as prep\n'), ((3919, 3963), 'pre_process.image_train', 'prep.image_train', ([], {}), "(**config['prep']['params'])\n", (3935, 3963), True, 'import pre_process as prep\n'), ((4395, 4560), 'data_list.split_train_test', 'split_train_test', (["data_config['source']['list_path']", "prep_dict['source']", "prep_dict['test']"], {'return_id': '(False)', 'perclass': '(3)', 'random_seed': "config['random_seed']"}), "(data_config['source']['list_path'], prep_dict['source'],\n prep_dict['test'], return_id=False, perclass=3, random_seed=config[\n 'random_seed'])\n", (4411, 4560), False, 'from data_list import ImageList, split_train_test\n'), ((4603, 4701), 'torch.utils.data.DataLoader', 'DataLoader', (["dsets['source']"], {'batch_size': 'train_bs', 'shuffle': '(True)', 'num_workers': '(2)', 'drop_last': '(True)'}), "(dsets['source'], batch_size=train_bs, shuffle=True, num_workers=\n 2, drop_last=True)\n", (4613, 4701), False, 'from torch.utils.data import DataLoader\n'), ((4891, 4989), 'torch.utils.data.DataLoader', 'DataLoader', (["dsets['target']"], {'batch_size': 'train_bs', 'shuffle': '(True)', 'num_workers': '(2)', 'drop_last': '(True)'}), "(dsets['target'], batch_size=train_bs, shuffle=True, num_workers=\n 2, drop_last=True)\n", (4901, 4989), False, 'from torch.utils.data import DataLoader\n'), ((5033, 5119), 'torch.utils.data.DataLoader', 'DataLoader', (["dsets['source_test']"], {'batch_size': 'test_bs', 'shuffle': '(False)', 'num_workers': '(2)'}), "(dsets['source_test'], batch_size=test_bs, shuffle=False,\n num_workers=2)\n", (5043, 5119), False, 'from torch.utils.data import DataLoader\n'), ((12537, 12614), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Conditional Domain Adversarial Network"""'}), "(description='Conditional Domain Adversarial Network')\n", (12560, 12614), False, 'import argparse\n'), ((15418, 15470), 'os.path.join', 'os.path.join', (["config['output_path']", 'output_filename'], {}), "(config['output_path'], output_filename)\n", (15430, 15470), False, 'import os\n'), ((903, 918), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (916, 918), False, 'import torch\n'), ((4027, 4077), 'pre_process.image_test_10crop', 'prep.image_test_10crop', ([], {}), "(**config['prep']['params'])\n", (4049, 4077), True, 'import pre_process as prep\n'), ((4116, 4159), 'pre_process.image_test', 'prep.image_test', ([], {}), "(**config['prep']['params'])\n", (4131, 4159), True, 'import pre_process as prep\n'), ((5750, 5825), 'torch.utils.data.DataLoader', 'DataLoader', (["dsets['test']"], {'batch_size': 'test_bs', 'shuffle': '(False)', 'num_workers': '(2)'}), "(dsets['test'], batch_size=test_bs, shuffle=False, num_workers=2)\n", (5760, 5825), False, 'from torch.utils.data import DataLoader\n'), ((6328, 6390), 'network.AdversarialNetwork', 'network.AdversarialNetwork', (["config['loss']['random_dim']", '(1024)'], {}), "(config['loss']['random_dim'], 1024)\n", (6354, 6390), False, 'import network\n'), ((11266, 11318), 'torch.cat', 'torch.cat', (['(features_source, features_target)'], {'dim': '(0)'}), '((features_source, features_target), dim=0)\n', (11275, 11318), False, 'import torch\n'), ((11337, 11387), 'torch.cat', 'torch.cat', (['(outputs_source, outputs_target)'], {'dim': '(0)'}), '((outputs_source, outputs_target), dim=0)\n', (11346, 11387), False, 'import torch\n'), ((15527, 15560), 'os.path.exists', 'osp.exists', (["config['output_path']"], {}), "(config['output_path'])\n", (15537, 15560), True, 'import os.path as osp\n'), ((15570, 15616), 'os.system', 'os.system', (["('mkdir -p ' + config['output_path'])"], {}), "('mkdir -p ' + config['output_path'])\n", (15579, 15616), False, 'import os\n'), ((15645, 15687), 'os.path.join', 'osp.join', (["config['output_path']", '"""log.txt"""'], {}), "(config['output_path'], 'log.txt')\n", (15653, 15687), True, 'import os.path as osp\n'), ((15705, 15738), 'os.path.exists', 'osp.exists', (["config['output_path']"], {}), "(config['output_path'])\n", (15715, 15738), True, 'import os.path as osp\n'), ((15748, 15779), 'os.mkdir', 'os.mkdir', (["config['output_path']"], {}), "(config['output_path'])\n", (15756, 15779), False, 'import os\n'), ((21542, 21569), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (21559, 21569), False, 'import logging\n'), ((21578, 21648), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': "config['out_file']", 'format': '"""%(message)s"""'}), "(filename=config['out_file'], format='%(message)s')\n", (21597, 21648), False, 'import logging\n'), ((3032, 3060), 'torch.nn.functional.normalize', 'F.normalize', (['all_output_soft'], {}), '(all_output_soft)\n', (3043, 3060), True, 'import torch.nn.functional as F\n'), ((3287, 3310), 'torch.nn.functional.normalize', 'F.normalize', (['all_output'], {}), '(all_output)\n', (3298, 3310), True, 'import torch.nn.functional as F\n'), ((8484, 8546), 'eval.test_dev', 'test_dev', (['i', 'dset_loaders', "config['result_path']", 'base_network'], {}), "(i, dset_loaders, config['result_path'], base_network)\n", (8492, 8546), False, 'from eval import test_dev\n'), ((9425, 9452), 'torch.nn.Sequential', 'nn.Sequential', (['base_network'], {}), '(base_network)\n', (9438, 9452), True, 'import torch.nn as nn\n'), ((11410, 11427), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (11420, 11427), True, 'import torch.nn as nn\n'), ((11511, 11536), 'loss.Entropy', 'loss.Entropy', (['softmax_out'], {}), '(softmax_out)\n', (11523, 11536), False, 'import loss\n'), ((12246, 12267), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (12265, 12267), True, 'import torch.nn as nn\n'), ((19730, 19761), 'neptune.init', 'neptune.init', (['args.path_neptune'], {}), '(args.path_neptune)\n', (19742, 19761), False, 'import neptune\n'), ((19789, 19815), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (19805, 19815), False, 'import os\n'), ((20209, 20268), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': 'current_name', 'params': 'PARAMS'}), '(name=current_name, params=PARAMS)\n', (20234, 20268), False, 'import neptune\n'), ((20281, 20347), 'neptune.append_tag', 'neptune.append_tag', (["('setting %s file %s' % (setting, current_name))"], {}), "('setting %s file %s' % (setting, current_name))\n", (20299, 20347), False, 'import neptune\n'), ((2280, 2298), 'torch.nn.functional.softmax', 'F.softmax', (['outputs'], {}), '(outputs)\n', (2289, 2298), True, 'import torch.nn.functional as F\n'), ((5432, 5498), 'torch.utils.data.DataLoader', 'DataLoader', (['dset'], {'batch_size': 'test_bs', 'shuffle': '(False)', 'num_workers': '(2)'}), '(dset, batch_size=test_bs, shuffle=False, num_workers=2)\n', (5442, 5498), False, 'from torch.utils.data import DataLoader\n'), ((10207, 10242), 'neptune.log_metric', 'neptune.log_metric', (['"""accuracy"""', 'acc'], {}), "('accuracy', acc)\n", (10225, 10242), False, 'import neptune\n'), ((10259, 10306), 'neptune.log_metric', 'neptune.log_metric', (['"""source test error"""', 's_risk'], {}), "('source test error', s_risk)\n", (10277, 10306), False, 'import neptune\n'), ((10323, 10366), 'neptune.log_metric', 'neptune.log_metric', (['"""weighted risk"""', 'd_risk'], {}), "('weighted risk', d_risk)\n", (10341, 10366), False, 'import neptune\n'), ((11617, 11638), 'network.calc_coeff', 'network.calc_coeff', (['i'], {}), '(i)\n', (11635, 11638), False, 'import network\n'), ((11724, 11792), 'loss.CDAN', 'loss.CDAN', (['[features, softmax_out]', 'ad_net', 'None', 'None', 'random_layer'], {}), '([features, softmax_out], ad_net, None, None, random_layer)\n', (11733, 11792), False, 'import loss\n'), ((19947, 19967), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (19965, 19967), False, 'import socket\n'), ((542, 562), 'torch.log', 'torch.log', (['(p + 1e-05)'], {}), '(p + 1e-05)\n', (551, 562), False, 'import torch\n'), ((710, 730), 'torch.log', 'torch.log', (['(p + 1e-05)'], {}), '(p + 1e-05)\n', (719, 730), False, 'import torch\n'), ((11863, 11890), 'loss.DANN', 'loss.DANN', (['features', 'ad_net'], {}), '(features, ad_net)\n', (11872, 11890), False, 'import loss\n'), ((615, 635), 'torch.log', 'torch.log', (['(p + 1e-05)'], {}), '(p + 1e-05)\n', (624, 635), False, 'import torch\n'), ((783, 803), 'torch.log', 'torch.log', (['(p + 1e-05)'], {}), '(p + 1e-05)\n', (792, 803), False, 'import torch\n'), ((11959, 12001), 'loss.DAN', 'loss.DAN', (['features_source', 'features_target'], {}), '(features_source, features_target)\n', (11967, 12001), False, 'import loss\n'), ((1493, 1510), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (1503, 1510), True, 'import torch.nn as nn\n'), ((12070, 12144), 'loss.JAN', 'loss.JAN', (['features_source', 'features_target', 'outputs_source', 'outputs_target'], {}), '(features_source, features_target, outputs_source, outputs_target)\n', (12078, 12144), False, 'import loss\n'), ((2897, 2919), 'torch.squeeze', 'torch.squeeze', (['predict'], {}), '(predict)\n', (2910, 2919), False, 'import torch\n')]
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from collections import defaultdict from neptune import Session import numpy as np import pandas as pd session = Session() project = session.get_projects('csadrian')['csadrian/global-sinkhorn'] def check_crit(params, crit): for k, v in crit.items(): if k not in params.keys(): return False if isinstance(v, list): if params[k] not in v: return False elif params[k] != v: return False return True crits={} for z_test in {'mmd', 'sinkhorn'}: for z_test_scope in {'global', 'local'}: for wae_lambda in {0.0001, 0.001, 0.01, 0.1, 1, 10}: crits['{:}_{:}_{:}'.format(z_test, z_test_scope, wae_lambda)]={'z_test': z_test, 'z_test_scope' : z_test_scope, 'lambda': wae_lambda} #channels = ['covered_area', 'mmd', 'sinkhorn_ot', 'loss_rec'] channels = ['covered_area', 'loss_rec'] all_exps = project.get_experiments() #use interval of experiments -- 120 experiments of checkers interval = [i for i in range(1703, 1883)] exps = [exp for exp in all_exps if exp.id[-4]!='-' and int(exp.id[-4:]) in interval] for exp in exps: exp._my_params = exp.get_parameters() #results={'mmd-local': [], 'mmd-global': [], 'sinkhorn-local': [], 'sinkhorn-global': []} results=[] for key, crit in crits.items(): res = defaultdict(list) for exp in exps: params = exp._my_params if not check_crit(params, crit): continue # else: # print(exp.id) vals = exp.get_logs() for channel in channels: if channel in vals: res[channel].append(float(vals[channel]['y'])) means=[] for channel in channels: v = np.array(res[channel]) # if v.shape[0] > 5: # print("{}: Warning: more than 5 experiments: {} using only 5 (no order assumed)".format(key, v.shape[0])) # v = v[:5] mean = np.mean(v) means.append(mean) # results.append([crit, mean]) std = np.std(v) cnt = v.shape[0] # print("{:} {} mean: {:.2f}, std: {:.2f}, cnt: {}".format(key, channel, mean, std, cnt)) results.append([crit, means[0], means[1]]) #print(results) scopedict = {} scopedict[('mmd', 'global')] = 0 scopedict[('mmd', 'local')] = 1 scopedict[('sinkhorn', 'global')] = 2 scopedict[('sinkhorn', 'local')] = 3 tables = [] improved_results = [] for z_test in {'mmd', 'sinkhorn'}: for z_test_scope in {'global', 'local'}: results_sliced=[[result[1], result[2], scopedict[(z_test, z_test_scope)]] for result in results if result[0]['z_test']==z_test and result[0]['z_test_scope']==z_test_scope] results_sliced=np.stack(results_sliced) optimal_value_area=np.max(results_sliced[0]) optimal_value_rec=np.max(results_sliced[1]) optimal_place_area=np.argmax(results_sliced[0]) optimal_place_rec=np.argmax(results_sliced[1]) optimal_lambda_area=results[optimal_place_area][0]['lambda'] optimal_lambda_rec=results[optimal_place_rec][0]['lambda'] improved_results.append([z_test, z_test_scope, optimal_value_area, optimal_value_rec, optimal_lambda_area, optimal_lambda_rec]) tables.append(results_sliced) tables = np.stack(tables) tables = [item for sublist in tables for item in sublist] #color_dict = {('mmd', 'global'): 'blue', ('mmd', 'local'): 'red', ('sinkhorn', 'global'): 'green', ('sinkhorn', 'local'): 'yellow'} fig, ax = plt.subplots() mmd_global = np.array([[result[1], result[2]] for result in results if result[0]['z_test']=='mmd' and result[0]['z_test_scope']=='global']) mmd_local = np.array([[result[1], result[2]] for result in results if result[0]['z_test']=='mmd' and result[0]['z_test_scope']=='local']) sinkhorn_global = np.array([[result[1], result[2]] for result in results if result[0]['z_test']=='sinkhorn' and result[0]['z_test_scope']=='global']) sinkhorn_local = np.array([[result[1], result[2]] for result in results if result[0]['z_test']=='sinkhorn' and result[0]['z_test_scope']=='local']) ax.scatter(mmd_global[:, 1], mmd_global[:, 0], c = 'blue') ax.scatter(mmd_local[:, 1], mmd_local[:, 0], c = 'red') ax.scatter(sinkhorn_global[:, 1], sinkhorn_global[:, 0], c = 'green') ax.scatter(sinkhorn_local[:, 1], sinkhorn_local[:, 0], c = 'yellow') ''' for i in range(len(results)): ax.scatter(x = results[i][2], y = results[i][1], c = color_dict[(results[i][0]['z_test'], results[i][0]['z_test_scope'])]) ''' plt.legend(['mmd_global', 'mmd_local', 'sinkhorn_global', 'sinkhorn_local']) plt.savefig('Scatter_plt.png') ''' best_covered = pd.DataFrame(improved_results, columns = ['z_test', 'z_test_scope', 'covered_area', 'lambda']) print(best_covered.to_latex()) #print(best_covered) ''' ''' points = pd.DataFrame(tables, columns = ['area', 'rec', 'param']) points.plot.scatter(x = 'rec', y = 'area', c = 'param', colormap = 'Set1') plt.savefig("Scatter2.png") '''
[ "neptune.Session" ]
[((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((187, 196), 'neptune.Session', 'Session', ([], {}), '()\n', (194, 196), False, 'from neptune import Session\n'), ((3150, 3166), 'numpy.stack', 'np.stack', (['tables'], {}), '(tables)\n', (3158, 3166), True, 'import numpy as np\n'), ((3372, 3386), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3384, 3386), True, 'import matplotlib.pyplot as plt\n'), ((3400, 3535), 'numpy.array', 'np.array', (["[[result[1], result[2]] for result in results if result[0]['z_test'] ==\n 'mmd' and result[0]['z_test_scope'] == 'global']"], {}), "([[result[1], result[2]] for result in results if result[0][\n 'z_test'] == 'mmd' and result[0]['z_test_scope'] == 'global'])\n", (3408, 3535), True, 'import numpy as np\n'), ((3539, 3673), 'numpy.array', 'np.array', (["[[result[1], result[2]] for result in results if result[0]['z_test'] ==\n 'mmd' and result[0]['z_test_scope'] == 'local']"], {}), "([[result[1], result[2]] for result in results if result[0][\n 'z_test'] == 'mmd' and result[0]['z_test_scope'] == 'local'])\n", (3547, 3673), True, 'import numpy as np\n'), ((3683, 3823), 'numpy.array', 'np.array', (["[[result[1], result[2]] for result in results if result[0]['z_test'] ==\n 'sinkhorn' and result[0]['z_test_scope'] == 'global']"], {}), "([[result[1], result[2]] for result in results if result[0][\n 'z_test'] == 'sinkhorn' and result[0]['z_test_scope'] == 'global'])\n", (3691, 3823), True, 'import numpy as np\n'), ((3832, 3971), 'numpy.array', 'np.array', (["[[result[1], result[2]] for result in results if result[0]['z_test'] ==\n 'sinkhorn' and result[0]['z_test_scope'] == 'local']"], {}), "([[result[1], result[2]] for result in results if result[0][\n 'z_test'] == 'sinkhorn' and result[0]['z_test_scope'] == 'local'])\n", (3840, 3971), True, 'import numpy as np\n'), ((4397, 4473), 'matplotlib.pyplot.legend', 'plt.legend', (["['mmd_global', 'mmd_local', 'sinkhorn_global', 'sinkhorn_local']"], {}), "(['mmd_global', 'mmd_local', 'sinkhorn_global', 'sinkhorn_local'])\n", (4407, 4473), True, 'import matplotlib.pyplot as plt\n'), ((4474, 4504), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Scatter_plt.png"""'], {}), "('Scatter_plt.png')\n", (4485, 4504), True, 'import matplotlib.pyplot as plt\n'), ((1345, 1362), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1356, 1362), False, 'from collections import defaultdict\n'), ((1678, 1700), 'numpy.array', 'np.array', (['res[channel]'], {}), '(res[channel])\n', (1686, 1700), True, 'import numpy as np\n'), ((1864, 1874), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (1871, 1874), True, 'import numpy as np\n'), ((1942, 1951), 'numpy.std', 'np.std', (['v'], {}), '(v)\n', (1948, 1951), True, 'import numpy as np\n'), ((2597, 2621), 'numpy.stack', 'np.stack', (['results_sliced'], {}), '(results_sliced)\n', (2605, 2621), True, 'import numpy as np\n'), ((2647, 2672), 'numpy.max', 'np.max', (['results_sliced[0]'], {}), '(results_sliced[0])\n', (2653, 2672), True, 'import numpy as np\n'), ((2697, 2722), 'numpy.max', 'np.max', (['results_sliced[1]'], {}), '(results_sliced[1])\n', (2703, 2722), True, 'import numpy as np\n'), ((2748, 2776), 'numpy.argmax', 'np.argmax', (['results_sliced[0]'], {}), '(results_sliced[0])\n', (2757, 2776), True, 'import numpy as np\n'), ((2801, 2829), 'numpy.argmax', 'np.argmax', (['results_sliced[1]'], {}), '(results_sliced[1])\n', (2810, 2829), True, 'import numpy as np\n')]
from functools import partial import hydra import neptune.new as neptune from omegaconf import DictConfig from data.dataset import load_train_dataset from tuning.bayesian import BayesianSearch, xgb_objective @hydra.main(config_path="../config/tuning/", config_name="xgb.yaml") def _main(cfg: DictConfig): print("loading dataset...") train = load_train_dataset(cfg) print("finish dataset...") ignore = ["sequence", "state", "subject"] features = [feat for feat in train.columns if feat not in ignore] train_x = train[features] train_y = train[cfg.dataset.target] groups = train[cfg.dataset.groups] run = neptune.init(project=cfg.experiment.project, tags=[*cfg.experiment.tags]) objective = partial( xgb_objective, config=cfg, train_x=train_x, train_y=train_y, groups=groups ) bayesian_search = BayesianSearch(config=cfg, objective_function=objective, run=run) study = bayesian_search.build_study(cfg.search.verbose) bayesian_search.save_xgb_hyperparameters(study) if __name__ == "__main__": _main()
[ "neptune.new.init" ]
[((213, 280), 'hydra.main', 'hydra.main', ([], {'config_path': '"""../config/tuning/"""', 'config_name': '"""xgb.yaml"""'}), "(config_path='../config/tuning/', config_name='xgb.yaml')\n", (223, 280), False, 'import hydra\n'), ((353, 376), 'data.dataset.load_train_dataset', 'load_train_dataset', (['cfg'], {}), '(cfg)\n', (371, 376), False, 'from data.dataset import load_train_dataset\n'), ((643, 716), 'neptune.new.init', 'neptune.init', ([], {'project': 'cfg.experiment.project', 'tags': '[*cfg.experiment.tags]'}), '(project=cfg.experiment.project, tags=[*cfg.experiment.tags])\n', (655, 716), True, 'import neptune.new as neptune\n'), ((733, 821), 'functools.partial', 'partial', (['xgb_objective'], {'config': 'cfg', 'train_x': 'train_x', 'train_y': 'train_y', 'groups': 'groups'}), '(xgb_objective, config=cfg, train_x=train_x, train_y=train_y, groups\n =groups)\n', (740, 821), False, 'from functools import partial\n'), ((853, 918), 'tuning.bayesian.BayesianSearch', 'BayesianSearch', ([], {'config': 'cfg', 'objective_function': 'objective', 'run': 'run'}), '(config=cfg, objective_function=objective, run=run)\n', (867, 918), False, 'from tuning.bayesian import BayesianSearch, xgb_objective\n')]
import neptune.new as neptune import pandas as pd from sklearn.ensemble import RandomForestClassifier TRAIN_DATASET_PATH = '../datasets/tables/train.csv' TEST_DATASET_PATH = '../datasets/tables/test.csv' PARAMS = {'n_estimators': 7, 'max_depth': 2, 'max_features': 2, } def train_model(params, train_path, test_path): train = pd.read_csv(train_path) test = pd.read_csv(test_path) FEATURE_COLUMNS = ['sepal.length', 'sepal.width', 'petal.length', 'petal.width'] TARGET_COLUMN = ['variety'] X_train, y_train = train[FEATURE_COLUMNS], train[TARGET_COLUMN] X_test, y_test = test[FEATURE_COLUMNS], test[TARGET_COLUMN] rf = RandomForestClassifier(**params) rf.fit(X_train, y_train) score = rf.score(X_test, y_test) return score # # Run model training and log dataset version, parameter and test score to Neptune # # Create Neptune Run and start logging run = neptune.init(project='common/data-versioning', api_token='<PASSWORD>') # Track dataset version run["datasets/train"].track_files(TRAIN_DATASET_PATH) run["datasets/test"].track_files(TEST_DATASET_PATH) # Log parameters run["parameters"] = PARAMS # Calculate and log test score score = train_model(PARAMS, TRAIN_DATASET_PATH, TEST_DATASET_PATH) run["metrics/test_score"] = score # Stop logging to the active Neptune Run run.stop() # # Change the training data # Run model training log dataset version, parameter and test score to Neptune # TRAIN_DATASET_PATH = '../datasets/tables/train_v2.csv' # Create a new Neptune Run and start logging new_run = neptune.init(project='common/data-versioning', api_token='ANONYMOUS') # Log dataset versions new_run["datasets/train"].track_files(TRAIN_DATASET_PATH) new_run["datasets/test"].track_files(TEST_DATASET_PATH) # Log parameters new_run["parameters"] = PARAMS # Caclulate and log test score score = train_model(PARAMS, TRAIN_DATASET_PATH, TEST_DATASET_PATH) new_run["metrics/test_score"] = score # Stop logging to the active Neptune Run new_run.stop() # # Go to Neptune to see how the datasets changed between training runs! #
[ "neptune.new.init" ]
[((956, 1026), 'neptune.new.init', 'neptune.init', ([], {'project': '"""common/data-versioning"""', 'api_token': '"""<PASSWORD>"""'}), "(project='common/data-versioning', api_token='<PASSWORD>')\n", (968, 1026), True, 'import neptune.new as neptune\n'), ((1630, 1699), 'neptune.new.init', 'neptune.init', ([], {'project': '"""common/data-versioning"""', 'api_token': '"""ANONYMOUS"""'}), "(project='common/data-versioning', api_token='ANONYMOUS')\n", (1642, 1699), True, 'import neptune.new as neptune\n'), ((364, 387), 'pandas.read_csv', 'pd.read_csv', (['train_path'], {}), '(train_path)\n', (375, 387), True, 'import pandas as pd\n'), ((399, 421), 'pandas.read_csv', 'pd.read_csv', (['test_path'], {}), '(test_path)\n', (410, 421), True, 'import pandas as pd\n'), ((705, 737), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '(**params)\n', (727, 737), False, 'from sklearn.ensemble import RandomForestClassifier\n')]
#!/usr/bin/env python # coding: utf-8 """investigate the effect of data augmentation with Adam optimizer without lr scheduler on model performance""" # NOTE: 000_004 is not improving score much. # TODO: perform the Learning Rate Range test and plot the result # TODO: add model parameters to Neptune # NOTE: Params: efficientnet-b5, Adam, triangular lr policy with step_size=max_iter, and data augmentation # NOTE: So far there is not improvement in Leaderboard score due to Data Augmentation import os import sys import time import math import glob import ast import random import neptune import argparse from tqdm import tqdm import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl from torchvision import transforms import torchvision.transforms.functional as TF from efficientnet_pytorch import EfficientNet import cv2 import PIL from PIL import Image from PIL import ImageFile from iterstrat.ml_stratifiers import MultilabelStratifiedKFold import albumentations as A from albumentations.pytorch import ToTensorV2 import warnings warnings.filterwarnings("ignore") from multiprocessing import Pool from joblib import Parallel, delayed # In[9]: ## Parameters HEIGHT = 224 WIDTH = 224 IMAGE_SIZE = (224, 224) PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True IMAGE_BACKEND = 'cv2' def set_seed(seed=0): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True # set_seed() # In[12]: def resize_one_image(input_path, output_path, image_size): image = cv2.imread(input_path) image = cv2.resize(image, image_size) cv2.imwrite(output_path, image) def resize_image_batch(input_dir, output_dir, image_size): """multiprocessing image resize function""" if not os.path.isdir(output_dir): os.mkdir(output_dir) input_paths = [os.path.join(input_dir, image_name) for image_name in os.listdir(input_dir)] output_paths = [os.path.join(output_dir, image_name) for image_name in os.listdir(input_dir)] image_sizes = [image_size]*len(input_paths) _ = Parallel(n_jobs=-1, verbose=3)(delayed(resize_one_image)(ipath, opath, img_size) for ipath, opath, img_size in zip(input_paths, output_paths, image_sizes)) class ImageDataset: def __init__( self, image_paths, targets=None, augmentations=None, backend="pil", channel_first=True, grayscale=False, grayscale_as_rgb=False, ): """ :param image_paths: list of paths to images :param targets: numpy array :param augmentations: albumentations augmentations :param backend: 'pil' or 'cv2' :param channel_first: f True Images in (C,H,W) format else (H,W,C) format :param grayscale: grayscale flag :grayscale_as_rgb: load grayscale images as RGB images for transfer learning purpose """ if grayscale is False and grayscale_as_rgb is True: raise Exception("Invalid combination of " "arguments 'grayscale=False' and 'grayscale_as_rgb=True'") self.image_paths = image_paths self.targets = targets self.augmentations = augmentations self.backend = backend self.channel_first = channel_first self.grayscale = grayscale self.grayscale_as_rgb = grayscale_as_rgb def __len__(self): return len(self.image_paths) def __getitem__(self, item): # TODO: add test loader logic if self.backend == "pil": image = Image.open(self.image_paths[item]) if self.grayscale is True and self.grayscale_as_rgb is True: image = image.convert('RGB') image = np.array(image) if self.augmentations is not None: augmented = self.augmentations(image=image) image = augmented["image"] elif self.backend == "cv2": if self.grayscale is False or self.grayscale_as_rgb is True: image = cv2.imread(self.image_paths[item]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) else: image = cv2.imread(self.image_paths[item], cv2.IMREAD_GRAYSCALE) if self.augmentations is not None: augmented = self.augmentations(image=image) image = augmented["image"] else: raise Exception("Backend not implemented") if not isinstance(image, torch.Tensor): if self.channel_first is True and image.ndim == 3: image = np.transpose(image, (2, 0, 1)).astype(np.float32) image = torch.tensor(image) if len(image.size()) == 2: image = image.unsqueeze(0) if self.targets is not None: targets = self.targets[item] targets = torch.tensor(targets) else: targets = torch.tensor([]) return { "image": image, "targets": targets, } # path related variable data_dir = "/home/welcome/github/ranzcr/ranzcr-clip-catheter-line-classification/" # path checkpoint path_checkpoints_dir = "/home/welcome/github/ranzcr/checkpoints" # submission files path_submissions_dir = "/home/welcome/github/ranzcr/submissions" # train folds file path path_train_folds_dir = "/home/welcome/github/ranzcr/train_folds" # resized image dir path_resized_train_image_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "train_resized") print(path_resized_train_image_dir) # test image resized path_resized_test_image_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_resized") print(path_resized_test_image_dir) path_train_dir= os.path.join(data_dir, 'train') path_test_dir= os.path.join(data_dir, 'test') path_train_csv= os.path.join(data_dir, 'train.csv') path_train_annotations= os.path.join(data_dir, 'train_annotations.csv') path_sample_submission_file= os.path.join(data_dir, 'sample_submission.csv') # Load data train_annotations = pd.read_csv(path_train_annotations) train = pd.read_csv(path_train_csv) target_cols = [i for i in train.columns if i not in ['StudyInstanceUID', 'PatientID']] # basic info about data print(f"number of patients in train csv= {train.PatientID.nunique()}") print(f"number of study instance id in train csv= {train.StudyInstanceUID.nunique()}") print(f"number of study instance id train_annotations= {train_annotations.StudyInstanceUID.nunique()}") # split train and validation set def create_folds(n_folds=5): global train # shuffle dataset train = train.sample(frac=1, random_state=0).reset_index(drop=True) mskf = MultilabelStratifiedKFold(n_splits=n_folds, shuffle=False, random_state=None) X = train.loc[:, [i for i in train.columns if i not in target_cols]] y = train.loc[:, target_cols] train.loc[:, 'kfold'] = 0 for tuple_val in enumerate(mskf.split(X, y)): kfold, (train_id, test_idx) = tuple_val train.loc[test_idx, 'kfold'] = kfold return train # In[31]: class DataModule(object): def __init__(self, train_dataset, valid_dataset, test_dataset): self.train_dataset = train_dataset self.valid_dataset = valid_dataset self.test_dataset = test_dataset def get_train_dataloader(self, **kwargs): return torch.utils.data.DataLoader(self.train_dataset, **kwargs) def get_valid_dataloader(self, **kwargs): return torch.utils.data.DataLoader(self.valid_dataset, **kwargs) def get_test_dataloader(self, **kwargs): return torch.utils.data.DataLoader(self.test_dataset, **kwargs) # In[63]: class EfficientNetModel(torch.nn.Module): def __init__(self, num_labels=11, pretrained=True): super().__init__() self.num_labels = num_labels if pretrained: self.backbone = EfficientNet.from_pretrained("efficientnet-b5",) else: self.backbone = EfficientNet.from_name("efficientnet-b5",) self.dropout = torch.nn.Dropout(p=0.5) self.avgpool = torch.nn.AdaptiveAvgPool2d(1) self.fc = torch.nn.Linear(2048, num_labels) self.sigmoid = torch.nn.Sigmoid() def forward(self, image, targets=None): image = self.backbone.extract_features(image) image = self.avgpool(image).squeeze(-1).squeeze(-1) image = self.dropout(image) image = self.fc(image) loss = None if targets is not None and targets.size(1) == self.num_labels: loss = torch.nn.BCEWithLogitsLoss()(image, targets.type_as(image)) with torch.no_grad(): y_pred = self.sigmoid(image) return y_pred, loss # In[64]: class Trainer: def __init__(self, model, data_module, experiment_id, optimizer=None, scheduler=None, device='cuda'): self.model = model self.data_module = data_module self.optimizer = optimizer self.scheduler = scheduler self.device = device self.fp16 = False self.step_scheduler_after = None self.n_epochs = None self.metrics = {} self.metrics['train'] = [] self.metrics['valid'] = [] self.current_epoch = 0 self.current_train_batch = 0 self.current_valid_batch = 0 self.scaler = None # early stopping related variables self._best_score = -np.inf self._delta = None self._current_score = None self._counter = 0 self._patience = None # variable related to model checkpoints self.experiment_id = experiment_id # scheduler variables self.step_size = None self.max_epoch = None self.max_iter = None self.num_iterations = None def configure_trainer(self): if self.optimizer is None: self.configure_optimizers() if self.scheduler is None: self.configure_schedulers() if next(self.model.parameters()).device != self.device: self.model.to(self.device) if self.fp16: self.scaler = torch.cuda.amp.GradScaler() def configure_optimizers(self): self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.base_lr) def configure_schedulers(self, **kwargs): if self.optimizer: # self.scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(self.optimizer, eta_min=1e-6, T_0=4) self.scheduler = torch.optim.lr_scheduler.CyclicLR(self.optimizer, base_lr=self.base_lr, max_lr=self.max_lr, step_size_up=self.step_size, cycle_momentum=False) else: raise Exception("optimizer cannot be None type: code fix required") def set_params(self, **kwargs): for parameter, value in kwargs.items(): setattr(self, parameter, value) def compute_metrics(self, batch_outputs_collection, batch_targets_collection): y_pred = np.concatenate(batch_outputs_collection, axis=0) y_true = np.concatenate(batch_targets_collection, axis=0) assert y_pred.shape == y_true.shape, "shape mismatch" scores = [] for i in range(y_true.shape[1]): try: score = roc_auc_score(y_true[:,i], y_pred[:,i]) scores.append(score) except ValueError: raise("Behaviour Not expected: FIXME") avg_score = np.mean(scores) return avg_score def model_forward_pass(self, data): """forward pass of model""" for key, value in data.items(): data[key] = value.to(self.device) if self.fp16: with torch.cuda.amp.autocast(): output, loss = self.model(**data) else: output, loss = self.model(**data) return output, loss def train_one_batch(self, data): """train one batch""" self.current_train_batch += 1 self.optimizer.zero_grad() output, loss = self.model_forward_pass(data) with torch.set_grad_enabled(True): if self.fp16: with torch.cuda.amp.autocast(): self.scaler.scale(loss).backward() self.scaler.step(self.optimizer) self.scaler.update() else: loss.backward() self.optimizer.step() if self.scheduler: if self.step_scheduler_after == "batch": if self.step_scheduler_metric is None: neptune.log_metric('scheduler_batch_learning_rate', self.scheduler.get_last_lr()[0]) self.scheduler.step() else: pass # step_metric = self.metrics['valid'] # self.scheduler.step(step_metric) neptune.log_metric("train_batch_loss", loss) neptune.log_metric("optimizer_batch_lr", self.optimizer.param_groups[0]['lr']) if self.scheduler: neptune.log_metric("scheduler_batch_lr", self.scheduler.get_last_lr()[0]) return output, loss def train_one_epoch(self, dataloader): self.model.train() all_outputs = [] all_targets = [] all_losses = [] tk0 = tqdm(enumerate(dataloader, 1), total=len(dataloader)) for batch_id, data in tk0: batch_outputs, batch_loss= self.train_one_batch(data) all_outputs.append(batch_outputs.detach().cpu().numpy()) all_targets.append(data['targets'].detach().cpu().numpy()) all_losses.append(batch_loss.detach().cpu().item()) tk0.set_postfix(loss=np.array(all_losses).mean(), stage="train", epoch=self.current_epoch) # if batch_id == 50: # break tk0.close() # compute metrics # compute average loss avg_auc = self.compute_metrics(all_outputs, all_targets) avg_loss = np.array(all_losses).mean() self.metrics['train'].append({'epoch': self.current_epoch, 'avg_loss': avg_loss, 'auc_score': avg_auc}) neptune.log_metric("train_epoch_loss", avg_loss) neptune.log_metric("train_epoch_auc", avg_auc) print(self.metrics['train'][-1]) def validate_one_batch(self, data): output, loss = self.model_forward_pass(data) neptune.log_metric("valid_batch_loss", loss.detach().cpu()) return output, loss def validate_one_epoch(self, dataloader): self.model.eval() all_outputs = [] all_targets = [] all_losses = [] tk0 = tqdm(enumerate(dataloader, 1), total=len(dataloader)) for batch_id, data in tk0: batch_outputs, batch_loss= self.validate_one_batch(data) all_outputs.append(batch_outputs.detach().cpu().numpy()) all_targets.append(data['targets'].detach().cpu().numpy()) all_losses.append(batch_loss.detach().cpu().item()) tk0.set_postfix(loss=np.array(all_losses).mean(), stage="validate", epoch=self.current_epoch) # if batch_id == 50: # break tk0.close() # compute metrics # compute average loss avg_auc = self.compute_metrics(all_outputs, all_targets) avg_loss = np.array(all_losses).mean() self.metrics['valid'].append({'epoch': self.current_epoch, 'avg_loss': avg_loss, 'auc_score': avg_auc}) neptune.log_metric("valid_epoch_loss", avg_loss) neptune.log_metric("valid_epoch_auc", avg_auc) print(self.metrics['valid'][-1]) def early_stoping(self): """early stoping function""" self._current_score = self.metrics['valid'][-1]['auc_score'] if (self._current_score - self._best_score) > self._delta: self._best_score = self._current_score self._counter = 0 self.save_checkpoint() print("early stopping counter reset to 0") else: self._counter += 1 print(f"early stopping counter {self._counter} out of {self._patience}") if self._counter == self._patience: return True return False def save_checkpoint(self): """save model and optimizer state for resuming training""" if not os.path.isdir(path_checkpoints_dir): os.mkdir(path_checkpoints_dir) model_path = os.path.join(path_checkpoints_dir, f"{self.experiment_id}.pth") print(f"saved the model at {model_path}") model_state_dict = self.model.state_dict() if self.optimizer is not None: opt_state_dict = self.optimizer.state_dict() else: opt_state_dict = None if self.scheduler is not None: sch_state_dict = self.scheduler.state_dict() else: sch_state_dict = None model_dict = {} model_dict["state_dict"] = model_state_dict model_dict["optimizer"] = opt_state_dict model_dict["scheduler"] = sch_state_dict model_dict["epoch"] = self.current_epoch model_dict["fp16"] = self.fp16 model_dict['base_lr'] = self.base_lr model_dict['max_lr'] = self.max_lr model_dict['step_size'] = self.step_size model_dict['metrics'] = self.metrics model_dict['best_score'] = self._best_score model_dict['patience'] = self._patience model_dict['delta'] = self._delta model_dict['train_batch_size'] = self.train_batch_size model_dict['validation_batch_size'] = self.validation_batch_size model_dict['experiment_id'] = self.experiment_id torch.save(model_dict, model_path) def load(self, model_path, device=None): """Load the saved model to resume training and inference""" if device: self.device = device checkpoint = torch.load(model_path) if self.model: self.model.load_state_dict(checkpoint['state_dict']) self.model.to(self.device) if self.optimizer: self.optimizer.load_state_dict(checkpoint['optimizer']) if self.scheduler: self.scheduler.load_state_dict(checkpoint['scheduler']) self.current_epoch = checkpoint['epoch'] self.fp16 = checkpoint['fp16'] self.lr = checkpoint['lr'] self.metrics = checkpoint['metrics'] self._best_score = checkpoint['best_score'] self._patience = checkpoint['patience'] self._delta = checkpoint['delta'] self.train_batch_size = checkpoint['train_batch_size'] self.validation_batch_size = checkpoint['validation_batch_size'] self.experiment_id = checkpoint['experiment_id'] self.base_lr = checkpoint['base_lr'] self.max_lr = checkpoint['max_lr'] self.step_size = checkpoint['step_size'] def predict(self, test_batch_size=64, device='cuda', load=False, model_path=None, dataloader_num_workers=4, save_prediction=True): """make predictions on test images""" self.model.eval() self.device = device self.test_batch_size = test_batch_size if load: if model_path: self.load(model_path, device=self.device) else: model_path = os.path.join(path_checkpoints_dir, f"{self.experiment_id}.pth") print(f"loaded model={model_path}") self.load(model_path, device=self.device) if self.model is None: raise Exception("model cannot be None. Load or train the model before inference") dataloader = self.data_module.get_test_dataloader(batch_size=self.test_batch_size, shuffle=False, num_workers=dataloader_num_workers) all_outputs = [] tk0 = tqdm(enumerate(dataloader, 1), total=len(dataloader)) for batch_id, data in tk0: for key, value in data.items(): data[key] = value.to(self.device) # batch_outputs, batch_loss = self.model(**data) batch_outputs, batch_loss= self.validate_one_batch(data) all_outputs.append(batch_outputs.detach().cpu().numpy()) predictions = np.concatenate(all_outputs, axis=0) if save_prediction: submission = pd.read_csv(path_sample_submission_file) assert submission.shape[0] == predictions.shape[0], "unexpected behavior.code fix required" submission.iloc[:, 1:] = predictions if not os.path.isdir(path_submissions_dir): os.mkdir(path_submissions_dir) submission.to_csv(os.path.join(path_submissions_dir, f"{self.experiment_id}.csv"), index=False) tk0.close() return predictions def fit(self, base_lr, max_lr, step_epoch, max_epoch, n_epochs=100, step_scheduler_after='epoch', step_scheduler_metric='val_auc', device='cuda', fp16=False, train_batch_size = 64, validation_batch_size=64, dataloader_shuffle=True, dataloader_num_workers=5, tensorboard_writer = None, es_delta=1e-4, es_patience=5, ): """fit method to train the model""" self.n_epochs = n_epochs self.step_scheduler_after = step_scheduler_after self.step_scheduler_metric = step_scheduler_metric self.device = device self.fp16 = fp16 self._delta = es_delta self._patience = es_patience self.train_batch_size = train_batch_size self.validation_batch_size = validation_batch_size self.num_iterations = np.ceil(len(self.data_module.get_train_dataloader())/ self.train_batch_size) print(f"number of batches in training={self.num_iterations}") self.step_size = step_epoch*self.num_iterations self.max_iter = self.num_iterations*max_epoch self.base_lr = base_lr self.max_lr = max_lr self.max_epoch = max_epoch self.configure_trainer() # self.set_params(**kwargs) for i in range(1, self.n_epochs+1): self.current_epoch = i # train train_dataloader = self.data_module.get_train_dataloader( batch_size=train_batch_size, shuffle=dataloader_shuffle, num_workers=dataloader_num_workers, pin_memory=True) self.train_one_epoch(train_dataloader) neptune.log_metric("optimizer_epoch_lr", self.optimizer.param_groups[0]['lr']) # validate validation_dataloader = self.data_module.get_valid_dataloader( batch_size=validation_batch_size, shuffle=dataloader_shuffle, num_workers=dataloader_num_workers, pin_memory=True ) self.validate_one_epoch(validation_dataloader) if self.scheduler: if self.step_scheduler_after == 'epoch': if self.step_scheduler_metric == 'val_auc': neptune.log_metric('scheduler_epoch_lr', self.scheduler.get_last_lr()[0]) self.scheduler.step(self.metrics['valid'][-1]['auc_score']) else: neptune.log_metric('scheduler_epoch_lr', self.scheduler.get_last_lr()[0]) self.scheduler.step() if self.current_train_batch >= self.max_iter: print("reached maximum iterations, stopping training") break es_flag = self.early_stoping() if es_flag: print(f"early stopping at epoch={i} out of {n_epochs}") break def run(fold, resize=False, **kwargs): """train single fold classifier""" experiment_tag = "000_006" experiment_id = f"{experiment_tag}_{fold}" # initialize Neptune neptune.init(project_qualified_name='aravind/kaggle-ranzcr') neptune.create_experiment(f"{experiment_id}") neptune.append_tag(experiment_tag) if os.path.isfile(os.path.join(path_train_folds_dir, 'train_folds.csv')): train = pd.read_csv(os.path.join(path_train_folds_dir, 'train_folds.csv')) print("train folds csv read from disk") else: train = create_folds() train.to_csv(os.path.join(path_train_folds_dir, 'train_folds.csv'), index=False) print("train folds csv saved to disk for reuse") create_folds_count = train.groupby('kfold').StudyInstanceUID.count() print(create_folds_count) if resize: resize_image_batch(path_train_dir, path_resized_train_image_dir, IMAGE_SIZE) valid = train.loc[train.kfold == fold].reset_index(drop=True) train = train.loc[train.kfold != fold].reset_index(drop=True) # image path for torch dataset path_train_images = [os.path.join(path_resized_train_image_dir, i + ".jpg") for i in train.StudyInstanceUID.values] path_valid_images = [os.path.join(path_resized_train_image_dir, i + ".jpg") for i in valid.StudyInstanceUID.values] # test images in the order of submission file submission_file = pd.read_csv(path_sample_submission_file) path_test_images = [os.path.join(path_resized_test_image_dir, i + ".jpg") for i in submission_file.StudyInstanceUID.values] # targets values for torch dataset targets_train = train[target_cols].values targets_valid = valid[target_cols].values print(f"number of train images={len(path_train_images)}") print(f"number of validation images={len(path_valid_images)}") print(f"train data size={train.shape}") print(f"valid data size={valid.shape}") train_augmentation = A.Compose([ A.HorizontalFlip(p=0.5), A.ShiftScaleRotate(p=0.5), A.OneOf([A.JpegCompression(), A.Downscale(scale_min=0.1, scale_max=0.15)], p=0.2), A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5), A.RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5), A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), A.CoarseDropout(p=0.5), A.Cutout(p=0.5), ToTensorV2(p=1.0), ] ) valid_augmentation = A.Compose([ A.Normalize( mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, always_apply=True, ), ToTensorV2(), ]) test_augmentation = A.Compose([ A.Normalize( mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, always_apply=True, ), ToTensorV2(), ]) train_dataset = ImageDataset( path_train_images, targets_train, augmentations=train_augmentation, backend=IMAGE_BACKEND, channel_first=True, grayscale=True, grayscale_as_rgb=True, ) valid_dataset = ImageDataset( path_valid_images, targets_valid, augmentations=valid_augmentation, backend=IMAGE_BACKEND, channel_first=True, grayscale=True, grayscale_as_rgb=True, ) test_dataset = ImageDataset( path_test_images, None, augmentations=test_augmentation, backend=IMAGE_BACKEND, channel_first=True, grayscale=True, grayscale_as_rgb=True, ) base_lr = 3e-5 max_lr = 1e-4 step_epoch = 3 max_epoch = 30 model = EfficientNetModel(pretrained=True) data_module = DataModule(train_dataset, valid_dataset, test_dataset) trainer = Trainer(model, data_module, f"{experiment_id}") trainer.fit(base_lr, max_lr, step_epoch, max_epoch, **kwargs) def ensemble_models(model_paths, output_file, model_tag): """combine different models to create the ensemble""" model = EfficientNetModel(pretrained=False) data_module = DataModule(train_dataset, valid_dataset, test_dataset) preds_list = [] num_models = len(model_paths) print(f"number of models to ensemble={num_models}") for mpath in model_paths: if not mpath.split('/')[-1].startswith(model_tag): print(f"skipped model={mpath}") continue else: print(f"using model={mpath} for inference") trainer = Trainer(model, data_module, None) prediction = trainer.predict(load=True, model_path=mpath, save_prediction=False) preds_list.append(prediction) mean_prediction = np.stack(preds_list, axis=-1).mean(axis=-1) print(f"mean prediction array shape={mean_prediction.shape}") submission = pd.read_csv(path_sample_submission_file) assert submission.shape[0] == mean_prediction.shape[0], "unexpected behavior.code fix required" submission.iloc[:, 1:] = mean_prediction if not os.path.isdir(path_submissions_dir): os.mkdir(path_submissions_dir) submission.to_csv(os.path.join(path_submissions_dir, f"{output_file}.csv"), index=False) if __name__ == '__main__': """do some tests here""" # trainer.predict(load=True) # model_paths = os.listdir(path_checkpoints_dir,) # model_paths = [os.path.join(path_checkpoints_dir, mpath) for mpath in model_paths] # ensemble_models(model_paths, "000_002_all_folds.csv") # print("done") parser = argparse.ArgumentParser() parser.add_argument("--fold", required=True, type=int) parser.add_argument("--resize", required=False, type=bool, default=False) args = vars(parser.parse_args()) fold = args['fold'] resize = args['resize'] run(fold, resize, fp16=True, train_batch_size=128, validation_batch_size=64, step_scheduler_after='batch', step_scheduler_metric=None, )
[ "neptune.log_metric", "neptune.create_experiment", "neptune.init", "neptune.append_tag" ]
[((1165, 1198), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1188, 1198), False, 'import warnings\n'), ((5943, 5974), 'os.path.join', 'os.path.join', (['data_dir', '"""train"""'], {}), "(data_dir, 'train')\n", (5955, 5974), False, 'import os\n'), ((5990, 6020), 'os.path.join', 'os.path.join', (['data_dir', '"""test"""'], {}), "(data_dir, 'test')\n", (6002, 6020), False, 'import os\n'), ((6037, 6072), 'os.path.join', 'os.path.join', (['data_dir', '"""train.csv"""'], {}), "(data_dir, 'train.csv')\n", (6049, 6072), False, 'import os\n'), ((6097, 6144), 'os.path.join', 'os.path.join', (['data_dir', '"""train_annotations.csv"""'], {}), "(data_dir, 'train_annotations.csv')\n", (6109, 6144), False, 'import os\n'), ((6174, 6221), 'os.path.join', 'os.path.join', (['data_dir', '"""sample_submission.csv"""'], {}), "(data_dir, 'sample_submission.csv')\n", (6186, 6221), False, 'import os\n'), ((6255, 6290), 'pandas.read_csv', 'pd.read_csv', (['path_train_annotations'], {}), '(path_train_annotations)\n', (6266, 6290), True, 'import pandas as pd\n'), ((6299, 6326), 'pandas.read_csv', 'pd.read_csv', (['path_train_csv'], {}), '(path_train_csv)\n', (6310, 6326), True, 'import pandas as pd\n'), ((1437, 1454), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1448, 1454), False, 'import random\n'), ((1459, 1479), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1473, 1479), True, 'import numpy as np\n'), ((1484, 1507), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1501, 1507), False, 'import torch\n'), ((1512, 1540), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (1534, 1540), False, 'import torch\n'), ((1545, 1577), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (1571, 1577), False, 'import torch\n'), ((1724, 1746), 'cv2.imread', 'cv2.imread', (['input_path'], {}), '(input_path)\n', (1734, 1746), False, 'import cv2\n'), ((1759, 1788), 'cv2.resize', 'cv2.resize', (['image', 'image_size'], {}), '(image, image_size)\n', (1769, 1788), False, 'import cv2\n'), ((1793, 1824), 'cv2.imwrite', 'cv2.imwrite', (['output_path', 'image'], {}), '(output_path, image)\n', (1804, 1824), False, 'import cv2\n'), ((6886, 6963), 'iterstrat.ml_stratifiers.MultilabelStratifiedKFold', 'MultilabelStratifiedKFold', ([], {'n_splits': 'n_folds', 'shuffle': '(False)', 'random_state': 'None'}), '(n_splits=n_folds, shuffle=False, random_state=None)\n', (6911, 6963), False, 'from iterstrat.ml_stratifiers import MultilabelStratifiedKFold\n'), ((24334, 24394), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""aravind/kaggle-ranzcr"""'}), "(project_qualified_name='aravind/kaggle-ranzcr')\n", (24346, 24394), False, 'import neptune\n'), ((24399, 24444), 'neptune.create_experiment', 'neptune.create_experiment', (['f"""{experiment_id}"""'], {}), "(f'{experiment_id}')\n", (24424, 24444), False, 'import neptune\n'), ((24449, 24483), 'neptune.append_tag', 'neptune.append_tag', (['experiment_tag'], {}), '(experiment_tag)\n', (24467, 24483), False, 'import neptune\n'), ((25567, 25607), 'pandas.read_csv', 'pd.read_csv', (['path_sample_submission_file'], {}), '(path_sample_submission_file)\n', (25578, 25607), True, 'import pandas as pd\n'), ((29262, 29302), 'pandas.read_csv', 'pd.read_csv', (['path_sample_submission_file'], {}), '(path_sample_submission_file)\n', (29273, 29302), True, 'import pandas as pd\n'), ((29955, 29980), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (29978, 29980), False, 'import argparse\n'), ((1944, 1969), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (1957, 1969), False, 'import os\n'), ((1979, 1999), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (1987, 1999), False, 'import os\n'), ((2019, 2054), 'os.path.join', 'os.path.join', (['input_dir', 'image_name'], {}), '(input_dir, image_name)\n', (2031, 2054), False, 'import os\n'), ((2116, 2152), 'os.path.join', 'os.path.join', (['output_dir', 'image_name'], {}), '(output_dir, image_name)\n', (2128, 2152), False, 'import os\n'), ((2255, 2285), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': '(-1)', 'verbose': '(3)'}), '(n_jobs=-1, verbose=3)\n', (2263, 2285), False, 'from joblib import Parallel, delayed\n'), ((5686, 5711), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (5701, 5711), False, 'import os\n'), ((5847, 5872), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (5862, 5872), False, 'import os\n'), ((7567, 7624), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['self.train_dataset'], {}), '(self.train_dataset, **kwargs)\n', (7594, 7624), False, 'import torch\n'), ((7691, 7748), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['self.valid_dataset'], {}), '(self.valid_dataset, **kwargs)\n', (7718, 7748), False, 'import torch\n'), ((7814, 7870), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['self.test_dataset'], {}), '(self.test_dataset, **kwargs)\n', (7841, 7870), False, 'import torch\n'), ((8255, 8278), 'torch.nn.Dropout', 'torch.nn.Dropout', ([], {'p': '(0.5)'}), '(p=0.5)\n', (8271, 8278), False, 'import torch\n'), ((8302, 8331), 'torch.nn.AdaptiveAvgPool2d', 'torch.nn.AdaptiveAvgPool2d', (['(1)'], {}), '(1)\n', (8328, 8331), False, 'import torch\n'), ((8350, 8383), 'torch.nn.Linear', 'torch.nn.Linear', (['(2048)', 'num_labels'], {}), '(2048, num_labels)\n', (8365, 8383), False, 'import torch\n'), ((8407, 8425), 'torch.nn.Sigmoid', 'torch.nn.Sigmoid', ([], {}), '()\n', (8423, 8425), False, 'import torch\n'), ((11231, 11279), 'numpy.concatenate', 'np.concatenate', (['batch_outputs_collection'], {'axis': '(0)'}), '(batch_outputs_collection, axis=0)\n', (11245, 11279), True, 'import numpy as np\n'), ((11298, 11346), 'numpy.concatenate', 'np.concatenate', (['batch_targets_collection'], {'axis': '(0)'}), '(batch_targets_collection, axis=0)\n', (11312, 11346), True, 'import numpy as np\n'), ((11695, 11710), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (11702, 11710), True, 'import numpy as np\n'), ((13189, 13233), 'neptune.log_metric', 'neptune.log_metric', (['"""train_batch_loss"""', 'loss'], {}), "('train_batch_loss', loss)\n", (13207, 13233), False, 'import neptune\n'), ((13242, 13320), 'neptune.log_metric', 'neptune.log_metric', (['"""optimizer_batch_lr"""', "self.optimizer.param_groups[0]['lr']"], {}), "('optimizer_batch_lr', self.optimizer.param_groups[0]['lr'])\n", (13260, 13320), False, 'import neptune\n'), ((14467, 14515), 'neptune.log_metric', 'neptune.log_metric', (['"""train_epoch_loss"""', 'avg_loss'], {}), "('train_epoch_loss', avg_loss)\n", (14485, 14515), False, 'import neptune\n'), ((14524, 14570), 'neptune.log_metric', 'neptune.log_metric', (['"""train_epoch_auc"""', 'avg_auc'], {}), "('train_epoch_auc', avg_auc)\n", (14542, 14570), False, 'import neptune\n'), ((15812, 15860), 'neptune.log_metric', 'neptune.log_metric', (['"""valid_epoch_loss"""', 'avg_loss'], {}), "('valid_epoch_loss', avg_loss)\n", (15830, 15860), False, 'import neptune\n'), ((15869, 15915), 'neptune.log_metric', 'neptune.log_metric', (['"""valid_epoch_auc"""', 'avg_auc'], {}), "('valid_epoch_auc', avg_auc)\n", (15887, 15915), False, 'import neptune\n'), ((16773, 16836), 'os.path.join', 'os.path.join', (['path_checkpoints_dir', 'f"""{self.experiment_id}.pth"""'], {}), "(path_checkpoints_dir, f'{self.experiment_id}.pth')\n", (16785, 16836), False, 'import os\n'), ((18014, 18048), 'torch.save', 'torch.save', (['model_dict', 'model_path'], {}), '(model_dict, model_path)\n', (18024, 18048), False, 'import torch\n'), ((18240, 18262), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (18250, 18262), False, 'import torch\n'), ((20544, 20579), 'numpy.concatenate', 'np.concatenate', (['all_outputs'], {'axis': '(0)'}), '(all_outputs, axis=0)\n', (20558, 20579), True, 'import numpy as np\n'), ((24507, 24560), 'os.path.join', 'os.path.join', (['path_train_folds_dir', '"""train_folds.csv"""'], {}), "(path_train_folds_dir, 'train_folds.csv')\n", (24519, 24560), False, 'import os\n'), ((25280, 25334), 'os.path.join', 'os.path.join', (['path_resized_train_image_dir', "(i + '.jpg')"], {}), "(path_resized_train_image_dir, i + '.jpg')\n", (25292, 25334), False, 'import os\n'), ((25400, 25454), 'os.path.join', 'os.path.join', (['path_resized_train_image_dir', "(i + '.jpg')"], {}), "(path_resized_train_image_dir, i + '.jpg')\n", (25412, 25454), False, 'import os\n'), ((25632, 25685), 'os.path.join', 'os.path.join', (['path_resized_test_image_dir', "(i + '.jpg')"], {}), "(path_resized_test_image_dir, i + '.jpg')\n", (25644, 25685), False, 'import os\n'), ((29459, 29494), 'os.path.isdir', 'os.path.isdir', (['path_submissions_dir'], {}), '(path_submissions_dir)\n', (29472, 29494), False, 'import os\n'), ((29504, 29534), 'os.mkdir', 'os.mkdir', (['path_submissions_dir'], {}), '(path_submissions_dir)\n', (29512, 29534), False, 'import os\n'), ((29558, 29614), 'os.path.join', 'os.path.join', (['path_submissions_dir', 'f"""{output_file}.csv"""'], {}), "(path_submissions_dir, f'{output_file}.csv')\n", (29570, 29614), False, 'import os\n'), ((2073, 2094), 'os.listdir', 'os.listdir', (['input_dir'], {}), '(input_dir)\n', (2083, 2094), False, 'import os\n'), ((2171, 2192), 'os.listdir', 'os.listdir', (['input_dir'], {}), '(input_dir)\n', (2181, 2192), False, 'import os\n'), ((3729, 3763), 'PIL.Image.open', 'Image.open', (['self.image_paths[item]'], {}), '(self.image_paths[item])\n', (3739, 3763), False, 'from PIL import Image\n'), ((3902, 3917), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (3910, 3917), True, 'import numpy as np\n'), ((5064, 5085), 'torch.tensor', 'torch.tensor', (['targets'], {}), '(targets)\n', (5076, 5085), False, 'import torch\n'), ((5123, 5139), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (5135, 5139), False, 'import torch\n'), ((8098, 8145), 'efficientnet_pytorch.EfficientNet.from_pretrained', 'EfficientNet.from_pretrained', (['"""efficientnet-b5"""'], {}), "('efficientnet-b5')\n", (8126, 8145), False, 'from efficientnet_pytorch import EfficientNet\n'), ((8189, 8230), 'efficientnet_pytorch.EfficientNet.from_name', 'EfficientNet.from_name', (['"""efficientnet-b5"""'], {}), "('efficientnet-b5')\n", (8211, 8230), False, 'from efficientnet_pytorch import EfficientNet\n'), ((8840, 8855), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8853, 8855), False, 'import torch\n'), ((10366, 10393), 'torch.cuda.amp.GradScaler', 'torch.cuda.amp.GradScaler', ([], {}), '()\n', (10391, 10393), False, 'import torch\n'), ((10755, 10901), 'torch.optim.lr_scheduler.CyclicLR', 'torch.optim.lr_scheduler.CyclicLR', (['self.optimizer'], {'base_lr': 'self.base_lr', 'max_lr': 'self.max_lr', 'step_size_up': 'self.step_size', 'cycle_momentum': '(False)'}), '(self.optimizer, base_lr=self.base_lr,\n max_lr=self.max_lr, step_size_up=self.step_size, cycle_momentum=False)\n', (10788, 10901), False, 'import torch\n'), ((12362, 12390), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (12384, 12390), False, 'import torch\n'), ((16672, 16707), 'os.path.isdir', 'os.path.isdir', (['path_checkpoints_dir'], {}), '(path_checkpoints_dir)\n', (16685, 16707), False, 'import os\n'), ((16721, 16751), 'os.mkdir', 'os.mkdir', (['path_checkpoints_dir'], {}), '(path_checkpoints_dir)\n', (16729, 16751), False, 'import os\n'), ((20633, 20673), 'pandas.read_csv', 'pd.read_csv', (['path_sample_submission_file'], {}), '(path_sample_submission_file)\n', (20644, 20673), True, 'import pandas as pd\n'), ((22898, 22976), 'neptune.log_metric', 'neptune.log_metric', (['"""optimizer_epoch_lr"""', "self.optimizer.param_groups[0]['lr']"], {}), "('optimizer_epoch_lr', self.optimizer.param_groups[0]['lr'])\n", (22916, 22976), False, 'import neptune\n'), ((24591, 24644), 'os.path.join', 'os.path.join', (['path_train_folds_dir', '"""train_folds.csv"""'], {}), "(path_train_folds_dir, 'train_folds.csv')\n", (24603, 24644), False, 'import os\n'), ((24756, 24809), 'os.path.join', 'os.path.join', (['path_train_folds_dir', '"""train_folds.csv"""'], {}), "(path_train_folds_dir, 'train_folds.csv')\n", (24768, 24809), False, 'import os\n'), ((26136, 26159), 'albumentations.HorizontalFlip', 'A.HorizontalFlip', ([], {'p': '(0.5)'}), '(p=0.5)\n', (26152, 26159), True, 'import albumentations as A\n'), ((26173, 26198), 'albumentations.ShiftScaleRotate', 'A.ShiftScaleRotate', ([], {'p': '(0.5)'}), '(p=0.5)\n', (26191, 26198), True, 'import albumentations as A\n'), ((26307, 26401), 'albumentations.HueSaturationValue', 'A.HueSaturationValue', ([], {'hue_shift_limit': '(0.2)', 'sat_shift_limit': '(0.2)', 'val_shift_limit': '(0.2)', 'p': '(0.5)'}), '(hue_shift_limit=0.2, sat_shift_limit=0.2,\n val_shift_limit=0.2, p=0.5)\n', (26327, 26401), True, 'import albumentations as A\n'), ((26411, 26507), 'albumentations.RandomBrightnessContrast', 'A.RandomBrightnessContrast', ([], {'brightness_limit': '(-0.1, 0.1)', 'contrast_limit': '(-0.1, 0.1)', 'p': '(0.5)'}), '(brightness_limit=(-0.1, 0.1), contrast_limit=(-\n 0.1, 0.1), p=0.5)\n', (26437, 26507), True, 'import albumentations as A\n'), ((26541, 26641), 'albumentations.Normalize', 'A.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]', 'max_pixel_value': '(255.0)', 'p': '(1.0)'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225],\n max_pixel_value=255.0, p=1.0)\n', (26552, 26641), True, 'import albumentations as A\n'), ((26651, 26673), 'albumentations.CoarseDropout', 'A.CoarseDropout', ([], {'p': '(0.5)'}), '(p=0.5)\n', (26666, 26673), True, 'import albumentations as A\n'), ((26687, 26702), 'albumentations.Cutout', 'A.Cutout', ([], {'p': '(0.5)'}), '(p=0.5)\n', (26695, 26702), True, 'import albumentations as A\n'), ((26716, 26733), 'albumentations.pytorch.ToTensorV2', 'ToTensorV2', ([], {'p': '(1.0)'}), '(p=1.0)\n', (26726, 26733), False, 'from albumentations.pytorch import ToTensorV2\n'), ((26806, 26918), 'albumentations.Normalize', 'A.Normalize', ([], {'mean': '(0.485, 0.456, 0.406)', 'std': '(0.229, 0.224, 0.225)', 'max_pixel_value': '(255.0)', 'always_apply': '(True)'}), '(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225),\n max_pixel_value=255.0, always_apply=True)\n', (26817, 26918), True, 'import albumentations as A\n'), ((26990, 27002), 'albumentations.pytorch.ToTensorV2', 'ToTensorV2', ([], {}), '()\n', (27000, 27002), False, 'from albumentations.pytorch import ToTensorV2\n'), ((27060, 27172), 'albumentations.Normalize', 'A.Normalize', ([], {'mean': '(0.485, 0.456, 0.406)', 'std': '(0.229, 0.224, 0.225)', 'max_pixel_value': '(255.0)', 'always_apply': '(True)'}), '(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225),\n max_pixel_value=255.0, always_apply=True)\n', (27071, 27172), True, 'import albumentations as A\n'), ((27244, 27256), 'albumentations.pytorch.ToTensorV2', 'ToTensorV2', ([], {}), '()\n', (27254, 27256), False, 'from albumentations.pytorch import ToTensorV2\n'), ((29135, 29164), 'numpy.stack', 'np.stack', (['preds_list'], {'axis': '(-1)'}), '(preds_list, axis=-1)\n', (29143, 29164), True, 'import numpy as np\n'), ((2286, 2311), 'joblib.delayed', 'delayed', (['resize_one_image'], {}), '(resize_one_image)\n', (2293, 2311), False, 'from joblib import Parallel, delayed\n'), ((4840, 4859), 'torch.tensor', 'torch.tensor', (['image'], {}), '(image)\n', (4852, 4859), False, 'import torch\n'), ((8766, 8794), 'torch.nn.BCEWithLogitsLoss', 'torch.nn.BCEWithLogitsLoss', ([], {}), '()\n', (8792, 8794), False, 'import torch\n'), ((11512, 11553), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_true[:, i]', 'y_pred[:, i]'], {}), '(y_true[:, i], y_pred[:, i])\n', (11525, 11553), False, 'from sklearn.metrics import roc_auc_score\n'), ((11960, 11985), 'torch.cuda.amp.autocast', 'torch.cuda.amp.autocast', ([], {}), '()\n', (11983, 11985), False, 'import torch\n'), ((14310, 14330), 'numpy.array', 'np.array', (['all_losses'], {}), '(all_losses)\n', (14318, 14330), True, 'import numpy as np\n'), ((15655, 15675), 'numpy.array', 'np.array', (['all_losses'], {}), '(all_losses)\n', (15663, 15675), True, 'import numpy as np\n'), ((19660, 19723), 'os.path.join', 'os.path.join', (['path_checkpoints_dir', 'f"""{self.experiment_id}.pth"""'], {}), "(path_checkpoints_dir, f'{self.experiment_id}.pth')\n", (19672, 19723), False, 'import os\n'), ((20847, 20882), 'os.path.isdir', 'os.path.isdir', (['path_submissions_dir'], {}), '(path_submissions_dir)\n', (20860, 20882), False, 'import os\n'), ((20900, 20930), 'os.mkdir', 'os.mkdir', (['path_submissions_dir'], {}), '(path_submissions_dir)\n', (20908, 20930), False, 'import os\n'), ((20961, 21024), 'os.path.join', 'os.path.join', (['path_submissions_dir', 'f"""{self.experiment_id}.csv"""'], {}), "(path_submissions_dir, f'{self.experiment_id}.csv')\n", (20973, 21024), False, 'import os\n'), ((4202, 4236), 'cv2.imread', 'cv2.imread', (['self.image_paths[item]'], {}), '(self.image_paths[item])\n', (4212, 4236), False, 'import cv2\n'), ((4261, 4299), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (4273, 4299), False, 'import cv2\n'), ((4342, 4398), 'cv2.imread', 'cv2.imread', (['self.image_paths[item]', 'cv2.IMREAD_GRAYSCALE'], {}), '(self.image_paths[item], cv2.IMREAD_GRAYSCALE)\n', (4352, 4398), False, 'import cv2\n'), ((12439, 12464), 'torch.cuda.amp.autocast', 'torch.cuda.amp.autocast', ([], {}), '()\n', (12462, 12464), False, 'import torch\n'), ((26221, 26240), 'albumentations.JpegCompression', 'A.JpegCompression', ([], {}), '()\n', (26238, 26240), True, 'import albumentations as A\n'), ((26242, 26284), 'albumentations.Downscale', 'A.Downscale', ([], {'scale_min': '(0.1)', 'scale_max': '(0.15)'}), '(scale_min=0.1, scale_max=0.15)\n', (26253, 26284), True, 'import albumentations as A\n'), ((4766, 4796), 'numpy.transpose', 'np.transpose', (['image', '(2, 0, 1)'], {}), '(image, (2, 0, 1))\n', (4778, 4796), True, 'import numpy as np\n'), ((14021, 14041), 'numpy.array', 'np.array', (['all_losses'], {}), '(all_losses)\n', (14029, 14041), True, 'import numpy as np\n'), ((15364, 15384), 'numpy.array', 'np.array', (['all_losses'], {}), '(all_losses)\n', (15372, 15384), True, 'import numpy as np\n')]
# # Copyright (c) 2019, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json import os import sys import click import neptune from neptune.api_exceptions import NotebookNotFound def sync(project_name, path, update_flag=None, new_flag=None): verify_file(path) absolute_path = os.path.abspath(path) project = neptune.init(project_qualified_name=project_name) notebook_json = load_notebook_json(path) nbformat = int(notebook_json["nbformat"]) if "nbformat" in notebook_json else 0 if nbformat < 4: show_nbformat_to_old_error() if new_flag: upload_new_notebook(project, path, notebook_json) else: notebook_id = get_notebook_id_from_metadata(notebook_json) if notebook_id: notebook = fetch_notebook(project, notebook_id) if notebook: old_path = notebook.get_path() if absolute_path == old_path or update_flag: upload_new_checkpoint(project, notebook, path) else: show_path_changed_error(project_name, old_path, absolute_path, path) elif update_flag: return show_unknown_notebook_error(project_name, path) else: upload_new_notebook(project, path, notebook_json) else: if update_flag: return show_unknown_notebook_error(project_name, path) else: upload_new_notebook(project, path, notebook_json) def upload_new_notebook(project, path, notebook_json): notebook = project.create_notebook() save_notebook_metadata(path, notebook_json, notebook.id) notebook.add_checkpoint(path) print_link_to_notebook(project, notebook.get_name(), notebook.id) def upload_new_checkpoint(project, notebook, path): notebook.add_checkpoint(path) print_link_to_notebook(project, notebook.get_name(), notebook.id) def load_notebook_json(path): with open(path) as f: return json.load(f) def get_notebook_id_from_metadata(notebook_json): metadata = None if 'metadata' in notebook_json: metadata = notebook_json['metadata'] neptune_metadata = None if metadata and 'neptune' in metadata: neptune_metadata = metadata['neptune'] notebook_id = None if neptune_metadata and 'notebookId' in neptune_metadata: notebook_id = neptune_metadata['notebookId'] return notebook_id def fetch_notebook(project, notebook_id): try: return project.get_notebook(notebook_id) except NotebookNotFound: return None def save_notebook_metadata(path, notebook_json, notebook_id): metadata = {} if 'metadata' in notebook_json: metadata = notebook_json['metadata'] metadata['neptune'] = {'notebookId': notebook_id} notebook_json['metadata'] = metadata with open(path, 'w') as f: f.write(json.dumps(notebook_json)) def verify_file(path): if not os.path.exists(path): click.echo("ERROR: File `{}` doesn't exist".format(path), err=True) sys.exit(1) if not os.path.isfile(path): click.echo("ERROR: `{}` is not a file".format(path), err=True) sys.exit(1) if not path.endswith(".ipynb"): click.echo("ERROR: '{}' is not a correct notebook file. Should end with '.ipynb'.".format(path), err=True) sys.exit(1) def print_link_to_notebook(project, notebook_name, notebook_id): try: print("{base_url}/{project}/n/{notebook_name}-{notebook_id}".format( base_url=project.client.api_address, project=project.full_id, notebook_name=notebook_name, notebook_id=notebook_id )) except Exception: pass def show_unknown_notebook_error(project_name, path): project_option = " --project {}".format(project_name) if project_name else "" # Disabling all, since what we actually want to disable doesn't work on python 2 # pylint: disable=all click.echo("ERROR: Cannot update notebook {} since it is not known to Neptune. " "Use following command to create new notebook in Neptune.\n\n" " neptune notebook sync{} {}\n" .format(path, project_option, path), err=True) sys.exit(1) def show_path_changed_error(project_name, old_path, new_absolute_path, path): project_option = " --project {}".format(project_name) if project_name else "" # Disabling all, since what we actually want to disable doesn't work on python 2 # pylint: disable=all click.echo("ERROR: Notebook path changed since last checkpoint from\n\n" " {}\n\nto\n\n {}\n\n" "Use following command if you want to create new notebook\n\n" " neptune notebook sync --new{} {}\n\n" "or following command if you want to update existing notebook\n\n" " neptune notebook sync --update{} {}\n" .format(old_path, new_absolute_path, project_option, path, project_option, path), err=True) sys.exit(1) def show_nbformat_to_old_error(): click.echo("ERROR: Version of this notebook is too old. " "Neptune support notebooks in version 4.0 or greater.", err=True) sys.exit(1)
[ "neptune.init" ]
[((819, 840), 'os.path.abspath', 'os.path.abspath', (['path'], {}), '(path)\n', (834, 840), False, 'import os\n'), ((855, 904), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': 'project_name'}), '(project_qualified_name=project_name)\n', (867, 904), False, 'import neptune\n'), ((4790, 4801), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4798, 4801), False, 'import sys\n'), ((5584, 5595), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5592, 5595), False, 'import sys\n'), ((5636, 5766), 'click.echo', 'click.echo', (['"""ERROR: Version of this notebook is too old. Neptune support notebooks in version 4.0 or greater."""'], {'err': '(True)'}), "(\n 'ERROR: Version of this notebook is too old. Neptune support notebooks in version 4.0 or greater.'\n , err=True)\n", (5646, 5766), False, 'import click\n'), ((5779, 5790), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5787, 5790), False, 'import sys\n'), ((2517, 2529), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2526, 2529), False, 'import json\n'), ((3486, 3506), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (3500, 3506), False, 'import os\n'), ((3592, 3603), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3600, 3603), False, 'import sys\n'), ((3616, 3636), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (3630, 3636), False, 'import os\n'), ((3717, 3728), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3725, 3728), False, 'import sys\n'), ((3889, 3900), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3897, 3900), False, 'import sys\n'), ((3423, 3448), 'json.dumps', 'json.dumps', (['notebook_json'], {}), '(notebook_json)\n', (3433, 3448), False, 'import json\n')]
from keras.backend import clear_session from keras.layers import Conv1D from keras.layers import Dense from keras.layers import Flatten import optuna import neptune import numpy as np import tensorflow as tf import neptunecontrib.monitoring.optuna as opt_utils from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from tensorflow.keras import callbacks from absl import flags, app from datetime import datetime from neptunecontrib.monitoring.keras import NeptuneMonitor from data_processor import read_data flags.DEFINE_string('data_dir', '../data/uniform_200k/', 'Relative path to the data folder') FLAGS = flags.FLAGS BATCHSIZE = 65536 EPOCHS = 50000 def input_fn(trainingset_path): x_train, y_train = read_data(trainingset_path, 'train') x_valid, y_valid = read_data(trainingset_path, 'eval') x_train = np.reshape(x_train.values, (-1, x_train.shape[1], 1)) y_train = np.reshape(y_train.values, (-1, 1)) x_valid = np.reshape(x_valid.values, (-1, x_valid.shape[1], 1)) y_valid = np.reshape(y_valid.values, (-1, 1)) return x_train, y_train, x_valid, y_valid def create_cnn(trial, width, height): inputShape = (width, height) num_of_conv_filters = trial.suggest_int("num_of_conv_filters", 3, 6) num_of_dense_filters = trial.suggest_int("num_of_dense_filters", 1, 3) kernel_size = trial.suggest_int("kernel_size", 1, 128) inputs = Input(shape=inputShape) x = inputs for i in range(num_of_conv_filters): x = Conv1D( filters=trial.suggest_int("conv_filter" + str(i), 1, 192), kernel_size=kernel_size, strides=trial.suggest_int("strides", 1, 20), activation="relu", padding="same" )(x) x = Activation("relu")(x) x = BatchNormalization()(x) x = MaxPooling1D( pool_size=trial.suggest_int("pool_size" + str(i), 1, 32), padding="same" )(x) x = Flatten()(x) for i in range(num_of_dense_filters): x = Dense( units=trial.suggest_int("dense_filter" + str(i), 1, 512), )(x) x = Activation("relu")(x) x = BatchNormalization()(x) x = Dropout( rate=trial.suggest_uniform("dense_dropout" + str(i), 0.0, 0.9) )(x) x = Dense(1, activation="linear")(x) model = Model(inputs, x) return model def objective(trial): clear_session() trainingset_path = FLAGS.data_dir x_train, y_train, x_valid, y_valid = input_fn(trainingset_path) model = create_cnn(trial, x_train.shape[1], 1) lr = trial.suggest_loguniform("lr", 1e-6, 1e-2) decay = trial.suggest_loguniform("decay", 1e-6, 1e-4) opt = Adam(lr=lr, decay=decay) model.compile( loss=tf.keras.losses.MeanSquaredError(), optimizer=opt ) model.fit( x_train, y_train, validation_data=(x_valid, y_valid), shuffle=True, batch_size=BATCHSIZE, epochs=EPOCHS, callbacks=[NeptuneMonitor()], verbose=0 ) score = model.evaluate(x_valid, y_valid, verbose=0) return score def main(argv): day_in_sec = 24 * 60 * 60 - 10 * 60 # minus 10 min neptune.init(project_qualified_name='kowson/OLN') neptune.create_experiment(name="CNN Optuna 2", tags=["CNN", "optuna", "data_v2", "mse"]) neptune_callback = opt_utils.NeptuneCallback(log_study=True, log_charts=True) study = optuna.create_study( study_name='cnn2', direction="minimize", storage='sqlite:///cnn1.db', pruner=optuna.pruners.MedianPruner(n_startup_trials=0, n_warmup_steps=10000, interval_steps=1000), load_if_exists=True ) study.optimize(objective, timeout=day_in_sec, callbacks=[neptune_callback]) opt_utils.log_study(study) study.set_user_attr('n_epochs', EPOCHS) print("Number of finished trials: {}".format(len(study.trials))) print("Best trial:") trial = study.best_trial print(" Value: {}".format(trial.value)) print(" Params: ") for key, value in trial.params.items(): print(" {}: {}".format(key, value)) neptune.stop() if __name__ == '__main__': app.run(main)
[ "neptune.create_experiment", "neptune.init", "neptune.stop" ]
[((685, 781), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""data_dir"""', '"""../data/uniform_200k/"""', '"""Relative path to the data folder"""'], {}), "('data_dir', '../data/uniform_200k/',\n 'Relative path to the data folder')\n", (704, 781), False, 'from absl import flags, app\n'), ((899, 935), 'data_processor.read_data', 'read_data', (['trainingset_path', '"""train"""'], {}), "(trainingset_path, 'train')\n", (908, 935), False, 'from data_processor import read_data\n'), ((960, 995), 'data_processor.read_data', 'read_data', (['trainingset_path', '"""eval"""'], {}), "(trainingset_path, 'eval')\n", (969, 995), False, 'from data_processor import read_data\n'), ((1011, 1064), 'numpy.reshape', 'np.reshape', (['x_train.values', '(-1, x_train.shape[1], 1)'], {}), '(x_train.values, (-1, x_train.shape[1], 1))\n', (1021, 1064), True, 'import numpy as np\n'), ((1080, 1115), 'numpy.reshape', 'np.reshape', (['y_train.values', '(-1, 1)'], {}), '(y_train.values, (-1, 1))\n', (1090, 1115), True, 'import numpy as np\n'), ((1131, 1184), 'numpy.reshape', 'np.reshape', (['x_valid.values', '(-1, x_valid.shape[1], 1)'], {}), '(x_valid.values, (-1, x_valid.shape[1], 1))\n', (1141, 1184), True, 'import numpy as np\n'), ((1200, 1235), 'numpy.reshape', 'np.reshape', (['y_valid.values', '(-1, 1)'], {}), '(y_valid.values, (-1, 1))\n', (1210, 1235), True, 'import numpy as np\n'), ((1588, 1611), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': 'inputShape'}), '(shape=inputShape)\n', (1593, 1611), False, 'from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout\n'), ((2616, 2632), 'tensorflow.keras.models.Model', 'Model', (['inputs', 'x'], {}), '(inputs, x)\n', (2621, 2632), False, 'from tensorflow.keras.models import Model\n'), ((2685, 2700), 'keras.backend.clear_session', 'clear_session', ([], {}), '()\n', (2698, 2700), False, 'from keras.backend import clear_session\n'), ((2990, 3014), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': 'lr', 'decay': 'decay'}), '(lr=lr, decay=decay)\n', (2994, 3014), False, 'from tensorflow.keras.optimizers import Adam\n'), ((3510, 3559), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""kowson/OLN"""'}), "(project_qualified_name='kowson/OLN')\n", (3522, 3559), False, 'import neptune\n'), ((3565, 3657), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""CNN Optuna 2"""', 'tags': "['CNN', 'optuna', 'data_v2', 'mse']"}), "(name='CNN Optuna 2', tags=['CNN', 'optuna',\n 'data_v2', 'mse'])\n", (3590, 3657), False, 'import neptune\n'), ((3709, 3767), 'neptunecontrib.monitoring.optuna.NeptuneCallback', 'opt_utils.NeptuneCallback', ([], {'log_study': '(True)', 'log_charts': '(True)'}), '(log_study=True, log_charts=True)\n', (3734, 3767), True, 'import neptunecontrib.monitoring.optuna as opt_utils\n'), ((4221, 4247), 'neptunecontrib.monitoring.optuna.log_study', 'opt_utils.log_study', (['study'], {}), '(study)\n', (4240, 4247), True, 'import neptunecontrib.monitoring.optuna as opt_utils\n'), ((4598, 4612), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (4610, 4612), False, 'import neptune\n'), ((4648, 4661), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (4655, 4661), False, 'from absl import flags, app\n'), ((2194, 2203), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2201, 2203), False, 'from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout\n'), ((2568, 2597), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""linear"""'}), "(1, activation='linear')\n", (2573, 2597), False, 'from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout\n'), ((1972, 1990), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (1982, 1990), False, 'from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout\n'), ((2007, 2027), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (2025, 2027), False, 'from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout\n'), ((2378, 2396), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2388, 2396), False, 'from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout\n'), ((2413, 2433), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (2431, 2433), False, 'from tensorflow.keras.layers import Input, Conv1D, Activation, BatchNormalization, MaxPooling1D, Flatten, Dense, Dropout\n'), ((3049, 3083), 'tensorflow.keras.losses.MeanSquaredError', 'tf.keras.losses.MeanSquaredError', ([], {}), '()\n', (3081, 3083), True, 'import tensorflow as tf\n'), ((3917, 4011), 'optuna.pruners.MedianPruner', 'optuna.pruners.MedianPruner', ([], {'n_startup_trials': '(0)', 'n_warmup_steps': '(10000)', 'interval_steps': '(1000)'}), '(n_startup_trials=0, n_warmup_steps=10000,\n interval_steps=1000)\n', (3944, 4011), False, 'import optuna\n'), ((3303, 3319), 'neptunecontrib.monitoring.keras.NeptuneMonitor', 'NeptuneMonitor', ([], {}), '()\n', (3317, 3319), False, 'from neptunecontrib.monitoring.keras import NeptuneMonitor\n')]
# coding=utf-8 # Copyright 2018 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Run experiments using Neptune.""" import json import os import socket import tempfile from absl import app from absl import flags from absl import logging import os import jax from language.mentionmemory.training.trainer import train import ml_collections import tensorflow.compat.v1 as tf import neptune FLAGS = flags.FLAGS # Training config. flags.DEFINE_string( "config_file", None, "Path to file that contains JSON serialized model configuration. If this" "is specified, ignores 'config' parameter.") flags.DEFINE_string("exp_name", None, "Experiment name") flags.DEFINE_string( "model_base_dir", None, "The output directory where the model checkpoints will be written.") flags.DEFINE_boolean( "debug", False, "Whether to run training without connecting to Neptune.ai") # Hyper parameters flags.DEFINE_float("learning_rate", None, "Learning rate") flags.DEFINE_integer("per_device_batch_size", None, "Per device batch size") flags.DEFINE_integer("num_train_steps", None, "Number of training steps") flags.DEFINE_integer("warmup_steps", None, "Number of warmup training steps") def validate_config(config): """Verify all paths in the config exist.""" for value in config.values(): if isinstance(value, str) and value.startswith('/'): if len(tf.io.gfile.glob(value)) == 0: raise ValueError('Invalid path %s' % value) elif isinstance(value, dict): validate_config(value) def get_and_validate_config(): with tf.io.gfile.GFile(FLAGS.config_file, "r") as reader: config = json.load(reader) if FLAGS.learning_rate is not None: config["learning_rate"] = FLAGS.learning_rate if FLAGS.per_device_batch_size is not None: config["per_device_batch_size"] = FLAGS.per_device_batch_size if FLAGS.num_train_steps is not None: config["num_train_steps"] = FLAGS.num_train_steps if FLAGS.warmup_steps is not None: config["warmup_steps"] = FLAGS.warmup_steps validate_config(config) return config def get_tags(config): TAGS = { 'task': 'task_name', 'lr': 'learning_rate', } def get_tag(prefix, name): if name in config: return prefix + ':' + str(config[name]) else: return None tags = [get_tag(k, v) for (k, v) in TAGS.items()] tags = list(filter(None, tags)) return tags def get_neptune_experiment(config): if not FLAGS.debug: neptune.init() return neptune.create_experiment(name=FLAGS.exp_name, params=config, tags=get_tags(config), git_info=neptune.utils.get_git_info(), hostname=socket.gethostname()) else: return None def main(argv): if len(argv) > 1: raise app.UsageError("Too many command-line arguments.") # Hide any GPUs form TensorFlow. Otherwise TF might reserve memory and make # it unavailable to JAX. tf.config.experimental.set_visible_devices([], "GPU") logging.info("JAX process: %d / %d", jax.process_index(), jax.process_count()) logging.info("JAX local devices: %r", jax.local_devices()) config = get_and_validate_config() experiment = get_neptune_experiment(config) if experiment is not None: exp_id = experiment.id model_dir = os.path.join(FLAGS.model_base_dir, exp_id) else: exp_id = None model_dir = tempfile.mkdtemp(prefix='debug_', dir=FLAGS.model_base_dir) config['exp_name'] = FLAGS.exp_name config['exp_id'] = exp_id config['model_dir'] = model_dir tf.io.gfile.makedirs(model_dir) train(ml_collections.ConfigDict(config)) if experiment is not None: experiment.stop() if __name__ == "__main__": flags.mark_flags_as_required(['config_file', 'exp_name', 'model_base_dir']) app.run(main)
[ "neptune.init", "neptune.utils.get_git_info" ]
[((937, 1102), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""config_file"""', 'None', '"""Path to file that contains JSON serialized model configuration. If thisis specified, ignores \'config\' parameter."""'], {}), '(\'config_file\', None,\n "Path to file that contains JSON serialized model configuration. If thisis specified, ignores \'config\' parameter."\n )\n', (956, 1102), False, 'from absl import flags\n'), ((1110, 1166), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""exp_name"""', 'None', '"""Experiment name"""'], {}), "('exp_name', None, 'Experiment name')\n", (1129, 1166), False, 'from absl import flags\n'), ((1167, 1283), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""model_base_dir"""', 'None', '"""The output directory where the model checkpoints will be written."""'], {}), "('model_base_dir', None,\n 'The output directory where the model checkpoints will be written.')\n", (1186, 1283), False, 'from absl import flags\n'), ((1289, 1389), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""debug"""', '(False)', '"""Whether to run training without connecting to Neptune.ai"""'], {}), "('debug', False,\n 'Whether to run training without connecting to Neptune.ai')\n", (1309, 1389), False, 'from absl import flags\n'), ((1411, 1469), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""learning_rate"""', 'None', '"""Learning rate"""'], {}), "('learning_rate', None, 'Learning rate')\n", (1429, 1469), False, 'from absl import flags\n'), ((1470, 1546), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""per_device_batch_size"""', 'None', '"""Per device batch size"""'], {}), "('per_device_batch_size', None, 'Per device batch size')\n", (1490, 1546), False, 'from absl import flags\n'), ((1547, 1620), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_train_steps"""', 'None', '"""Number of training steps"""'], {}), "('num_train_steps', None, 'Number of training steps')\n", (1567, 1620), False, 'from absl import flags\n'), ((1621, 1698), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""warmup_steps"""', 'None', '"""Number of warmup training steps"""'], {}), "('warmup_steps', None, 'Number of warmup training steps')\n", (1641, 1698), False, 'from absl import flags\n'), ((3519, 3572), 'tensorflow.compat.v1.config.experimental.set_visible_devices', 'tf.config.experimental.set_visible_devices', (['[]', '"""GPU"""'], {}), "([], 'GPU')\n", (3561, 3572), True, 'import tensorflow.compat.v1 as tf\n'), ((4121, 4152), 'tensorflow.compat.v1.io.gfile.makedirs', 'tf.io.gfile.makedirs', (['model_dir'], {}), '(model_dir)\n', (4141, 4152), True, 'import tensorflow.compat.v1 as tf\n'), ((4280, 4355), 'absl.flags.mark_flags_as_required', 'flags.mark_flags_as_required', (["['config_file', 'exp_name', 'model_base_dir']"], {}), "(['config_file', 'exp_name', 'model_base_dir'])\n", (4308, 4355), False, 'from absl import flags\n'), ((4358, 4371), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (4365, 4371), False, 'from absl import app\n'), ((2064, 2105), 'tensorflow.compat.v1.io.gfile.GFile', 'tf.io.gfile.GFile', (['FLAGS.config_file', '"""r"""'], {}), "(FLAGS.config_file, 'r')\n", (2081, 2105), True, 'import tensorflow.compat.v1 as tf\n'), ((2130, 2147), 'json.load', 'json.load', (['reader'], {}), '(reader)\n', (2139, 2147), False, 'import json\n'), ((2959, 2973), 'neptune.init', 'neptune.init', ([], {}), '()\n', (2971, 2973), False, 'import neptune\n'), ((3360, 3410), 'absl.app.UsageError', 'app.UsageError', (['"""Too many command-line arguments."""'], {}), "('Too many command-line arguments.')\n", (3374, 3410), False, 'from absl import app\n'), ((3613, 3632), 'jax.process_index', 'jax.process_index', ([], {}), '()\n', (3630, 3632), False, 'import jax\n'), ((3634, 3653), 'jax.process_count', 'jax.process_count', ([], {}), '()\n', (3651, 3653), False, 'import jax\n'), ((3695, 3714), 'jax.local_devices', 'jax.local_devices', ([], {}), '()\n', (3712, 3714), False, 'import jax\n'), ((3873, 3915), 'os.path.join', 'os.path.join', (['FLAGS.model_base_dir', 'exp_id'], {}), '(FLAGS.model_base_dir, exp_id)\n', (3885, 3915), False, 'import os\n'), ((3958, 4017), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'prefix': '"""debug_"""', 'dir': 'FLAGS.model_base_dir'}), "(prefix='debug_', dir=FLAGS.model_base_dir)\n", (3974, 4017), False, 'import tempfile\n'), ((4162, 4195), 'ml_collections.ConfigDict', 'ml_collections.ConfigDict', (['config'], {}), '(config)\n', (4187, 4195), False, 'import ml_collections\n'), ((3190, 3218), 'neptune.utils.get_git_info', 'neptune.utils.get_git_info', ([], {}), '()\n', (3216, 3218), False, 'import neptune\n'), ((3266, 3286), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (3284, 3286), False, 'import socket\n'), ((1878, 1901), 'tensorflow.compat.v1.io.gfile.glob', 'tf.io.gfile.glob', (['value'], {}), '(value)\n', (1894, 1901), True, 'import tensorflow.compat.v1 as tf\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=protected-access from datetime import datetime from mock import MagicMock from neptune.new.internal.operation import AssignDatetime from neptune.new.attributes.atoms.datetime import Datetime, DatetimeVal from tests.neptune.new.attributes.test_attribute_base import TestAttributeBase class TestDatetime(TestAttributeBase): def test_assign(self): now = datetime.now() value_and_expected = [ (now, now.replace(microsecond=1000*int(now.microsecond/1000))), (DatetimeVal(now), now.replace(microsecond=1000*int(now.microsecond/1000))) ] for value, expected in value_and_expected: processor = MagicMock() exp, path, wait = self._create_run(processor), self._random_path(), self._random_wait() var = Datetime(exp, path) var.assign(value, wait=wait) processor.enqueue_operation.assert_called_once_with(AssignDatetime(path, expected), wait) def test_assign_type_error(self): values = [55, None] for value in values: with self.assertRaises(TypeError): Datetime(MagicMock(), MagicMock()).assign(value) def test_get(self): exp, path = self._create_run(), self._random_path() var = Datetime(exp, path) now = datetime.now() now = now.replace(microsecond=int(now.microsecond/1000)*1000) var.assign(now) self.assertEqual(now, var.fetch())
[ "neptune.new.attributes.atoms.datetime.DatetimeVal", "neptune.new.attributes.atoms.datetime.Datetime", "neptune.new.internal.operation.AssignDatetime" ]
[((984, 998), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (996, 998), False, 'from datetime import datetime\n'), ((1880, 1899), 'neptune.new.attributes.atoms.datetime.Datetime', 'Datetime', (['exp', 'path'], {}), '(exp, path)\n', (1888, 1899), False, 'from neptune.new.attributes.atoms.datetime import Datetime, DatetimeVal\n'), ((1914, 1928), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1926, 1928), False, 'from datetime import datetime\n'), ((1280, 1291), 'mock.MagicMock', 'MagicMock', ([], {}), '()\n', (1289, 1291), False, 'from mock import MagicMock\n'), ((1410, 1429), 'neptune.new.attributes.atoms.datetime.Datetime', 'Datetime', (['exp', 'path'], {}), '(exp, path)\n', (1418, 1429), False, 'from neptune.new.attributes.atoms.datetime import Datetime, DatetimeVal\n'), ((1119, 1135), 'neptune.new.attributes.atoms.datetime.DatetimeVal', 'DatetimeVal', (['now'], {}), '(now)\n', (1130, 1135), False, 'from neptune.new.attributes.atoms.datetime import Datetime, DatetimeVal\n'), ((1535, 1565), 'neptune.new.internal.operation.AssignDatetime', 'AssignDatetime', (['path', 'expected'], {}), '(path, expected)\n', (1549, 1565), False, 'from neptune.new.internal.operation import AssignDatetime\n'), ((1741, 1752), 'mock.MagicMock', 'MagicMock', ([], {}), '()\n', (1750, 1752), False, 'from mock import MagicMock\n'), ((1754, 1765), 'mock.MagicMock', 'MagicMock', ([], {}), '()\n', (1763, 1765), False, 'from mock import MagicMock\n')]
import random import neptune import numpy as np import tensorflow as tf import neptune_tensorboard as neptune_tb from absl import flags from absl import app from data_processor import read_data from tensorflow.keras import callbacks, Sequential from tensorflow.keras.layers import SimpleRNN, Dense, Dropout, BatchNormalization from tensorflow.keras.optimizers import Adam flags.DEFINE_string('mode', 'train', 'In which mode should the program be run train/eval') flags.DEFINE_float('dropout', 0.2, 'Set dropout') flags.DEFINE_float('learning_rate', 0.0001, 'Set learning rate') flags.DEFINE_string('activation', 'relu', 'Set activation method') flags.DEFINE_string('data_dir', '../data/uniform_200k/', 'Relative path to the data folder') flags.DEFINE_integer('epochs', 1, 'Number of epochs') flags.DEFINE_integer('rnn_filter', 128, 'Number of units in RNN') FLAGS = flags.FLAGS RUN_NAME = 'run_{}'.format(random.getrandbits(64)) EXPERIMENT_LOG_DIR = 'logs/{}'.format(RUN_NAME) def input_fn(trainingset_path): x_train, y_train = read_data(trainingset_path, 'train') x_eval, y_eval = read_data(trainingset_path, 'eval') x_train = np.reshape(x_train.values, (-1, x_train.shape[1], 1)) y_train = np.reshape(y_train.values, (-1, 1)) x_eval = np.reshape(x_eval.values, (-1, x_eval.shape[1], 1)) y_eval = np.reshape(y_eval.values, (-1, 1)) return x_train, y_train, x_eval, y_eval def create_rnn(input_shape, hparams): model = Sequential() for _ in range(1): model.add(SimpleRNN(units=hparams['rnn_filter'], return_sequences=True)) model.add(SimpleRNN(units=hparams['rnn_filter'])) for _ in range(2): model.add(Dense(128, activation='relu')) model.add(Dropout(hparams['dropout'])) model.add(BatchNormalization()) return model def train(hparams, dataset_path): neptune.init(project_qualified_name='kowson/OLN') with neptune.create_experiment(name="Recurrent neural network", params=hparams, tags=["RNN", "grid", "10k_uniform", "testing", "data_v2", "mse"]): x_train, y_train, x_eval, y_eval = input_fn(dataset_path) model = create_rnn(hparams) opt = Adam(lr=hparams["learning_rate"], decay=1e-3 / 200) model.compile(loss=tf.keras.losses.MeanSquaredError(), optimizer=opt) tbCallBack = callbacks.TensorBoard(log_dir=EXPERIMENT_LOG_DIR) history_callback = model.fit( x_train, y_train, validation_data=(x_eval, y_eval), epochs=hparams["num_epochs"], batch_size=hparams["batch_size"], callbacks=[tbCallBack] ) def create_experiment(): neptune_tb.integrate_with_tensorflow() hyper_params = { "shuffle": False, "num_threads": 1, "batch_size": 16384, "initializer": "uniform_unit_scaling", "rnn_filter": FLAGS.rnn_filter, "dropout": FLAGS.dropout, "learning_rate": FLAGS.learning_rate, "activation": 'relu', 'num_epochs': FLAGS.epochs, } data_dir = FLAGS.data_dir print('--- Starting trial ---') train(hyper_params, data_dir) def main(argv): if FLAGS.mode == 'train': create_experiment() elif FLAGS.mode == 'eval': pass if __name__ == '__main__': app.run(main)
[ "neptune.create_experiment", "neptune.init" ]
[((374, 468), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""mode"""', '"""train"""', '"""In which mode should the program be run train/eval"""'], {}), "('mode', 'train',\n 'In which mode should the program be run train/eval')\n", (393, 468), False, 'from absl import flags\n'), ((465, 514), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""dropout"""', '(0.2)', '"""Set dropout"""'], {}), "('dropout', 0.2, 'Set dropout')\n", (483, 514), False, 'from absl import flags\n'), ((515, 579), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""learning_rate"""', '(0.0001)', '"""Set learning rate"""'], {}), "('learning_rate', 0.0001, 'Set learning rate')\n", (533, 579), False, 'from absl import flags\n'), ((580, 646), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""activation"""', '"""relu"""', '"""Set activation method"""'], {}), "('activation', 'relu', 'Set activation method')\n", (599, 646), False, 'from absl import flags\n'), ((647, 743), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""data_dir"""', '"""../data/uniform_200k/"""', '"""Relative path to the data folder"""'], {}), "('data_dir', '../data/uniform_200k/',\n 'Relative path to the data folder')\n", (666, 743), False, 'from absl import flags\n'), ((740, 793), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""epochs"""', '(1)', '"""Number of epochs"""'], {}), "('epochs', 1, 'Number of epochs')\n", (760, 793), False, 'from absl import flags\n'), ((794, 859), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""rnn_filter"""', '(128)', '"""Number of units in RNN"""'], {}), "('rnn_filter', 128, 'Number of units in RNN')\n", (814, 859), False, 'from absl import flags\n'), ((909, 931), 'random.getrandbits', 'random.getrandbits', (['(64)'], {}), '(64)\n', (927, 931), False, 'import random\n'), ((1037, 1073), 'data_processor.read_data', 'read_data', (['trainingset_path', '"""train"""'], {}), "(trainingset_path, 'train')\n", (1046, 1073), False, 'from data_processor import read_data\n'), ((1095, 1130), 'data_processor.read_data', 'read_data', (['trainingset_path', '"""eval"""'], {}), "(trainingset_path, 'eval')\n", (1104, 1130), False, 'from data_processor import read_data\n'), ((1145, 1198), 'numpy.reshape', 'np.reshape', (['x_train.values', '(-1, x_train.shape[1], 1)'], {}), '(x_train.values, (-1, x_train.shape[1], 1))\n', (1155, 1198), True, 'import numpy as np\n'), ((1213, 1248), 'numpy.reshape', 'np.reshape', (['y_train.values', '(-1, 1)'], {}), '(y_train.values, (-1, 1))\n', (1223, 1248), True, 'import numpy as np\n'), ((1262, 1313), 'numpy.reshape', 'np.reshape', (['x_eval.values', '(-1, x_eval.shape[1], 1)'], {}), '(x_eval.values, (-1, x_eval.shape[1], 1))\n', (1272, 1313), True, 'import numpy as np\n'), ((1327, 1361), 'numpy.reshape', 'np.reshape', (['y_eval.values', '(-1, 1)'], {}), '(y_eval.values, (-1, 1))\n', (1337, 1361), True, 'import numpy as np\n'), ((1458, 1470), 'tensorflow.keras.Sequential', 'Sequential', ([], {}), '()\n', (1468, 1470), False, 'from tensorflow.keras import callbacks, Sequential\n'), ((1848, 1897), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""kowson/OLN"""'}), "(project_qualified_name='kowson/OLN')\n", (1860, 1897), False, 'import neptune\n'), ((2748, 2786), 'neptune_tensorboard.integrate_with_tensorflow', 'neptune_tb.integrate_with_tensorflow', ([], {}), '()\n', (2784, 2786), True, 'import neptune_tensorboard as neptune_tb\n'), ((3418, 3431), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (3425, 3431), False, 'from absl import app\n'), ((1590, 1628), 'tensorflow.keras.layers.SimpleRNN', 'SimpleRNN', ([], {'units': "hparams['rnn_filter']"}), "(units=hparams['rnn_filter'])\n", (1599, 1628), False, 'from tensorflow.keras.layers import SimpleRNN, Dense, Dropout, BatchNormalization\n'), ((1907, 2051), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""Recurrent neural network"""', 'params': 'hparams', 'tags': "['RNN', 'grid', '10k_uniform', 'testing', 'data_v2', 'mse']"}), "(name='Recurrent neural network', params=hparams,\n tags=['RNN', 'grid', '10k_uniform', 'testing', 'data_v2', 'mse'])\n", (1932, 2051), False, 'import neptune\n'), ((2236, 2288), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': "hparams['learning_rate']", 'decay': '(0.001 / 200)'}), "(lr=hparams['learning_rate'], decay=0.001 / 200)\n", (2240, 2288), False, 'from tensorflow.keras.optimizers import Adam\n'), ((2407, 2456), 'tensorflow.keras.callbacks.TensorBoard', 'callbacks.TensorBoard', ([], {'log_dir': 'EXPERIMENT_LOG_DIR'}), '(log_dir=EXPERIMENT_LOG_DIR)\n', (2428, 2456), False, 'from tensorflow.keras import callbacks, Sequential\n'), ((1513, 1574), 'tensorflow.keras.layers.SimpleRNN', 'SimpleRNN', ([], {'units': "hparams['rnn_filter']", 'return_sequences': '(True)'}), "(units=hparams['rnn_filter'], return_sequences=True)\n", (1522, 1574), False, 'from tensorflow.keras.layers import SimpleRNN, Dense, Dropout, BatchNormalization\n'), ((1672, 1701), 'tensorflow.keras.layers.Dense', 'Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (1677, 1701), False, 'from tensorflow.keras.layers import SimpleRNN, Dense, Dropout, BatchNormalization\n'), ((1721, 1748), 'tensorflow.keras.layers.Dropout', 'Dropout', (["hparams['dropout']"], {}), "(hparams['dropout'])\n", (1728, 1748), False, 'from tensorflow.keras.layers import SimpleRNN, Dense, Dropout, BatchNormalization\n'), ((1768, 1788), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1786, 1788), False, 'from tensorflow.keras.layers import SimpleRNN, Dense, Dropout, BatchNormalization\n'), ((2334, 2368), 'tensorflow.keras.losses.MeanSquaredError', 'tf.keras.losses.MeanSquaredError', ([], {}), '()\n', (2366, 2368), True, 'import tensorflow as tf\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=protected-access import uuid from neptune.new.exceptions import MetadataInconsistency from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor from neptune.new.internal.operation import ( AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet, ) from tests.neptune.new.attributes.test_attribute_base import TestAttributeBase FLog = LogFloats.ValueType SLog = LogStrings.ValueType ILog = LogImages.ValueType class TestOperationsPreprocessor(TestAttributeBase): def test_delete_attribute(self): # given processor = OperationsPreprocessor() operations = [ DeleteAttribute(["a"]), AssignFloat(["a"], 1), DeleteAttribute(["a"]), AssignString(["b"], "2"), DeleteAttribute(["b"]), AssignString(["c"], "2"), AssignString(["c"], "3"), DeleteAttribute(["c"]), DeleteAttribute(["d"]), DeleteAttribute(["d"]), DeleteAttribute(["e"]), ] # when processor.process(operations) # then result = processor.get_operations() self.assertEqual(result.upload_operations, []) self.assertEqual(result.artifact_operations, []) self.assertEqual( result.other_operations, [ DeleteAttribute(["a"]), AssignString(["b"], "2"), DeleteAttribute(["b"]), AssignString(["c"], "3"), DeleteAttribute(["c"]), DeleteAttribute(["d"]), DeleteAttribute(["e"]), ], ) self.assertEqual(result.errors, []) self.assertEqual(processor.processed_ops_count, len(operations)) def test_assign(self): # given processor = OperationsPreprocessor() operations = [ AssignFloat(["a"], 1), DeleteAttribute(["a"]), AssignString(["a"], "111"), DeleteAttribute(["b"]), AssignFloat(["b"], 2), AssignFloat(["c"], 3), AssignString(["c"], "333"), AssignString(["d"], "44"), AssignFloat(["e"], 5), AssignFloat(["e"], 10), AssignFloat(["e"], 33), ] # when processor.process(operations) # then result = processor.get_operations() self.assertEqual(result.upload_operations, []) self.assertEqual(result.artifact_operations, []) self.assertEqual( result.other_operations, [ AssignFloat(["a"], 1), DeleteAttribute(["a"]), AssignString(["a"], "111"), DeleteAttribute(["b"]), AssignFloat(["b"], 2), AssignFloat(["c"], 3), AssignString(["d"], "44"), AssignFloat(["e"], 33), ], ) self.assertEqual( result.errors, [ MetadataInconsistency( "Cannot perform AssignString operation on c: Attribute is not a String" ) ], ) self.assertEqual(processor.processed_ops_count, len(operations)) def test_series(self): # given processor = OperationsPreprocessor() operations = [ LogFloats(["a"], [FLog(1, 2, 3)]), ConfigFloatSeries(["a"], min=7, max=70, unit="%"), DeleteAttribute(["a"]), LogStrings(["a"], [SLog("111", 3, 4)]), DeleteAttribute(["b"]), LogStrings(["b"], [SLog("222", None, 6)]), LogFloats(["c"], [FLog(1, 2, 3)]), LogFloats(["c"], [FLog(10, 20, 30), FLog(100, 200, 300)]), LogStrings(["d"], [SLog("4", 111, 222)]), ClearFloatLog(["e"]), LogImages(["f"], [ILog("1", 2, 3)]), LogImages(["f"], [ILog("10", 20, 30), FLog("100", 200, 300)]), LogImages(["f"], [ILog("1", 2, 3)]), LogImages(["f"], [ILog("10", 20, 30), FLog("100", 200, 300)]), ClearImageLog(["f"]), LogImages(["f"], [ILog("3", 20, 30), FLog("4", 200, 300)]), LogImages(["f"], [ILog("5", 2, 3)]), LogImages(["f"], [ILog("8", 20, 30), FLog("1000", 200, 300)]), LogImages(["g"], [ILog("10", 20, 30), FLog("100", 200, 300)]), ClearImageLog(["g"]), AssignString(["h"], "44"), LogFloats(["h"], [FLog(10, 20, 30), FLog(100, 200, 300)]), LogFloats(["i"], [FLog(1, 2, 3)]), ConfigFloatSeries(["i"], min=7, max=70, unit="%"), ClearFloatLog(["i"]), LogFloats(["i"], [FLog(10, 20, 30), FLog(100, 200, 300)]), ] # when processor.process(operations) # then result = processor.get_operations() self.assertEqual(result.upload_operations, []) self.assertEqual(result.artifact_operations, []) self.assertEqual( result.other_operations, [ LogFloats(["a"], [FLog(1, 2, 3)]), DeleteAttribute(["a"]), LogStrings(["a"], [FLog("111", 3, 4)]), DeleteAttribute(["b"]), LogStrings(["b"], [SLog("222", None, 6)]), LogFloats(["c"], [FLog(1, 2, 3), FLog(10, 20, 30), FLog(100, 200, 300)]), LogStrings(["d"], [SLog("4", 111, 222)]), ClearFloatLog(["e"]), ClearImageLog(["f"]), LogImages( ["f"], [ ILog("3", 20, 30), FLog("4", 200, 300), ILog("5", 2, 3), ILog("8", 20, 30), FLog("1000", 200, 300), ], ), ClearImageLog(["g"]), AssignString(["h"], "44"), ClearFloatLog(["i"]), LogFloats(["i"], [FLog(10, 20, 30), FLog(100, 200, 300)]), ConfigFloatSeries(["i"], min=7, max=70, unit="%"), ], ) self.assertEqual( result.errors, [ MetadataInconsistency( "Cannot perform LogFloats operation on h: Attribute is not a Float Series" ) ], ) self.assertEqual(processor.processed_ops_count, len(operations)) def test_sets(self): # given processor = OperationsPreprocessor() operations = [ AddStrings(["a"], {"xx", "y", "abc"}), DeleteAttribute(["a"]), AddStrings(["a"], {"hhh", "gij"}), DeleteAttribute(["b"]), RemoveStrings(["b"], {"abc", "defgh"}), AddStrings(["c"], {"hhh", "gij"}), RemoveStrings(["c"], {"abc", "defgh"}), AddStrings(["c"], {"qqq"}), ClearStringSet(["d"]), RemoveStrings(["e"], {"abc", "defgh"}), AddStrings(["e"], {"qqq"}), ClearStringSet(["e"]), AddStrings(["f"], {"hhh", "gij"}), RemoveStrings(["f"], {"abc", "defgh"}), AddStrings(["f"], {"qqq"}), ClearStringSet(["f"]), AddStrings(["f"], {"xx", "y", "abc"}), RemoveStrings(["f"], {"abc", "defgh"}), AssignString(["h"], "44"), RemoveStrings(["h"], {""}), AssignFloat(["i"], 5), AddStrings(["i"], {""}), ] # when processor.process(operations) # then result = processor.get_operations() self.assertEqual(result.upload_operations, []) self.assertEqual(result.artifact_operations, []) self.assertEqual( result.other_operations, [ AddStrings(["a"], {"xx", "y", "abc"}), DeleteAttribute(["a"]), AddStrings(["a"], {"hhh", "gij"}), DeleteAttribute(["b"]), RemoveStrings(["b"], {"abc", "defgh"}), AddStrings(["c"], {"hhh", "gij"}), RemoveStrings(["c"], {"abc", "defgh"}), AddStrings(["c"], {"qqq"}), ClearStringSet(["d"]), ClearStringSet(["e"]), ClearStringSet(["f"]), AddStrings(["f"], {"xx", "y", "abc"}), RemoveStrings(["f"], {"abc", "defgh"}), AssignString(["h"], "44"), AssignFloat(["i"], 5), ], ) self.assertEqual( result.errors, [ MetadataInconsistency( "Cannot perform RemoveStrings operation on h: Attribute is not a String Set" ), MetadataInconsistency( "Cannot perform AddStrings operation on i: Attribute is not a String Set" ), ], ) self.assertEqual(processor.processed_ops_count, len(operations)) def test_file_set(self): # given processor = OperationsPreprocessor() operations = [ UploadFileSet(["a"], ["xx", "y", "abc"], reset=False), UploadFileSet(["a"], ["hhh", "gij"], reset=False), UploadFileSet(["b"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["hhh", "gij"], reset=False), UploadFileSet(["c"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["qqq"], reset=False), UploadFileSet(["d"], ["hhh", "gij"], reset=False), AssignFloat(["e"], 5), UploadFileSet(["e"], [""], reset=False), ] # when processor.process(operations) # then result = processor.get_operations() self.assertEqual( result.upload_operations, [ UploadFileSet(["a"], ["xx", "y", "abc"], reset=False), UploadFileSet(["a"], ["hhh", "gij"], reset=False), UploadFileSet(["b"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["qqq"], reset=False), UploadFileSet(["d"], ["hhh", "gij"], reset=False), ], ) self.assertEqual(result.artifact_operations, []) self.assertEqual( result.other_operations, [ AssignFloat(["e"], 5), ], ) self.assertEqual( result.errors, [ MetadataInconsistency( "Cannot perform UploadFileSet operation on e: Attribute is not a File Set" ) ], ) self.assertEqual(processor.processed_ops_count, len(operations)) def test_file_ops_delete(self): # given processor = OperationsPreprocessor() operations = [ UploadFileSet(["b"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["hhh", "gij"], reset=False), UploadFileSet(["c"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["qqq"], reset=False), UploadFileSet(["d"], ["hhh", "gij"], reset=False), DeleteAttribute(["a"]), UploadFileSet(["a"], ["xx", "y", "abc"], reset=False), UploadFileSet(["a"], ["hhh", "gij"], reset=False), DeleteAttribute(["b"]), ] # when processor.process(operations) # then: there's a cutoff after DeleteAttribute(["a"]) result = processor.get_operations() self.assertEqual( result.upload_operations, [ UploadFileSet(["b"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["abc", "defgh"], reset=True), UploadFileSet(["c"], ["qqq"], reset=False), UploadFileSet(["d"], ["hhh", "gij"], reset=False), ], ) self.assertEqual(result.artifact_operations, []) self.assertEqual( result.other_operations, [ DeleteAttribute(["a"]), ], ) self.assertEqual(result.errors, []) self.assertEqual(processor.processed_ops_count, 6) def test_artifacts(self): # given processor = OperationsPreprocessor() project_uuid = str(uuid.uuid4()) operations = [ TrackFilesToArtifact(["a"], project_uuid, [("dir1/", None)]), DeleteAttribute(["a"]), TrackFilesToArtifact(["b"], project_uuid, [("dir1/", None)]), TrackFilesToArtifact(["b"], project_uuid, [("dir2/dir3/", "dir2/")]), TrackFilesToArtifact(["b"], project_uuid, [("dir4/dir5/", "dir4/")]), AssignFloat(["c"], 5), TrackFilesToArtifact(["c"], project_uuid, [("dir1/", None)]), TrackFilesToArtifact(["d"], project_uuid, [("dir2/dir3/", "dir2/")]), TrackFilesToArtifact(["d"], project_uuid, [("dir4/", None)]), TrackFilesToArtifact(["e"], project_uuid, [("dir1/", None)]), TrackFilesToArtifact(["e"], project_uuid, [("dir2/dir3/", "dir2/")]), TrackFilesToArtifact(["f"], project_uuid, [("dir1/", None)]), TrackFilesToArtifact(["f"], project_uuid, [("dir2/dir3/", "dir2/")]), TrackFilesToArtifact(["f"], project_uuid, [("dir4/", None)]), TrackFilesToArtifact(["a"], project_uuid, [("dir1/", None)]), ] # when processor.process(operations) # then: there's a cutoff before second TrackFilesToArtifact(["a"]) due to DeleteAttribute(["a"]) result = processor.get_operations() self.assertEqual(result.upload_operations, []) self.assertEqual( result.artifact_operations, [ TrackFilesToArtifact(["a"], project_uuid, [("dir1/", None)]), TrackFilesToArtifact( ["b"], project_uuid, [("dir1/", None), ("dir2/dir3/", "dir2/"), ("dir4/dir5/", "dir4/")], ), TrackFilesToArtifact( ["d"], project_uuid, [("dir2/dir3/", "dir2/"), ("dir4/", None)] ), TrackFilesToArtifact( ["e"], project_uuid, [("dir1/", None), ("dir2/dir3/", "dir2/")] ), TrackFilesToArtifact( ["f"], project_uuid, [("dir1/", None), ("dir2/dir3/", "dir2/"), ("dir4/", None)], ), ], ) self.assertEqual( result.other_operations, [ DeleteAttribute(["a"]), AssignFloat(["c"], 5), ], ) self.assertEqual( result.errors, [ MetadataInconsistency( "Cannot perform TrackFilesToArtifact operation on c: Attribute is not a Artifact" ), ], ) self.assertEqual(processor.processed_ops_count, len(operations) - 1)
[ "neptune.new.internal.operation.AssignString", "neptune.new.internal.operation.ClearFloatLog", "neptune.new.internal.operation.ClearImageLog", "neptune.new.internal.operation.ConfigFloatSeries", "neptune.new.internal.operation.ClearStringSet", "neptune.new.internal.operation.RemoveStrings", "neptune.new...
[((1392, 1416), 'neptune.new.internal.backends.operations_preprocessor.OperationsPreprocessor', 'OperationsPreprocessor', ([], {}), '()\n', (1414, 1416), False, 'from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor\n'), ((2645, 2669), 'neptune.new.internal.backends.operations_preprocessor.OperationsPreprocessor', 'OperationsPreprocessor', ([], {}), '()\n', (2667, 2669), False, 'from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor\n'), ((4137, 4161), 'neptune.new.internal.backends.operations_preprocessor.OperationsPreprocessor', 'OperationsPreprocessor', ([], {}), '()\n', (4159, 4161), False, 'from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor\n'), ((7379, 7403), 'neptune.new.internal.backends.operations_preprocessor.OperationsPreprocessor', 'OperationsPreprocessor', ([], {}), '()\n', (7401, 7403), False, 'from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor\n'), ((9958, 9982), 'neptune.new.internal.backends.operations_preprocessor.OperationsPreprocessor', 'OperationsPreprocessor', ([], {}), '()\n', (9980, 9982), False, 'from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor\n'), ((11751, 11775), 'neptune.new.internal.backends.operations_preprocessor.OperationsPreprocessor', 'OperationsPreprocessor', ([], {}), '()\n', (11773, 11775), False, 'from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor\n'), ((13218, 13242), 'neptune.new.internal.backends.operations_preprocessor.OperationsPreprocessor', 'OperationsPreprocessor', ([], {}), '()\n', (13240, 13242), False, 'from neptune.new.internal.backends.operations_preprocessor import OperationsPreprocessor\n'), ((1453, 1475), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (1468, 1475), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1489, 1510), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['a']", '(1)'], {}), "(['a'], 1)\n", (1500, 1510), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1524, 1546), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (1539, 1546), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1560, 1584), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['b']", '"""2"""'], {}), "(['b'], '2')\n", (1572, 1584), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1598, 1620), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (1613, 1620), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1634, 1658), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['c']", '"""2"""'], {}), "(['c'], '2')\n", (1646, 1658), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1672, 1696), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['c']", '"""3"""'], {}), "(['c'], '3')\n", (1684, 1696), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1710, 1732), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['c']"], {}), "(['c'])\n", (1725, 1732), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1746, 1768), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['d']"], {}), "(['d'])\n", (1761, 1768), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1782, 1804), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['d']"], {}), "(['d'])\n", (1797, 1804), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((1818, 1840), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['e']"], {}), "(['e'])\n", (1833, 1840), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2706, 2727), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['a']", '(1)'], {}), "(['a'], 1)\n", (2717, 2727), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2741, 2763), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (2756, 2763), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2777, 2803), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['a']", '"""111"""'], {}), "(['a'], '111')\n", (2789, 2803), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2817, 2839), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (2832, 2839), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2853, 2874), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['b']", '(2)'], {}), "(['b'], 2)\n", (2864, 2874), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2888, 2909), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['c']", '(3)'], {}), "(['c'], 3)\n", (2899, 2909), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2923, 2949), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['c']", '"""333"""'], {}), "(['c'], '333')\n", (2935, 2949), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2963, 2988), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['d']", '"""44"""'], {}), "(['d'], '44')\n", (2975, 2988), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3002, 3023), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['e']", '(5)'], {}), "(['e'], 5)\n", (3013, 3023), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3037, 3059), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['e']", '(10)'], {}), "(['e'], 10)\n", (3048, 3059), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3073, 3095), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['e']", '(33)'], {}), "(['e'], 33)\n", (3084, 3095), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((4245, 4294), 'neptune.new.internal.operation.ConfigFloatSeries', 'ConfigFloatSeries', (["['a']"], {'min': '(7)', 'max': '(70)', 'unit': '"""%"""'}), "(['a'], min=7, max=70, unit='%')\n", (4262, 4294), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((4308, 4330), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (4323, 4330), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((4396, 4418), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (4411, 4418), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((4659, 4679), 'neptune.new.internal.operation.ClearFloatLog', 'ClearFloatLog', (["['e']"], {}), "(['e'])\n", (4672, 4679), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((4941, 4961), 'neptune.new.internal.operation.ClearImageLog', 'ClearImageLog', (["['f']"], {}), "(['f'])\n", (4954, 4961), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((5246, 5266), 'neptune.new.internal.operation.ClearImageLog', 'ClearImageLog', (["['g']"], {}), "(['g'])\n", (5259, 5266), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((5280, 5305), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['h']", '"""44"""'], {}), "(['h'], '44')\n", (5292, 5305), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((5437, 5486), 'neptune.new.internal.operation.ConfigFloatSeries', 'ConfigFloatSeries', (["['i']"], {'min': '(7)', 'max': '(70)', 'unit': '"""%"""'}), "(['i'], min=7, max=70, unit='%')\n", (5454, 5486), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((5500, 5520), 'neptune.new.internal.operation.ClearFloatLog', 'ClearFloatLog', (["['i']"], {}), "(['i'])\n", (5513, 5520), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7440, 7477), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['a']", "{'xx', 'y', 'abc'}"], {}), "(['a'], {'xx', 'y', 'abc'})\n", (7450, 7477), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7491, 7513), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (7506, 7513), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7527, 7560), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['a']", "{'hhh', 'gij'}"], {}), "(['a'], {'hhh', 'gij'})\n", (7537, 7560), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7574, 7596), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (7589, 7596), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7610, 7648), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['b']", "{'abc', 'defgh'}"], {}), "(['b'], {'abc', 'defgh'})\n", (7623, 7648), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7662, 7695), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['c']", "{'hhh', 'gij'}"], {}), "(['c'], {'hhh', 'gij'})\n", (7672, 7695), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7709, 7747), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['c']", "{'abc', 'defgh'}"], {}), "(['c'], {'abc', 'defgh'})\n", (7722, 7747), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7761, 7787), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['c']", "{'qqq'}"], {}), "(['c'], {'qqq'})\n", (7771, 7787), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7801, 7822), 'neptune.new.internal.operation.ClearStringSet', 'ClearStringSet', (["['d']"], {}), "(['d'])\n", (7815, 7822), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7836, 7874), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['e']", "{'abc', 'defgh'}"], {}), "(['e'], {'abc', 'defgh'})\n", (7849, 7874), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7888, 7914), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['e']", "{'qqq'}"], {}), "(['e'], {'qqq'})\n", (7898, 7914), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7928, 7949), 'neptune.new.internal.operation.ClearStringSet', 'ClearStringSet', (["['e']"], {}), "(['e'])\n", (7942, 7949), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7963, 7996), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['f']", "{'hhh', 'gij'}"], {}), "(['f'], {'hhh', 'gij'})\n", (7973, 7996), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8010, 8048), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['f']", "{'abc', 'defgh'}"], {}), "(['f'], {'abc', 'defgh'})\n", (8023, 8048), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8062, 8088), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['f']", "{'qqq'}"], {}), "(['f'], {'qqq'})\n", (8072, 8088), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8102, 8123), 'neptune.new.internal.operation.ClearStringSet', 'ClearStringSet', (["['f']"], {}), "(['f'])\n", (8116, 8123), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8137, 8174), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['f']", "{'xx', 'y', 'abc'}"], {}), "(['f'], {'xx', 'y', 'abc'})\n", (8147, 8174), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8188, 8226), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['f']", "{'abc', 'defgh'}"], {}), "(['f'], {'abc', 'defgh'})\n", (8201, 8226), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8240, 8265), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['h']", '"""44"""'], {}), "(['h'], '44')\n", (8252, 8265), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8279, 8305), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['h']", "{''}"], {}), "(['h'], {''})\n", (8292, 8305), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8319, 8340), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['i']", '(5)'], {}), "(['i'], 5)\n", (8330, 8340), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8354, 8377), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['i']", "{''}"], {}), "(['i'], {''})\n", (8364, 8377), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10019, 10072), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['a']", "['xx', 'y', 'abc']"], {'reset': '(False)'}), "(['a'], ['xx', 'y', 'abc'], reset=False)\n", (10032, 10072), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10086, 10135), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['a']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['a'], ['hhh', 'gij'], reset=False)\n", (10099, 10135), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10149, 10199), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['b']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['b'], ['abc', 'defgh'], reset=True)\n", (10162, 10199), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10213, 10262), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['c'], ['hhh', 'gij'], reset=False)\n", (10226, 10262), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10276, 10326), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['c'], ['abc', 'defgh'], reset=True)\n", (10289, 10326), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10340, 10382), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['qqq']"], {'reset': '(False)'}), "(['c'], ['qqq'], reset=False)\n", (10353, 10382), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10396, 10445), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['d']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['d'], ['hhh', 'gij'], reset=False)\n", (10409, 10445), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10459, 10480), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['e']", '(5)'], {}), "(['e'], 5)\n", (10470, 10480), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10494, 10533), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['e']", "['']"], {'reset': '(False)'}), "(['e'], [''], reset=False)\n", (10507, 10533), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((11812, 11862), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['b']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['b'], ['abc', 'defgh'], reset=True)\n", (11825, 11862), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((11876, 11925), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['c'], ['hhh', 'gij'], reset=False)\n", (11889, 11925), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((11939, 11989), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['c'], ['abc', 'defgh'], reset=True)\n", (11952, 11989), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12003, 12045), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['qqq']"], {'reset': '(False)'}), "(['c'], ['qqq'], reset=False)\n", (12016, 12045), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12059, 12108), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['d']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['d'], ['hhh', 'gij'], reset=False)\n", (12072, 12108), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12122, 12144), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (12137, 12144), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12158, 12211), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['a']", "['xx', 'y', 'abc']"], {'reset': '(False)'}), "(['a'], ['xx', 'y', 'abc'], reset=False)\n", (12171, 12211), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12225, 12274), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['a']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['a'], ['hhh', 'gij'], reset=False)\n", (12238, 12274), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12288, 12310), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (12303, 12310), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13270, 13282), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (13280, 13282), False, 'import uuid\n'), ((13320, 13380), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['a']", 'project_uuid', "[('dir1/', None)]"], {}), "(['a'], project_uuid, [('dir1/', None)])\n", (13340, 13380), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13394, 13416), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (13409, 13416), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13430, 13490), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['b']", 'project_uuid', "[('dir1/', None)]"], {}), "(['b'], project_uuid, [('dir1/', None)])\n", (13450, 13490), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13504, 13572), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['b']", 'project_uuid', "[('dir2/dir3/', 'dir2/')]"], {}), "(['b'], project_uuid, [('dir2/dir3/', 'dir2/')])\n", (13524, 13572), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13586, 13654), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['b']", 'project_uuid', "[('dir4/dir5/', 'dir4/')]"], {}), "(['b'], project_uuid, [('dir4/dir5/', 'dir4/')])\n", (13606, 13654), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13668, 13689), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['c']", '(5)'], {}), "(['c'], 5)\n", (13679, 13689), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13703, 13763), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['c']", 'project_uuid', "[('dir1/', None)]"], {}), "(['c'], project_uuid, [('dir1/', None)])\n", (13723, 13763), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13777, 13845), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['d']", 'project_uuid', "[('dir2/dir3/', 'dir2/')]"], {}), "(['d'], project_uuid, [('dir2/dir3/', 'dir2/')])\n", (13797, 13845), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13859, 13919), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['d']", 'project_uuid', "[('dir4/', None)]"], {}), "(['d'], project_uuid, [('dir4/', None)])\n", (13879, 13919), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((13933, 13993), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['e']", 'project_uuid', "[('dir1/', None)]"], {}), "(['e'], project_uuid, [('dir1/', None)])\n", (13953, 13993), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((14007, 14075), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['e']", 'project_uuid', "[('dir2/dir3/', 'dir2/')]"], {}), "(['e'], project_uuid, [('dir2/dir3/', 'dir2/')])\n", (14027, 14075), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((14089, 14149), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['f']", 'project_uuid', "[('dir1/', None)]"], {}), "(['f'], project_uuid, [('dir1/', None)])\n", (14109, 14149), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((14163, 14231), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['f']", 'project_uuid', "[('dir2/dir3/', 'dir2/')]"], {}), "(['f'], project_uuid, [('dir2/dir3/', 'dir2/')])\n", (14183, 14231), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((14245, 14305), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['f']", 'project_uuid', "[('dir4/', None)]"], {}), "(['f'], project_uuid, [('dir4/', None)])\n", (14265, 14305), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((14319, 14379), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['a']", 'project_uuid', "[('dir1/', None)]"], {}), "(['a'], project_uuid, [('dir1/', None)])\n", (14339, 14379), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2171, 2193), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (2186, 2193), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2211, 2235), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['b']", '"""2"""'], {}), "(['b'], '2')\n", (2223, 2235), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2253, 2275), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (2268, 2275), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2293, 2317), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['c']", '"""3"""'], {}), "(['c'], '3')\n", (2305, 2317), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2335, 2357), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['c']"], {}), "(['c'])\n", (2350, 2357), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2375, 2397), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['d']"], {}), "(['d'])\n", (2390, 2397), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((2415, 2437), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['e']"], {}), "(['e'])\n", (2430, 2437), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3426, 3447), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['a']", '(1)'], {}), "(['a'], 1)\n", (3437, 3447), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3465, 3487), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (3480, 3487), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3505, 3531), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['a']", '"""111"""'], {}), "(['a'], '111')\n", (3517, 3531), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3549, 3571), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (3564, 3571), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3589, 3610), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['b']", '(2)'], {}), "(['b'], 2)\n", (3600, 3610), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3628, 3649), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['c']", '(3)'], {}), "(['c'], 3)\n", (3639, 3649), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3667, 3692), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['d']", '"""44"""'], {}), "(['d'], '44')\n", (3679, 3692), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3710, 3732), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['e']", '(33)'], {}), "(['e'], 33)\n", (3721, 3732), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((3842, 3941), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot perform AssignString operation on c: Attribute is not a String"""'], {}), "(\n 'Cannot perform AssignString operation on c: Attribute is not a String')\n", (3863, 3941), False, 'from neptune.new.exceptions import MetadataInconsistency\n'), ((5973, 5995), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (5988, 5995), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((6069, 6091), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (6084, 6091), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((6316, 6336), 'neptune.new.internal.operation.ClearFloatLog', 'ClearFloatLog', (["['e']"], {}), "(['e'])\n", (6329, 6336), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((6354, 6374), 'neptune.new.internal.operation.ClearImageLog', 'ClearImageLog', (["['f']"], {}), "(['f'])\n", (6367, 6374), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((6730, 6750), 'neptune.new.internal.operation.ClearImageLog', 'ClearImageLog', (["['g']"], {}), "(['g'])\n", (6743, 6750), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((6768, 6793), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['h']", '"""44"""'], {}), "(['h'], '44')\n", (6780, 6793), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((6811, 6831), 'neptune.new.internal.operation.ClearFloatLog', 'ClearFloatLog', (["['i']"], {}), "(['i'])\n", (6824, 6831), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((6924, 6973), 'neptune.new.internal.operation.ConfigFloatSeries', 'ConfigFloatSeries', (["['i']"], {'min': '(7)', 'max': '(70)', 'unit': '"""%"""'}), "(['i'], min=7, max=70, unit='%')\n", (6941, 6973), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((7083, 7185), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot perform LogFloats operation on h: Attribute is not a Float Series"""'], {}), "(\n 'Cannot perform LogFloats operation on h: Attribute is not a Float Series')\n", (7104, 7185), False, 'from neptune.new.exceptions import MetadataInconsistency\n'), ((8708, 8745), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['a']", "{'xx', 'y', 'abc'}"], {}), "(['a'], {'xx', 'y', 'abc'})\n", (8718, 8745), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8763, 8785), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (8778, 8785), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8803, 8836), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['a']", "{'hhh', 'gij'}"], {}), "(['a'], {'hhh', 'gij'})\n", (8813, 8836), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8854, 8876), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['b']"], {}), "(['b'])\n", (8869, 8876), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8894, 8932), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['b']", "{'abc', 'defgh'}"], {}), "(['b'], {'abc', 'defgh'})\n", (8907, 8932), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((8950, 8983), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['c']", "{'hhh', 'gij'}"], {}), "(['c'], {'hhh', 'gij'})\n", (8960, 8983), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9001, 9039), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['c']", "{'abc', 'defgh'}"], {}), "(['c'], {'abc', 'defgh'})\n", (9014, 9039), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9057, 9083), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['c']", "{'qqq'}"], {}), "(['c'], {'qqq'})\n", (9067, 9083), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9101, 9122), 'neptune.new.internal.operation.ClearStringSet', 'ClearStringSet', (["['d']"], {}), "(['d'])\n", (9115, 9122), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9140, 9161), 'neptune.new.internal.operation.ClearStringSet', 'ClearStringSet', (["['e']"], {}), "(['e'])\n", (9154, 9161), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9179, 9200), 'neptune.new.internal.operation.ClearStringSet', 'ClearStringSet', (["['f']"], {}), "(['f'])\n", (9193, 9200), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9218, 9255), 'neptune.new.internal.operation.AddStrings', 'AddStrings', (["['f']", "{'xx', 'y', 'abc'}"], {}), "(['f'], {'xx', 'y', 'abc'})\n", (9228, 9255), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9273, 9311), 'neptune.new.internal.operation.RemoveStrings', 'RemoveStrings', (["['f']", "{'abc', 'defgh'}"], {}), "(['f'], {'abc', 'defgh'})\n", (9286, 9311), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9329, 9354), 'neptune.new.internal.operation.AssignString', 'AssignString', (["['h']", '"""44"""'], {}), "(['h'], '44')\n", (9341, 9354), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9372, 9393), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['i']", '(5)'], {}), "(['i'], 5)\n", (9383, 9393), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((9503, 9612), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot perform RemoveStrings operation on h: Attribute is not a String Set"""'], {}), "(\n 'Cannot perform RemoveStrings operation on h: Attribute is not a String Set'\n )\n", (9524, 9612), False, 'from neptune.new.exceptions import MetadataInconsistency\n'), ((9658, 9759), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot perform AddStrings operation on i: Attribute is not a String Set"""'], {}), "(\n 'Cannot perform AddStrings operation on i: Attribute is not a String Set')\n", (9679, 9759), False, 'from neptune.new.exceptions import MetadataInconsistency\n'), ((10753, 10806), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['a']", "['xx', 'y', 'abc']"], {'reset': '(False)'}), "(['a'], ['xx', 'y', 'abc'], reset=False)\n", (10766, 10806), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10824, 10873), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['a']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['a'], ['hhh', 'gij'], reset=False)\n", (10837, 10873), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10891, 10941), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['b']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['b'], ['abc', 'defgh'], reset=True)\n", (10904, 10941), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((10959, 11009), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['c'], ['abc', 'defgh'], reset=True)\n", (10972, 11009), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((11027, 11069), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['qqq']"], {'reset': '(False)'}), "(['c'], ['qqq'], reset=False)\n", (11040, 11069), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((11087, 11136), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['d']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['d'], ['hhh', 'gij'], reset=False)\n", (11100, 11136), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((11313, 11334), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['e']", '(5)'], {}), "(['e'], 5)\n", (11324, 11334), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((11444, 11546), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot perform UploadFileSet operation on e: Attribute is not a File Set"""'], {}), "(\n 'Cannot perform UploadFileSet operation on e: Attribute is not a File Set')\n", (11465, 11546), False, 'from neptune.new.exceptions import MetadataInconsistency\n'), ((12577, 12627), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['b']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['b'], ['abc', 'defgh'], reset=True)\n", (12590, 12627), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12645, 12695), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['abc', 'defgh']"], {'reset': '(True)'}), "(['c'], ['abc', 'defgh'], reset=True)\n", (12658, 12695), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12713, 12755), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['c']", "['qqq']"], {'reset': '(False)'}), "(['c'], ['qqq'], reset=False)\n", (12726, 12755), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12773, 12822), 'neptune.new.internal.operation.UploadFileSet', 'UploadFileSet', (["['d']", "['hhh', 'gij']"], {'reset': '(False)'}), "(['d'], ['hhh', 'gij'], reset=False)\n", (12786, 12822), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((12999, 13021), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (13014, 13021), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((14746, 14806), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['a']", 'project_uuid', "[('dir1/', None)]"], {}), "(['a'], project_uuid, [('dir1/', None)])\n", (14766, 14806), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((14824, 14938), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['b']", 'project_uuid', "[('dir1/', None), ('dir2/dir3/', 'dir2/'), ('dir4/dir5/', 'dir4/')]"], {}), "(['b'], project_uuid, [('dir1/', None), ('dir2/dir3/',\n 'dir2/'), ('dir4/dir5/', 'dir4/')])\n", (14844, 14938), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((15031, 15121), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['d']", 'project_uuid', "[('dir2/dir3/', 'dir2/'), ('dir4/', None)]"], {}), "(['d'], project_uuid, [('dir2/dir3/', 'dir2/'), (\n 'dir4/', None)])\n", (15051, 15121), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((15172, 15261), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['e']", 'project_uuid', "[('dir1/', None), ('dir2/dir3/', 'dir2/')]"], {}), "(['e'], project_uuid, [('dir1/', None), ('dir2/dir3/',\n 'dir2/')])\n", (15192, 15261), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((15313, 15419), 'neptune.new.internal.operation.TrackFilesToArtifact', 'TrackFilesToArtifact', (["['f']", 'project_uuid', "[('dir1/', None), ('dir2/dir3/', 'dir2/'), ('dir4/', None)]"], {}), "(['f'], project_uuid, [('dir1/', None), ('dir2/dir3/',\n 'dir2/'), ('dir4/', None)])\n", (15333, 15419), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((15614, 15636), 'neptune.new.internal.operation.DeleteAttribute', 'DeleteAttribute', (["['a']"], {}), "(['a'])\n", (15629, 15636), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((15654, 15675), 'neptune.new.internal.operation.AssignFloat', 'AssignFloat', (["['c']", '(5)'], {}), "(['c'], 5)\n", (15665, 15675), False, 'from neptune.new.internal.operation import AddStrings, AssignFloat, AssignString, ClearFloatLog, ClearImageLog, ClearStringSet, ConfigFloatSeries, DeleteAttribute, LogFloats, LogImages, LogStrings, RemoveStrings, TrackFilesToArtifact, UploadFileSet\n'), ((15785, 15899), 'neptune.new.exceptions.MetadataInconsistency', 'MetadataInconsistency', (['"""Cannot perform TrackFilesToArtifact operation on c: Attribute is not a Artifact"""'], {}), "(\n 'Cannot perform TrackFilesToArtifact operation on c: Attribute is not a Artifact'\n )\n", (15806, 15899), False, 'from neptune.new.exceptions import MetadataInconsistency\n')]
import gym import neptune import tensorflow as tf from spinup import ppo_tf1 as ppo def env_fn(): return gym.make('LunarLander-v2') ac_kwargs = dict(hidden_sizes=[64, 64], activation=tf.nn.relu) neptune.init(project_qualified_name='<namespace/project_name>') experiment = neptune.create_experiment(name='Spinning Up example') logger_kwargs = dict(output_dir='./out', exp_name='neptune_logging', neptune_experiment=experiment) ppo(env_fn=env_fn, ac_kwargs=ac_kwargs, steps_per_epoch=5000, epochs=250, logger_kwargs=logger_kwargs)
[ "neptune.create_experiment", "neptune.init" ]
[((201, 264), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""<namespace/project_name>"""'}), "(project_qualified_name='<namespace/project_name>')\n", (213, 264), False, 'import neptune\n'), ((278, 331), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""Spinning Up example"""'}), "(name='Spinning Up example')\n", (303, 331), False, 'import neptune\n'), ((476, 582), 'spinup.ppo_tf1', 'ppo', ([], {'env_fn': 'env_fn', 'ac_kwargs': 'ac_kwargs', 'steps_per_epoch': '(5000)', 'epochs': '(250)', 'logger_kwargs': 'logger_kwargs'}), '(env_fn=env_fn, ac_kwargs=ac_kwargs, steps_per_epoch=5000, epochs=250,\n logger_kwargs=logger_kwargs)\n', (479, 582), True, 'from spinup import ppo_tf1 as ppo\n'), ((108, 134), 'gym.make', 'gym.make', (['"""LunarLander-v2"""'], {}), "('LunarLander-v2')\n", (116, 134), False, 'import gym\n')]
# -*- coding: utf-8 -*- # @Time : 5/27/2020 5:45 PM # @Author : <NAME> # @Email : <EMAIL> # @File : logger.py # from pathlib import Path # import pandas as pd # import yaml from abc import ABCMeta, abstractmethod # from collections import defaultdict from typing import Any, Optional, Union, Sequence import wandb class GenericLogger(metaclass=ABCMeta): def __init__(self, root, project_name, experiment_name, params, hyperparams): self.root = root self.project_name = project_name self.experiment_name = experiment_name self.params = params self.hyperparams = hyperparams @abstractmethod def log_history(self, phase, epoch, history): pass @abstractmethod def log_metric(self, metric_name, phase, epoch, metric_value, timestamp=None): pass @abstractmethod def log_image(self, img, image_name=None, description=None, timestamp=None, **kwargs): raise NotImplementedError() @abstractmethod def log_text(self, text, timestamp=None, **kwargs): raise NotImplementedError() @abstractmethod def save(self): raise NotImplementedError() def log_dataframe(self, key, dataframe): pass def log_model(self, path, name): pass def stop(self): pass class MultiLogger(GenericLogger): def __init__(self, root, project_name, experiment_name, params, hyperparams, offline=False): super(MultiLogger, self).__init__(root, project_name, experiment_name, params, hyperparams) self.project_name = project_name self.experiment_name = experiment_name self.params = params self.hyperparams = hyperparams self.offline = offline self._loggers = { "local": LocalLogger(root, project_name, experiment_name, params, hyperparams), } if not offline: self._loggers["neptune"] = NeptuneLogger(root, project_name, experiment_name, params, hyperparams) def log_metric(self, metric_name, phase, epoch, metric_value, timestamp=None): for logger_name, logger in self._loggers.items(): logger.log_metric(metric_name, phase, epoch, metric_value, timestamp) def log_history(self, phase, epoch, history): raise NotImplementedError() def log_image(self, img, image_name=None, description=None, timestamp=None, **kwargs): for logger_name, logger in self._loggers.items(): logger.log_image(img, image_name, description, timestamp, **kwargs) def log_text(self, text, timestamp=None, **kwargs): for logger_name, logger in self._loggers.items(): logger.log_text(text, timestamp=None, **kwargs) def log_dataframe(self, key, dataframe): for logger_name, logger in self._loggers.items(): logger.log_dataframe(key, dataframe) def log_model(self, path, name="model"): for logger_name, logger in self._loggers.items(): logger.log_model(path, name) def save(self): for logger_name, logger in self._loggers.items(): logger.save() def stop(self): for logger_name, logger in self._loggers.items(): logger.stop() class LocalLogger(GenericLogger): def __init__(self, root, project_name, experiment_name, params, hyperparams): super(LocalLogger, self).__init__(root, project_name, experiment_name, params, hyperparams) self.experiment_fpath = self.root.absolute() / "projects" / project_name / experiment_name try: self.experiment_fpath.mkdir(parents=True) except FileExistsError: if "debug" == project_name: print("Logger running because of debug keyword.") elif params["pretrained"] or params["resume"]: print("Logger starting from existing directory because of pretrained or resume keyword.") else: raise FileExistsError(f"Did you change experiment name? : {self.experiment_fpath}") # save params and hyperparams with open(self.experiment_fpath / "params.yaml", "w") as file: pa = params.copy() pa["root"] = str(pa["root"].absolute()) yaml.dump({**pa, **hyperparams}, file, default_flow_style=False, sort_keys=False) self.container = { "metric": defaultdict(lambda: defaultdict(list)), "image": list(), "text": list(), "history": defaultdict(dict), } def log_metric(self, metric_name, phase, epoch, metric_value, timestamp=None): self.container["metric"][phase][metric_name].append({"epoch": epoch, "value": metric_value}) def log_history(self, phase, epoch, history): self.container["history"][phase][epoch] = history def log_image(self, img, image_name=None, description=None, timestamp=None, **kwargs): # self.container['image'].append({ # 'img': img, # 'image_name': image_name, # 'description': description, # **kwargs, 'timestamp': timestamp # }) pass def log_text(self, text, timestamp=None, **kwargs): self.container["text"].append({"text": text, **kwargs, "timestamp": timestamp}) def save(self): for ckey, cval in self.container.items(): tpath = self.experiment_fpath / ckey if cval: tpath.mkdir(parents=True, exist_ok=True) if ckey == "history": for phase, epoch_dict in cval.items(): for epoch, history_dict in epoch_dict.items(): # for each history_dict's key # there will be a ndarray of corresponding history item # so we need to transform ndarray to 1d array d = dict() for key, ndarr in history_dict.items(): if ndarr.ndim == 0: raise Exception("ndarr dim should be at least 1") elif ndarr.ndim == 1: d[key] = ndarr elif ndarr.ndim == 2: for col_ix in range(ndarr.shape[1]): d[f"{key}_{col_ix}"] = ndarr[:, col_ix] pd.DataFrame(d).to_csv(tpath / f"{phase}-{epoch}-history.csv") # reset container self.container["history"] = defaultdict(dict) if ckey == "metric": # cval: dict[phase]][metric_name] for ( phase, metric_dict, ) in cval.items(): # metric_dict: key: metric_name, val: [{'epoch', 'metric_Value'}] metrics = list() for metric_name, metric_list in metric_dict.items(): metric_df = pd.DataFrame(metric_list).set_index("epoch").rename(columns={"value": metric_name}) metrics.append(metric_df) write_path = tpath / f"{phase}-metric.csv" mode, header = ("a", False) if write_path.exists() else ("w", True) # yapf:disable pd.concat(metrics, axis=1).to_csv(write_path, mode=mode, header=header) # reset container self.container["metric"] = defaultdict(lambda: defaultdict(list)) # yapf:disable if ckey == "image": for item_dict in cval: item_dict["img"].save(tpath / f"{item_dict['image_name']}.png") # drop image container after successful save operation self.container["image"] = defaultdict(list) if ckey == "text": if cval: # if it has any element pd.DataFrame(cval).to_csv(tpath / "text.csv", index=False) def log_model(self, path, name="model"): pass def log_dataframe(self, key, dataframe): return dataframe.to_csv(self.experiment_fpath / f"{key}.csv") class NeptuneLogger(GenericLogger): # todo: test log_metric, log_image and log_text methods def __init__(self, root, project_name, experiment_name, params, hyperparams): super(NeptuneLogger, self).__init__(root, project_name, experiment_name, params, hyperparams) import neptune.new as neptune from neptune.new.types import File self._File = File neptune_params = params["neptune"] workspace = neptune_params["workspace"] project = neptune_params["project"] source_files = neptune_params["source_files"] run_id = neptune_params.get("id", False) if run_id: self.run = neptune.init(project=f"{workspace}/{project}", run=run_id, source_files=source_files) else: self.run = neptune.init(project=f"{workspace}/{project}", source_files=source_files) self.run["sys/tags"].add(neptune_params["tags"]) self.run["parameters"] = params self.run["hyperparameters"] = hyperparams def log_metric(self, metric_name, phase, epoch, metric_value, timestamp=None): self.run[f"{phase}/{metric_name}"].log(metric_value, step=epoch) def log_history(self, phase, epoch, history): raise NotImplementedError() def log_image(self, img, image_name=None, description=None, timestamp=None, **kwargs): self.run["image_preds"].log(self._File.as_image(img)) def log_text(self, text, timestamp=None, **kwargs): log_name = "text" x = None y = text self.experiment.log_text(log_name, x, y, timestamp) def log_dataframe(self, key, dataframe): self.run[key].upload(self._File.as_html(dataframe)) def log_model(self, path, name="model"): self.run[name].upload(str(path)) def save(self): pass def stop(self): self.run.stop() class WandBLogger: def __init__( self, job_type: Optional[str] = None, dir=None, config: Union[dict, str, None] = None, project: Optional[str] = None, entity: Optional[str] = None, reinit: bool = None, tags: Optional[Sequence] = None, group: Optional[str] = None, name: Optional[str] = None, notes: Optional[str] = None, magic: Union[dict, str, bool] = None, config_exclude_keys=None, config_include_keys=None, anonymous: Optional[str] = None, mode: Optional[str] = None, allow_val_change: Optional[bool] = None, resume: Optional[Union[bool, str]] = None, force: Optional[bool] = None, tensorboard=None, sync_tensorboard=None, monitor_gym=None, save_code=None, id=None, settings=None, ): self.run = wandb.init( job_type, dir, config, project, entity, reinit, tags, group, name, notes, magic, config_exclude_keys, config_include_keys, anonymous, mode, allow_val_change, resume, force, tensorboard, sync_tensorboard, monitor_gym, save_code, id, settings, ) def log( self, data: dict[str, Any], step: int = None, commit: bool = None, sync: bool = None, ): wandb.log(data, step=step, commit=commit, sync=sync) def watch( self, models, criterion=None, log="gradients", log_freq=1000, idx=None, log_graph=(False), ): wandb.watch(models, criterion, log, log_freq, idx, log_graph) def log_model(self, path, name="model"): artifact = wandb.Artifact("model", type="model") artifact.add_file(path) self.run.log_artifact(artifact) def stop(self, exit_code: int = None, quiet: bool = None) -> None: wandb.finish(exit_code=exit_code, quiet=quiet) if __name__ == "__main__": from PIL import Image logger = MultiLogger( root=Path("C:/Users/ugur/Documents/GitHub/ai-framework"), project_name="machining", experiment_name="test2", params={"param1": 1, "param2": 2}, hyperparams={"hyperparam1": "1t", "hyperparam2": "2t"}, ) for epoch in range(10): logger.log_metric(log_name="training_loss", x=epoch, y=epoch + 1) logger.log_metric(log_name="validation_loss", x=epoch, y=epoch + 3) logger.log_image( log_name="img", x=epoch, y=Image.open(Path("../../dereotu.jpeg")), image_name=f"image-{epoch}", ) logger.log_text(log_name="text", x=epoch, y=f"{epoch} - Some Text") logger.save() logger.stop()
[ "neptune.new.init" ]
[((10878, 11142), 'wandb.init', 'wandb.init', (['job_type', 'dir', 'config', 'project', 'entity', 'reinit', 'tags', 'group', 'name', 'notes', 'magic', 'config_exclude_keys', 'config_include_keys', 'anonymous', 'mode', 'allow_val_change', 'resume', 'force', 'tensorboard', 'sync_tensorboard', 'monitor_gym', 'save_code', 'id', 'settings'], {}), '(job_type, dir, config, project, entity, reinit, tags, group,\n name, notes, magic, config_exclude_keys, config_include_keys, anonymous,\n mode, allow_val_change, resume, force, tensorboard, sync_tensorboard,\n monitor_gym, save_code, id, settings)\n', (10888, 11142), False, 'import wandb\n'), ((11554, 11606), 'wandb.log', 'wandb.log', (['data'], {'step': 'step', 'commit': 'commit', 'sync': 'sync'}), '(data, step=step, commit=commit, sync=sync)\n', (11563, 11606), False, 'import wandb\n'), ((11737, 11798), 'wandb.watch', 'wandb.watch', (['models', 'criterion', 'log', 'log_freq', 'idx', 'log_graph'], {}), '(models, criterion, log, log_freq, idx, log_graph)\n', (11748, 11798), False, 'import wandb\n'), ((11864, 11901), 'wandb.Artifact', 'wandb.Artifact', (['"""model"""'], {'type': '"""model"""'}), "('model', type='model')\n", (11878, 11901), False, 'import wandb\n'), ((12054, 12100), 'wandb.finish', 'wandb.finish', ([], {'exit_code': 'exit_code', 'quiet': 'quiet'}), '(exit_code=exit_code, quiet=quiet)\n', (12066, 12100), False, 'import wandb\n'), ((8766, 8856), 'neptune.new.init', 'neptune.init', ([], {'project': 'f"""{workspace}/{project}"""', 'run': 'run_id', 'source_files': 'source_files'}), "(project=f'{workspace}/{project}', run=run_id, source_files=\n source_files)\n", (8778, 8856), True, 'import neptune.new as neptune\n'), ((8889, 8962), 'neptune.new.init', 'neptune.init', ([], {'project': 'f"""{workspace}/{project}"""', 'source_files': 'source_files'}), "(project=f'{workspace}/{project}', source_files=source_files)\n", (8901, 8962), True, 'import neptune.new as neptune\n')]
import lightgbm import matplotlib.pyplot as plt import neptune from neptunecontrib.monitoring.utils import pickle_and_send_artifact from neptunecontrib.monitoring.metrics import log_binary_classification_metrics from neptunecontrib.versioning.data import log_data_version import pandas as pd plt.rcParams.update({'font.size': 18}) plt.rcParams.update({'figure.figsize': [16, 12]}) plt.style.use('seaborn-whitegrid') # Define parameters PROJECT_NAME = 'neptune-ai/binary-classification-metrics' TRAIN_PATH = 'data/train.csv' TEST_PATH = 'data/test.csv' NROWS = None MODEL_PARAMS = {'random_state': 1234, 'learning_rate': 0.1, 'n_estimators': 1500} # Load data train = pd.read_csv(TRAIN_PATH, nrows=NROWS) test = pd.read_csv(TEST_PATH, nrows=NROWS) feature_names = [col for col in train.columns if col not in ['isFraud']] X_train, y_train = train[feature_names], train['isFraud'] X_test, y_test = test[feature_names], test['isFraud'] # Start experiment neptune.init(PROJECT_NAME) neptune.create_experiment(name='lightGBM training', params=MODEL_PARAMS, upload_source_files=['train.py', 'environment.yaml']) log_data_version(TRAIN_PATH, prefix='train_') log_data_version(TEST_PATH, prefix='test_') # Train model model = lightgbm.LGBMClassifier(**MODEL_PARAMS) model.fit(X_train, y_train) # Evaluate model y_test_pred = model.predict_proba(X_test) log_binary_classification_metrics(y_test, y_test_pred) pickle_and_send_artifact((y_test, y_test_pred), 'test_predictions.pkl') neptune.stop()
[ "neptune.create_experiment", "neptune.stop", "neptune.init" ]
[((293, 331), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 18}"], {}), "({'font.size': 18})\n", (312, 331), True, 'import matplotlib.pyplot as plt\n'), ((332, 381), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.figsize': [16, 12]}"], {}), "({'figure.figsize': [16, 12]})\n", (351, 381), True, 'import matplotlib.pyplot as plt\n'), ((382, 416), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-whitegrid"""'], {}), "('seaborn-whitegrid')\n", (395, 416), True, 'import matplotlib.pyplot as plt\n'), ((704, 740), 'pandas.read_csv', 'pd.read_csv', (['TRAIN_PATH'], {'nrows': 'NROWS'}), '(TRAIN_PATH, nrows=NROWS)\n', (715, 740), True, 'import pandas as pd\n'), ((748, 783), 'pandas.read_csv', 'pd.read_csv', (['TEST_PATH'], {'nrows': 'NROWS'}), '(TEST_PATH, nrows=NROWS)\n', (759, 783), True, 'import pandas as pd\n'), ((991, 1017), 'neptune.init', 'neptune.init', (['PROJECT_NAME'], {}), '(PROJECT_NAME)\n', (1003, 1017), False, 'import neptune\n'), ((1018, 1148), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""lightGBM training"""', 'params': 'MODEL_PARAMS', 'upload_source_files': "['train.py', 'environment.yaml']"}), "(name='lightGBM training', params=MODEL_PARAMS,\n upload_source_files=['train.py', 'environment.yaml'])\n", (1043, 1148), False, 'import neptune\n'), ((1197, 1242), 'neptunecontrib.versioning.data.log_data_version', 'log_data_version', (['TRAIN_PATH'], {'prefix': '"""train_"""'}), "(TRAIN_PATH, prefix='train_')\n", (1213, 1242), False, 'from neptunecontrib.versioning.data import log_data_version\n'), ((1243, 1286), 'neptunecontrib.versioning.data.log_data_version', 'log_data_version', (['TEST_PATH'], {'prefix': '"""test_"""'}), "(TEST_PATH, prefix='test_')\n", (1259, 1286), False, 'from neptunecontrib.versioning.data import log_data_version\n'), ((1310, 1349), 'lightgbm.LGBMClassifier', 'lightgbm.LGBMClassifier', ([], {}), '(**MODEL_PARAMS)\n', (1333, 1349), False, 'import lightgbm\n'), ((1439, 1493), 'neptunecontrib.monitoring.metrics.log_binary_classification_metrics', 'log_binary_classification_metrics', (['y_test', 'y_test_pred'], {}), '(y_test, y_test_pred)\n', (1472, 1493), False, 'from neptunecontrib.monitoring.metrics import log_binary_classification_metrics\n'), ((1494, 1565), 'neptunecontrib.monitoring.utils.pickle_and_send_artifact', 'pickle_and_send_artifact', (['(y_test, y_test_pred)', '"""test_predictions.pkl"""'], {}), "((y_test, y_test_pred), 'test_predictions.pkl')\n", (1518, 1565), False, 'from neptunecontrib.monitoring.utils import pickle_and_send_artifact\n'), ((1567, 1581), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (1579, 1581), False, 'import neptune\n')]
from functools import partial import os import shutil from attrdict import AttrDict import neptune import numpy as np import pandas as pd from sklearn.externals import joblib from steppy.base import Step, IdentityOperation from steppy.adapter import Adapter, E from common_blocks import augmentation as aug from common_blocks import metrics from common_blocks import models from common_blocks import pipelines from common_blocks import utils from common_blocks import postprocessing CTX = neptune.Context() LOGGER = utils.init_logger() # ______ ______ .__ __. _______ __ _______ _______. # / | / __ \ | \ | | | ____|| | / _____| / | # | ,----'| | | | | \| | | |__ | | | | __ | (----` # | | | | | | | . ` | | __| | | | | |_ | \ \ # | `----.| `--' | | |\ | | | | | | |__| | .----) | # \______| \______/ |__| \__| |__| |__| \______| |_______/ # EXPERIMENT_DIR = '/output/experiment' CLONE_EXPERIMENT_DIR_FROM = '' # When running eval in the cloud specify this as for example /input/SAL-14/output/experiment OVERWRITE_EXPERIMENT_DIR = False DEV_MODE = False if OVERWRITE_EXPERIMENT_DIR and os.path.isdir(EXPERIMENT_DIR): shutil.rmtree(EXPERIMENT_DIR) if CLONE_EXPERIMENT_DIR_FROM != '': if os.path.exists(EXPERIMENT_DIR): shutil.rmtree(EXPERIMENT_DIR) shutil.copytree(CLONE_EXPERIMENT_DIR_FROM, EXPERIMENT_DIR) if CTX.params.__class__.__name__ == 'OfflineContextParams': PARAMS = utils.read_yaml().parameters else: PARAMS = CTX.params MEAN = [0.485, 0.456, 0.406] STD = [0.229, 0.224, 0.225] SEED = 1234 ID_COLUMN = 'id' DEPTH_COLUMN = 'z' X_COLUMN = 'file_path_image' Y_COLUMN = 'file_path_mask' CONFIG = AttrDict({ 'execution': {'experiment_dir': EXPERIMENT_DIR, 'num_workers': PARAMS.num_workers, }, 'general': {'img_H-W': (PARAMS.image_h, PARAMS.image_w), 'loader_mode': PARAMS.loader_mode, 'num_classes': 2, 'original_size': (101, 101), }, 'xy_splitter': { 'unet': {'x_columns': [X_COLUMN], 'y_columns': [Y_COLUMN], }, }, 'reader': { 'unet': {'x_columns': [X_COLUMN], 'y_columns': [Y_COLUMN], }, }, 'loaders': {'crop_and_pad': {'dataset_params': {'h': PARAMS.image_h, 'w': PARAMS.image_w, 'pad_method': PARAMS.pad_method, 'image_source': PARAMS.image_source, 'divisor': 64, 'target_format': PARAMS.target_format, 'MEAN': MEAN, 'STD': STD }, 'loader_params': {'training': {'batch_size': PARAMS.batch_size_train, 'shuffle': True, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, 'inference': {'batch_size': PARAMS.batch_size_inference, 'shuffle': False, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, }, 'augmentation_params': {'image_augment_train': aug.intensity_seq, 'image_augment_with_target_train': aug.crop_seq( crop_size=(PARAMS.image_h, PARAMS.image_w)), 'image_augment_inference': aug.pad_to_fit_net(64, PARAMS.pad_method), 'image_augment_with_target_inference': aug.pad_to_fit_net(64, PARAMS.pad_method) }, }, 'crop_and_pad_tta': {'dataset_params': {'h': PARAMS.image_h, 'w': PARAMS.image_w, 'pad_method': PARAMS.pad_method, 'image_source': PARAMS.image_source, 'divisor': 64, 'target_format': PARAMS.target_format, 'MEAN': MEAN, 'STD': STD }, 'loader_params': {'training': {'batch_size': PARAMS.batch_size_train, 'shuffle': True, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, 'inference': {'batch_size': PARAMS.batch_size_inference, 'shuffle': False, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, }, 'augmentation_params': { 'image_augment_inference': aug.pad_to_fit_net(64, PARAMS.pad_method), 'image_augment_with_target_inference': aug.pad_to_fit_net(64, PARAMS.pad_method), 'tta_transform': aug.test_time_augmentation_transform }, }, 'resize': {'dataset_params': {'h': PARAMS.image_h, 'w': PARAMS.image_w, 'pad_method': PARAMS.pad_method, 'image_source': PARAMS.image_source, 'divisor': 64, 'target_format': PARAMS.target_format, 'MEAN': MEAN, 'STD': STD }, 'loader_params': {'training': {'batch_size': PARAMS.batch_size_train, 'shuffle': True, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, 'inference': {'batch_size': PARAMS.batch_size_inference, 'shuffle': False, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, }, 'augmentation_params': {'image_augment_train': aug.intensity_seq, 'image_augment_with_target_train': aug.affine_seq }, }, 'resize_tta': {'dataset_params': {'h': PARAMS.image_h, 'w': PARAMS.image_w, 'pad_method': PARAMS.pad_method, 'image_source': PARAMS.image_source, 'divisor': 64, 'target_format': PARAMS.target_format, 'MEAN': MEAN, 'STD': STD }, 'loader_params': {'training': {'batch_size': PARAMS.batch_size_train, 'shuffle': True, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, 'inference': {'batch_size': PARAMS.batch_size_inference, 'shuffle': False, 'num_workers': PARAMS.num_workers, 'pin_memory': PARAMS.pin_memory }, }, 'augmentation_params': {'tta_transform': aug.test_time_augmentation_transform }, }, }, 'model': { 'unet': { 'architecture_config': {'model_params': {'n_filters': PARAMS.n_filters, 'conv_kernel': PARAMS.conv_kernel, 'pool_kernel': PARAMS.pool_kernel, 'pool_stride': PARAMS.pool_stride, 'repeat_blocks': PARAMS.repeat_blocks, 'batch_norm': PARAMS.use_batch_norm, 'dropout': PARAMS.dropout_conv, 'in_channels': PARAMS.image_channels, 'out_channels': PARAMS.unet_output_channels, 'nr_outputs': PARAMS.nr_unet_outputs, 'encoder': PARAMS.encoder, 'activation': PARAMS.unet_activation, 'dice_weight': PARAMS.dice_weight, 'bce_weight': PARAMS.bce_weight, }, 'optimizer_params': {'lr': PARAMS.lr, }, 'regularizer_params': {'regularize': True, 'weight_decay_conv2d': PARAMS.l2_reg_conv, }, 'weights_init': {'function': 'xavier', }, }, 'training_config': {'epochs': PARAMS.epochs_nr, 'shuffle': True, 'batch_size': PARAMS.batch_size_train, }, 'callbacks_config': {'model_checkpoint': { 'filepath': os.path.join(EXPERIMENT_DIR, 'checkpoints', 'unet', 'best.torch'), 'epoch_every': 1, 'metric_name': PARAMS.validation_metric_name, 'minimize': PARAMS.minimize_validation_metric}, 'lr_scheduler': {'gamma': PARAMS.gamma, 'epoch_every': 1}, 'training_monitor': {'batch_every': 0, 'epoch_every': 1}, 'experiment_timing': {'batch_every': 0, 'epoch_every': 1}, 'validation_monitor': {'epoch_every': 1, 'data_dir': PARAMS.train_images_dir, 'loader_mode': PARAMS.loader_mode}, 'neptune_monitor': {'model_name': 'unet', 'image_nr': 4, 'image_resize': 1.0}, 'early_stopping': {'patience': PARAMS.patience, 'metric_name': PARAMS.validation_metric_name, 'minimize': PARAMS.minimize_validation_metric}, } }, }, 'tta_generator': {'flip_ud': False, 'flip_lr': True, 'rotation': False, 'color_shift_runs': 0}, 'tta_aggregator': {'tta_inverse_transform': aug.test_time_augmentation_inverse_transform, 'method': PARAMS.tta_aggregation_method, 'nthreads': PARAMS.num_threads }, 'thresholder': {'threshold_masks': PARAMS.threshold_masks, }, }) # .______ __ .______ _______ __ __ .__ __. _______ _______. # | _ \ | | | _ \ | ____|| | | | | \ | | | ____| / | # | |_) | | | | |_) | | |__ | | | | | \| | | |__ | (----` # | ___/ | | | ___/ | __| | | | | | . ` | | __| \ \ # | | | | | | | |____ | `----.| | | |\ | | |____.----) | # | _| |__| | _| |_______||_______||__| |__| \__| |_______|_______/ # def unet(config, suffix='', train_mode=True): if train_mode: preprocessing = pipelines.preprocessing_train(config, model_name='unet', suffix=suffix) else: preprocessing = pipelines.preprocessing_inference(config, suffix=suffix) unet = Step(name='unet{}'.format(suffix), transformer=models.PyTorchUNet(**config.model['unet']), input_data=['callback_input'], input_steps=[preprocessing], adapter=Adapter({'datagen': E(preprocessing.name, 'datagen'), 'validation_datagen': E(preprocessing.name, 'validation_datagen'), 'meta_valid': E('callback_input', 'meta_valid'), }), is_trainable=True, experiment_directory=config.execution.experiment_dir) if config.general.loader_mode == 'resize_and_pad': size_adjustment_function = partial(postprocessing.crop_image, target_size=config.general.original_size) elif config.general.loader_mode == 'resize': size_adjustment_function = partial(postprocessing.resize_image, target_size=config.general.original_size) else: raise NotImplementedError mask_resize = Step(name='mask_resize{}'.format(suffix), transformer=utils.make_apply_transformer(size_adjustment_function, output_name='resized_images', apply_on=['images']), input_steps=[unet], adapter=Adapter({'images': E(unet.name, 'mask_prediction'), }), experiment_directory=config.execution.experiment_dir) return mask_resize def unet_tta(config, suffix=''): preprocessing, tta_generator = pipelines.preprocessing_inference_tta(config, model_name='unet') unet = Step(name='unet{}'.format(suffix), transformer=models.PyTorchUNet(**config.model['unet']), input_data=['callback_input'], input_steps=[preprocessing], is_trainable=True, experiment_directory=config.execution.experiment_dir) tta_aggregator = pipelines.aggregator('tta_aggregator{}'.format(suffix), unet, tta_generator=tta_generator, experiment_directory=config.execution.experiment_dir, config=config.tta_aggregator) prediction_renamed = Step(name='prediction_renamed{}'.format(suffix), transformer=IdentityOperation(), input_steps=[tta_aggregator], adapter=Adapter({'mask_prediction': E(tta_aggregator.name, 'aggregated_prediction') }), experiment_directory=config.execution.experiment_dir) if config.general.loader_mode == 'resize_and_pad': size_adjustment_function = partial(postprocessing.crop_image, target_size=config.general.original_size) elif config.general.loader_mode == 'resize': size_adjustment_function = partial(postprocessing.resize_image, target_size=config.general.original_size) else: raise NotImplementedError mask_resize = Step(name='mask_resize{}'.format(suffix), transformer=utils.make_apply_transformer(size_adjustment_function, output_name='resized_images', apply_on=['images']), input_steps=[prediction_renamed], adapter=Adapter({'images': E(prediction_renamed.name, 'mask_prediction'), }), experiment_directory=config.execution.experiment_dir) return mask_resize # __________ ___ _______ ______ __ __ .___________. __ ______ .__ __. # | ____\ \ / / | ____| / || | | | | || | / __ \ | \ | | # | |__ \ V / | |__ | ,----'| | | | `---| |----`| | | | | | | \| | # | __| > < | __| | | | | | | | | | | | | | | | . ` | # | |____ / . \ | |____ | `----.| `--' | | | | | | `--' | | |\ | # |_______/__/ \__\ |_______| \______| \______/ |__| |__| \______/ |__| \__| # def prepare_metadata(): LOGGER.info('creating metadata') meta = utils.generate_metadata(train_images_dir=PARAMS.train_images_dir, test_images_dir=PARAMS.test_images_dir, depths_filepath=PARAMS.depths_filepath ) meta.to_csv(PARAMS.metadata_filepath, index=None) def train(): meta = pd.read_csv(PARAMS.metadata_filepath) meta_train = meta[meta['is_train'] == 1] cv = utils.KFoldBySortedValue(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.shuffle, random_state=SEED) for train_idx, valid_idx in cv.split(meta_train[DEPTH_COLUMN].values.reshape(-1)): break meta_train_split, meta_valid_split = meta_train.iloc[train_idx], meta_train.iloc[valid_idx] if DEV_MODE: meta_train_split = meta_train_split.sample(PARAMS.dev_mode_size, random_state=SEED) meta_valid_split = meta_valid_split.sample(int(PARAMS.dev_mode_size / 2), random_state=SEED) data = {'input': {'meta': meta_train_split }, 'callback_input': {'meta_valid': meta_valid_split } } pipeline_network = unet(config=CONFIG, train_mode=True) pipeline_network.clean_cache() pipeline_network.fit_transform(data) pipeline_network.clean_cache() def evaluate(): meta = pd.read_csv(PARAMS.metadata_filepath) meta_train = meta[meta['is_train'] == 1] cv = utils.KFoldBySortedValue(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.shuffle, random_state=SEED) for train_idx, valid_idx in cv.split(meta_train[DEPTH_COLUMN].values.reshape(-1)): break meta_valid_split = meta_train.iloc[valid_idx] y_true_valid = utils.read_masks(meta_valid_split[Y_COLUMN].values) if DEV_MODE: meta_valid_split = meta_valid_split.sample(PARAMS.dev_mode_size, random_state=SEED) data = {'input': {'meta': meta_valid_split, }, 'callback_input': {'meta_valid': None } } pipeline_network = unet(config=CONFIG, train_mode=False) pipeline_postprocessing = pipelines.mask_postprocessing(config=CONFIG) pipeline_network.clean_cache() output = pipeline_network.transform(data) valid_masks = {'input_masks': output } output = pipeline_postprocessing.transform(valid_masks) pipeline_network.clean_cache() pipeline_postprocessing.clean_cache() y_pred_valid = output['binarized_images'] LOGGER.info('Calculating IOU and IOUT Scores') iou_score, iout_score = calculate_scores(y_true_valid, y_pred_valid) LOGGER.info('IOU score on validation is {}'.format(iou_score)) CTX.channel_send('IOU', 0, iou_score) LOGGER.info('IOUT score on validation is {}'.format(iout_score)) CTX.channel_send('IOUT', 0, iout_score) results_filepath = os.path.join(EXPERIMENT_DIR, 'validation_results.pkl') LOGGER.info('Saving validation results to {}'.format(results_filepath)) joblib.dump((meta_valid_split, y_true_valid, y_pred_valid), results_filepath) def predict(): meta = pd.read_csv(PARAMS.metadata_filepath) meta_test = meta[meta['is_train'] == 0] if DEV_MODE: meta_test = meta_test.sample(PARAMS.dev_mode_size, random_state=SEED) data = {'input': {'meta': meta_test, }, 'callback_input': {'meta_valid': None } } pipeline_network = unet(config=CONFIG, train_mode=False) pipeline_postprocessing = pipelines.mask_postprocessing(config=CONFIG) pipeline_network.clean_cache() predicted_masks = pipeline_network.transform(data) test_masks = {'input_masks': predicted_masks } output = pipeline_postprocessing.transform(test_masks) pipeline_network.clean_cache() pipeline_postprocessing.clean_cache() y_pred_test = output['binarized_images'] submission = utils.create_submission(meta_test, y_pred_test) submission_filepath = os.path.join(EXPERIMENT_DIR, 'submission.csv') submission.to_csv(submission_filepath, index=None, encoding='utf-8') LOGGER.info('submission saved to {}'.format(submission_filepath)) LOGGER.info('submission head \n\n{}'.format(submission.head())) def train_evaluate_cv(): meta = pd.read_csv(PARAMS.metadata_filepath) if DEV_MODE: meta = meta.sample(PARAMS.dev_mode_size, random_state=SEED) meta_train = meta[meta['is_train'] == 1] cv = utils.KFoldBySortedValue(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.shuffle, random_state=SEED) fold_iou, fold_iout = [], [] for fold_id, (train_idx, valid_idx) in enumerate(cv.split(meta_train[DEPTH_COLUMN].values.reshape(-1))): train_data_split, valid_data_split = meta_train.iloc[train_idx], meta_train.iloc[valid_idx] LOGGER.info('Started fold {}'.format(fold_id)) iou, iout, _ = fold_fit_evaluate_loop(train_data_split, valid_data_split, fold_id) LOGGER.info('Fold {} IOU {}'.format(fold_id, iou)) CTX.channel_send('Fold {} IOU'.format(fold_id), 0, iou) LOGGER.info('Fold {} IOUT {}'.format(fold_id, iout)) CTX.channel_send('Fold {} IOUT'.format(fold_id), 0, iout) fold_iou.append(iou) fold_iout.append(iout) iou_mean, iou_std = np.mean(fold_iou), np.std(fold_iou) iout_mean, iout_std = np.mean(fold_iout), np.std(fold_iout) log_scores(iou_mean, iou_std, iout_mean, iout_std) def train_evaluate_predict_cv(): meta = pd.read_csv(PARAMS.metadata_filepath) if DEV_MODE: meta = meta.sample(PARAMS.dev_mode_size, random_state=SEED) meta_train = meta[meta['is_train'] == 1] meta_test = meta[meta['is_train'] == 0] cv = utils.KFoldBySortedValue(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.shuffle, random_state=SEED) fold_iou, fold_iout, out_of_fold_train_predictions, out_of_fold_test_predictions = [], [], [], [] for fold_id, (train_idx, valid_idx) in enumerate(cv.split(meta_train[DEPTH_COLUMN].values.reshape(-1))): train_data_split, valid_data_split = meta_train.iloc[train_idx], meta_train.iloc[valid_idx] LOGGER.info('Started fold {}'.format(fold_id)) iou, iout, out_of_fold_prediction, test_prediction = fold_fit_evaluate_predict_loop(train_data_split, valid_data_split, meta_test, fold_id) LOGGER.info('Fold {} IOU {}'.format(fold_id, iou)) CTX.channel_send('Fold {} IOU'.format(fold_id), 0, iou) LOGGER.info('Fold {} IOUT {}'.format(fold_id, iout)) CTX.channel_send('Fold {} IOUT'.format(fold_id), 0, iout) fold_iou.append(iou) fold_iout.append(iout) out_of_fold_train_predictions.append(out_of_fold_prediction) out_of_fold_test_predictions.append(test_prediction) train_ids, train_predictions = [], [] for idx_fold, train_pred_fold in out_of_fold_train_predictions: train_ids.extend(idx_fold) train_predictions.extend(train_pred_fold) iou_mean, iou_std = np.mean(fold_iou), np.std(fold_iou) iout_mean, iout_std = np.mean(fold_iout), np.std(fold_iout) log_scores(iou_mean, iou_std, iout_mean, iout_std) save_predictions(train_ids, train_predictions, meta_test, out_of_fold_test_predictions) def evaluate_cv(): meta = pd.read_csv(PARAMS.metadata_filepath) if DEV_MODE: meta = meta.sample(PARAMS.dev_mode_size, random_state=SEED) meta_train = meta[meta['is_train'] == 1] cv = utils.KFoldBySortedValue(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.shuffle, random_state=SEED) fold_iou, fold_iout = [], [] for fold_id, (train_idx, valid_idx) in enumerate(cv.split(meta_train[DEPTH_COLUMN].values.reshape(-1))): valid_data_split = meta_train.iloc[valid_idx] LOGGER.info('Started fold {}'.format(fold_id)) iou, iout, _ = fold_evaluate_loop(valid_data_split, fold_id) LOGGER.info('Fold {} IOU {}'.format(fold_id, iou)) CTX.channel_send('Fold {} IOU'.format(fold_id), 0, iou) LOGGER.info('Fold {} IOUT {}'.format(fold_id, iout)) CTX.channel_send('Fold {} IOUT'.format(fold_id), 0, iout) fold_iou.append(iou) fold_iout.append(iout) iou_mean, iou_std = np.mean(fold_iou), np.std(fold_iou) iout_mean, iout_std = np.mean(fold_iout), np.std(fold_iout) log_scores(iou_mean, iou_std, iout_mean, iout_std) def evaluate_predict_cv(): meta = pd.read_csv(PARAMS.metadata_filepath) if DEV_MODE: meta = meta.sample(PARAMS.dev_mode_size, random_state=SEED) meta_train = meta[meta['is_train'] == 1] meta_test = meta[meta['is_train'] == 0] cv = utils.KFoldBySortedValue(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.shuffle, random_state=SEED) fold_iou, fold_iout, out_of_fold_train_predictions, out_of_fold_test_predictions = [], [], [], [] for fold_id, (train_idx, valid_idx) in enumerate(cv.split(meta_train[DEPTH_COLUMN].values.reshape(-1))): valid_data_split = meta_train.iloc[valid_idx] LOGGER.info('Started fold {}'.format(fold_id)) iou, iout, out_of_fold_prediction, test_prediction = fold_evaluate_predict_loop(valid_data_split, meta_test, fold_id) LOGGER.info('Fold {} IOU {}'.format(fold_id, iou)) CTX.channel_send('Fold {} IOU'.format(fold_id), 0, iou) LOGGER.info('Fold {} IOUT {}'.format(fold_id, iout)) CTX.channel_send('Fold {} IOUT'.format(fold_id), 0, iout) fold_iou.append(iou) fold_iout.append(iout) out_of_fold_train_predictions.append(out_of_fold_prediction) out_of_fold_test_predictions.append(test_prediction) train_ids, train_predictions = [], [] for idx_fold, train_pred_fold in out_of_fold_train_predictions: train_ids.extend(idx_fold) train_predictions.extend(train_pred_fold) iou_mean, iou_std = np.mean(fold_iou), np.std(fold_iou) iout_mean, iout_std = np.mean(fold_iout), np.std(fold_iout) log_scores(iou_mean, iou_std, iout_mean, iout_std) save_predictions(train_ids, train_predictions, meta_test, out_of_fold_test_predictions) def fold_fit_evaluate_predict_loop(train_data_split, valid_data_split, test, fold_id): iou, iout, predicted_masks_valid = fold_fit_evaluate_loop(train_data_split, valid_data_split, fold_id) test_pipe_input = {'input': {'meta': test }, 'callback_input': {'meta_valid': None } } pipeline_network = unet(config=CONFIG, suffix='_fold_{}'.format(fold_id), train_mode=False) LOGGER.info('Start pipeline transform on test') pipeline_network.clean_cache() predicted_masks_test = pipeline_network.transform(test_pipe_input) utils.clean_object_from_memory(pipeline_network) predicted_masks_test = predicted_masks_test['resized_images'] return iou, iout, predicted_masks_valid, predicted_masks_test def fold_fit_evaluate_loop(train_data_split, valid_data_split, fold_id): train_pipe_input = {'input': {'meta': train_data_split }, 'callback_input': {'meta_valid': valid_data_split } } valid_pipe_input = {'input': {'meta': valid_data_split }, 'callback_input': {'meta_valid': None } } valid_ids = valid_data_split[ID_COLUMN].tolist() LOGGER.info('Start pipeline fit and transform on train') config = add_fold_id_suffix(CONFIG, fold_id) pipeline_network = unet(config=config, suffix='_fold_{}'.format(fold_id), train_mode=True) pipeline_network.clean_cache() pipeline_network.fit_transform(train_pipe_input) utils.clean_object_from_memory(pipeline_network) LOGGER.info('Start pipeline transform on valid') pipeline_network = unet(config=config, suffix='_fold_{}'.format(fold_id), train_mode=False) pipeline_postprocessing = pipelines.mask_postprocessing(config=config, suffix='_fold_{}'.format(fold_id)) pipeline_network.clean_cache() pipeline_postprocessing.clean_cache() predicted_masks_valid = pipeline_network.transform(valid_pipe_input) valid_pipe_masks = {'input_masks': predicted_masks_valid } output_valid = pipeline_postprocessing.transform(valid_pipe_masks) utils.clean_object_from_memory(pipeline_network) y_pred_valid = output_valid['binarized_images'] y_true_valid = utils.read_masks(valid_data_split[Y_COLUMN].values) iou, iout = calculate_scores(y_true_valid, y_pred_valid) predicted_masks_valid = predicted_masks_valid['resized_images'] return iou, iout, (valid_ids, predicted_masks_valid) def fold_evaluate_predict_loop(valid_data_split, test, fold_id): iou, iout, predicted_masks_valid = fold_evaluate_loop(valid_data_split, fold_id) test_pipe_input = {'input': {'meta': test }, 'callback_input': {'meta_valid': None } } pipeline_network = unet(config=CONFIG, suffix='_fold_{}'.format(fold_id), train_mode=False) LOGGER.info('Start pipeline transform on test') pipeline_network.clean_cache() predicted_masks_test = pipeline_network.transform(test_pipe_input) utils.clean_object_from_memory(pipeline_network) predicted_masks_test = predicted_masks_test['resized_images'] return iou, iout, predicted_masks_valid, predicted_masks_test def fold_evaluate_loop(valid_data_split, fold_id): valid_pipe_input = {'input': {'meta': valid_data_split }, 'callback_input': {'meta_valid': None } } valid_ids = valid_data_split[ID_COLUMN].tolist() LOGGER.info('Start pipeline transform on valid') pipeline_network = unet(config=CONFIG, suffix='_fold_{}'.format(fold_id), train_mode=False) pipeline_postprocessing = pipelines.mask_postprocessing(config=CONFIG, suffix='_fold_{}'.format(fold_id)) pipeline_network.clean_cache() pipeline_postprocessing.clean_cache() predicted_masks_valid = pipeline_network.transform(valid_pipe_input) valid_pipe_masks = {'input_masks': predicted_masks_valid } output_valid = pipeline_postprocessing.transform(valid_pipe_masks) utils.clean_object_from_memory(pipeline_network) y_pred_valid = output_valid['binarized_images'] y_true_valid = utils.read_masks(valid_data_split[Y_COLUMN].values) iou, iout = calculate_scores(y_true_valid, y_pred_valid) predicted_masks_valid = predicted_masks_valid['resized_images'] return iou, iout, (valid_ids, predicted_masks_valid) # __ __ .___________. __ __ _______. # | | | | | || | | | / | # | | | | `---| |----`| | | | | (----` # | | | | | | | | | | \ \ # | `--' | | | | | | `----.----) | # \______/ |__| |__| |_______|_______/ # def calculate_scores(y_true, y_pred): iou = metrics.intersection_over_union(y_true, y_pred) iout = metrics.intersection_over_union_thresholds(y_true, y_pred) return iou, iout def add_fold_id_suffix(config, fold_id): config['model']['unet']['callbacks_config']['neptune_monitor']['model_name'] = 'unet_{}'.format(fold_id) checkpoint_filepath = config['model']['unet']['callbacks_config']['model_checkpoint']['filepath'] fold_checkpoint_filepath = checkpoint_filepath.replace('unet/best.torch', 'unet_{}/best.torch'.format(fold_id)) config['model']['unet']['callbacks_config']['model_checkpoint']['filepath'] = fold_checkpoint_filepath return config def log_scores(iou_mean, iou_std, iout_mean, iout_std): LOGGER.info('IOU mean {}, IOU std {}'.format(iou_mean, iou_std)) CTX.channel_send('IOU', 0, iou_mean) CTX.channel_send('IOU STD', 0, iou_std) LOGGER.info('IOUT mean {}, IOUT std {}'.format(iout_mean, iout_std)) CTX.channel_send('IOUT', 0, iout_mean) CTX.channel_send('IOUT STD', 0, iout_std) def save_predictions(train_ids, train_predictions, meta_test, out_of_fold_test_predictions): averaged_mask_predictions_test = np.mean(np.array(out_of_fold_test_predictions), axis=0) pipeline_postprocessing = pipelines.mask_postprocessing(config=CONFIG) pipeline_postprocessing.clean_cache() test_pipe_masks = {'input_masks': {'resized_images': averaged_mask_predictions_test} } y_pred_test = pipeline_postprocessing.transform(test_pipe_masks)['binarized_images'] LOGGER.info('Saving predictions') out_of_fold_train_predictions_path = os.path.join(EXPERIMENT_DIR, 'out_of_fold_train_predictions.pkl') joblib.dump({'ids': train_ids, 'images': train_predictions}, out_of_fold_train_predictions_path) out_of_fold_test_predictions_path = os.path.join(EXPERIMENT_DIR, 'out_of_fold_test_predictions.pkl') joblib.dump({'ids': meta_test[ID_COLUMN].tolist(), 'images': averaged_mask_predictions_test}, out_of_fold_test_predictions_path) submission = utils.create_submission(meta_test, y_pred_test) submission_filepath = os.path.join(EXPERIMENT_DIR, 'submission.csv') submission.to_csv(submission_filepath, index=None, encoding='utf-8') LOGGER.info('submission saved to {}'.format(submission_filepath)) LOGGER.info('submission head \n\n{}'.format(submission.head())) # .___ ___. ___ __ .__ __. # | \/ | / \ | | | \ | | # | \ / | / ^ \ | | | \| | # | |\/| | / /_\ \ | | | . ` | # | | | | / _____ \ | | | |\ | # |__| |__| /__/ \__\ |__| |__| \__| # if __name__ == '__main__': prepare_metadata() train_evaluate_predict_cv()
[ "neptune.Context" ]
[((492, 509), 'neptune.Context', 'neptune.Context', ([], {}), '()\n', (507, 509), False, 'import neptune\n'), ((519, 538), 'common_blocks.utils.init_logger', 'utils.init_logger', ([], {}), '()\n', (536, 538), False, 'from common_blocks import utils\n'), ((1204, 1233), 'os.path.isdir', 'os.path.isdir', (['EXPERIMENT_DIR'], {}), '(EXPERIMENT_DIR)\n', (1217, 1233), False, 'import os\n'), ((1239, 1268), 'shutil.rmtree', 'shutil.rmtree', (['EXPERIMENT_DIR'], {}), '(EXPERIMENT_DIR)\n', (1252, 1268), False, 'import shutil\n'), ((1312, 1342), 'os.path.exists', 'os.path.exists', (['EXPERIMENT_DIR'], {}), '(EXPERIMENT_DIR)\n', (1326, 1342), False, 'import os\n'), ((1386, 1444), 'shutil.copytree', 'shutil.copytree', (['CLONE_EXPERIMENT_DIR_FROM', 'EXPERIMENT_DIR'], {}), '(CLONE_EXPERIMENT_DIR_FROM, EXPERIMENT_DIR)\n', (1401, 1444), False, 'import shutil\n'), ((16976, 17040), 'common_blocks.pipelines.preprocessing_inference_tta', 'pipelines.preprocessing_inference_tta', (['config'], {'model_name': '"""unet"""'}), "(config, model_name='unet')\n", (17013, 17040), False, 'from common_blocks import pipelines\n'), ((19743, 19897), 'common_blocks.utils.generate_metadata', 'utils.generate_metadata', ([], {'train_images_dir': 'PARAMS.train_images_dir', 'test_images_dir': 'PARAMS.test_images_dir', 'depths_filepath': 'PARAMS.depths_filepath'}), '(train_images_dir=PARAMS.train_images_dir,\n test_images_dir=PARAMS.test_images_dir, depths_filepath=PARAMS.\n depths_filepath)\n', (19766, 19897), False, 'from common_blocks import utils\n'), ((20075, 20112), 'pandas.read_csv', 'pd.read_csv', (['PARAMS.metadata_filepath'], {}), '(PARAMS.metadata_filepath)\n', (20086, 20112), True, 'import pandas as pd\n'), ((20168, 20269), 'common_blocks.utils.KFoldBySortedValue', 'utils.KFoldBySortedValue', ([], {'n_splits': 'PARAMS.n_cv_splits', 'shuffle': 'PARAMS.shuffle', 'random_state': 'SEED'}), '(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.\n shuffle, random_state=SEED)\n', (20192, 20269), False, 'from common_blocks import utils\n'), ((21057, 21094), 'pandas.read_csv', 'pd.read_csv', (['PARAMS.metadata_filepath'], {}), '(PARAMS.metadata_filepath)\n', (21068, 21094), True, 'import pandas as pd\n'), ((21150, 21251), 'common_blocks.utils.KFoldBySortedValue', 'utils.KFoldBySortedValue', ([], {'n_splits': 'PARAMS.n_cv_splits', 'shuffle': 'PARAMS.shuffle', 'random_state': 'SEED'}), '(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.\n shuffle, random_state=SEED)\n', (21174, 21251), False, 'from common_blocks import utils\n'), ((21418, 21469), 'common_blocks.utils.read_masks', 'utils.read_masks', (['meta_valid_split[Y_COLUMN].values'], {}), '(meta_valid_split[Y_COLUMN].values)\n', (21434, 21469), False, 'from common_blocks import utils\n'), ((21842, 21886), 'common_blocks.pipelines.mask_postprocessing', 'pipelines.mask_postprocessing', ([], {'config': 'CONFIG'}), '(config=CONFIG)\n', (21871, 21886), False, 'from common_blocks import pipelines\n'), ((22584, 22638), 'os.path.join', 'os.path.join', (['EXPERIMENT_DIR', '"""validation_results.pkl"""'], {}), "(EXPERIMENT_DIR, 'validation_results.pkl')\n", (22596, 22638), False, 'import os\n'), ((22719, 22796), 'sklearn.externals.joblib.dump', 'joblib.dump', (['(meta_valid_split, y_true_valid, y_pred_valid)', 'results_filepath'], {}), '((meta_valid_split, y_true_valid, y_pred_valid), results_filepath)\n', (22730, 22796), False, 'from sklearn.externals import joblib\n'), ((22825, 22862), 'pandas.read_csv', 'pd.read_csv', (['PARAMS.metadata_filepath'], {}), '(PARAMS.metadata_filepath)\n', (22836, 22862), True, 'import pandas as pd\n'), ((23259, 23303), 'common_blocks.pipelines.mask_postprocessing', 'pipelines.mask_postprocessing', ([], {'config': 'CONFIG'}), '(config=CONFIG)\n', (23288, 23303), False, 'from common_blocks import pipelines\n'), ((23662, 23709), 'common_blocks.utils.create_submission', 'utils.create_submission', (['meta_test', 'y_pred_test'], {}), '(meta_test, y_pred_test)\n', (23685, 23709), False, 'from common_blocks import utils\n'), ((23737, 23783), 'os.path.join', 'os.path.join', (['EXPERIMENT_DIR', '"""submission.csv"""'], {}), "(EXPERIMENT_DIR, 'submission.csv')\n", (23749, 23783), False, 'import os\n'), ((24034, 24071), 'pandas.read_csv', 'pd.read_csv', (['PARAMS.metadata_filepath'], {}), '(PARAMS.metadata_filepath)\n', (24045, 24071), True, 'import pandas as pd\n'), ((24213, 24314), 'common_blocks.utils.KFoldBySortedValue', 'utils.KFoldBySortedValue', ([], {'n_splits': 'PARAMS.n_cv_splits', 'shuffle': 'PARAMS.shuffle', 'random_state': 'SEED'}), '(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.\n shuffle, random_state=SEED)\n', (24237, 24314), False, 'from common_blocks import utils\n'), ((25238, 25275), 'pandas.read_csv', 'pd.read_csv', (['PARAMS.metadata_filepath'], {}), '(PARAMS.metadata_filepath)\n', (25249, 25275), True, 'import pandas as pd\n'), ((25461, 25562), 'common_blocks.utils.KFoldBySortedValue', 'utils.KFoldBySortedValue', ([], {'n_splits': 'PARAMS.n_cv_splits', 'shuffle': 'PARAMS.shuffle', 'random_state': 'SEED'}), '(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.\n shuffle, random_state=SEED)\n', (25485, 25562), False, 'from common_blocks import utils\n'), ((27294, 27331), 'pandas.read_csv', 'pd.read_csv', (['PARAMS.metadata_filepath'], {}), '(PARAMS.metadata_filepath)\n', (27305, 27331), True, 'import pandas as pd\n'), ((27473, 27574), 'common_blocks.utils.KFoldBySortedValue', 'utils.KFoldBySortedValue', ([], {'n_splits': 'PARAMS.n_cv_splits', 'shuffle': 'PARAMS.shuffle', 'random_state': 'SEED'}), '(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.\n shuffle, random_state=SEED)\n', (27497, 27574), False, 'from common_blocks import utils\n'), ((28424, 28461), 'pandas.read_csv', 'pd.read_csv', (['PARAMS.metadata_filepath'], {}), '(PARAMS.metadata_filepath)\n', (28435, 28461), True, 'import pandas as pd\n'), ((28647, 28748), 'common_blocks.utils.KFoldBySortedValue', 'utils.KFoldBySortedValue', ([], {'n_splits': 'PARAMS.n_cv_splits', 'shuffle': 'PARAMS.shuffle', 'random_state': 'SEED'}), '(n_splits=PARAMS.n_cv_splits, shuffle=PARAMS.\n shuffle, random_state=SEED)\n', (28671, 28748), False, 'from common_blocks import utils\n'), ((30946, 30994), 'common_blocks.utils.clean_object_from_memory', 'utils.clean_object_from_memory', (['pipeline_network'], {}), '(pipeline_network)\n', (30976, 30994), False, 'from common_blocks import utils\n'), ((32027, 32075), 'common_blocks.utils.clean_object_from_memory', 'utils.clean_object_from_memory', (['pipeline_network'], {}), '(pipeline_network)\n', (32057, 32075), False, 'from common_blocks import utils\n'), ((32648, 32696), 'common_blocks.utils.clean_object_from_memory', 'utils.clean_object_from_memory', (['pipeline_network'], {}), '(pipeline_network)\n', (32678, 32696), False, 'from common_blocks import utils\n'), ((32769, 32820), 'common_blocks.utils.read_masks', 'utils.read_masks', (['valid_data_split[Y_COLUMN].values'], {}), '(valid_data_split[Y_COLUMN].values)\n', (32785, 32820), False, 'from common_blocks import utils\n'), ((33632, 33680), 'common_blocks.utils.clean_object_from_memory', 'utils.clean_object_from_memory', (['pipeline_network'], {}), '(pipeline_network)\n', (33662, 33680), False, 'from common_blocks import utils\n'), ((34721, 34769), 'common_blocks.utils.clean_object_from_memory', 'utils.clean_object_from_memory', (['pipeline_network'], {}), '(pipeline_network)\n', (34751, 34769), False, 'from common_blocks import utils\n'), ((34842, 34893), 'common_blocks.utils.read_masks', 'utils.read_masks', (['valid_data_split[Y_COLUMN].values'], {}), '(valid_data_split[Y_COLUMN].values)\n', (34858, 34893), False, 'from common_blocks import utils\n'), ((35447, 35494), 'common_blocks.metrics.intersection_over_union', 'metrics.intersection_over_union', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (35478, 35494), False, 'from common_blocks import metrics\n'), ((35506, 35564), 'common_blocks.metrics.intersection_over_union_thresholds', 'metrics.intersection_over_union_thresholds', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (35548, 35564), False, 'from common_blocks import metrics\n'), ((36674, 36718), 'common_blocks.pipelines.mask_postprocessing', 'pipelines.mask_postprocessing', ([], {'config': 'CONFIG'}), '(config=CONFIG)\n', (36703, 36718), False, 'from common_blocks import pipelines\n'), ((37044, 37109), 'os.path.join', 'os.path.join', (['EXPERIMENT_DIR', '"""out_of_fold_train_predictions.pkl"""'], {}), "(EXPERIMENT_DIR, 'out_of_fold_train_predictions.pkl')\n", (37056, 37109), False, 'import os\n'), ((37114, 37214), 'sklearn.externals.joblib.dump', 'joblib.dump', (["{'ids': train_ids, 'images': train_predictions}", 'out_of_fold_train_predictions_path'], {}), "({'ids': train_ids, 'images': train_predictions},\n out_of_fold_train_predictions_path)\n", (37125, 37214), False, 'from sklearn.externals import joblib\n'), ((37269, 37333), 'os.path.join', 'os.path.join', (['EXPERIMENT_DIR', '"""out_of_fold_test_predictions.pkl"""'], {}), "(EXPERIMENT_DIR, 'out_of_fold_test_predictions.pkl')\n", (37281, 37333), False, 'import os\n'), ((37502, 37549), 'common_blocks.utils.create_submission', 'utils.create_submission', (['meta_test', 'y_pred_test'], {}), '(meta_test, y_pred_test)\n', (37525, 37549), False, 'from common_blocks import utils\n'), ((37576, 37622), 'os.path.join', 'os.path.join', (['EXPERIMENT_DIR', '"""submission.csv"""'], {}), "(EXPERIMENT_DIR, 'submission.csv')\n", (37588, 37622), False, 'import os\n'), ((1352, 1381), 'shutil.rmtree', 'shutil.rmtree', (['EXPERIMENT_DIR'], {}), '(EXPERIMENT_DIR)\n', (1365, 1381), False, 'import shutil\n'), ((1519, 1536), 'common_blocks.utils.read_yaml', 'utils.read_yaml', ([], {}), '()\n', (1534, 1536), False, 'from common_blocks import utils\n'), ((15153, 15224), 'common_blocks.pipelines.preprocessing_train', 'pipelines.preprocessing_train', (['config'], {'model_name': '"""unet"""', 'suffix': 'suffix'}), "(config, model_name='unet', suffix=suffix)\n", (15182, 15224), False, 'from common_blocks import pipelines\n'), ((15259, 15315), 'common_blocks.pipelines.preprocessing_inference', 'pipelines.preprocessing_inference', (['config'], {'suffix': 'suffix'}), '(config, suffix=suffix)\n', (15292, 15315), False, 'from common_blocks import pipelines\n'), ((16020, 16096), 'functools.partial', 'partial', (['postprocessing.crop_image'], {'target_size': 'config.general.original_size'}), '(postprocessing.crop_image, target_size=config.general.original_size)\n', (16027, 16096), False, 'from functools import partial\n'), ((18218, 18294), 'functools.partial', 'partial', (['postprocessing.crop_image'], {'target_size': 'config.general.original_size'}), '(postprocessing.crop_image, target_size=config.general.original_size)\n', (18225, 18294), False, 'from functools import partial\n'), ((25036, 25053), 'numpy.mean', 'np.mean', (['fold_iou'], {}), '(fold_iou)\n', (25043, 25053), True, 'import numpy as np\n'), ((25055, 25071), 'numpy.std', 'np.std', (['fold_iou'], {}), '(fold_iou)\n', (25061, 25071), True, 'import numpy as np\n'), ((25098, 25116), 'numpy.mean', 'np.mean', (['fold_iout'], {}), '(fold_iout)\n', (25105, 25116), True, 'import numpy as np\n'), ((25118, 25135), 'numpy.std', 'np.std', (['fold_iout'], {}), '(fold_iout)\n', (25124, 25135), True, 'import numpy as np\n'), ((27013, 27030), 'numpy.mean', 'np.mean', (['fold_iou'], {}), '(fold_iou)\n', (27020, 27030), True, 'import numpy as np\n'), ((27032, 27048), 'numpy.std', 'np.std', (['fold_iou'], {}), '(fold_iou)\n', (27038, 27048), True, 'import numpy as np\n'), ((27075, 27093), 'numpy.mean', 'np.mean', (['fold_iout'], {}), '(fold_iout)\n', (27082, 27093), True, 'import numpy as np\n'), ((27095, 27112), 'numpy.std', 'np.std', (['fold_iout'], {}), '(fold_iout)\n', (27101, 27112), True, 'import numpy as np\n'), ((28228, 28245), 'numpy.mean', 'np.mean', (['fold_iou'], {}), '(fold_iou)\n', (28235, 28245), True, 'import numpy as np\n'), ((28247, 28263), 'numpy.std', 'np.std', (['fold_iou'], {}), '(fold_iou)\n', (28253, 28263), True, 'import numpy as np\n'), ((28290, 28308), 'numpy.mean', 'np.mean', (['fold_iout'], {}), '(fold_iout)\n', (28297, 28308), True, 'import numpy as np\n'), ((28310, 28327), 'numpy.std', 'np.std', (['fold_iout'], {}), '(fold_iout)\n', (28316, 28327), True, 'import numpy as np\n'), ((30031, 30048), 'numpy.mean', 'np.mean', (['fold_iou'], {}), '(fold_iou)\n', (30038, 30048), True, 'import numpy as np\n'), ((30050, 30066), 'numpy.std', 'np.std', (['fold_iou'], {}), '(fold_iou)\n', (30056, 30066), True, 'import numpy as np\n'), ((30093, 30111), 'numpy.mean', 'np.mean', (['fold_iout'], {}), '(fold_iout)\n', (30100, 30111), True, 'import numpy as np\n'), ((30113, 30130), 'numpy.std', 'np.std', (['fold_iout'], {}), '(fold_iout)\n', (30119, 30130), True, 'import numpy as np\n'), ((36596, 36634), 'numpy.array', 'np.array', (['out_of_fold_test_predictions'], {}), '(out_of_fold_test_predictions)\n', (36604, 36634), True, 'import numpy as np\n'), ((15391, 15433), 'common_blocks.models.PyTorchUNet', 'models.PyTorchUNet', ([], {}), "(**config.model['unet'])\n", (15409, 15433), False, 'from common_blocks import models\n'), ((16181, 16259), 'functools.partial', 'partial', (['postprocessing.resize_image'], {'target_size': 'config.general.original_size'}), '(postprocessing.resize_image, target_size=config.general.original_size)\n', (16188, 16259), False, 'from functools import partial\n'), ((16400, 16510), 'common_blocks.utils.make_apply_transformer', 'utils.make_apply_transformer', (['size_adjustment_function'], {'output_name': '"""resized_images"""', 'apply_on': "['images']"}), "(size_adjustment_function, output_name=\n 'resized_images', apply_on=['images'])\n", (16428, 16510), False, 'from common_blocks import utils\n'), ((17116, 17158), 'common_blocks.models.PyTorchUNet', 'models.PyTorchUNet', ([], {}), "(**config.model['unet'])\n", (17134, 17158), False, 'from common_blocks import models\n'), ((17797, 17816), 'steppy.base.IdentityOperation', 'IdentityOperation', ([], {}), '()\n', (17814, 17816), False, 'from steppy.base import Step, IdentityOperation\n'), ((18379, 18457), 'functools.partial', 'partial', (['postprocessing.resize_image'], {'target_size': 'config.general.original_size'}), '(postprocessing.resize_image, target_size=config.general.original_size)\n', (18386, 18457), False, 'from functools import partial\n'), ((18598, 18708), 'common_blocks.utils.make_apply_transformer', 'utils.make_apply_transformer', (['size_adjustment_function'], {'output_name': '"""resized_images"""', 'apply_on': "['images']"}), "(size_adjustment_function, output_name=\n 'resized_images', apply_on=['images'])\n", (18626, 18708), False, 'from common_blocks import utils\n'), ((4167, 4223), 'common_blocks.augmentation.crop_seq', 'aug.crop_seq', ([], {'crop_size': '(PARAMS.image_h, PARAMS.image_w)'}), '(crop_size=(PARAMS.image_h, PARAMS.image_w))\n', (4179, 4223), True, 'from common_blocks import augmentation as aug\n'), ((4371, 4412), 'common_blocks.augmentation.pad_to_fit_net', 'aug.pad_to_fit_net', (['(64)', 'PARAMS.pad_method'], {}), '(64, PARAMS.pad_method)\n', (4389, 4412), True, 'from common_blocks import augmentation as aug\n'), ((4613, 4654), 'common_blocks.augmentation.pad_to_fit_net', 'aug.pad_to_fit_net', (['(64)', 'PARAMS.pad_method'], {}), '(64, PARAMS.pad_method)\n', (4631, 4654), True, 'from common_blocks import augmentation as aug\n'), ((6695, 6736), 'common_blocks.augmentation.pad_to_fit_net', 'aug.pad_to_fit_net', (['(64)', 'PARAMS.pad_method'], {}), '(64, PARAMS.pad_method)\n', (6713, 6736), True, 'from common_blocks import augmentation as aug\n'), ((6818, 6859), 'common_blocks.augmentation.pad_to_fit_net', 'aug.pad_to_fit_net', (['(64)', 'PARAMS.pad_method'], {}), '(64, PARAMS.pad_method)\n', (6836, 6859), True, 'from common_blocks import augmentation as aug\n'), ((15571, 15603), 'steppy.adapter.E', 'E', (['preprocessing.name', '"""datagen"""'], {}), "(preprocessing.name, 'datagen')\n", (15572, 15603), False, 'from steppy.adapter import Adapter, E\n'), ((15660, 15703), 'steppy.adapter.E', 'E', (['preprocessing.name', '"""validation_datagen"""'], {}), "(preprocessing.name, 'validation_datagen')\n", (15661, 15703), False, 'from steppy.adapter import Adapter, E\n'), ((15752, 15785), 'steppy.adapter.E', 'E', (['"""callback_input"""', '"""meta_valid"""'], {}), "('callback_input', 'meta_valid')\n", (15753, 15785), False, 'from steppy.adapter import Adapter, E\n'), ((16728, 16759), 'steppy.adapter.E', 'E', (['unet.name', '"""mask_prediction"""'], {}), "(unet.name, 'mask_prediction')\n", (16729, 16759), False, 'from steppy.adapter import Adapter, E\n'), ((17944, 17991), 'steppy.adapter.E', 'E', (['tta_aggregator.name', '"""aggregated_prediction"""'], {}), "(tta_aggregator.name, 'aggregated_prediction')\n", (17945, 17991), False, 'from steppy.adapter import Adapter, E\n'), ((18940, 18985), 'steppy.adapter.E', 'E', (['prediction_renamed.name', '"""mask_prediction"""'], {}), "(prediction_renamed.name, 'mask_prediction')\n", (18941, 18985), False, 'from steppy.adapter import Adapter, E\n'), ((12885, 12950), 'os.path.join', 'os.path.join', (['EXPERIMENT_DIR', '"""checkpoints"""', '"""unet"""', '"""best.torch"""'], {}), "(EXPERIMENT_DIR, 'checkpoints', 'unet', 'best.torch')\n", (12897, 12950), False, 'import os\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from typing import Optional from neptune.new.internal.utils import verify_type, base64_encode from neptune.new.internal.operation import UploadFile, UploadFileContent from neptune.new.types.atoms.file import File as FileVal from neptune.new.attributes.atoms.atom import Atom # pylint: disable=protected-access class File(Atom): def assign(self, value: FileVal, wait: bool = False) -> None: verify_type("value", value, FileVal) if value.path is not None: operation = UploadFile( self._path, ext=value.extension, file_path=os.path.abspath(value.path) ) elif value.content is not None: operation = UploadFileContent( self._path, ext=value.extension, file_content=base64_encode(value.content), ) else: raise ValueError("File path and content are None") with self._container.lock(): self._enqueue_operation(operation, wait) def upload(self, value, wait: bool = False) -> None: self.assign(FileVal.create_from(value), wait) def download(self, destination: Optional[str] = None) -> None: verify_type("destination", destination, (str, type(None))) self._backend.download_file( self._container_id, self._container_type, self._path, destination ) def fetch_extension(self): # pylint: disable=protected-access val = self._backend.get_file_attribute( self._container_id, self._container_type, self._path ) return val.ext
[ "neptune.new.internal.utils.verify_type", "neptune.new.internal.utils.base64_encode", "neptune.new.types.atoms.file.File.create_from" ]
[((1013, 1049), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""value"""', 'value', 'FileVal'], {}), "('value', value, FileVal)\n", (1024, 1049), False, 'from neptune.new.internal.utils import verify_type, base64_encode\n'), ((1690, 1716), 'neptune.new.types.atoms.file.File.create_from', 'FileVal.create_from', (['value'], {}), '(value)\n', (1709, 1716), True, 'from neptune.new.types.atoms.file import File as FileVal\n'), ((1181, 1208), 'os.path.abspath', 'os.path.abspath', (['value.path'], {}), '(value.path)\n', (1196, 1208), False, 'import os\n'), ((1400, 1428), 'neptune.new.internal.utils.base64_encode', 'base64_encode', (['value.content'], {}), '(value.content)\n', (1413, 1428), False, 'from neptune.new.internal.utils import verify_type, base64_encode\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=redefined-outer-name import os import time import boto3 import pytest from faker import Faker from e2e_tests.utils import Environment, a_project_name, initialize_container from neptune.management import add_project_member, create_project from neptune.management.internal.utils import normalize_project_name fake = Faker() @pytest.fixture(scope="session") def environment(): workspace = os.getenv("WORKSPACE_NAME") admin_token = os.getenv("ADMIN_NEPTUNE_API_TOKEN") user = os.getenv("USER_USERNAME") project_name, project_key = a_project_name(project_slug=fake.slug()) project_identifier = normalize_project_name(name=project_name, workspace=workspace) created_project_identifier = create_project( name=project_name, key=project_key, visibility="priv", workspace=workspace, api_token=admin_token, ) time.sleep(10) add_project_member( name=created_project_identifier, username=user, # pylint: disable=no-member role="contributor", api_token=admin_token, ) yield Environment( workspace=workspace, project=project_identifier, user_token=os.getenv("NEPTUNE_API_TOKEN"), admin_token=admin_token, admin=os.getenv("ADMIN_USERNAME"), user=user, ) @pytest.fixture(scope="session") def container(request, environment): exp = initialize_container(container_type=request.param, project=environment.project) yield exp exp.stop() @pytest.fixture(scope="session") def containers_pair(request, environment): container_a_type, container_b_type = request.param.split("-") container_a = initialize_container(container_type=container_a_type, project=environment.project) container_b = initialize_container(container_type=container_b_type, project=environment.project) yield container_a, container_b container_b.stop() container_a.stop() @pytest.fixture(scope="session") def bucket(environment): bucket_name = os.environ.get("BUCKET_NAME") s3_client = boto3.resource("s3") s3_bucket = s3_client.Bucket(bucket_name) yield bucket_name, s3_client s3_bucket.objects.filter(Prefix=environment.project).delete()
[ "neptune.management.create_project", "neptune.management.add_project_member", "neptune.management.internal.utils.normalize_project_name" ]
[((931, 938), 'faker.Faker', 'Faker', ([], {}), '()\n', (936, 938), False, 'from faker import Faker\n'), ((942, 973), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (956, 973), False, 'import pytest\n'), ((1940, 1971), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1954, 1971), False, 'import pytest\n'), ((2131, 2162), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (2145, 2162), False, 'import pytest\n'), ((2560, 2591), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (2574, 2591), False, 'import pytest\n'), ((1009, 1036), 'os.getenv', 'os.getenv', (['"""WORKSPACE_NAME"""'], {}), "('WORKSPACE_NAME')\n", (1018, 1036), False, 'import os\n'), ((1055, 1091), 'os.getenv', 'os.getenv', (['"""ADMIN_NEPTUNE_API_TOKEN"""'], {}), "('ADMIN_NEPTUNE_API_TOKEN')\n", (1064, 1091), False, 'import os\n'), ((1103, 1129), 'os.getenv', 'os.getenv', (['"""USER_USERNAME"""'], {}), "('USER_USERNAME')\n", (1112, 1129), False, 'import os\n'), ((1229, 1291), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'project_name', 'workspace': 'workspace'}), '(name=project_name, workspace=workspace)\n', (1251, 1291), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((1325, 1442), 'neptune.management.create_project', 'create_project', ([], {'name': 'project_name', 'key': 'project_key', 'visibility': '"""priv"""', 'workspace': 'workspace', 'api_token': 'admin_token'}), "(name=project_name, key=project_key, visibility='priv',\n workspace=workspace, api_token=admin_token)\n", (1339, 1442), False, 'from neptune.management import add_project_member, create_project\n'), ((1491, 1505), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (1501, 1505), False, 'import time\n'), ((1511, 1625), 'neptune.management.add_project_member', 'add_project_member', ([], {'name': 'created_project_identifier', 'username': 'user', 'role': '"""contributor"""', 'api_token': 'admin_token'}), "(name=created_project_identifier, username=user, role=\n 'contributor', api_token=admin_token)\n", (1529, 1625), False, 'from neptune.management import add_project_member, create_project\n'), ((2019, 2098), 'e2e_tests.utils.initialize_container', 'initialize_container', ([], {'container_type': 'request.param', 'project': 'environment.project'}), '(container_type=request.param, project=environment.project)\n', (2039, 2098), False, 'from e2e_tests.utils import Environment, a_project_name, initialize_container\n'), ((2290, 2377), 'e2e_tests.utils.initialize_container', 'initialize_container', ([], {'container_type': 'container_a_type', 'project': 'environment.project'}), '(container_type=container_a_type, project=environment.\n project)\n', (2310, 2377), False, 'from e2e_tests.utils import Environment, a_project_name, initialize_container\n'), ((2391, 2478), 'e2e_tests.utils.initialize_container', 'initialize_container', ([], {'container_type': 'container_b_type', 'project': 'environment.project'}), '(container_type=container_b_type, project=environment.\n project)\n', (2411, 2478), False, 'from e2e_tests.utils import Environment, a_project_name, initialize_container\n'), ((2635, 2664), 'os.environ.get', 'os.environ.get', (['"""BUCKET_NAME"""'], {}), "('BUCKET_NAME')\n", (2649, 2664), False, 'import os\n'), ((2682, 2702), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (2696, 2702), False, 'import boto3\n'), ((1804, 1834), 'os.getenv', 'os.getenv', (['"""NEPTUNE_API_TOKEN"""'], {}), "('NEPTUNE_API_TOKEN')\n", (1813, 1834), False, 'import os\n'), ((1883, 1910), 'os.getenv', 'os.getenv', (['"""ADMIN_USERNAME"""'], {}), "('ADMIN_USERNAME')\n", (1892, 1910), False, 'import os\n')]
from __future__ import print_function import yaml import easydict import os import argparse import numpy as np import torch from torch import nn from torch.autograd import Variable from apex import amp, optimizers from data_loader.get_loader import get_dataloaders from utils.utils import get_models, get_optimizers, log_set from utils.lr_schedule import inv_lr_scheduler from models.LinearAverage import LinearAverage from eval import test, test_dev, test_and_nd from trainer_funcs import train_adapt def train(configs): print("random seed for data %s "%configs['random_seed']) source_loader, target_loader, \ source_test_loader, test_loader = get_dataloaders(configs) filename, logger = log_set(configs) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) if args.use_neptune: import socket import neptune neptune.init(configs['path_neptune']) current_name = os.path.basename(__file__) PARAMS = {'learning rate': hp, 'method': configs['method'], 'machine': socket.gethostname(), 'gpu': gpu_devices[0], 'file': current_name, 'net': configs["conf"].model.base_model, 'eta': args.eta} print(PARAMS) neptune.create_experiment(name=filename, params=PARAMS) neptune.append_tag("config %s file %s" % (config_file, filename)) models, opt_g, opt_c, param_lr_g, param_lr_c = get_models(configs) if configs['method'] == 'NC': ## Memory ndata = target_loader.dataset.__len__() M = LinearAverage(configs['dim'], ndata, configs['temp'], 0.0).cuda() models['M'] = M criterion = nn.CrossEntropyLoss().cuda() print('train start!') data_iter_s = iter(source_loader) data_iter_t = iter(target_loader) len_train_source = len(source_loader) len_train_target = len(target_loader) metric_names = {"neighborhood_density": "nd", "entropy": "ent", "source_risk": "s_risk", "dev_risk": "d_risk"} ## For s_risk, d_risk, ent, smaller is better. ## For neighborhood density, larger is better. metrics = {k: 1e5 for k in metric_names.keys()} metrics["neighborhood_density"] = 0 acc_dict = {k: 0 for k in metric_names.keys()} iter_dict = {k: 0 for k in metric_names.keys()} acc_best = 0 iter_best = 0 ## set hyper parameter for this run. args.hp = float(hp) for step in range(conf.train.min_step + 1): models['G'].train() models['C'].train() if step % len_train_target == 0: data_iter_t = iter(target_loader) if step % len_train_source == 0: data_iter_s = iter(source_loader) data_t = next(data_iter_t) data_s = next(data_iter_s) inv_lr_scheduler(param_lr_g, opt_g, step, init_lr=conf.train.lr, max_iter=conf.train.min_step) inv_lr_scheduler(param_lr_c, opt_c, step, init_lr=conf.train.lr, max_iter=conf.train.min_step) img_s = data_s[0] label_s = data_s[1] img_t = data_t[0] index_t = data_t[2] img_s, label_s = Variable(img_s.cuda()), \ Variable(label_s.cuda()) img_t = Variable(img_t.cuda()) index_t = Variable(index_t.cuda()) opt_g.zero_grad() opt_c.zero_grad() ## Weight normalizztion models['C'].module.weight_norm() ## Source loss calculation feat_s = models['G'](img_s) out_s = models['C'](feat_s) loss_s = criterion(out_s, label_s) feat_t = models['G'](img_t) out_t = models['C'](feat_t) loss_adapt = train_adapt(configs['method'], feat_s, feat_t, out_t, index_t, models, conf, args) all_loss = loss_s + loss_adapt with amp.scale_loss(all_loss, [opt_g, opt_c]) as scaled_loss: scaled_loss.backward() opt_g.step() opt_c.step() opt_g.zero_grad() opt_c.zero_grad() if configs['method'] == 'NC': models['M'].update_weight(feat_t, index_t) if step % conf.train.log_interval == 0: print('Train [{}/{} ({:.2f}%)]\tLoss Source: {:.6f} ' 'Loss Adapt: {:.6f}\t'.format( step, conf.train.min_step, 100 * float(step / conf.train.min_step), loss_s.item(), loss_adapt.item())) if step >= 1000 and step % conf.test.test_interval == 0: acc, nd, nd_nosoft, ent = test_and_nd(step, test_loader, filename, models['G'], models['C']) s_risk, d_risk = test_dev(step, source_test_loader, test_loader, source_loader, filename, models['G'], models['C']) output = "Iteration {} : current selected accs".format(step) for k, v in metric_names.items(): value_rep = eval(v) if v is not "nd": ## For s_risk, d_risk, ent, smaller is better. if value_rep < metrics[k]: metrics[k] = value_rep acc_dict[k] = acc iter_dict[k] = step elif v is "nd": if value_rep > metrics[k]: metrics[k] = value_rep acc_dict[k] = acc iter_dict[k] = step output += " {} : {} ".format(k, acc_dict[k]) if acc > acc_best: acc_best = acc iter_best = step output += "Acc best: {}".format(acc_best) print(output) logger.info(output) if args.use_neptune: neptune.log_metric('neighborhood density', nd) neptune.log_metric('neighborhood density w/o softmax', nd_nosoft) neptune.log_metric('entropy', ent) neptune.log_metric('accuracy', acc) neptune.log_metric('weighted risk', d_risk) neptune.log_metric('source risk', s_risk) models['G'].train() models['C'].train() del models return acc_dict, metrics, iter_dict, acc_best, iter_best if __name__ == "__main__": parser = argparse.ArgumentParser(description='Pytorch UDA Validation', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--config', type=str, default='config.yaml', help='/path/to/config/file') parser.add_argument('--source_path', type=str, default='./utils/source_list.txt', help='path to source list') parser.add_argument('--target_path', type=str, default='./utils/target_list.txt', help='path to target list') parser.add_argument('--log-interval', type=int, default=100, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--exp_name', type=str, default='record', help='/path/to/config/file') parser.add_argument('--method', type=str, default='NC', choices=['NC', 'PS', 'ENT', 'DANN'], help='method name') parser.add_argument("--gpu_devices", type=int, nargs='+', default=None, help="") parser.add_argument('--hps', type=float, default=[1.0, 2.0, 1.5, 0.5], nargs="*", help='hyper parameter, specific to each method') parser.add_argument('--eta', type=float, default=0.05, help='trade-off for loss') parser.add_argument("--random_seed", type=int, default=0, help='random seed to select source validation data') parser.add_argument("--use_neptune", default=False, action='store_true') parser.add_argument("--path_neptune", type=str, default="keisaito/sandbox", help='path in neptune') args = parser.parse_args() config_file = args.config conf = yaml.load(open(config_file)) save_config = yaml.load(open(config_file)) conf = easydict.EasyDict(conf) gpu_devices = ','.join([str(id) for id in args.gpu_devices]) os.environ["CUDA_VISIBLE_DEVICES"] = gpu_devices args.cuda = torch.cuda.is_available() use_gpu = torch.cuda.is_available() n_share = conf.data.dataset.n_share n_source_private = conf.data.dataset.n_source_private n_total = conf.data.dataset.n_total num_class = n_share + n_source_private script_name = os.path.basename(__file__) metric_names = {"neighborhood_density": "nd", "entropy": "ent", "source_risk": "s_risk", "dev_risk": "d_risk"} all_metrics = {k:{} for k in metric_names.keys()} all_iters = {k:{} for k in metric_names.keys()} all_acc_dict = {k:{} for k in metric_names.keys()} acc_best_all = 0 iter_best_all = 0 configs = vars(args) configs["conf"] = conf configs["script_name"] = script_name configs["num_class"] = num_class configs["config_file"] = config_file configs["hp"] = float(args.hps[0]) filename, _ = log_set(configs) dirname = os.path.dirname(filename) summary_path = os.path.join(dirname, "summary_result.txt") for hp in args.hps: configs["hp"] = float(hp) acc_choosen, metrics, iter_choosen, acc_best_gt, iter_best_gt = train(configs) if acc_best_gt > acc_best_all: acc_best_all = acc_best_gt iter_best_all = iter_best_gt for name in metric_names.keys(): all_acc_dict[name][hp], \ all_metrics[name][hp],\ all_iters[name][hp] = acc_choosen[name], metrics[name], iter_choosen[name] print(all_metrics) print(all_acc_dict) for met, acc, in zip(all_metrics.keys(), all_acc_dict.keys()): dict_met = all_metrics[met] if met == 'neighborhood_density': hp_best = max(dict_met, key=dict_met.get) else: hp_best = min(dict_met, key=dict_met.get) output = "metric %s selected hp %s iteration %s, " \ "metrics value %s acc choosen %s" % (met, hp_best, all_iters[met][hp_best], dict_met[hp_best], all_acc_dict[met][hp_best]) print(output) import logging logger = logging.getLogger(__name__) logging.basicConfig(filename=summary_path, format="%(message)s") logger.setLevel(logging.INFO) print(output) logger.info(output)
[ "neptune.log_metric", "neptune.create_experiment", "neptune.init", "neptune.append_tag" ]
[((660, 684), 'data_loader.get_loader.get_dataloaders', 'get_dataloaders', (['configs'], {}), '(configs)\n', (675, 684), False, 'from data_loader.get_loader import get_dataloaders\n'), ((708, 724), 'utils.utils.log_set', 'log_set', (['configs'], {}), '(configs)\n', (715, 724), False, 'from utils.utils import get_models, get_optimizers, log_set\n'), ((1566, 1585), 'utils.utils.get_models', 'get_models', (['configs'], {}), '(configs)\n', (1576, 1585), False, 'from utils.utils import get_models, get_optimizers, log_set\n'), ((7116, 7237), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Pytorch UDA Validation"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Pytorch UDA Validation',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (7139, 7237), False, 'import argparse\n'), ((9193, 9216), 'easydict.EasyDict', 'easydict.EasyDict', (['conf'], {}), '(conf)\n', (9210, 9216), False, 'import easydict\n'), ((9351, 9376), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9374, 9376), False, 'import torch\n'), ((9391, 9416), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9414, 9416), False, 'import torch\n'), ((9616, 9642), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (9632, 9642), False, 'import os\n'), ((10212, 10228), 'utils.utils.log_set', 'log_set', (['configs'], {}), '(configs)\n', (10219, 10228), False, 'from utils.utils import get_models, get_optimizers, log_set\n'), ((10243, 10268), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (10258, 10268), False, 'import os\n'), ((10288, 10331), 'os.path.join', 'os.path.join', (['dirname', '"""summary_result.txt"""'], {}), "(dirname, 'summary_result.txt')\n", (10300, 10331), False, 'import os\n'), ((904, 941), 'neptune.init', 'neptune.init', (["configs['path_neptune']"], {}), "(configs['path_neptune'])\n", (916, 941), False, 'import neptune\n'), ((965, 991), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (981, 991), False, 'import os\n'), ((1334, 1389), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': 'filename', 'params': 'PARAMS'}), '(name=filename, params=PARAMS)\n', (1359, 1389), False, 'import neptune\n'), ((1398, 1463), 'neptune.append_tag', 'neptune.append_tag', (["('config %s file %s' % (config_file, filename))"], {}), "('config %s file %s' % (config_file, filename))\n", (1416, 1463), False, 'import neptune\n'), ((2931, 3030), 'utils.lr_schedule.inv_lr_scheduler', 'inv_lr_scheduler', (['param_lr_g', 'opt_g', 'step'], {'init_lr': 'conf.train.lr', 'max_iter': 'conf.train.min_step'}), '(param_lr_g, opt_g, step, init_lr=conf.train.lr, max_iter=\n conf.train.min_step)\n', (2947, 3030), False, 'from utils.lr_schedule import inv_lr_scheduler\n'), ((3084, 3183), 'utils.lr_schedule.inv_lr_scheduler', 'inv_lr_scheduler', (['param_lr_c', 'opt_c', 'step'], {'init_lr': 'conf.train.lr', 'max_iter': 'conf.train.min_step'}), '(param_lr_c, opt_c, step, init_lr=conf.train.lr, max_iter=\n conf.train.min_step)\n', (3100, 3183), False, 'from utils.lr_schedule import inv_lr_scheduler\n'), ((3888, 3974), 'trainer_funcs.train_adapt', 'train_adapt', (["configs['method']", 'feat_s', 'feat_t', 'out_t', 'index_t', 'models', 'conf', 'args'], {}), "(configs['method'], feat_s, feat_t, out_t, index_t, models, conf,\n args)\n", (3899, 3974), False, 'from trainer_funcs import train_adapt\n'), ((11530, 11557), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (11547, 11557), False, 'import logging\n'), ((11566, 11630), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'summary_path', 'format': '"""%(message)s"""'}), "(filename=summary_path, format='%(message)s')\n", (11585, 11630), False, 'import logging\n'), ((751, 776), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (766, 776), False, 'import os\n'), ((799, 824), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (814, 824), False, 'import os\n'), ((1107, 1127), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (1125, 1127), False, 'import socket\n'), ((1831, 1852), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1850, 1852), False, 'from torch import nn\n'), ((4090, 4130), 'apex.amp.scale_loss', 'amp.scale_loss', (['all_loss', '[opt_g, opt_c]'], {}), '(all_loss, [opt_g, opt_c])\n', (4104, 4130), False, 'from apex import amp, optimizers\n'), ((4786, 4852), 'eval.test_and_nd', 'test_and_nd', (['step', 'test_loader', 'filename', "models['G']", "models['C']"], {}), "(step, test_loader, filename, models['G'], models['C'])\n", (4797, 4852), False, 'from eval import test, test_dev, test_and_nd\n'), ((5082, 5184), 'eval.test_dev', 'test_dev', (['step', 'source_test_loader', 'test_loader', 'source_loader', 'filename', "models['G']", "models['C']"], {}), "(step, source_test_loader, test_loader, source_loader, filename,\n models['G'], models['C'])\n", (5090, 5184), False, 'from eval import test, test_dev, test_and_nd\n'), ((1698, 1756), 'models.LinearAverage.LinearAverage', 'LinearAverage', (["configs['dim']", 'ndata', "configs['temp']", '(0.0)'], {}), "(configs['dim'], ndata, configs['temp'], 0.0)\n", (1711, 1756), False, 'from models.LinearAverage import LinearAverage\n'), ((6375, 6421), 'neptune.log_metric', 'neptune.log_metric', (['"""neighborhood density"""', 'nd'], {}), "('neighborhood density', nd)\n", (6393, 6421), False, 'import neptune\n'), ((6473, 6538), 'neptune.log_metric', 'neptune.log_metric', (['"""neighborhood density w/o softmax"""', 'nd_nosoft'], {}), "('neighborhood density w/o softmax', nd_nosoft)\n", (6491, 6538), False, 'import neptune\n'), ((6590, 6624), 'neptune.log_metric', 'neptune.log_metric', (['"""entropy"""', 'ent'], {}), "('entropy', ent)\n", (6608, 6624), False, 'import neptune\n'), ((6676, 6711), 'neptune.log_metric', 'neptune.log_metric', (['"""accuracy"""', 'acc'], {}), "('accuracy', acc)\n", (6694, 6711), False, 'import neptune\n'), ((6763, 6806), 'neptune.log_metric', 'neptune.log_metric', (['"""weighted risk"""', 'd_risk'], {}), "('weighted risk', d_risk)\n", (6781, 6806), False, 'import neptune\n'), ((6858, 6899), 'neptune.log_metric', 'neptune.log_metric', (['"""source risk"""', 's_risk'], {}), "('source risk', s_risk)\n", (6876, 6899), False, 'import neptune\n')]
from collections import OrderedDict from hyperopt import hp, tpe, fmin, Trials import neptune import neptunecontrib.hpo.utils as hpo_utils import neptunecontrib.monitoring.skopt as sk_utils import numpy as np import pandas as pd from sklearn.externals import joblib from utils import train_evaluate, axes2fig neptune.init(project_qualified_name='jakub-czakon/blog-hpo') N_ROWS = 10000 TRAIN_PATH = '/mnt/ml-team/minerva/open-solutions/santander/data/train.csv' STATIC_PARAMS = {'boosting': 'gbdt', 'objective': 'binary', 'metric': 'auc', 'num_threads': 12, } HPO_PARAMS = {'max_evals': 100, } SPACE = OrderedDict([('learning_rate', hp.loguniform('learning_rate', np.log(0.01), np.log(0.5))), ('max_depth', hp.choice('max_depth', range(1, 30, 1))), ('num_leaves', hp.choice('num_leaves', range(2, 100, 1))), ('min_data_in_leaf', hp.choice('min_data_in_leaf', range(10, 1000, 1))), ('feature_fraction', hp.uniform('feature_fraction', 0.1, 1.0)), ('subsample', hp.uniform('subsample', 0.1, 1.0)) ]) data = pd.read_csv(TRAIN_PATH, nrows=N_ROWS) X = data.drop(['ID_code', 'target'], axis=1) y = data['target'] def objective(params): all_params = {**params, **STATIC_PARAMS} return -1.0 * train_evaluate(X, y, all_params) experiment_params = {**STATIC_PARAMS, **HPO_PARAMS, 'n_rows': N_ROWS } with neptune.create_experiment(name='hyperopt sweep', params=experiment_params, tags=['hyperopt', 'random'], upload_source_files=['search_hyperopt.py', 'search_hyperopt_basic.py', 'utils.py']): trials = Trials() _ = fmin(objective, SPACE, trials=trials, algo=tpe.rand.suggest, **HPO_PARAMS) results = hpo_utils.hyperopt2skopt(trials, SPACE) best_auc = -1.0 * results.fun best_params = results.x # log metrics print('Best Validation AUC: {}'.format(best_auc)) print('Best Params: {}'.format(best_params)) neptune.send_metric('validation auc', best_auc) # log results joblib.dump(trials, 'artifacts/hyperopt_trials.pkl') joblib.dump(results, 'artifacts/hyperopt_results.pkl') joblib.dump(SPACE, 'artifacts/hyperopt_space.pkl') neptune.send_artifact('artifacts/hyperopt_trials.pkl') neptune.send_artifact('artifacts/hyperopt_results.pkl') neptune.send_artifact('artifacts/hyperopt_space.pkl') # log runs sk_utils.send_runs(results) sk_utils.send_best_parameters(results) sk_utils.send_plot_convergence(results, channel_name='diagnostics') sk_utils.send_plot_evaluations(results, channel_name='diagnostics')
[ "neptune.send_metric", "neptune.create_experiment", "neptune.send_artifact", "neptune.init" ]
[((312, 372), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""jakub-czakon/blog-hpo"""'}), "(project_qualified_name='jakub-czakon/blog-hpo')\n", (324, 372), False, 'import neptune\n'), ((1217, 1254), 'pandas.read_csv', 'pd.read_csv', (['TRAIN_PATH'], {'nrows': 'N_ROWS'}), '(TRAIN_PATH, nrows=N_ROWS)\n', (1228, 1254), True, 'import pandas as pd\n'), ((1583, 1778), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""hyperopt sweep"""', 'params': 'experiment_params', 'tags': "['hyperopt', 'random']", 'upload_source_files': "['search_hyperopt.py', 'search_hyperopt_basic.py', 'utils.py']"}), "(name='hyperopt sweep', params=experiment_params,\n tags=['hyperopt', 'random'], upload_source_files=['search_hyperopt.py',\n 'search_hyperopt_basic.py', 'utils.py'])\n", (1608, 1778), False, 'import neptune\n'), ((1982, 1990), 'hyperopt.Trials', 'Trials', ([], {}), '()\n', (1988, 1990), False, 'from hyperopt import hp, tpe, fmin, Trials\n'), ((1999, 2073), 'hyperopt.fmin', 'fmin', (['objective', 'SPACE'], {'trials': 'trials', 'algo': 'tpe.rand.suggest'}), '(objective, SPACE, trials=trials, algo=tpe.rand.suggest, **HPO_PARAMS)\n', (2003, 2073), False, 'from hyperopt import hp, tpe, fmin, Trials\n'), ((2089, 2128), 'neptunecontrib.hpo.utils.hyperopt2skopt', 'hpo_utils.hyperopt2skopt', (['trials', 'SPACE'], {}), '(trials, SPACE)\n', (2113, 2128), True, 'import neptunecontrib.hpo.utils as hpo_utils\n'), ((2319, 2366), 'neptune.send_metric', 'neptune.send_metric', (['"""validation auc"""', 'best_auc'], {}), "('validation auc', best_auc)\n", (2338, 2366), False, 'import neptune\n'), ((2390, 2442), 'sklearn.externals.joblib.dump', 'joblib.dump', (['trials', '"""artifacts/hyperopt_trials.pkl"""'], {}), "(trials, 'artifacts/hyperopt_trials.pkl')\n", (2401, 2442), False, 'from sklearn.externals import joblib\n'), ((2447, 2501), 'sklearn.externals.joblib.dump', 'joblib.dump', (['results', '"""artifacts/hyperopt_results.pkl"""'], {}), "(results, 'artifacts/hyperopt_results.pkl')\n", (2458, 2501), False, 'from sklearn.externals import joblib\n'), ((2506, 2556), 'sklearn.externals.joblib.dump', 'joblib.dump', (['SPACE', '"""artifacts/hyperopt_space.pkl"""'], {}), "(SPACE, 'artifacts/hyperopt_space.pkl')\n", (2517, 2556), False, 'from sklearn.externals import joblib\n'), ((2562, 2616), 'neptune.send_artifact', 'neptune.send_artifact', (['"""artifacts/hyperopt_trials.pkl"""'], {}), "('artifacts/hyperopt_trials.pkl')\n", (2583, 2616), False, 'import neptune\n'), ((2621, 2676), 'neptune.send_artifact', 'neptune.send_artifact', (['"""artifacts/hyperopt_results.pkl"""'], {}), "('artifacts/hyperopt_results.pkl')\n", (2642, 2676), False, 'import neptune\n'), ((2681, 2734), 'neptune.send_artifact', 'neptune.send_artifact', (['"""artifacts/hyperopt_space.pkl"""'], {}), "('artifacts/hyperopt_space.pkl')\n", (2702, 2734), False, 'import neptune\n'), ((2755, 2782), 'neptunecontrib.monitoring.skopt.send_runs', 'sk_utils.send_runs', (['results'], {}), '(results)\n', (2773, 2782), True, 'import neptunecontrib.monitoring.skopt as sk_utils\n'), ((2787, 2825), 'neptunecontrib.monitoring.skopt.send_best_parameters', 'sk_utils.send_best_parameters', (['results'], {}), '(results)\n', (2816, 2825), True, 'import neptunecontrib.monitoring.skopt as sk_utils\n'), ((2830, 2897), 'neptunecontrib.monitoring.skopt.send_plot_convergence', 'sk_utils.send_plot_convergence', (['results'], {'channel_name': '"""diagnostics"""'}), "(results, channel_name='diagnostics')\n", (2860, 2897), True, 'import neptunecontrib.monitoring.skopt as sk_utils\n'), ((2902, 2969), 'neptunecontrib.monitoring.skopt.send_plot_evaluations', 'sk_utils.send_plot_evaluations', (['results'], {'channel_name': '"""diagnostics"""'}), "(results, channel_name='diagnostics')\n", (2932, 2969), True, 'import neptunecontrib.monitoring.skopt as sk_utils\n'), ((1408, 1440), 'utils.train_evaluate', 'train_evaluate', (['X', 'y', 'all_params'], {}), '(X, y, all_params)\n', (1422, 1440), False, 'from utils import train_evaluate, axes2fig\n'), ((1072, 1112), 'hyperopt.hp.uniform', 'hp.uniform', (['"""feature_fraction"""', '(0.1)', '(1.0)'], {}), "('feature_fraction', 0.1, 1.0)\n", (1082, 1112), False, 'from hyperopt import hp, tpe, fmin, Trials\n'), ((1150, 1183), 'hyperopt.hp.uniform', 'hp.uniform', (['"""subsample"""', '(0.1)', '(1.0)'], {}), "('subsample', 0.1, 1.0)\n", (1160, 1183), False, 'from hyperopt import hp, tpe, fmin, Trials\n'), ((750, 762), 'numpy.log', 'np.log', (['(0.01)'], {}), '(0.01)\n', (756, 762), True, 'import numpy as np\n'), ((764, 775), 'numpy.log', 'np.log', (['(0.5)'], {}), '(0.5)\n', (770, 775), True, 'import numpy as np\n')]
import random import json import argparse import os import torch from torch.utils.data import DataLoader from torch.optim import Adam from runner.gegl_trainer import GeneticExpertGuidedLearningTrainer from runner.guacamol_generator import GeneticExpertGuidedLearningGenerator from model.neural_apprentice import SmilesGenerator, SmilesGeneratorHandler from model.genetic_expert import GeneticOperatorHandler from util.storage.priority_queue import MaxRewardPriorityQueue from util.storage.recorder import Recorder from util.chemistry.benchmarks import load_benchmark from util.smiles.char_dict import SmilesCharDictionary import neptune if __name__ == "__main__": parser = argparse.ArgumentParser( description="", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("--benchmark_id", type=int, default=12) parser.add_argument("--dataset", type=str, default="guacamol") parser.add_argument("--max_smiles_length", type=int, default=100) parser.add_argument("--apprentice_load_dir", type=str, default="./resource/checkpoint/guacamol") parser.add_argument("--learning_rate", type=float, default=1e-3) parser.add_argument("--sample_batch_size", type=int, default=512) parser.add_argument("--optimize_batch_size", type=int, default=256) parser.add_argument("--mutation_rate", type=float, default=0.01) parser.add_argument("--num_steps", type=int, default=200) parser.add_argument("--num_keep", type=int, default=1024) parser.add_argument("--max_sampling_batch_size", type=int, default=1024) parser.add_argument("--apprentice_sampling_batch_size", type=int, default=8192) parser.add_argument("--expert_sampling_batch_size", type=int, default=8192) parser.add_argument("--apprentice_training_batch_size", type=int, default=256) parser.add_argument("--num_apprentice_training_steps", type=int, default=8) parser.add_argument("--num_jobs", type=int, default=8) parser.add_argument("--record_filtered", action="store_true") args = parser.parse_args() # Prepare CUDA device device = torch.device(0) # Initialize neptune neptune.init(project_qualified_name="sungsoo.ahn/deep-molecular-optimization") experiment = neptune.create_experiment(name="gegl", params=vars(args)) neptune.append_tag(args.benchmark_id) # Load benchmark, i.e., the scoring function and its corresponding protocol benchmark, scoring_num_list = load_benchmark(args.benchmark_id) # Load character directory used for mapping atoms to integers char_dict = SmilesCharDictionary(dataset=args.dataset, max_smi_len=args.max_smiles_length) # Prepare max-reward priority queues apprentice_storage = MaxRewardPriorityQueue() expert_storage = MaxRewardPriorityQueue() # Prepare neural apprentice (we use the weights pretrained on existing dataset) apprentice = SmilesGenerator.load(load_dir=args.apprentice_load_dir) apprentice = apprentice.to(device) apprentice_optimizer = Adam(apprentice.parameters(), lr=args.learning_rate) apprentice_handler = SmilesGeneratorHandler( model=apprentice, optimizer=apprentice_optimizer, char_dict=char_dict, max_sampling_batch_size=args.max_sampling_batch_size, ) apprentice.train() # Prepare genetic expert expert_handler = GeneticOperatorHandler(mutation_rate=args.mutation_rate) # Prepare trainer that collect samples from the models & optimize the neural apprentice trainer = GeneticExpertGuidedLearningTrainer( apprentice_storage=apprentice_storage, expert_storage=expert_storage, apprentice_handler=apprentice_handler, expert_handler=expert_handler, char_dict=char_dict, num_keep=args.num_keep, apprentice_sampling_batch_size=args.apprentice_sampling_batch_size, expert_sampling_batch_size=args.expert_sampling_batch_size, apprentice_training_batch_size=args.apprentice_training_batch_size, num_apprentice_training_steps=args.num_apprentice_training_steps, init_smis=[], ) # Prepare recorder that takes care of intermediate logging recorder = Recorder(scoring_num_list=scoring_num_list, record_filtered=args.record_filtered) # Prepare our version of GoalDirectedGenerator for evaluating our algorithm guacamol_generator = GeneticExpertGuidedLearningGenerator( trainer=trainer, recorder=recorder, num_steps=args.num_steps, device=device, scoring_num_list=scoring_num_list, num_jobs=args.num_jobs, ) # Run the experiment result = benchmark.assess_model(guacamol_generator) # Dump the final result to neptune neptune.set_property("benchmark_score", result.score)
[ "neptune.set_property", "neptune.append_tag", "neptune.init" ]
[((681, 781), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='', formatter_class=argparse.\n ArgumentDefaultsHelpFormatter)\n", (704, 781), False, 'import argparse\n'), ((2098, 2113), 'torch.device', 'torch.device', (['(0)'], {}), '(0)\n', (2110, 2113), False, 'import torch\n'), ((2144, 2222), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""sungsoo.ahn/deep-molecular-optimization"""'}), "(project_qualified_name='sungsoo.ahn/deep-molecular-optimization')\n", (2156, 2222), False, 'import neptune\n'), ((2302, 2339), 'neptune.append_tag', 'neptune.append_tag', (['args.benchmark_id'], {}), '(args.benchmark_id)\n', (2320, 2339), False, 'import neptune\n'), ((2455, 2488), 'util.chemistry.benchmarks.load_benchmark', 'load_benchmark', (['args.benchmark_id'], {}), '(args.benchmark_id)\n', (2469, 2488), False, 'from util.chemistry.benchmarks import load_benchmark\n'), ((2572, 2650), 'util.smiles.char_dict.SmilesCharDictionary', 'SmilesCharDictionary', ([], {'dataset': 'args.dataset', 'max_smi_len': 'args.max_smiles_length'}), '(dataset=args.dataset, max_smi_len=args.max_smiles_length)\n', (2592, 2650), False, 'from util.smiles.char_dict import SmilesCharDictionary\n'), ((2718, 2742), 'util.storage.priority_queue.MaxRewardPriorityQueue', 'MaxRewardPriorityQueue', ([], {}), '()\n', (2740, 2742), False, 'from util.storage.priority_queue import MaxRewardPriorityQueue\n'), ((2764, 2788), 'util.storage.priority_queue.MaxRewardPriorityQueue', 'MaxRewardPriorityQueue', ([], {}), '()\n', (2786, 2788), False, 'from util.storage.priority_queue import MaxRewardPriorityQueue\n'), ((2891, 2946), 'model.neural_apprentice.SmilesGenerator.load', 'SmilesGenerator.load', ([], {'load_dir': 'args.apprentice_load_dir'}), '(load_dir=args.apprentice_load_dir)\n', (2911, 2946), False, 'from model.neural_apprentice import SmilesGenerator, SmilesGeneratorHandler\n'), ((3091, 3242), 'model.neural_apprentice.SmilesGeneratorHandler', 'SmilesGeneratorHandler', ([], {'model': 'apprentice', 'optimizer': 'apprentice_optimizer', 'char_dict': 'char_dict', 'max_sampling_batch_size': 'args.max_sampling_batch_size'}), '(model=apprentice, optimizer=apprentice_optimizer,\n char_dict=char_dict, max_sampling_batch_size=args.max_sampling_batch_size)\n', (3113, 3242), False, 'from model.neural_apprentice import SmilesGenerator, SmilesGeneratorHandler\n'), ((3352, 3408), 'model.genetic_expert.GeneticOperatorHandler', 'GeneticOperatorHandler', ([], {'mutation_rate': 'args.mutation_rate'}), '(mutation_rate=args.mutation_rate)\n', (3374, 3408), False, 'from model.genetic_expert import GeneticOperatorHandler\n'), ((3516, 4044), 'runner.gegl_trainer.GeneticExpertGuidedLearningTrainer', 'GeneticExpertGuidedLearningTrainer', ([], {'apprentice_storage': 'apprentice_storage', 'expert_storage': 'expert_storage', 'apprentice_handler': 'apprentice_handler', 'expert_handler': 'expert_handler', 'char_dict': 'char_dict', 'num_keep': 'args.num_keep', 'apprentice_sampling_batch_size': 'args.apprentice_sampling_batch_size', 'expert_sampling_batch_size': 'args.expert_sampling_batch_size', 'apprentice_training_batch_size': 'args.apprentice_training_batch_size', 'num_apprentice_training_steps': 'args.num_apprentice_training_steps', 'init_smis': '[]'}), '(apprentice_storage=apprentice_storage,\n expert_storage=expert_storage, apprentice_handler=apprentice_handler,\n expert_handler=expert_handler, char_dict=char_dict, num_keep=args.\n num_keep, apprentice_sampling_batch_size=args.\n apprentice_sampling_batch_size, expert_sampling_batch_size=args.\n expert_sampling_batch_size, apprentice_training_batch_size=args.\n apprentice_training_batch_size, num_apprentice_training_steps=args.\n num_apprentice_training_steps, init_smis=[])\n', (3550, 4044), False, 'from runner.gegl_trainer import GeneticExpertGuidedLearningTrainer\n'), ((4186, 4272), 'util.storage.recorder.Recorder', 'Recorder', ([], {'scoring_num_list': 'scoring_num_list', 'record_filtered': 'args.record_filtered'}), '(scoring_num_list=scoring_num_list, record_filtered=args.\n record_filtered)\n', (4194, 4272), False, 'from util.storage.recorder import Recorder\n'), ((4374, 4555), 'runner.guacamol_generator.GeneticExpertGuidedLearningGenerator', 'GeneticExpertGuidedLearningGenerator', ([], {'trainer': 'trainer', 'recorder': 'recorder', 'num_steps': 'args.num_steps', 'device': 'device', 'scoring_num_list': 'scoring_num_list', 'num_jobs': 'args.num_jobs'}), '(trainer=trainer, recorder=recorder,\n num_steps=args.num_steps, device=device, scoring_num_list=\n scoring_num_list, num_jobs=args.num_jobs)\n', (4410, 4555), False, 'from runner.guacamol_generator import GeneticExpertGuidedLearningGenerator\n'), ((4728, 4781), 'neptune.set_property', 'neptune.set_property', (['"""benchmark_score"""', 'result.score'], {}), "('benchmark_score', result.score)\n", (4748, 4781), False, 'import neptune\n')]
import math from typing import Any, Dict from neptune import new as neptune import pandas as pd from kedro.pipeline import Pipeline, node # ------ Looking for furthest planet ------- def distances(planets: pd.DataFrame) -> Any: planets['Distance from Sun'] = planets['Distance from Sun (106 km)'].apply(lambda row: row * 1e6) return planets[[ 'Planet', 'Distance from Sun' ]] def furthest(distances_to_planets: pd.DataFrame) -> Dict[str, Any]: furthest_planet = distances_to_planets.iloc[distances_to_planets['Distance from Sun'].argmax()]\ return dict( furthest_planet_name=furthest_planet.Planet, furthest_planet_distance=furthest_planet['Distance from Sun'] ) def travel_time(furthest_planet_distance: float, furthest_planet_name: str, travel_speed: float) -> float: travel_hours = furthest_planet_distance / travel_speed neptune_run = neptune.init( capture_stdout=False, capture_stderr=False, capture_hardware_metrics=False, source_files=[] ) neptune_run['furthest_planet/name'] = furthest_planet_name neptune_run['furthest_planet/travel_hours'] = travel_hours neptune_run['furthest_planet/travel_days'] = math.ceil(travel_hours / 24.0) neptune_run['furthest_planet/travel_months'] = math.ceil(travel_hours / 720.0) neptune_run['furthest_planet/travel_years'] = math.ceil(travel_hours / 720.0 / 365.0) neptune_run.sync() return travel_hours def create_pipeline(**kwargs): return Pipeline( [ node( distances, ["planets"], 'distances_to_planets', name="distances", ), node( furthest, ["distances_to_planets"], dict( furthest_planet_name="furthest_planet_name", furthest_planet_distance="furthest_planet_distance" ), name="furthest", ), node( travel_time, ["furthest_planet_distance", "furthest_planet_name", "params:travel_speed"], 'travel_hours', name="travel_time", ) ] )
[ "neptune.new.init" ]
[((914, 1023), 'neptune.new.init', 'neptune.init', ([], {'capture_stdout': '(False)', 'capture_stderr': '(False)', 'capture_hardware_metrics': '(False)', 'source_files': '[]'}), '(capture_stdout=False, capture_stderr=False,\n capture_hardware_metrics=False, source_files=[])\n', (926, 1023), True, 'from neptune import new as neptune\n'), ((1234, 1264), 'math.ceil', 'math.ceil', (['(travel_hours / 24.0)'], {}), '(travel_hours / 24.0)\n', (1243, 1264), False, 'import math\n'), ((1316, 1347), 'math.ceil', 'math.ceil', (['(travel_hours / 720.0)'], {}), '(travel_hours / 720.0)\n', (1325, 1347), False, 'import math\n'), ((1398, 1437), 'math.ceil', 'math.ceil', (['(travel_hours / 720.0 / 365.0)'], {}), '(travel_hours / 720.0 / 365.0)\n', (1407, 1437), False, 'import math\n'), ((1563, 1633), 'kedro.pipeline.node', 'node', (['distances', "['planets']", '"""distances_to_planets"""'], {'name': '"""distances"""'}), "(distances, ['planets'], 'distances_to_planets', name='distances')\n", (1567, 1633), False, 'from kedro.pipeline import Pipeline, node\n'), ((2038, 2172), 'kedro.pipeline.node', 'node', (['travel_time', "['furthest_planet_distance', 'furthest_planet_name', 'params:travel_speed']", '"""travel_hours"""'], {'name': '"""travel_time"""'}), "(travel_time, ['furthest_planet_distance', 'furthest_planet_name',\n 'params:travel_speed'], 'travel_hours', name='travel_time')\n", (2042, 2172), False, 'from kedro.pipeline import Pipeline, node\n')]
import hashlib import neptune import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from sklearn.metrics import accuracy_score from torchvision import datasets, transforms class Net(nn.Module): def __init__(self, fc_out_features): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(4 * 4 * 50, fc_out_features) self.fc2 = nn.Linear(fc_out_features, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2, 2) x = x.view(-1, 4 * 4 * 50) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.log_softmax(x, dim=1) PARAMS = {'fc_out_features': 400, 'lr': 0.008, 'momentum': 0.99, 'iterations': 300, 'batch_size': 64} # Initialize Neptune neptune.init('neptune-ai/tour-with-pytorch') # Create experiment neptune.create_experiment(name='pytorch-run', tags=['pytorch', 'MNIST'], params=PARAMS) dataset = datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) # Log data version neptune.set_property('data_version', hashlib.md5(dataset.data.cpu().detach().numpy()).hexdigest()) train_loader = torch.utils.data.DataLoader(dataset, batch_size=PARAMS['batch_size'], shuffle=True) model = Net(PARAMS['fc_out_features']) optimizer = optim.SGD(model.parameters(), PARAMS['lr'], PARAMS['momentum']) for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() outputs = model(data) loss = F.nll_loss(outputs, target) # Log loss neptune.log_metric('batch_loss', loss) y_true = target.cpu().detach().numpy() y_pred = outputs.argmax(axis=1).cpu().detach().numpy() acc = accuracy_score(y_true, y_pred) # Log accuracy neptune.log_metric('batch_acc', acc) loss.backward() optimizer.step() # Log image predictions if batch_idx % 50 == 1: for image, prediction in zip(data, outputs): description = '\n'.join(['class {}: {}'.format(i, pred) for i, pred in enumerate(F.softmax(prediction, dim=0))]) neptune.log_image('predictions', image.squeeze(), description=description) if batch_idx == PARAMS['iterations']: break # Log model weights torch.save(model.state_dict(), 'model_dict.pth') neptune.log_artifact('model_dict.pth')
[ "neptune.log_metric", "neptune.create_experiment", "neptune.log_artifact", "neptune.init" ]
[((971, 1015), 'neptune.init', 'neptune.init', (['"""neptune-ai/tour-with-pytorch"""'], {}), "('neptune-ai/tour-with-pytorch')\n", (983, 1015), False, 'import neptune\n'), ((1037, 1128), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""pytorch-run"""', 'tags': "['pytorch', 'MNIST']", 'params': 'PARAMS'}), "(name='pytorch-run', tags=['pytorch', 'MNIST'],\n params=PARAMS)\n", (1062, 1128), False, 'import neptune\n'), ((1526, 1613), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': "PARAMS['batch_size']", 'shuffle': '(True)'}), "(dataset, batch_size=PARAMS['batch_size'],\n shuffle=True)\n", (1553, 1613), False, 'import torch\n'), ((2814, 2852), 'neptune.log_artifact', 'neptune.log_artifact', (['"""model_dict.pth"""'], {}), "('model_dict.pth')\n", (2834, 2852), False, 'import neptune\n'), ((1934, 1961), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['outputs', 'target'], {}), '(outputs, target)\n', (1944, 1961), True, 'import torch.nn.functional as F\n'), ((1982, 2020), 'neptune.log_metric', 'neptune.log_metric', (['"""batch_loss"""', 'loss'], {}), "('batch_loss', loss)\n", (2000, 2020), False, 'import neptune\n'), ((2134, 2164), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (2148, 2164), False, 'from sklearn.metrics import accuracy_score\n'), ((2189, 2225), 'neptune.log_metric', 'neptune.log_metric', (['"""batch_acc"""', 'acc'], {}), "('batch_acc', acc)\n", (2207, 2225), False, 'import neptune\n'), ((336, 358), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(20)', '(5)', '(1)'], {}), '(1, 20, 5, 1)\n', (345, 358), True, 'import torch.nn as nn\n'), ((380, 403), 'torch.nn.Conv2d', 'nn.Conv2d', (['(20)', '(50)', '(5)', '(1)'], {}), '(20, 50, 5, 1)\n', (389, 403), True, 'import torch.nn as nn\n'), ((423, 461), 'torch.nn.Linear', 'nn.Linear', (['(4 * 4 * 50)', 'fc_out_features'], {}), '(4 * 4 * 50, fc_out_features)\n', (432, 461), True, 'import torch.nn as nn\n'), ((481, 511), 'torch.nn.Linear', 'nn.Linear', (['fc_out_features', '(10)'], {}), '(fc_out_features, 10)\n', (490, 511), True, 'import torch.nn as nn\n'), ((585, 606), 'torch.nn.functional.max_pool2d', 'F.max_pool2d', (['x', '(2)', '(2)'], {}), '(x, 2, 2)\n', (597, 606), True, 'import torch.nn.functional as F\n'), ((653, 674), 'torch.nn.functional.max_pool2d', 'F.max_pool2d', (['x', '(2)', '(2)'], {}), '(x, 2, 2)\n', (665, 674), True, 'import torch.nn.functional as F\n'), ((781, 804), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['x'], {'dim': '(1)'}), '(x, dim=1)\n', (794, 804), True, 'import torch.nn.functional as F\n'), ((1345, 1366), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1364, 1366), False, 'from torchvision import datasets, transforms\n'), ((2508, 2536), 'torch.nn.functional.softmax', 'F.softmax', (['prediction'], {'dim': '(0)'}), '(prediction, dim=0)\n', (2517, 2536), True, 'import torch.nn.functional as F\n')]
import argparse import copy import os import neptune from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from hyperopt import Trials, fmin, hp, tpe from purano.clusterer.clusterer import Clusterer from purano.clusterer.metrics import calc_metrics from purano.io import parse_tg_jsonl, parse_clustering_markup_tsv SEARCH_SPACE = hp.pchoice( "clustering_type", [(0.999, { "type": "agglomerative", "distance_threshold": hp.quniform("distance_threshold", 0.01, 0.95, 0.01), "linkage": "average", "n_clusters": None, "affinity": "precomputed" }), (0.001, { "type": "dbscan", "eps": hp.quniform("dbscan_eps", 0.01, 0.8, 0.01), "min_samples": hp.quniform("dbscan_min_samples", 1, 20, 1), "leaf_size": hp.quniform("dbscan_leaf_size", 2, 50, 2), "metric": "precomputed" })] ) def fit_param( input_file: str, nrows: int, sort_by_date: bool, start_date: str, end_date: str, config: str, clustering_markup_tsv: str, original_jsonl: str, neptune_project: str, neptune_tags: str ): assert input_file.endswith(".db") assert os.path.isfile(clustering_markup_tsv) assert clustering_markup_tsv.endswith(".tsv") assert os.path.isfile(original_jsonl) assert original_jsonl.endswith(".jsonl") assert os.path.isfile(config) assert config.endswith(".jsonnet") assert neptune_tags neptune_tags = neptune_tags.split(",") neptune_api_token = os.getenv("NEPTUNE_API_TOKEN") neptune.init(project_qualified_name=neptune_project, api_token=neptune_api_token) url2record = {r["url"]: r for r in parse_tg_jsonl(original_jsonl)} markup = parse_clustering_markup_tsv(clustering_markup_tsv) db_engine = "sqlite:///{}".format(input_file) engine = create_engine(db_engine) Session = sessionmaker(bind=engine, autoflush=False) session = Session() clusterer = Clusterer(session, config) clusterer.fetch_info( start_date, end_date, sort_by_date, nrows ) config_copy = copy.deepcopy(clusterer.config) def calc_accuracy(params): neptune.create_experiment( name="clustering", params=params, upload_source_files=['configs/*.jsonnet'], tags=neptune_tags ) clusterer.config = copy.deepcopy(config_copy) clusterer.config["clustering"] = params clusterer.config["distances"]["cache_distances"] = True clusterer.calc_distances() clusterer.cluster() labels = clusterer.get_labels() clusterer.reset_clusters() metrics, _ = calc_metrics(markup, url2record, labels) accuracy = metrics["accuracy"] f1_score_0 = metrics["0"]["f1-score"] f1_score_1 = metrics["1"]["f1-score"] neptune.log_metric("accuracy", accuracy) neptune.log_metric("f1_score_0", f1_score_0) neptune.log_metric("f1_score_1", f1_score_1) neptune.stop() return -accuracy trials = Trials() best = fmin( fn=calc_accuracy, space=SEARCH_SPACE, algo=tpe.suggest, max_evals=200, trials=trials ) print(best) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--input-file", type=str, default="output/0525_annotated.db") parser.add_argument("--nrows", type=int, default=None) parser.add_argument("--sort-by-date", default=False, action='store_true') parser.add_argument("--start-date", type=str, default=None) parser.add_argument("--end-date", type=str, default=None) parser.add_argument("--config", type=str, required=True) parser.add_argument("--clustering-markup-tsv", type=str, required=True) parser.add_argument("--original-jsonl", type=str, required=True) parser.add_argument("--neptune-project", type=str, required=True) parser.add_argument("--neptune-tags", type=str, required=True) args = parser.parse_args() fit_param(**vars(args))
[ "neptune.log_metric", "neptune.create_experiment", "neptune.stop", "neptune.init" ]
[((1179, 1216), 'os.path.isfile', 'os.path.isfile', (['clustering_markup_tsv'], {}), '(clustering_markup_tsv)\n', (1193, 1216), False, 'import os\n'), ((1278, 1308), 'os.path.isfile', 'os.path.isfile', (['original_jsonl'], {}), '(original_jsonl)\n', (1292, 1308), False, 'import os\n'), ((1365, 1387), 'os.path.isfile', 'os.path.isfile', (['config'], {}), '(config)\n', (1379, 1387), False, 'import os\n'), ((1519, 1549), 'os.getenv', 'os.getenv', (['"""NEPTUNE_API_TOKEN"""'], {}), "('NEPTUNE_API_TOKEN')\n", (1528, 1549), False, 'import os\n'), ((1555, 1641), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': 'neptune_project', 'api_token': 'neptune_api_token'}), '(project_qualified_name=neptune_project, api_token=\n neptune_api_token)\n', (1567, 1641), False, 'import neptune\n'), ((1722, 1772), 'purano.io.parse_clustering_markup_tsv', 'parse_clustering_markup_tsv', (['clustering_markup_tsv'], {}), '(clustering_markup_tsv)\n', (1749, 1772), False, 'from purano.io import parse_tg_jsonl, parse_clustering_markup_tsv\n'), ((1837, 1861), 'sqlalchemy.create_engine', 'create_engine', (['db_engine'], {}), '(db_engine)\n', (1850, 1861), False, 'from sqlalchemy import create_engine\n'), ((1876, 1918), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'bind': 'engine', 'autoflush': '(False)'}), '(bind=engine, autoflush=False)\n', (1888, 1918), False, 'from sqlalchemy.orm import sessionmaker\n'), ((1960, 1986), 'purano.clusterer.clusterer.Clusterer', 'Clusterer', (['session', 'config'], {}), '(session, config)\n', (1969, 1986), False, 'from purano.clusterer.clusterer import Clusterer\n'), ((2112, 2143), 'copy.deepcopy', 'copy.deepcopy', (['clusterer.config'], {}), '(clusterer.config)\n', (2125, 2143), False, 'import copy\n'), ((3078, 3086), 'hyperopt.Trials', 'Trials', ([], {}), '()\n', (3084, 3086), False, 'from hyperopt import Trials, fmin, hp, tpe\n'), ((3098, 3192), 'hyperopt.fmin', 'fmin', ([], {'fn': 'calc_accuracy', 'space': 'SEARCH_SPACE', 'algo': 'tpe.suggest', 'max_evals': '(200)', 'trials': 'trials'}), '(fn=calc_accuracy, space=SEARCH_SPACE, algo=tpe.suggest, max_evals=200,\n trials=trials)\n', (3102, 3192), False, 'from hyperopt import Trials, fmin, hp, tpe\n'), ((3293, 3318), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3316, 3318), False, 'import argparse\n'), ((2184, 2309), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""clustering"""', 'params': 'params', 'upload_source_files': "['configs/*.jsonnet']", 'tags': 'neptune_tags'}), "(name='clustering', params=params,\n upload_source_files=['configs/*.jsonnet'], tags=neptune_tags)\n", (2209, 2309), False, 'import neptune\n'), ((2391, 2417), 'copy.deepcopy', 'copy.deepcopy', (['config_copy'], {}), '(config_copy)\n', (2404, 2417), False, 'import copy\n'), ((2689, 2729), 'purano.clusterer.metrics.calc_metrics', 'calc_metrics', (['markup', 'url2record', 'labels'], {}), '(markup, url2record, labels)\n', (2701, 2729), False, 'from purano.clusterer.metrics import calc_metrics\n'), ((2869, 2909), 'neptune.log_metric', 'neptune.log_metric', (['"""accuracy"""', 'accuracy'], {}), "('accuracy', accuracy)\n", (2887, 2909), False, 'import neptune\n'), ((2918, 2962), 'neptune.log_metric', 'neptune.log_metric', (['"""f1_score_0"""', 'f1_score_0'], {}), "('f1_score_0', f1_score_0)\n", (2936, 2962), False, 'import neptune\n'), ((2971, 3015), 'neptune.log_metric', 'neptune.log_metric', (['"""f1_score_1"""', 'f1_score_1'], {}), "('f1_score_1', f1_score_1)\n", (2989, 3015), False, 'import neptune\n'), ((3024, 3038), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (3036, 3038), False, 'import neptune\n'), ((1677, 1707), 'purano.io.parse_tg_jsonl', 'parse_tg_jsonl', (['original_jsonl'], {}), '(original_jsonl)\n', (1691, 1707), False, 'from purano.io import parse_tg_jsonl, parse_clustering_markup_tsv\n'), ((465, 516), 'hyperopt.hp.quniform', 'hp.quniform', (['"""distance_threshold"""', '(0.01)', '(0.95)', '(0.01)'], {}), "('distance_threshold', 0.01, 0.95, 0.01)\n", (476, 516), False, 'from hyperopt import Trials, fmin, hp, tpe\n'), ((669, 711), 'hyperopt.hp.quniform', 'hp.quniform', (['"""dbscan_eps"""', '(0.01)', '(0.8)', '(0.01)'], {}), "('dbscan_eps', 0.01, 0.8, 0.01)\n", (680, 711), False, 'from hyperopt import Trials, fmin, hp, tpe\n'), ((736, 779), 'hyperopt.hp.quniform', 'hp.quniform', (['"""dbscan_min_samples"""', '(1)', '(20)', '(1)'], {}), "('dbscan_min_samples', 1, 20, 1)\n", (747, 779), False, 'from hyperopt import Trials, fmin, hp, tpe\n'), ((802, 843), 'hyperopt.hp.quniform', 'hp.quniform', (['"""dbscan_leaf_size"""', '(2)', '(50)', '(2)'], {}), "('dbscan_leaf_size', 2, 50, 2)\n", (813, 843), False, 'from hyperopt import Trials, fmin, hp, tpe\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import uuid from collections import defaultdict from datetime import datetime from shutil import copyfile from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar, Union from zipfile import ZipFile from neptune.new.exceptions import ( ContainerUUIDNotFound, InternalClientError, MetadataInconsistency, ModelVersionNotFound, NeptuneException, ProjectNotFound, RunNotFound, ) from neptune.new.internal.artifacts.types import ArtifactFileData from neptune.new.internal.backends.api_model import ( ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace, ) from neptune.new.internal.backends.hosted_file_operations import ( get_unique_upload_entries, ) from neptune.new.internal.backends.neptune_backend import NeptuneBackend from neptune.new.internal.backends.nql import NQLQuery from neptune.new.internal.container_structure import ContainerStructure from neptune.new.internal.container_type import ContainerType from neptune.new.internal.id_formats import QualifiedName, SysId, UniqueId from neptune.new.internal.operation import ( AddStrings, AssignArtifact, AssignBool, AssignDatetime, AssignFloat, AssignInt, AssignString, ClearArtifact, ClearFloatLog, ClearImageLog, ClearStringLog, ClearStringSet, ConfigFloatSeries, CopyAttribute, DeleteAttribute, DeleteFiles, LogFloats, LogImages, LogStrings, Operation, RemoveStrings, TrackFilesToArtifact, UploadFile, UploadFileContent, UploadFileSet, ) from neptune.new.internal.operation_visitor import OperationVisitor from neptune.new.internal.utils import base64_decode from neptune.new.internal.utils.generic_attribute_mapper import NoValue from neptune.new.internal.utils.paths import path_to_str from neptune.new.metadata_containers import Model from neptune.new.types import Boolean, Integer from neptune.new.types.atoms import GitRef from neptune.new.types.atoms.artifact import Artifact from neptune.new.types.atoms.datetime import Datetime from neptune.new.types.atoms.file import File from neptune.new.types.atoms.float import Float from neptune.new.types.atoms.string import String from neptune.new.types.file_set import FileSet from neptune.new.types.namespace import Namespace from neptune.new.types.series.file_series import FileSeries from neptune.new.types.series.float_series import FloatSeries from neptune.new.types.series.string_series import StringSeries from neptune.new.types.sets.string_set import StringSet from neptune.new.types.value import Value from neptune.new.types.value_visitor import ValueVisitor Val = TypeVar("Val", bound=Value) class NeptuneBackendMock(NeptuneBackend): WORKSPACE_NAME = "offline" PROJECT_NAME = "project-placeholder" PROJECT_KEY = SysId("OFFLINE") MODEL_SYS_ID = SysId("OFFLINE-MOD") def __init__(self, credentials=None, proxies=None): # pylint: disable=unused-argument self._project_id: UniqueId = UniqueId(str(uuid.uuid4())) self._containers: Dict[(UniqueId, ContainerType), ContainerStructure[Value, dict]] = dict() self._next_run = 1 # counter for runs self._next_model_version = defaultdict(lambda: 1) # counter for model versions self._artifacts: Dict[Tuple[str, str], List[ArtifactFileData]] = dict() self._attribute_type_converter_value_visitor = self.AttributeTypeConverterValueVisitor() self._create_container(self._project_id, ContainerType.PROJECT, self.PROJECT_KEY) def get_display_address(self) -> str: return "OFFLINE" def get_available_projects( self, workspace_id: Optional[str] = None, search_term: Optional[str] = None ) -> List[Project]: return [ Project( id=UniqueId(str(uuid.uuid4())), name=self.PROJECT_NAME, workspace=self.WORKSPACE_NAME, sys_id=self.PROJECT_KEY, ) ] def get_available_workspaces(self) -> List[Workspace]: return [Workspace(id=UniqueId(str(uuid.uuid4())), name=self.WORKSPACE_NAME)] def _create_container( self, container_id: UniqueId, container_type: ContainerType, sys_id: SysId ): container = self._containers.setdefault( (container_id, container_type), ContainerStructure[Value, dict]() ) container.set(["sys", "id"], String(sys_id)) container.set(["sys", "state"], String("running")) container.set(["sys", "owner"], String("offline_user")) container.set(["sys", "size"], Float(0)) container.set(["sys", "tags"], StringSet(set())) container.set(["sys", "creation_time"], Datetime(datetime.now())) container.set(["sys", "modification_time"], Datetime(datetime.now())) container.set(["sys", "failed"], Boolean(False)) if container_type == ContainerType.MODEL_VERSION: container.set(["sys", "model_id"], String(self.MODEL_SYS_ID)) container.set(["sys", "stage"], String("none")) return container def _get_container(self, container_id: UniqueId, container_type: ContainerType): key = (container_id, container_type) if key not in self._containers: raise ContainerUUIDNotFound(container_id, container_type) container = self._containers[(container_id, container_type)] return container def create_run( self, project_id: UniqueId, git_ref: Optional[GitRef] = None, custom_run_id: Optional[str] = None, notebook_id: Optional[str] = None, checkpoint_id: Optional[str] = None, ) -> ApiExperiment: sys_id = SysId(f"{self.PROJECT_KEY}-{self._next_run}") self._next_run += 1 new_run_id = UniqueId(str(uuid.uuid4())) container = self._create_container(new_run_id, ContainerType.RUN, sys_id=sys_id) if git_ref: container.set(["source_code", "git"], git_ref) return ApiExperiment( id=new_run_id, type=ContainerType.RUN, sys_id=sys_id, workspace=self.WORKSPACE_NAME, project_name=self.PROJECT_NAME, trashed=False, ) def create_model(self, project_id: str, key: str) -> ApiExperiment: sys_id = SysId(f"{self.PROJECT_KEY}-{key}") new_run_id = UniqueId(str(uuid.uuid4())) self._create_container(new_run_id, ContainerType.MODEL, sys_id=sys_id) return ApiExperiment( id=new_run_id, type=ContainerType.MODEL, sys_id=sys_id, workspace=self.WORKSPACE_NAME, project_name=self.PROJECT_NAME, trashed=False, ) def create_model_version(self, project_id: str, model_id: UniqueId) -> ApiExperiment: try: model_key = self._get_container( container_id=model_id, container_type=ContainerType.MODEL ).get("sys/id") except ContainerUUIDNotFound: model_key = "MOD" sys_id = SysId(f"{self.PROJECT_KEY}-{model_key}-{self._next_model_version[model_id]}") self._next_model_version[model_id] += 1 new_run_id = UniqueId(str(uuid.uuid4())) self._create_container(new_run_id, ContainerType.MODEL_VERSION, sys_id=sys_id) return ApiExperiment( id=new_run_id, type=ContainerType.MODEL, sys_id=sys_id, workspace=self.WORKSPACE_NAME, project_name=self.PROJECT_NAME, trashed=False, ) def create_checkpoint(self, notebook_id: str, jupyter_path: str) -> Optional[str]: return None def get_project(self, project_id: QualifiedName) -> Project: return Project( id=self._project_id, name=self.PROJECT_NAME, workspace=self.WORKSPACE_NAME, sys_id=self.PROJECT_KEY, ) def get_metadata_container( self, container_id: Union[UniqueId, QualifiedName], expected_container_type: ContainerType, ) -> ApiExperiment: if "/" not in container_id: raise ValueError("Backend mock expect container_id as QualifiedName only") if expected_container_type == ContainerType.RUN: raise RunNotFound(container_id) elif expected_container_type == ContainerType.MODEL: return ApiExperiment( id=UniqueId(str(uuid.uuid4())), type=Model.container_type, sys_id=SysId(container_id.rsplit("/", 1)[-1]), workspace=self.WORKSPACE_NAME, project_name=self.PROJECT_NAME, ) elif expected_container_type == ContainerType.MODEL_VERSION: raise ModelVersionNotFound(container_id) else: raise ProjectNotFound(container_id) def execute_operations( self, container_id: UniqueId, container_type: ContainerType, operations: List[Operation], ) -> Tuple[int, List[NeptuneException]]: result = [] for op in operations: try: self._execute_operation(container_id, container_type, op) except NeptuneException as e: result.append(e) return len(operations), result def _execute_operation( self, container_id: UniqueId, container_type: ContainerType, op: Operation ) -> None: run = self._get_container(container_id, container_type) val = run.get(op.path) if val is not None and not isinstance(val, Value): if isinstance(val, dict): raise MetadataInconsistency("{} is a namespace, not an attribute".format(op.path)) else: raise InternalClientError("{} is a {}".format(op.path, type(val))) visitor = NeptuneBackendMock.NewValueOpVisitor(self, op.path, val) new_val = visitor.visit(op) if new_val is not None: run.set(op.path, new_val) else: run.pop(op.path) def get_attributes(self, container_id: str, container_type: ContainerType) -> List[Attribute]: run = self._get_container(container_id, container_type) return list(self._generate_attributes(None, run.get_structure())) def _generate_attributes(self, base_path: Optional[str], values: dict): for key, value_or_dict in values.items(): new_path = base_path + "/" + key if base_path is not None else key if isinstance(value_or_dict, dict): yield from self._generate_attributes(new_path, value_or_dict) else: yield Attribute( new_path, value_or_dict.accept(self._attribute_type_converter_value_visitor), ) def download_file( self, container_id: str, container_type: ContainerType, path: List[str], destination: Optional[str] = None, ): run = self._get_container(container_id, container_type) value: File = run.get(path) target_path = os.path.abspath( destination or (path[-1] + ("." + value.extension if value.extension else "")) ) if value.content is not None: with open(target_path, "wb") as target_file: target_file.write(value.content) elif value.path != target_path: copyfile(value.path, target_path) def download_file_set( self, container_id: str, container_type: ContainerType, path: List[str], destination: Optional[str] = None, ): run = self._get_container(container_id, container_type) source_file_set_value: FileSet = run.get(path) if destination is None: target_file = path[-1] + ".zip" elif os.path.isdir(destination): target_file = os.path.join(destination, path[-1] + ".zip") else: target_file = destination upload_entries = get_unique_upload_entries(source_file_set_value.file_globs) with ZipFile(target_file, "w") as zipObj: for upload_entry in upload_entries: zipObj.write(upload_entry.source_path, upload_entry.target_path) def get_float_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> FloatAttribute: val = self._get_attribute(container_id, container_type, path, Float) return FloatAttribute(val.value) def get_int_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> IntAttribute: val = self._get_attribute(container_id, container_type, path, Integer) return IntAttribute(val.value) def get_bool_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> BoolAttribute: val = self._get_attribute(container_id, container_type, path, Boolean) return BoolAttribute(val.value) def get_file_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> FileAttribute: val = self._get_attribute(container_id, container_type, path, File) return FileAttribute( name=os.path.basename(val.path) if val.path else "", ext=val.extension or "", size=0, ) def get_string_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> StringAttribute: val = self._get_attribute(container_id, container_type, path, String) return StringAttribute(val.value) def get_datetime_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> DatetimeAttribute: val = self._get_attribute(container_id, container_type, path, Datetime) return DatetimeAttribute(val.value) def get_artifact_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> ArtifactAttribute: val = self._get_attribute(container_id, container_type, path, Artifact) return ArtifactAttribute(val.hash) def list_artifact_files(self, project_id: str, artifact_hash: str) -> List[ArtifactFileData]: return self._artifacts[(project_id, artifact_hash)] def get_float_series_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> FloatSeriesAttribute: val = self._get_attribute(container_id, container_type, path, FloatSeries) return FloatSeriesAttribute(val.values[-1] if val.values else None) def get_string_series_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> StringSeriesAttribute: val = self._get_attribute(container_id, container_type, path, StringSeries) return StringSeriesAttribute(val.values[-1] if val.values else None) def get_string_set_attribute( self, container_id: str, container_type: ContainerType, path: List[str] ) -> StringSetAttribute: val = self._get_attribute(container_id, container_type, path, StringSet) return StringSetAttribute(set(val.values)) def _get_attribute( self, container_id: str, container_type: ContainerType, path: List[str], expected_type: Type[Val], ) -> Val: run = self._get_container(container_id, container_type) value: Optional[Value] = run.get(path) str_path = path_to_str(path) if value is None: raise MetadataInconsistency("Attribute {} not found".format(str_path)) if isinstance(value, expected_type): return value raise MetadataInconsistency("Attribute {} is not {}".format(str_path, type.__name__)) def get_string_series_values( self, container_id: str, container_type: ContainerType, path: List[str], offset: int, limit: int, ) -> StringSeriesValues: val = self._get_attribute(container_id, container_type, path, StringSeries) return StringSeriesValues( len(val.values), [ StringPointValue(timestampMillis=42342, step=idx, value=v) for idx, v in enumerate(val.values) ], ) def get_float_series_values( self, container_id: str, container_type: ContainerType, path: List[str], offset: int, limit: int, ) -> FloatSeriesValues: val = self._get_attribute(container_id, container_type, path, FloatSeries) return FloatSeriesValues( len(val.values), [ FloatPointValue(timestampMillis=42342, step=idx, value=v) for idx, v in enumerate(val.values) ], ) def get_image_series_values( self, container_id: str, container_type: ContainerType, path: List[str], offset: int, limit: int, ) -> ImageSeriesValues: return ImageSeriesValues(0) def download_file_series_by_index( self, container_id: str, container_type: ContainerType, path: List[str], index: int, destination: str, ): """Non relevant for backend""" def get_run_url(self, run_id: str, workspace: str, project_name: str, sys_id: str) -> str: return f"offline/{run_id}" def get_project_url(self, project_id: str, workspace: str, project_name: str) -> str: return f"offline/{project_id}" def get_model_url(self, model_id: str, workspace: str, project_name: str, sys_id: str) -> str: return f"offline/{model_id}" def get_model_version_url( self, model_version_id: str, model_id: str, workspace: str, project_name: str, sys_id: str, ) -> str: return f"offline/{model_version_id}" def _get_attribute_values(self, value_dict, path_prefix: List[str]): assert isinstance(value_dict, dict) for k, value in value_dict.items(): if isinstance(value, dict): yield from self._get_attribute_values(value, path_prefix + [k]) else: attr_type = value.accept(self._attribute_type_converter_value_visitor).value attr_path = "/".join(path_prefix + [k]) if hasattr(value, "value"): yield attr_path, attr_type, value.value else: return attr_path, attr_type, NoValue def fetch_atom_attribute_values( self, container_id: str, container_type: ContainerType, path: List[str] ) -> List[Tuple[str, AttributeType, Any]]: run = self._get_container(container_id, container_type) values = self._get_attribute_values(run.get(path), path) namespace_prefix = path_to_str(path) if namespace_prefix: # don't want to catch "ns/attribute/other" while looking for "ns/attr" namespace_prefix += "/" return [ (full_path, attr_type, attr_value) for (full_path, attr_type, attr_value) in values if full_path.startswith(namespace_prefix) ] def search_leaderboard_entries( self, project_id: UniqueId, types: Optional[Iterable[ContainerType]] = None, query: Optional[NQLQuery] = None, ) -> List[LeaderboardEntry]: """Non relevant for mock""" class AttributeTypeConverterValueVisitor(ValueVisitor[AttributeType]): def visit_float(self, _: Float) -> AttributeType: return AttributeType.FLOAT def visit_integer(self, _: Integer) -> AttributeType: return AttributeType.INT def visit_boolean(self, _: Boolean) -> AttributeType: return AttributeType.BOOL def visit_string(self, _: String) -> AttributeType: return AttributeType.STRING def visit_datetime(self, _: Datetime) -> AttributeType: return AttributeType.DATETIME def visit_file(self, _: File) -> AttributeType: return AttributeType.FILE def visit_file_set(self, _: FileSet) -> AttributeType: return AttributeType.FILE_SET def visit_float_series(self, _: FloatSeries) -> AttributeType: return AttributeType.FLOAT_SERIES def visit_string_series(self, _: StringSeries) -> AttributeType: return AttributeType.STRING_SERIES def visit_image_series(self, _: FileSeries) -> AttributeType: return AttributeType.IMAGE_SERIES def visit_string_set(self, _: StringSet) -> AttributeType: return AttributeType.STRING_SET def visit_git_ref(self, _: GitRef) -> AttributeType: return AttributeType.GIT_REF def visit_artifact(self, _: Artifact) -> AttributeType: return AttributeType.ARTIFACT def visit_namespace(self, _: Namespace) -> AttributeType: raise NotImplementedError def copy_value(self, source_type: Type[Attribute], source_path: List[str]) -> AttributeType: raise NotImplementedError class NewValueOpVisitor(OperationVisitor[Optional[Value]]): def __init__(self, backend, path: List[str], current_value: Optional[Value]): self._backend = backend self._path = path self._current_value = current_value self._artifact_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" def visit_assign_float(self, op: AssignFloat) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, Float): raise self._create_type_error("assign", Float.__name__) return Float(op.value) def visit_assign_int(self, op: AssignInt) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, Integer): raise self._create_type_error("assign", Integer.__name__) return Integer(op.value) def visit_assign_bool(self, op: AssignBool) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, Boolean): raise self._create_type_error("assign", Boolean.__name__) return Boolean(op.value) def visit_assign_string(self, op: AssignString) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, String): raise self._create_type_error("assign", String.__name__) return String(op.value) def visit_assign_datetime(self, op: AssignDatetime) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, Datetime): raise self._create_type_error("assign", Datetime.__name__) return Datetime(op.value) def visit_assign_artifact(self, op: AssignArtifact) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, Artifact): raise self._create_type_error("assign", Artifact.__name__) return Artifact(op.hash) def visit_track_files_to_artifact(self, _: TrackFilesToArtifact) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, Artifact): raise self._create_type_error("save", Artifact.__name__) return Artifact(self._artifact_hash) def visit_clear_artifact(self, _: ClearArtifact) -> Optional[Value]: if self._current_value is None: return Artifact() if not isinstance(self._current_value, Artifact): raise self._create_type_error("clear", Artifact.__name__) return Artifact() def visit_upload_file(self, op: UploadFile) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, File): raise self._create_type_error("save", File.__name__) return File(path=op.file_path, extension=op.ext) def visit_upload_file_content(self, op: UploadFileContent) -> Optional[Value]: if self._current_value is not None and not isinstance(self._current_value, File): raise self._create_type_error("upload_files", File.__name__) return File(content=base64_decode(op.file_content), extension=op.ext) def visit_upload_file_set(self, op: UploadFileSet) -> Optional[Value]: if self._current_value is None or op.reset: return FileSet(op.file_globs) if not isinstance(self._current_value, FileSet): raise self._create_type_error("save", FileSet.__name__) return FileSet(self._current_value.file_globs + op.file_globs) def visit_log_floats(self, op: LogFloats) -> Optional[Value]: raw_values = [x.value for x in op.values] if self._current_value is None: return FloatSeries(raw_values) if not isinstance(self._current_value, FloatSeries): raise self._create_type_error("log", FloatSeries.__name__) return FloatSeries( self._current_value.values + raw_values, min=self._current_value.min, max=self._current_value.max, unit=self._current_value.unit, ) def visit_log_strings(self, op: LogStrings) -> Optional[Value]: raw_values = [x.value for x in op.values] if self._current_value is None: return StringSeries(raw_values) if not isinstance(self._current_value, StringSeries): raise self._create_type_error("log", StringSeries.__name__) return StringSeries(self._current_value.values + raw_values) def visit_log_images(self, op: LogImages) -> Optional[Value]: raw_values = [File.from_content(base64_decode(x.value.data)) for x in op.values] if self._current_value is None: return FileSeries(raw_values) if not isinstance(self._current_value, FileSeries): raise self._create_type_error("log", FileSeries.__name__) return FileSeries(self._current_value.values + raw_values) def visit_clear_float_log(self, op: ClearFloatLog) -> Optional[Value]: # pylint: disable=unused-argument if self._current_value is None: return FloatSeries([]) if not isinstance(self._current_value, FloatSeries): raise self._create_type_error("clear", FloatSeries.__name__) return FloatSeries( [], min=self._current_value.min, max=self._current_value.max, unit=self._current_value.unit, ) def visit_clear_string_log(self, op: ClearStringLog) -> Optional[Value]: # pylint: disable=unused-argument if self._current_value is None: return StringSeries([]) if not isinstance(self._current_value, StringSeries): raise self._create_type_error("clear", StringSeries.__name__) return StringSeries([]) def visit_clear_image_log(self, op: ClearImageLog) -> Optional[Value]: # pylint: disable=unused-argument if self._current_value is None: return FileSeries([]) if not isinstance(self._current_value, FileSeries): raise self._create_type_error("clear", FileSeries.__name__) return FileSeries([]) def visit_config_float_series(self, op: ConfigFloatSeries) -> Optional[Value]: if self._current_value is None: return FloatSeries([], min=op.min, max=op.max, unit=op.unit) if not isinstance(self._current_value, FloatSeries): raise self._create_type_error("log", FloatSeries.__name__) return FloatSeries(self._current_value.values, min=op.min, max=op.max, unit=op.unit) def visit_add_strings(self, op: AddStrings) -> Optional[Value]: if self._current_value is None: return StringSet(op.values) if not isinstance(self._current_value, StringSet): raise self._create_type_error("add", StringSet.__name__) return StringSet(self._current_value.values.union(op.values)) def visit_remove_strings(self, op: RemoveStrings) -> Optional[Value]: if self._current_value is None: return StringSet(set()) if not isinstance(self._current_value, StringSet): raise self._create_type_error("remove", StringSet.__name__) return StringSet(self._current_value.values.difference(op.values)) def visit_clear_string_set(self, op: ClearStringSet) -> Optional[Value]: # pylint: disable=unused-argument if self._current_value is None: return StringSet(set()) if not isinstance(self._current_value, StringSet): raise self._create_type_error("clear", StringSet.__name__) return StringSet(set()) def visit_delete_files(self, op: DeleteFiles) -> Optional[Value]: # pylint: disable=unused-argument if self._current_value is None: return FileSet([]) if not isinstance(self._current_value, FileSet): raise self._create_type_error("delete_files", FileSet.__name__) # It is not important to support deleting properly in debug mode, let's just ignore this operation return self._current_value def visit_delete_attribute(self, op: DeleteAttribute) -> Optional[Value]: # pylint: disable=unused-argument if self._current_value is None: raise MetadataInconsistency( "Cannot perform delete operation on {}. Attribute is undefined.".format( self._path ) ) return None def visit_copy_attribute(self, op: CopyAttribute) -> Optional[Value]: return op.resolve(self._backend).accept(self) def _create_type_error(self, op_name, expected): return MetadataInconsistency( "Cannot perform {} operation on {}. Expected {}, {} found.".format( op_name, self._path, expected, type(self._current_value) ) )
[ "neptune.new.internal.backends.api_model.BoolAttribute", "neptune.new.types.atoms.artifact.Artifact", "neptune.new.exceptions.RunNotFound", "neptune.new.internal.backends.api_model.StringAttribute", "neptune.new.types.atoms.float.Float", "neptune.new.internal.backends.api_model.Project", "neptune.new.ty...
[((3621, 3648), 'typing.TypeVar', 'TypeVar', (['"""Val"""'], {'bound': 'Value'}), "('Val', bound=Value)\n", (3628, 3648), False, 'from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar, Union\n'), ((3783, 3799), 'neptune.new.internal.id_formats.SysId', 'SysId', (['"""OFFLINE"""'], {}), "('OFFLINE')\n", (3788, 3799), False, 'from neptune.new.internal.id_formats import QualifiedName, SysId, UniqueId\n'), ((3819, 3839), 'neptune.new.internal.id_formats.SysId', 'SysId', (['"""OFFLINE-MOD"""'], {}), "('OFFLINE-MOD')\n", (3824, 3839), False, 'from neptune.new.internal.id_formats import QualifiedName, SysId, UniqueId\n'), ((4186, 4209), 'collections.defaultdict', 'defaultdict', (['(lambda : 1)'], {}), '(lambda : 1)\n', (4197, 4209), False, 'from collections import defaultdict\n'), ((6677, 6722), 'neptune.new.internal.id_formats.SysId', 'SysId', (['f"""{self.PROJECT_KEY}-{self._next_run}"""'], {}), "(f'{self.PROJECT_KEY}-{self._next_run}')\n", (6682, 6722), False, 'from neptune.new.internal.id_formats import QualifiedName, SysId, UniqueId\n'), ((6983, 7137), 'neptune.new.internal.backends.api_model.ApiExperiment', 'ApiExperiment', ([], {'id': 'new_run_id', 'type': 'ContainerType.RUN', 'sys_id': 'sys_id', 'workspace': 'self.WORKSPACE_NAME', 'project_name': 'self.PROJECT_NAME', 'trashed': '(False)'}), '(id=new_run_id, type=ContainerType.RUN, sys_id=sys_id,\n workspace=self.WORKSPACE_NAME, project_name=self.PROJECT_NAME, trashed=\n False)\n', (6996, 7137), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((7302, 7336), 'neptune.new.internal.id_formats.SysId', 'SysId', (['f"""{self.PROJECT_KEY}-{key}"""'], {}), "(f'{self.PROJECT_KEY}-{key}')\n", (7307, 7336), False, 'from neptune.new.internal.id_formats import QualifiedName, SysId, UniqueId\n'), ((7480, 7636), 'neptune.new.internal.backends.api_model.ApiExperiment', 'ApiExperiment', ([], {'id': 'new_run_id', 'type': 'ContainerType.MODEL', 'sys_id': 'sys_id', 'workspace': 'self.WORKSPACE_NAME', 'project_name': 'self.PROJECT_NAME', 'trashed': '(False)'}), '(id=new_run_id, type=ContainerType.MODEL, sys_id=sys_id,\n workspace=self.WORKSPACE_NAME, project_name=self.PROJECT_NAME, trashed=\n False)\n', (7493, 7636), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((8048, 8125), 'neptune.new.internal.id_formats.SysId', 'SysId', (['f"""{self.PROJECT_KEY}-{model_key}-{self._next_model_version[model_id]}"""'], {}), "(f'{self.PROJECT_KEY}-{model_key}-{self._next_model_version[model_id]}')\n", (8053, 8125), False, 'from neptune.new.internal.id_formats import QualifiedName, SysId, UniqueId\n'), ((8325, 8481), 'neptune.new.internal.backends.api_model.ApiExperiment', 'ApiExperiment', ([], {'id': 'new_run_id', 'type': 'ContainerType.MODEL', 'sys_id': 'sys_id', 'workspace': 'self.WORKSPACE_NAME', 'project_name': 'self.PROJECT_NAME', 'trashed': '(False)'}), '(id=new_run_id, type=ContainerType.MODEL, sys_id=sys_id,\n workspace=self.WORKSPACE_NAME, project_name=self.PROJECT_NAME, trashed=\n False)\n', (8338, 8481), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((8745, 8858), 'neptune.new.internal.backends.api_model.Project', 'Project', ([], {'id': 'self._project_id', 'name': 'self.PROJECT_NAME', 'workspace': 'self.WORKSPACE_NAME', 'sys_id': 'self.PROJECT_KEY'}), '(id=self._project_id, name=self.PROJECT_NAME, workspace=self.\n WORKSPACE_NAME, sys_id=self.PROJECT_KEY)\n', (8752, 8858), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((12105, 12203), 'os.path.abspath', 'os.path.abspath', (["(destination or path[-1] + ('.' + value.extension if value.extension else ''))"], {}), "(destination or path[-1] + ('.' + value.extension if value.\n extension else ''))\n", (12120, 12203), False, 'import os\n'), ((13022, 13081), 'neptune.new.internal.backends.hosted_file_operations.get_unique_upload_entries', 'get_unique_upload_entries', (['source_file_set_value.file_globs'], {}), '(source_file_set_value.file_globs)\n', (13047, 13081), False, 'from neptune.new.internal.backends.hosted_file_operations import get_unique_upload_entries\n'), ((13489, 13514), 'neptune.new.internal.backends.api_model.FloatAttribute', 'FloatAttribute', (['val.value'], {}), '(val.value)\n', (13503, 13514), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((13740, 13763), 'neptune.new.internal.backends.api_model.IntAttribute', 'IntAttribute', (['val.value'], {}), '(val.value)\n', (13752, 13763), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((13991, 14015), 'neptune.new.internal.backends.api_model.BoolAttribute', 'BoolAttribute', (['val.value'], {}), '(val.value)\n', (14004, 14015), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((14617, 14643), 'neptune.new.internal.backends.api_model.StringAttribute', 'StringAttribute', (['val.value'], {}), '(val.value)\n', (14632, 14643), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((14880, 14908), 'neptune.new.internal.backends.api_model.DatetimeAttribute', 'DatetimeAttribute', (['val.value'], {}), '(val.value)\n', (14897, 14908), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((15145, 15172), 'neptune.new.internal.backends.api_model.ArtifactAttribute', 'ArtifactAttribute', (['val.hash'], {}), '(val.hash)\n', (15162, 15172), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((15578, 15638), 'neptune.new.internal.backends.api_model.FloatSeriesAttribute', 'FloatSeriesAttribute', (['(val.values[-1] if val.values else None)'], {}), '(val.values[-1] if val.values else None)\n', (15598, 15638), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((15888, 15949), 'neptune.new.internal.backends.api_model.StringSeriesAttribute', 'StringSeriesAttribute', (['(val.values[-1] if val.values else None)'], {}), '(val.values[-1] if val.values else None)\n', (15909, 15949), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((16534, 16551), 'neptune.new.internal.utils.paths.path_to_str', 'path_to_str', (['path'], {}), '(path)\n', (16545, 16551), False, 'from neptune.new.internal.utils.paths import path_to_str\n'), ((18091, 18111), 'neptune.new.internal.backends.api_model.ImageSeriesValues', 'ImageSeriesValues', (['(0)'], {}), '(0)\n', (18108, 18111), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((19931, 19948), 'neptune.new.internal.utils.paths.path_to_str', 'path_to_str', (['path'], {}), '(path)\n', (19942, 19948), False, 'from neptune.new.internal.utils.paths import path_to_str\n'), ((5390, 5404), 'neptune.new.types.atoms.string.String', 'String', (['sys_id'], {}), '(sys_id)\n', (5396, 5404), False, 'from neptune.new.types.atoms.string import String\n'), ((5446, 5463), 'neptune.new.types.atoms.string.String', 'String', (['"""running"""'], {}), "('running')\n", (5452, 5463), False, 'from neptune.new.types.atoms.string import String\n'), ((5505, 5527), 'neptune.new.types.atoms.string.String', 'String', (['"""offline_user"""'], {}), "('offline_user')\n", (5511, 5527), False, 'from neptune.new.types.atoms.string import String\n'), ((5568, 5576), 'neptune.new.types.atoms.float.Float', 'Float', (['(0)'], {}), '(0)\n', (5573, 5576), False, 'from neptune.new.types.atoms.float import Float\n'), ((5828, 5842), 'neptune.new.types.Boolean', 'Boolean', (['(False)'], {}), '(False)\n', (5835, 5842), False, 'from neptune.new.types import Boolean, Integer\n'), ((6250, 6301), 'neptune.new.exceptions.ContainerUUIDNotFound', 'ContainerUUIDNotFound', (['container_id', 'container_type'], {}), '(container_id, container_type)\n', (6271, 6301), False, 'from neptune.new.exceptions import ContainerUUIDNotFound, InternalClientError, MetadataInconsistency, ModelVersionNotFound, NeptuneException, ProjectNotFound, RunNotFound\n'), ((9285, 9310), 'neptune.new.exceptions.RunNotFound', 'RunNotFound', (['container_id'], {}), '(container_id)\n', (9296, 9310), False, 'from neptune.new.exceptions import ContainerUUIDNotFound, InternalClientError, MetadataInconsistency, ModelVersionNotFound, NeptuneException, ProjectNotFound, RunNotFound\n'), ((12845, 12871), 'os.path.isdir', 'os.path.isdir', (['destination'], {}), '(destination)\n', (12858, 12871), False, 'import os\n'), ((13096, 13121), 'zipfile.ZipFile', 'ZipFile', (['target_file', '"""w"""'], {}), "(target_file, 'w')\n", (13103, 13121), False, 'from zipfile import ZipFile\n'), ((22868, 22883), 'neptune.new.types.atoms.float.Float', 'Float', (['op.value'], {}), '(op.value)\n', (22873, 22883), False, 'from neptune.new.types.atoms.float import Float\n'), ((23145, 23162), 'neptune.new.types.Integer', 'Integer', (['op.value'], {}), '(op.value)\n', (23152, 23162), False, 'from neptune.new.types import Boolean, Integer\n'), ((23426, 23443), 'neptune.new.types.Boolean', 'Boolean', (['op.value'], {}), '(op.value)\n', (23433, 23443), False, 'from neptune.new.types import Boolean, Integer\n'), ((23709, 23725), 'neptune.new.types.atoms.string.String', 'String', (['op.value'], {}), '(op.value)\n', (23715, 23725), False, 'from neptune.new.types.atoms.string import String\n'), ((23999, 24017), 'neptune.new.types.atoms.datetime.Datetime', 'Datetime', (['op.value'], {}), '(op.value)\n', (24007, 24017), False, 'from neptune.new.types.atoms.datetime import Datetime\n'), ((24291, 24308), 'neptune.new.types.atoms.artifact.Artifact', 'Artifact', (['op.hash'], {}), '(op.hash)\n', (24299, 24308), False, 'from neptune.new.types.atoms.artifact import Artifact\n'), ((24593, 24622), 'neptune.new.types.atoms.artifact.Artifact', 'Artifact', (['self._artifact_hash'], {}), '(self._artifact_hash)\n', (24601, 24622), False, 'from neptune.new.types.atoms.artifact import Artifact\n'), ((24934, 24944), 'neptune.new.types.atoms.artifact.Artifact', 'Artifact', ([], {}), '()\n', (24942, 24944), False, 'from neptune.new.types.atoms.artifact import Artifact\n'), ((25200, 25241), 'neptune.new.types.atoms.file.File', 'File', ([], {'path': 'op.file_path', 'extension': 'op.ext'}), '(path=op.file_path, extension=op.ext)\n', (25204, 25241), False, 'from neptune.new.types.atoms.file import File\n'), ((25917, 25972), 'neptune.new.types.file_set.FileSet', 'FileSet', (['(self._current_value.file_globs + op.file_globs)'], {}), '(self._current_value.file_globs + op.file_globs)\n', (25924, 25972), False, 'from neptune.new.types.file_set import FileSet\n'), ((26348, 26499), 'neptune.new.types.series.float_series.FloatSeries', 'FloatSeries', (['(self._current_value.values + raw_values)'], {'min': 'self._current_value.min', 'max': 'self._current_value.max', 'unit': 'self._current_value.unit'}), '(self._current_value.values + raw_values, min=self.\n _current_value.min, max=self._current_value.max, unit=self.\n _current_value.unit)\n', (26359, 26499), False, 'from neptune.new.types.series.float_series import FloatSeries\n'), ((26949, 27002), 'neptune.new.types.series.string_series.StringSeries', 'StringSeries', (['(self._current_value.values + raw_values)'], {}), '(self._current_value.values + raw_values)\n', (26961, 27002), False, 'from neptune.new.types.series.string_series import StringSeries\n'), ((27414, 27465), 'neptune.new.types.series.file_series.FileSeries', 'FileSeries', (['(self._current_value.values + raw_values)'], {}), '(self._current_value.values + raw_values)\n', (27424, 27465), False, 'from neptune.new.types.series.file_series import FileSeries\n'), ((27836, 27944), 'neptune.new.types.series.float_series.FloatSeries', 'FloatSeries', (['[]'], {'min': 'self._current_value.min', 'max': 'self._current_value.max', 'unit': 'self._current_value.unit'}), '([], min=self._current_value.min, max=self._current_value.max,\n unit=self._current_value.unit)\n', (27847, 27944), False, 'from neptune.new.types.series.float_series import FloatSeries\n'), ((28395, 28411), 'neptune.new.types.series.string_series.StringSeries', 'StringSeries', (['[]'], {}), '([])\n', (28407, 28411), False, 'from neptune.new.types.series.string_series import StringSeries\n'), ((28779, 28793), 'neptune.new.types.series.file_series.FileSeries', 'FileSeries', (['[]'], {}), '([])\n', (28789, 28793), False, 'from neptune.new.types.series.file_series import FileSeries\n'), ((29162, 29239), 'neptune.new.types.series.float_series.FloatSeries', 'FloatSeries', (['self._current_value.values'], {'min': 'op.min', 'max': 'op.max', 'unit': 'op.unit'}), '(self._current_value.values, min=op.min, max=op.max, unit=op.unit)\n', (29173, 29239), False, 'from neptune.new.types.series.float_series import FloatSeries\n'), ((3989, 4001), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (3999, 4001), False, 'import uuid\n'), ((5692, 5706), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5704, 5706), False, 'from datetime import datetime\n'), ((5770, 5784), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5782, 5784), False, 'from datetime import datetime\n'), ((5949, 5974), 'neptune.new.types.atoms.string.String', 'String', (['self.MODEL_SYS_ID'], {}), '(self.MODEL_SYS_ID)\n', (5955, 5974), False, 'from neptune.new.types.atoms.string import String\n'), ((6020, 6034), 'neptune.new.types.atoms.string.String', 'String', (['"""none"""'], {}), "('none')\n", (6026, 6034), False, 'from neptune.new.types.atoms.string import String\n'), ((6785, 6797), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (6795, 6797), False, 'import uuid\n'), ((7371, 7383), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (7381, 7383), False, 'import uuid\n'), ((8208, 8220), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (8218, 8220), False, 'import uuid\n'), ((12419, 12452), 'shutil.copyfile', 'copyfile', (['value.path', 'target_path'], {}), '(value.path, target_path)\n', (12427, 12452), False, 'from shutil import copyfile\n'), ((12899, 12943), 'os.path.join', 'os.path.join', (['destination', "(path[-1] + '.zip')"], {}), "(destination, path[-1] + '.zip')\n", (12911, 12943), False, 'import os\n'), ((17213, 17271), 'neptune.new.internal.backends.api_model.StringPointValue', 'StringPointValue', ([], {'timestampMillis': '(42342)', 'step': 'idx', 'value': 'v'}), '(timestampMillis=42342, step=idx, value=v)\n', (17229, 17271), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((17733, 17790), 'neptune.new.internal.backends.api_model.FloatPointValue', 'FloatPointValue', ([], {'timestampMillis': '(42342)', 'step': 'idx', 'value': 'v'}), '(timestampMillis=42342, step=idx, value=v)\n', (17748, 17790), False, 'from neptune.new.internal.backends.api_model import ApiExperiment, ArtifactAttribute, Attribute, AttributeType, BoolAttribute, DatetimeAttribute, FileAttribute, FloatAttribute, FloatPointValue, FloatSeriesAttribute, FloatSeriesValues, ImageSeriesValues, IntAttribute, LeaderboardEntry, Project, StringAttribute, StringPointValue, StringSeriesAttribute, StringSeriesValues, StringSetAttribute, Workspace\n'), ((24768, 24778), 'neptune.new.types.atoms.artifact.Artifact', 'Artifact', ([], {}), '()\n', (24776, 24778), False, 'from neptune.new.types.atoms.artifact import Artifact\n'), ((25742, 25764), 'neptune.new.types.file_set.FileSet', 'FileSet', (['op.file_globs'], {}), '(op.file_globs)\n', (25749, 25764), False, 'from neptune.new.types.file_set import FileSet\n'), ((26165, 26188), 'neptune.new.types.series.float_series.FloatSeries', 'FloatSeries', (['raw_values'], {}), '(raw_values)\n', (26176, 26188), False, 'from neptune.new.types.series.float_series import FloatSeries\n'), ((26763, 26787), 'neptune.new.types.series.string_series.StringSeries', 'StringSeries', (['raw_values'], {}), '(raw_values)\n', (26775, 26787), False, 'from neptune.new.types.series.string_series import StringSeries\n'), ((27234, 27256), 'neptune.new.types.series.file_series.FileSeries', 'FileSeries', (['raw_values'], {}), '(raw_values)\n', (27244, 27256), False, 'from neptune.new.types.series.file_series import FileSeries\n'), ((27659, 27674), 'neptune.new.types.series.float_series.FloatSeries', 'FloatSeries', (['[]'], {}), '([])\n', (27670, 27674), False, 'from neptune.new.types.series.float_series import FloatSeries\n'), ((28215, 28231), 'neptune.new.types.series.string_series.StringSeries', 'StringSeries', (['[]'], {}), '([])\n', (28227, 28231), False, 'from neptune.new.types.series.string_series import StringSeries\n'), ((28605, 28619), 'neptune.new.types.series.file_series.FileSeries', 'FileSeries', (['[]'], {}), '([])\n', (28615, 28619), False, 'from neptune.new.types.series.file_series import FileSeries\n'), ((28949, 29002), 'neptune.new.types.series.float_series.FloatSeries', 'FloatSeries', (['[]'], {'min': 'op.min', 'max': 'op.max', 'unit': 'op.unit'}), '([], min=op.min, max=op.max, unit=op.unit)\n', (28960, 29002), False, 'from neptune.new.types.series.float_series import FloatSeries\n'), ((29380, 29400), 'neptune.new.types.sets.string_set.StringSet', 'StringSet', (['op.values'], {}), '(op.values)\n', (29389, 29400), False, 'from neptune.new.types.sets.string_set import StringSet\n'), ((30566, 30577), 'neptune.new.types.file_set.FileSet', 'FileSet', (['[]'], {}), '([])\n', (30573, 30577), False, 'from neptune.new.types.file_set import FileSet\n'), ((9756, 9790), 'neptune.new.exceptions.ModelVersionNotFound', 'ModelVersionNotFound', (['container_id'], {}), '(container_id)\n', (9776, 9790), False, 'from neptune.new.exceptions import ContainerUUIDNotFound, InternalClientError, MetadataInconsistency, ModelVersionNotFound, NeptuneException, ProjectNotFound, RunNotFound\n'), ((9823, 9852), 'neptune.new.exceptions.ProjectNotFound', 'ProjectNotFound', (['container_id'], {}), '(container_id)\n', (9838, 9852), False, 'from neptune.new.exceptions import ContainerUUIDNotFound, InternalClientError, MetadataInconsistency, ModelVersionNotFound, NeptuneException, ProjectNotFound, RunNotFound\n'), ((14272, 14298), 'os.path.basename', 'os.path.basename', (['val.path'], {}), '(val.path)\n', (14288, 14298), False, 'import os\n'), ((25533, 25563), 'neptune.new.internal.utils.base64_decode', 'base64_decode', (['op.file_content'], {}), '(op.file_content)\n', (25546, 25563), False, 'from neptune.new.internal.utils import base64_decode\n'), ((27118, 27145), 'neptune.new.internal.utils.base64_decode', 'base64_decode', (['x.value.data'], {}), '(x.value.data)\n', (27131, 27145), False, 'from neptune.new.internal.utils import base64_decode\n'), ((4785, 4797), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (4795, 4797), False, 'import uuid\n'), ((5055, 5067), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (5065, 5067), False, 'import uuid\n'), ((9438, 9450), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (9448, 9450), False, 'import uuid\n')]
"""Neptune logger.""" import neptune import numpy as np from ray import tune class NeptuneLogger(tune.logger.Logger): """RLlib Neptune logger. Example usage: ``` import ray from ray import tune ray.init() tune.run( "PPO", stop={"episode_reward_mean": 200}, config={ "env": "CartPole-v0", "num_gpus": 0, "num_workers": 1, "lr": tune.grid_search([0.01, 0.001, 0.0001]), "logger_config": {"neptune_project_name": '<user name>/sandbox'}, }, loggers=tune.logger.DEFAULT_LOGGERS + (NeptuneLogger,), ) ``` """ def _init(self): logger_config = self.config.get('logger_config') neptune.init(logger_config.get('neptune_project_name')) self.neptune_experiment = neptune.create_experiment( name=str(self.trial), # Gets the trial name. params=self.config, ) @staticmethod def dict_multiple_get(dict_, indices): if not isinstance(indices, list): indices = [indices] value = dict_ index = None for index in indices: try: value = value[index] except KeyError: print("Skipping", indices) return {} if isinstance(value, dict): return value else: return {index: value} def on_result(self, result): list_to_traverse = [ [], ['custom_metrics'], ['evaluation'], ['info', 'num_steps_trained'], ['info', 'learner'], ['info', 'exploration_infos', 0], ['info', 'exploration_infos', 1], ['info', 'learner', "default_policy"] ] for indices in list_to_traverse: res_ = self.dict_multiple_get(result, indices) prefix = '/'.join([str(idx) for idx in indices]) for key, value in res_.items(): prefixed_key = '/'.join([prefix, key]) if prefix else key if isinstance(value, float) or isinstance(value, int): self.neptune_experiment.log_metric( prefixed_key, value) elif (isinstance(value, np.ndarray) or isinstance(value, np.number)): self.neptune_experiment.log_metric( prefixed_key, float(value)) # Otherwise ignore def close(self): neptune.stop()
[ "neptune.stop" ]
[((2525, 2539), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (2537, 2539), False, 'import neptune\n')]
import neptune neptune.init('shared/onboarding', api_token='<KEY>') with neptune.create_experiment(name='hello-neptune'): neptune.append_tag('introduction-minimal-example') n = 117 for i in range(1, n): neptune.log_metric('iteration', i) neptune.log_metric('loss', 1/i**0.5) neptune.log_text('magic values', 'magic value{}'.format(0.95*i**2)) neptune.set_property('n_iterations', n)
[ "neptune.set_property", "neptune.log_metric", "neptune.create_experiment", "neptune.append_tag", "neptune.init" ]
[((16, 68), 'neptune.init', 'neptune.init', (['"""shared/onboarding"""'], {'api_token': '"""<KEY>"""'}), "('shared/onboarding', api_token='<KEY>')\n", (28, 68), False, 'import neptune\n'), ((75, 122), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""hello-neptune"""'}), "(name='hello-neptune')\n", (100, 122), False, 'import neptune\n'), ((127, 177), 'neptune.append_tag', 'neptune.append_tag', (['"""introduction-minimal-example"""'], {}), "('introduction-minimal-example')\n", (145, 177), False, 'import neptune\n'), ((369, 408), 'neptune.set_property', 'neptune.set_property', (['"""n_iterations"""', 'n'], {}), "('n_iterations', n)\n", (389, 408), False, 'import neptune\n'), ((218, 252), 'neptune.log_metric', 'neptune.log_metric', (['"""iteration"""', 'i'], {}), "('iteration', i)\n", (236, 252), False, 'import neptune\n'), ((257, 297), 'neptune.log_metric', 'neptune.log_metric', (['"""loss"""', '(1 / i ** 0.5)'], {}), "('loss', 1 / i ** 0.5)\n", (275, 297), False, 'import neptune\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Remember to set environment values: # self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH].pop('tag2_to_remove') # self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH].pop('tag4_remove_non_existing') * NEPTUNE_API_TOKEN * NEPTUNE_PROJECT """ import sys from datetime import datetime from PIL import Image from neptune.new.types import File import neptune.new as neptune from alpha_integration_dev.common_client_code import ClientFeatures from neptune.new.attributes.constants import ( ARTIFACT_ATTRIBUTE_SPACE, LOG_ATTRIBUTE_SPACE, PROPERTIES_ATTRIBUTE_SPACE, SOURCE_CODE_FILES_ATTRIBUTE_PATH, SYSTEM_TAGS_ATTRIBUTE_PATH, ) class NewClientFeatures(ClientFeatures): def __init__(self): super().__init__() self.exp = neptune.init( source_files='alpha_integration_dev/*.py' ) # download sources self.exp.sync() with self.with_check_if_file_appears('files.zip'): self.exp[SOURCE_CODE_FILES_ATTRIBUTE_PATH].download() def modify_tags(self): self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH].add('tag1') self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH].add(['tag2_to_remove', 'tag3']) self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH].remove('tag2_to_remove') self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH].remove('tag4_remove_non_existing') # del self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH] # TODO: NPT-9222 self.exp.sync() assert set(self.exp[SYSTEM_TAGS_ATTRIBUTE_PATH].fetch()) == {'tag1', 'tag3'} def modify_properties(self): self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop'] = 'some text' self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_number'] = 42 self.exp[PROPERTIES_ATTRIBUTE_SPACE]['nested/prop'] = 42 self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_to_del'] = 42 self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_list'] = [1, 2, 3] with open(self.text_file_path, mode='r') as f: self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_IO'] = f self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_datetime'] = datetime.now() self.exp.sync() del self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_to_del'] assert self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop'].fetch() == 'some text' assert self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_number'].fetch() == 42 assert self.exp[PROPERTIES_ATTRIBUTE_SPACE]['nested/prop'].fetch() == 42 prop_to_del_absent = False try: self.exp[PROPERTIES_ATTRIBUTE_SPACE]['prop_to_del'].fetch() except AttributeError: prop_to_del_absent = True assert prop_to_del_absent def log_std(self): print('stdout text1') print('stdout text2') print('stderr text1', file=sys.stderr) print('stderr text2', file=sys.stderr) def log_series(self): # floats self.exp[LOG_ATTRIBUTE_SPACE]['m1'].log(1) self.exp[LOG_ATTRIBUTE_SPACE]['m1'].log(2) self.exp[LOG_ATTRIBUTE_SPACE]['m1'].log(3) self.exp[LOG_ATTRIBUTE_SPACE]['m1'].log(2) self.exp[LOG_ATTRIBUTE_SPACE]['nested']['m1'].log(1) # texts self.exp[LOG_ATTRIBUTE_SPACE]['m2'].log('a') self.exp[LOG_ATTRIBUTE_SPACE]['m2'].log('b') self.exp[LOG_ATTRIBUTE_SPACE]['m2'].log('c') # images im_frame = Image.open(self.img_path) g_img = File.as_image(im_frame) self.exp[LOG_ATTRIBUTE_SPACE]['g_img'].log(g_img) def handle_files_and_images(self): # image im_frame = Image.open(self.img_path) g_img = File.as_image(im_frame) self.exp[ARTIFACT_ATTRIBUTE_SPACE]['assigned image'] = g_img self.exp.wait() with self.with_check_if_file_appears('assigned image.png'): self.exp[ARTIFACT_ATTRIBUTE_SPACE]['assigned image'].download() with self.with_check_if_file_appears('custom_dest.png'): self.exp[ARTIFACT_ATTRIBUTE_SPACE]['assigned image'].download('custom_dest.png') self.exp[ARTIFACT_ATTRIBUTE_SPACE]['logged image'].log(g_img) with open(self.img_path, mode='r') as f: # self.exp[ARTIFACT_ATTRIBUTE_SPACE]['assigned image stream'] = f self.exp[ARTIFACT_ATTRIBUTE_SPACE]['logged image stream'].log(f) # artifact text_file = neptune.types.File(self.text_file_path) self.exp[ARTIFACT_ATTRIBUTE_SPACE]['assigned file'] = text_file # self.exp[ARTIFACT_ATTRIBUTE_SPACE]['logged file'].log(text_file) # wrong type with open(self.text_file_path, mode='r') as f: self.exp[ARTIFACT_ATTRIBUTE_SPACE]['assigned file stream'] = f self.exp[ARTIFACT_ATTRIBUTE_SPACE]['logged file stream'].log(f) def handle_directories(self): pass def finalize(self): return if __name__ == '__main__': NewClientFeatures().run()
[ "neptune.new.init", "neptune.new.types.File.as_image", "neptune.new.types.File" ]
[((1343, 1398), 'neptune.new.init', 'neptune.init', ([], {'source_files': '"""alpha_integration_dev/*.py"""'}), "(source_files='alpha_integration_dev/*.py')\n", (1355, 1398), True, 'import neptune.new as neptune\n'), ((2638, 2652), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2650, 2652), False, 'from datetime import datetime\n'), ((3910, 3935), 'PIL.Image.open', 'Image.open', (['self.img_path'], {}), '(self.img_path)\n', (3920, 3935), False, 'from PIL import Image\n'), ((3952, 3975), 'neptune.new.types.File.as_image', 'File.as_image', (['im_frame'], {}), '(im_frame)\n', (3965, 3975), False, 'from neptune.new.types import File\n'), ((4109, 4134), 'PIL.Image.open', 'Image.open', (['self.img_path'], {}), '(self.img_path)\n', (4119, 4134), False, 'from PIL import Image\n'), ((4151, 4174), 'neptune.new.types.File.as_image', 'File.as_image', (['im_frame'], {}), '(im_frame)\n', (4164, 4174), False, 'from neptune.new.types import File\n'), ((4886, 4925), 'neptune.new.types.File', 'neptune.types.File', (['self.text_file_path'], {}), '(self.text_file_path)\n', (4904, 4925), True, 'import neptune.new as neptune\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import os import re import sys import time import math import json from collections import namedtuple from http.client import NOT_FOUND from io import StringIO from itertools import groupby from pathlib import Path from typing import Dict, List, TYPE_CHECKING import requests import six from bravado.exception import HTTPNotFound from neptune.backend import LeaderboardApiClient from neptune.checkpoint import Checkpoint from neptune.internal.api_clients.hosted_api_clients.mixins import HostedNeptuneMixin from neptune.internal.websockets.reconnecting_websocket_factory import ( ReconnectingWebsocketFactory, ) from neptune.api_exceptions import NotebookNotFound from neptune.api_exceptions import ( ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound, ) from neptune.exceptions import ( DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException, ) from neptune.experiments import Experiment from neptune.internal.channels.channels import ( ChannelNamespace, ChannelType, ChannelValueType, ) from neptune.internal.storage.storage_utils import normalize_file_name from neptune.internal.utils.alpha_integration import ( AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image, ) from neptune.model import ChannelWithLastValue, LeaderboardEntry from neptune.new import exceptions as alpha_exceptions from neptune.new.attributes import constants as alpha_consts from neptune.new.attributes.constants import ( MONITORING_TRACEBACK_ATTRIBUTE_PATH, SYSTEM_FAILED_ATTRIBUTE_PATH, ) from neptune.new.exceptions import ClientHttpError from neptune.new.internal import operation as alpha_operation from neptune.new.internal.backends import ( hosted_file_operations as alpha_hosted_file_operations, ) from neptune.new.internal.backends.api_model import AttributeType from neptune.new.internal.backends.operation_api_name_visitor import ( OperationApiNameVisitor as AlphaOperationApiNameVisitor, ) from neptune.new.internal.backends.operation_api_object_converter import ( OperationApiObjectConverter as AlphaOperationApiObjectConverter, ) from neptune.new.internal.backends.utils import ( handle_server_raw_response_messages, ) from neptune.new.internal.operation import ( AssignString, ConfigFloatSeries, LogFloats, AssignBool, LogStrings, ) from neptune.new.internal.utils import ( base64_decode, base64_encode, paths as alpha_path_utils, ) from neptune.new.internal.utils.paths import parse_path from neptune.notebook import Notebook from neptune.utils import ( assure_directory_exists, with_api_exceptions_handler, NoopObject, ) _logger = logging.getLogger(__name__) LegacyExperiment = namedtuple( "LegacyExperiment", "shortId " "name " "timeOfCreation " "timeOfCompletion " "runningTime " "owner " "storageSize " "channelsSize " "tags " "description " "hostname " "state " "properties " "parameters", ) LegacyLeaderboardEntry = namedtuple( "LegacyExperiment", "id " "organizationName " "projectName " "shortId " "name " "state " "timeOfCreation " "timeOfCompletion " "runningTime " "owner " "size " "tags " "description " "channelsLastValues " "parameters " "properties", ) if TYPE_CHECKING: from neptune.internal.api_clients import HostedNeptuneBackendApiClient class HostedAlphaLeaderboardApiClient(HostedNeptuneMixin, LeaderboardApiClient): @with_api_exceptions_handler def __init__(self, backend_api_client: "HostedNeptuneBackendApiClient"): self._backend_api_client = backend_api_client self._client_config = self._create_client_config( api_token=self.credentials.api_token, backend_client=self.backend_client ) self.leaderboard_swagger_client = self._get_swagger_client( "{}/api/leaderboard/swagger.json".format(self._client_config.api_url), self._backend_api_client.http_client, ) if sys.version_info >= (3, 7): try: # pylint: disable=no-member os.register_at_fork(after_in_child=self._handle_fork_in_child) except AttributeError: pass def _handle_fork_in_child(self): self.leaderboard_swagger_client = NoopObject() @property def http_client(self): return self._backend_api_client.http_client @property def backend_client(self): return self._backend_api_client.backend_client @property def authenticator(self): return self._backend_api_client.authenticator @property def credentials(self): return self._backend_api_client.credentials @property def backend_swagger_client(self): return self._backend_api_client.backend_swagger_client @property def client_lib_version(self): return self._backend_api_client.client_lib_version @property def api_address(self): return self._client_config.api_url @property def display_address(self): return self._backend_api_client.display_address @property def proxies(self): return self._backend_api_client.proxies @with_api_exceptions_handler def get_project_members(self, project_identifier): try: r = self.backend_swagger_client.api.listProjectMembers( projectIdentifier=project_identifier ).response() return r.result except HTTPNotFound: raise ProjectNotFound(project_identifier) @with_api_exceptions_handler def create_experiment( self, project, name, description, params, properties, tags, abortable, # deprecated in alpha monitored, # deprecated in alpha git_info, hostname, entrypoint, notebook_id, checkpoint_id, ): if not isinstance(name, six.string_types): raise ValueError("Invalid name {}, should be a string.".format(name)) if not isinstance(description, six.string_types): raise ValueError( "Invalid description {}, should be a string.".format(description) ) if not isinstance(params, dict): raise ValueError("Invalid params {}, should be a dict.".format(params)) if not isinstance(properties, dict): raise ValueError( "Invalid properties {}, should be a dict.".format(properties) ) if hostname is not None and not isinstance(hostname, six.string_types): raise ValueError( "Invalid hostname {}, should be a string.".format(hostname) ) if entrypoint is not None and not isinstance(entrypoint, six.string_types): raise ValueError( "Invalid entrypoint {}, should be a string.".format(entrypoint) ) git_info = ( { "commit": { "commitId": git_info.commit_id, "message": git_info.message, "authorName": git_info.author_name, "authorEmail": git_info.author_email, "commitDate": git_info.commit_date, }, "repositoryDirty": git_info.repository_dirty, "currentBranch": git_info.active_branch, "remotes": git_info.remote_urls, } if git_info else None ) api_params = { "notebookId": notebook_id, "checkpointId": checkpoint_id, "projectIdentifier": str(project.internal_id), "cliVersion": self.client_lib_version, "gitInfo": git_info, "customId": None, } kwargs = { "experimentCreationParams": api_params, "X-Neptune-CliVersion": self.client_lib_version, "_request_options": {"headers": {"X-Neptune-LegacyClient": "true"}}, } try: api_experiment = ( self.leaderboard_swagger_client.api.createExperiment(**kwargs) .response() .result ) except HTTPNotFound: raise ProjectNotFound(project_identifier=project.full_id) experiment = self._convert_to_experiment(api_experiment, project) # Initialize new experiment init_experiment_operations = self._get_init_experiment_operations( name, description, params, properties, tags, hostname, entrypoint ) self._execute_operations( experiment=experiment, operations=init_experiment_operations, ) return experiment def upload_source_code(self, experiment, source_target_pairs): dest_path = alpha_path_utils.parse_path( alpha_consts.SOURCE_CODE_FILES_ATTRIBUTE_PATH ) file_globs = [source_path for source_path, target_path in source_target_pairs] upload_files_operation = alpha_operation.UploadFileSet( path=dest_path, file_globs=file_globs, reset=True, ) self._execute_upload_operations_with_400_retry( experiment, upload_files_operation ) @with_api_exceptions_handler def get_notebook(self, project, notebook_id): try: api_notebook_list = ( self.leaderboard_swagger_client.api.listNotebooks( projectIdentifier=project.internal_id, id=[notebook_id] ) .response() .result ) if not api_notebook_list.entries: raise NotebookNotFound(notebook_id=notebook_id, project=project.full_id) api_notebook = api_notebook_list.entries[0] return Notebook( backend=self, project=project, _id=api_notebook.id, owner=api_notebook.owner, ) except HTTPNotFound: raise NotebookNotFound(notebook_id=notebook_id, project=project.full_id) @with_api_exceptions_handler def get_last_checkpoint(self, project, notebook_id): try: api_checkpoint_list = ( self.leaderboard_swagger_client.api.listCheckpoints( notebookId=notebook_id, offset=0, limit=1 ) .response() .result ) if not api_checkpoint_list.entries: raise NotebookNotFound(notebook_id=notebook_id, project=project.full_id) checkpoint = api_checkpoint_list.entries[0] return Checkpoint(checkpoint.id, checkpoint.name, checkpoint.path) except HTTPNotFound: raise NotebookNotFound(notebook_id=notebook_id, project=project.full_id) @with_api_exceptions_handler def create_notebook(self, project): try: api_notebook = ( self.leaderboard_swagger_client.api.createNotebook( projectIdentifier=project.internal_id ) .response() .result ) return Notebook( backend=self, project=project, _id=api_notebook.id, owner=api_notebook.owner, ) except HTTPNotFound: raise ProjectNotFound(project_identifier=project.full_id) @with_api_exceptions_handler def create_checkpoint(self, notebook_id, jupyter_path, _file=None): if _file is not None: with self._upload_raw_data( api_method=self.leaderboard_swagger_client.api.createCheckpoint, data=_file, headers={"Content-Type": "application/octet-stream"}, path_params={"notebookId": notebook_id}, query_params={"jupyterPath": jupyter_path}, ) as response: if response.status_code == NOT_FOUND: raise NotebookNotFound(notebook_id=notebook_id) else: response.raise_for_status() CheckpointDTO = self.leaderboard_swagger_client.get_model( "CheckpointDTO" ) return CheckpointDTO.unmarshal(response.json()) else: try: NewCheckpointDTO = self.leaderboard_swagger_client.get_model( "NewCheckpointDTO" ) return ( self.leaderboard_swagger_client.api.createEmptyCheckpoint( notebookId=notebook_id, checkpoint=NewCheckpointDTO(path=jupyter_path), ) .response() .result ) except HTTPNotFound: return None @with_api_exceptions_handler def get_experiment(self, experiment_id): api_attributes = self._get_api_experiment_attributes(experiment_id) attributes = api_attributes.attributes system_attributes = api_attributes.systemAttributes return LegacyExperiment( shortId=system_attributes.shortId.value, name=system_attributes.name.value, timeOfCreation=system_attributes.creationTime.value, timeOfCompletion=None, runningTime=system_attributes.runningTime.value, owner=system_attributes.owner.value, storageSize=system_attributes.size.value, channelsSize=0, tags=system_attributes.tags.values, description=system_attributes.description.value, hostname=system_attributes.hostname.value if system_attributes.hostname else None, state="running" if system_attributes.state.value == "running" else "succeeded", properties=[ AlphaPropertyDTO(attr) for attr in attributes if AlphaPropertyDTO.is_valid_attribute(attr) ], parameters=[ AlphaParameterDTO(attr) for attr in attributes if AlphaParameterDTO.is_valid_attribute(attr) ], ) @with_api_exceptions_handler def set_property(self, experiment, key, value): """Save attribute casted to string under `alpha_consts.PROPERTIES_ATTRIBUTE_SPACE` namespace""" self._execute_operations( experiment=experiment, operations=[ alpha_operation.AssignString( path=alpha_path_utils.parse_path( f"{alpha_consts.PROPERTIES_ATTRIBUTE_SPACE}{key}" ), value=str(value), ) ], ) @with_api_exceptions_handler def remove_property(self, experiment, key): self._remove_attribute( experiment, str_path=f"{alpha_consts.PROPERTIES_ATTRIBUTE_SPACE}{key}" ) @with_api_exceptions_handler def update_tags(self, experiment, tags_to_add, tags_to_delete): operations = [ alpha_operation.AddStrings( path=alpha_path_utils.parse_path( alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH ), values=tags_to_add, ), alpha_operation.RemoveStrings( path=alpha_path_utils.parse_path( alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH ), values=tags_to_delete, ), ] self._execute_operations( experiment=experiment, operations=operations, ) @staticmethod def _get_channel_attribute_path( channel_name: str, channel_namespace: ChannelNamespace ) -> str: if channel_namespace == ChannelNamespace.USER: prefix = alpha_consts.LOG_ATTRIBUTE_SPACE else: prefix = alpha_consts.MONITORING_ATTRIBUTE_SPACE return f"{prefix}{channel_name}" def _create_channel( self, experiment: Experiment, channel_id: str, channel_name: str, channel_type: ChannelType, channel_namespace: ChannelNamespace, ): """This function is responsible for creating 'fake' channels in alpha projects. Since channels are abandoned in alpha api, we're mocking them using empty logging operation.""" operation = channel_type_to_operation(channel_type) log_empty_operation = operation( path=alpha_path_utils.parse_path( self._get_channel_attribute_path(channel_name, channel_namespace) ), values=[], ) # this operation is used to create empty attribute self._execute_operations( experiment=experiment, operations=[log_empty_operation], ) return ChannelWithLastValue( AlphaChannelWithValueDTO( channelId=channel_id, channelName=channel_name, channelType=channel_type.value, x=None, y=None, ) ) @with_api_exceptions_handler def create_channel(self, experiment, name, channel_type) -> ChannelWithLastValue: channel_id = f"{alpha_consts.LOG_ATTRIBUTE_SPACE}{name}" return self._create_channel( experiment, channel_id, channel_name=name, channel_type=ChannelType(channel_type), channel_namespace=ChannelNamespace.USER, ) def _get_channels(self, experiment) -> List[AlphaChannelDTO]: try: return [ AlphaChannelDTO(attr) for attr in self._get_attributes(experiment.internal_id) if AlphaChannelDTO.is_valid_attribute(attr) ] except HTTPNotFound: # pylint: disable=protected-access raise ExperimentNotFound( experiment_short_id=experiment.id, project_qualified_name=experiment._project.full_id, ) @with_api_exceptions_handler def get_channels(self, experiment) -> Dict[str, AlphaChannelDTO]: api_channels = [ channel for channel in self._get_channels(experiment) # return channels from LOG_ATTRIBUTE_SPACE namespace only if channel.id.startswith(alpha_consts.LOG_ATTRIBUTE_SPACE) ] return {ch.name: ch for ch in api_channels} @with_api_exceptions_handler def create_system_channel( self, experiment, name, channel_type ) -> ChannelWithLastValue: channel_id = f"{alpha_consts.MONITORING_ATTRIBUTE_SPACE}{name}" return self._create_channel( experiment, channel_id, channel_name=name, channel_type=ChannelType(channel_type), channel_namespace=ChannelNamespace.SYSTEM, ) @with_api_exceptions_handler def get_system_channels(self, experiment) -> Dict[str, AlphaChannelDTO]: return { channel.name: channel for channel in self._get_channels(experiment) if ( channel.channelType == ChannelType.TEXT.value and channel.id.startswith(alpha_consts.MONITORING_ATTRIBUTE_SPACE) ) } @with_api_exceptions_handler def send_channels_values(self, experiment, channels_with_values): send_operations = [] for channel_with_values in channels_with_values: channel_value_type = channel_with_values.channel_type operation = channel_value_type_to_operation(channel_value_type) if channel_value_type == ChannelValueType.IMAGE_VALUE: # IMAGE_VALUE requires minor data modification before it's sent data_transformer = deprecated_img_to_alpha_image else: # otherwise use identity function as transformer data_transformer = lambda e: e ch_values = [ alpha_operation.LogSeriesValue( value=data_transformer(ch_value.value), step=ch_value.x, ts=ch_value.ts, ) for ch_value in channel_with_values.channel_values ] send_operations.append( operation( path=alpha_path_utils.parse_path( self._get_channel_attribute_path( channel_with_values.channel_name, channel_with_values.channel_namespace, ) ), values=ch_values, ) ) self._execute_operations(experiment, send_operations) def mark_failed(self, experiment, traceback): operations = [] path = parse_path(SYSTEM_FAILED_ATTRIBUTE_PATH) traceback_values = [ LogStrings.ValueType(val, step=None, ts=time.time()) for val in traceback.split("\n") ] operations.append(AssignBool(path=path, value=True)) operations.append( LogStrings( values=traceback_values, path=parse_path(MONITORING_TRACEBACK_ATTRIBUTE_PATH), ) ) self._execute_operations(experiment, operations) def ping_experiment(self, experiment): try: self.leaderboard_swagger_client.api.ping( experimentId=str(experiment.internal_id) ).response().result except HTTPNotFound: # pylint: disable=protected-access raise ExperimentNotFound( experiment_short_id=experiment.id, project_qualified_name=experiment._project.full_id, ) @staticmethod def _get_attribute_name_for_metric(resource_type, gauge_name, gauges_count) -> str: if gauges_count > 1: return "monitoring/{}_{}".format(resource_type, gauge_name).lower() return "monitoring/{}".format(resource_type).lower() @with_api_exceptions_handler def create_hardware_metric(self, experiment, metric): operations = [] gauges_count = len(metric.gauges) for gauge in metric.gauges: path = parse_path( self._get_attribute_name_for_metric( metric.resource_type, gauge.name(), gauges_count ) ) operations.append( ConfigFloatSeries( path, min=metric.min_value, max=metric.max_value, unit=metric.unit ) ) self._execute_operations(experiment, operations) @with_api_exceptions_handler def send_hardware_metric_reports(self, experiment, metrics, metric_reports): operations = [] metrics_by_name = {metric.name: metric for metric in metrics} for report in metric_reports: metric = metrics_by_name.get(report.metric.name) gauges_count = len(metric.gauges) for gauge_name, metric_values in groupby( report.values, lambda value: value.gauge_name ): metric_values = list(metric_values) path = parse_path( self._get_attribute_name_for_metric( metric.resource_type, gauge_name, gauges_count ) ) operations.append( LogFloats( path, [ LogFloats.ValueType( value.value, step=None, ts=value.timestamp ) for value in metric_values ], ) ) self._execute_operations(experiment, operations) def log_artifact(self, experiment, artifact, destination=None): if isinstance(artifact, str): if os.path.isfile(artifact): target_name = ( os.path.basename(artifact) if destination is None else destination ) dest_path = self._get_dest_and_ext(target_name) operation = alpha_operation.UploadFile( path=dest_path, ext="", file_path=os.path.abspath(artifact), ) elif os.path.isdir(artifact): for path, file_destination in self._log_dir_artifacts( artifact, destination ): self.log_artifact(experiment, path, file_destination) return else: raise FileNotFound(artifact) elif hasattr(artifact, "read"): if not destination: raise ValueError("destination is required for IO streams") dest_path = self._get_dest_and_ext(destination) data = artifact.read() content = data.encode("utf-8") if isinstance(data, str) else data operation = alpha_operation.UploadFileContent( path=dest_path, ext="", file_content=base64_encode(content) ) else: raise ValueError("Artifact must be a local path or an IO object") self._execute_upload_operations_with_400_retry(experiment, operation) @staticmethod def _get_dest_and_ext(target_name): qualified_target_name = f"{alpha_consts.ARTIFACT_ATTRIBUTE_SPACE}{target_name}" return alpha_path_utils.parse_path(normalize_file_name(qualified_target_name)) def _log_dir_artifacts(self, directory_path, destination): directory_path = Path(directory_path) prefix = directory_path.name if destination is None else destination for path in directory_path.glob("**/*"): if path.is_file(): relative_path = path.relative_to(directory_path) file_destination = prefix + "/" + str(relative_path) yield str(path), file_destination def delete_artifacts(self, experiment, path): try: self._remove_attribute( experiment, str_path=f"{alpha_consts.ARTIFACT_ATTRIBUTE_SPACE}{path}" ) except ExperimentOperationErrors as e: if all( isinstance(err, alpha_exceptions.MetadataInconsistency) for err in e.errors ): raise DeleteArtifactUnsupportedInAlphaException( path, experiment ) from None raise @with_api_exceptions_handler def download_data(self, experiment: Experiment, path: str, destination): project_storage_path = f"artifacts/{path}" with self._download_raw_data( api_method=self.leaderboard_swagger_client.api.downloadAttribute, headers={"Accept": "application/octet-stream"}, path_params={}, query_params={ "experimentId": experiment.internal_id, "attribute": project_storage_path, }, ) as response: if response.status_code == NOT_FOUND: raise PathInExperimentNotFound( path=path, exp_identifier=experiment.internal_id ) else: response.raise_for_status() with open(destination, "wb") as f: for chunk in response.iter_content(chunk_size=10 * 1024 * 1024): if chunk: f.write(chunk) def download_sources(self, experiment: Experiment, path=None, destination_dir=None): if path is not None: # in alpha all source files stored as single FileSet must be downloaded at once raise DownloadSourcesException(experiment) path = alpha_consts.SOURCE_CODE_FILES_ATTRIBUTE_PATH destination_dir = assure_directory_exists(destination_dir) download_request = self._get_file_set_download_request( experiment.internal_id, path ) alpha_hosted_file_operations.download_file_set_attribute( swagger_client=self.leaderboard_swagger_client, download_id=download_request.id, destination=destination_dir, ) @with_api_exceptions_handler def _get_file_set_download_request(self, run_id: str, path: str): params = { "experimentId": run_id, "attribute": path, } return ( self.leaderboard_swagger_client.api.prepareForDownloadFileSetAttributeZip( **params ) .response() .result ) def download_artifacts( self, experiment: Experiment, path=None, destination_dir=None ): raise DownloadArtifactsUnsupportedException(experiment) def download_artifact( self, experiment: Experiment, path=None, destination_dir=None ): destination_dir = assure_directory_exists(destination_dir) destination_path = os.path.join(destination_dir, os.path.basename(path)) try: self.download_data(experiment, path, destination_path) except PathInExperimentNotFound: raise DownloadArtifactUnsupportedException(path, experiment) from None def _get_attributes(self, experiment_id) -> list: return self._get_api_experiment_attributes(experiment_id).attributes def _get_api_experiment_attributes(self, experiment_id): params = { "experimentId": experiment_id, } return ( self.leaderboard_swagger_client.api.getExperimentAttributes(**params) .response() .result ) def _remove_attribute(self, experiment, str_path: str): """Removes given attribute""" self._execute_operations( experiment=experiment, operations=[ alpha_operation.DeleteAttribute( path=alpha_path_utils.parse_path(str_path), ) ], ) @staticmethod def _get_client_config_args(api_token): return dict( X_Neptune_Api_Token=api_token, alpha="true", ) def _execute_upload_operation( self, experiment: Experiment, upload_operation: alpha_operation.Operation ): experiment_id = experiment.internal_id try: if isinstance(upload_operation, alpha_operation.UploadFile): alpha_hosted_file_operations.upload_file_attribute( swagger_client=self.leaderboard_swagger_client, container_id=experiment_id, attribute=alpha_path_utils.path_to_str(upload_operation.path), source=upload_operation.file_path, ext=upload_operation.ext, multipart_config=self._client_config.multipart_config, ) elif isinstance(upload_operation, alpha_operation.UploadFileContent): alpha_hosted_file_operations.upload_file_attribute( swagger_client=self.leaderboard_swagger_client, container_id=experiment_id, attribute=alpha_path_utils.path_to_str(upload_operation.path), source=base64_decode(upload_operation.file_content), ext=upload_operation.ext, multipart_config=self._client_config.multipart_config, ) elif isinstance(upload_operation, alpha_operation.UploadFileSet): alpha_hosted_file_operations.upload_file_set_attribute( swagger_client=self.leaderboard_swagger_client, container_id=experiment_id, attribute=alpha_path_utils.path_to_str(upload_operation.path), file_globs=upload_operation.file_globs, reset=upload_operation.reset, multipart_config=self._client_config.multipart_config, ) else: raise NeptuneException("Upload operation in neither File or FileSet") except alpha_exceptions.NeptuneException as e: raise NeptuneException(e) from e return None def _execute_upload_operations_with_400_retry( self, experiment: Experiment, upload_operation: alpha_operation.Operation ): while True: try: return self._execute_upload_operation(experiment, upload_operation) except ClientHttpError as ex: if "Length of stream does not match given range" not in ex.response: raise ex @with_api_exceptions_handler def _execute_operations( self, experiment: Experiment, operations: List[alpha_operation.Operation] ): experiment_id = experiment.internal_id file_operations = ( alpha_operation.UploadFile, alpha_operation.UploadFileContent, alpha_operation.UploadFileSet, ) if any(isinstance(op, file_operations) for op in operations): raise NeptuneException( "File operations must be handled directly by `_execute_upload_operation`," " not by `_execute_operations` function call." ) kwargs = { "experimentId": experiment_id, "operations": [ { "path": alpha_path_utils.path_to_str(op.path), AlphaOperationApiNameVisitor() .visit(op): AlphaOperationApiObjectConverter() .convert(op), } for op in operations ], } try: result = ( self.leaderboard_swagger_client.api.executeOperations(**kwargs) .response() .result ) errors = [ alpha_exceptions.MetadataInconsistency(err.errorDescription) for err in result ] if errors: raise ExperimentOperationErrors(errors=errors) return None except HTTPNotFound as e: # pylint: disable=protected-access raise ExperimentNotFound( experiment_short_id=experiment.id, project_qualified_name=experiment._project.full_id, ) from e def _get_init_experiment_operations( self, name, description, params, properties, tags, hostname, entrypoint ) -> List[alpha_operation.Operation]: """Returns operations required to initialize newly created experiment""" init_operations = list() # Assign experiment name init_operations.append( alpha_operation.AssignString( path=alpha_path_utils.parse_path( alpha_consts.SYSTEM_NAME_ATTRIBUTE_PATH ), value=name, ) ) # Assign experiment description init_operations.append( alpha_operation.AssignString( path=alpha_path_utils.parse_path( alpha_consts.SYSTEM_DESCRIPTION_ATTRIBUTE_PATH ), value=description, ) ) # Assign experiment parameters for p_name, p_val in params.items(): parameter_type, string_value = self._get_parameter_with_type(p_val) operation_cls = ( alpha_operation.AssignFloat if parameter_type == "double" else alpha_operation.AssignString ) init_operations.append( operation_cls( path=alpha_path_utils.parse_path( f"{alpha_consts.PARAMETERS_ATTRIBUTE_SPACE}{p_name}" ), value=string_value, ) ) # Assign experiment properties for p_key, p_val in properties.items(): init_operations.append( AssignString( path=alpha_path_utils.parse_path( f"{alpha_consts.PROPERTIES_ATTRIBUTE_SPACE}{p_key}" ), value=str(p_val), ) ) # Assign tags if tags: init_operations.append( alpha_operation.AddStrings( path=alpha_path_utils.parse_path( alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH ), values=set(tags), ) ) # Assign source hostname if hostname: init_operations.append( alpha_operation.AssignString( path=alpha_path_utils.parse_path( alpha_consts.SYSTEM_HOSTNAME_ATTRIBUTE_PATH ), value=hostname, ) ) # Assign source entrypoint if entrypoint: init_operations.append( alpha_operation.AssignString( path=alpha_path_utils.parse_path( alpha_consts.SOURCE_CODE_ENTRYPOINT_ATTRIBUTE_PATH ), value=entrypoint, ) ) return init_operations @with_api_exceptions_handler def reset_channel(self, experiment, channel_id, channel_name, channel_type): op = channel_type_to_clear_operation(ChannelType(channel_type)) attr_path = self._get_channel_attribute_path( channel_name, ChannelNamespace.USER ) self._execute_operations( experiment=experiment, operations=[op(path=alpha_path_utils.parse_path(attr_path))], ) @with_api_exceptions_handler def _get_channel_tuples_from_csv(self, experiment, channel_attribute_path): try: csv = ( self.leaderboard_swagger_client.api.getFloatSeriesValuesCSV( experimentId=experiment.internal_id, attribute=channel_attribute_path, ) .response() .incoming_response.text ) lines = csv.split("\n")[:-1] return [line.split(",") for line in lines] except HTTPNotFound: # pylint: disable=protected-access raise ExperimentNotFound( experiment_short_id=experiment.id, project_qualified_name=experiment._project.full_id, ) @with_api_exceptions_handler def get_channel_points_csv(self, experiment, channel_internal_id, channel_name): try: channel_attr_path = self._get_channel_attribute_path( channel_name, ChannelNamespace.USER ) values = self._get_channel_tuples_from_csv(experiment, channel_attr_path) step_and_value = [val[0] + "," + val[2] for val in values] csv = StringIO() for line in step_and_value: csv.write(line + "\n") csv.seek(0) return csv except HTTPNotFound: # pylint: disable=protected-access raise ExperimentNotFound( experiment_short_id=experiment.id, project_qualified_name=experiment._project.full_id, ) @with_api_exceptions_handler def get_metrics_csv(self, experiment): metric_channels = [ channel for channel in self._get_channels(experiment) if ( channel.channelType == ChannelType.NUMERIC.value and channel.id.startswith(alpha_consts.MONITORING_ATTRIBUTE_SPACE) ) ] data = { # val[1] + ',' + val[2] is timestamp,value ch.name: [ val[1] + "," + val[2] for val in self._get_channel_tuples_from_csv(experiment, ch.id) ] for ch in metric_channels } values_count = max(len(values) for values in data.values()) csv = StringIO() csv.write( ",".join( ["x_{name},y_{name}".format(name=ch.name) for ch in metric_channels] ) ) csv.write("\n") for i in range(0, values_count): csv.write( ",".join( [ data[ch.name][i] if i < len(data[ch.name]) else "," for ch in metric_channels ] ) ) csv.write("\n") csv.seek(0) return csv @with_api_exceptions_handler def get_leaderboard_entries( self, project, entry_types=None, # deprecated ids=None, states=None, owners=None, tags=None, min_running_time=None, ): if states is not None: states = [state if state == "running" else "idle" for state in states] try: def get_portion(limit, offset): return ( self.leaderboard_swagger_client.api.getLeaderboard( projectIdentifier=project.full_id, shortId=ids, state=states, owner=owners, tags=tags, tagsMode="and", minRunningTimeSeconds=min_running_time, sortBy=["sys/id"], sortFieldType=["string"], sortDirection=["ascending"], limit=limit, offset=offset, ) .response() .result.entries ) return [ LeaderboardEntry(self._to_leaderboard_entry_dto(e)) for e in self._get_all_items(get_portion, step=100) ] except HTTPNotFound: raise ProjectNotFound(project_identifier=project.full_id) def websockets_factory(self, project_id, experiment_id): base_url = re.sub(r"^http", "ws", self.api_address) + "/api/notifications/v1" return ReconnectingWebsocketFactory( backend=self, url=base_url + f"/runs/{project_id}/{experiment_id}/signal" ) @staticmethod def _to_leaderboard_entry_dto(experiment_attributes): attributes = experiment_attributes.attributes system_attributes = experiment_attributes.systemAttributes def is_channel_namespace(name): return name.startswith(alpha_consts.LOG_ATTRIBUTE_SPACE) or name.startswith( alpha_consts.MONITORING_ATTRIBUTE_SPACE ) numeric_channels = [ HostedAlphaLeaderboardApiClient._float_series_to_channel_last_value_dto( attr ) for attr in attributes if ( attr.type == AttributeType.FLOAT_SERIES.value and is_channel_namespace(attr.name) and attr.floatSeriesProperties.last is not None ) ] text_channels = [ HostedAlphaLeaderboardApiClient._string_series_to_channel_last_value_dto( attr ) for attr in attributes if ( attr.type == AttributeType.STRING_SERIES.value and is_channel_namespace(attr.name) and attr.stringSeriesProperties.last is not None ) ] return LegacyLeaderboardEntry( id=experiment_attributes.id, organizationName=experiment_attributes.organizationName, projectName=experiment_attributes.projectName, shortId=system_attributes.shortId.value, name=system_attributes.name.value, state="running" if system_attributes.state.value == "running" else "succeeded", timeOfCreation=system_attributes.creationTime.value, timeOfCompletion=None, runningTime=system_attributes.runningTime.value, owner=system_attributes.owner.value, size=system_attributes.size.value, tags=system_attributes.tags.values, description=system_attributes.description.value, channelsLastValues=numeric_channels + text_channels, parameters=[ AlphaParameterDTO(attr) for attr in attributes if AlphaParameterDTO.is_valid_attribute(attr) ], properties=[ AlphaPropertyDTO(attr) for attr in attributes if AlphaPropertyDTO.is_valid_attribute(attr) ], ) @staticmethod def _float_series_to_channel_last_value_dto(attribute): return AlphaChannelWithValueDTO( channelId=attribute.name, channelName=attribute.name.split("/", 1)[-1], channelType="numeric", x=attribute.floatSeriesProperties.lastStep, y=attribute.floatSeriesProperties.last, ) @staticmethod def _string_series_to_channel_last_value_dto(attribute): return AlphaChannelWithValueDTO( channelId=attribute.name, channelName=attribute.name.split("/", 1)[-1], channelType="text", x=attribute.stringSeriesProperties.lastStep, y=attribute.stringSeriesProperties.last, ) @staticmethod def _get_all_items(get_portion, step): items = [] previous_items = None while previous_items is None or len(previous_items) >= step: previous_items = get_portion(limit=step, offset=len(items)) items += previous_items return items def _upload_raw_data(self, api_method, data, headers, path_params, query_params): url = self.api_address + api_method.operation.path_name + "?" for key, val in path_params.items(): url = url.replace("{" + key + "}", val) for key, val in query_params.items(): url = url + key + "=" + val + "&" session = self.http_client.session request = self.authenticator.apply( requests.Request(method="POST", url=url, data=data, headers=headers) ) return handle_server_raw_response_messages( session.send(session.prepare_request(request)) ) def _get_parameter_with_type(self, parameter): string_type = "string" double_type = "double" if isinstance(parameter, bool): return (string_type, str(parameter)) elif isinstance(parameter, float) or isinstance(parameter, int): if math.isinf(parameter) or math.isnan(parameter): return (string_type, json.dumps(parameter)) else: return (double_type, str(parameter)) else: return (string_type, str(parameter)) def _convert_to_experiment(self, api_experiment, project): # pylint: disable=protected-access return Experiment( backend=project._backend, project=project, _id=api_experiment.shortId, internal_id=api_experiment.id, ) def _download_raw_data(self, api_method, headers, path_params, query_params): url = self.api_address + api_method.operation.path_name + "?" for key, val in path_params.items(): url = url.replace("{" + key + "}", val) for key, val in query_params.items(): url = url + key + "=" + val + "&" session = self.http_client.session request = self.authenticator.apply( requests.Request(method="GET", url=url, headers=headers) ) return handle_server_raw_response_messages( session.send(session.prepare_request(request), stream=True) )
[ "neptune.internal.utils.alpha_integration.AlphaPropertyDTO.is_valid_attribute", "neptune.new.internal.backends.operation_api_name_visitor.OperationApiNameVisitor", "neptune.new.internal.operation.ConfigFloatSeries", "neptune.internal.utils.alpha_integration.AlphaChannelDTO.is_valid_attribute", "neptune.inte...
[((3608, 3635), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (3625, 3635), False, 'import logging\n'), ((3656, 3840), 'collections.namedtuple', 'namedtuple', (['"""LegacyExperiment"""', '"""shortId name timeOfCreation timeOfCompletion runningTime owner storageSize channelsSize tags description hostname state properties parameters"""'], {}), "('LegacyExperiment',\n 'shortId name timeOfCreation timeOfCompletion runningTime owner storageSize channelsSize tags description hostname state properties parameters'\n )\n", (3666, 3840), False, 'from collections import namedtuple\n'), ((3960, 4166), 'collections.namedtuple', 'namedtuple', (['"""LegacyExperiment"""', '"""id organizationName projectName shortId name state timeOfCreation timeOfCompletion runningTime owner size tags description channelsLastValues parameters properties"""'], {}), "('LegacyExperiment',\n 'id organizationName projectName shortId name state timeOfCreation timeOfCompletion runningTime owner size tags description channelsLastValues parameters properties'\n )\n", (3970, 4166), False, 'from collections import namedtuple\n'), ((5297, 5309), 'neptune.utils.NoopObject', 'NoopObject', ([], {}), '()\n', (5307, 5309), False, 'from neptune.utils import assure_directory_exists, with_api_exceptions_handler, NoopObject\n'), ((9849, 9923), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SOURCE_CODE_FILES_ATTRIBUTE_PATH'], {}), '(alpha_consts.SOURCE_CODE_FILES_ATTRIBUTE_PATH)\n', (9876, 9923), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((10066, 10151), 'neptune.new.internal.operation.UploadFileSet', 'alpha_operation.UploadFileSet', ([], {'path': 'dest_path', 'file_globs': 'file_globs', 'reset': '(True)'}), '(path=dest_path, file_globs=file_globs, reset=True\n )\n', (10095, 10151), True, 'from neptune.new.internal import operation as alpha_operation\n'), ((17612, 17651), 'neptune.internal.utils.alpha_integration.channel_type_to_operation', 'channel_type_to_operation', (['channel_type'], {}), '(channel_type)\n', (17637, 17651), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((22091, 22131), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['SYSTEM_FAILED_ATTRIBUTE_PATH'], {}), '(SYSTEM_FAILED_ATTRIBUTE_PATH)\n', (22101, 22131), False, 'from neptune.new.internal.utils.paths import parse_path\n'), ((26966, 26986), 'pathlib.Path', 'Path', (['directory_path'], {}), '(directory_path)\n', (26970, 26986), False, 'from pathlib import Path\n'), ((29203, 29243), 'neptune.utils.assure_directory_exists', 'assure_directory_exists', (['destination_dir'], {}), '(destination_dir)\n', (29226, 29243), False, 'from neptune.utils import assure_directory_exists, with_api_exceptions_handler, NoopObject\n'), ((29368, 29543), 'neptune.new.internal.backends.hosted_file_operations.download_file_set_attribute', 'alpha_hosted_file_operations.download_file_set_attribute', ([], {'swagger_client': 'self.leaderboard_swagger_client', 'download_id': 'download_request.id', 'destination': 'destination_dir'}), '(swagger_client=\n self.leaderboard_swagger_client, download_id=download_request.id,\n destination=destination_dir)\n', (29424, 29543), True, 'from neptune.new.internal.backends import hosted_file_operations as alpha_hosted_file_operations\n'), ((30099, 30148), 'neptune.exceptions.DownloadArtifactsUnsupportedException', 'DownloadArtifactsUnsupportedException', (['experiment'], {}), '(experiment)\n', (30136, 30148), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((30280, 30320), 'neptune.utils.assure_directory_exists', 'assure_directory_exists', (['destination_dir'], {}), '(destination_dir)\n', (30303, 30320), False, 'from neptune.utils import assure_directory_exists, with_api_exceptions_handler, NoopObject\n'), ((41509, 41519), 'io.StringIO', 'StringIO', ([], {}), '()\n', (41517, 41519), False, 'from io import StringIO\n'), ((43652, 43759), 'neptune.internal.websockets.reconnecting_websocket_factory.ReconnectingWebsocketFactory', 'ReconnectingWebsocketFactory', ([], {'backend': 'self', 'url': "(base_url + f'/runs/{project_id}/{experiment_id}/signal')"}), "(backend=self, url=base_url +\n f'/runs/{project_id}/{experiment_id}/signal')\n", (43680, 43759), False, 'from neptune.internal.websockets.reconnecting_websocket_factory import ReconnectingWebsocketFactory\n'), ((48563, 48680), 'neptune.experiments.Experiment', 'Experiment', ([], {'backend': 'project._backend', 'project': 'project', '_id': 'api_experiment.shortId', 'internal_id': 'api_experiment.id'}), '(backend=project._backend, project=project, _id=api_experiment.\n shortId, internal_id=api_experiment.id)\n', (48573, 48680), False, 'from neptune.experiments import Experiment\n'), ((10878, 10969), 'neptune.notebook.Notebook', 'Notebook', ([], {'backend': 'self', 'project': 'project', '_id': 'api_notebook.id', 'owner': 'api_notebook.owner'}), '(backend=self, project=project, _id=api_notebook.id, owner=\n api_notebook.owner)\n', (10886, 10969), False, 'from neptune.notebook import Notebook\n'), ((11727, 11786), 'neptune.checkpoint.Checkpoint', 'Checkpoint', (['checkpoint.id', 'checkpoint.name', 'checkpoint.path'], {}), '(checkpoint.id, checkpoint.name, checkpoint.path)\n', (11737, 11786), False, 'from neptune.checkpoint import Checkpoint\n'), ((12247, 12338), 'neptune.notebook.Notebook', 'Notebook', ([], {'backend': 'self', 'project': 'project', '_id': 'api_notebook.id', 'owner': 'api_notebook.owner'}), '(backend=self, project=project, _id=api_notebook.id, owner=\n api_notebook.owner)\n', (12255, 12338), False, 'from neptune.notebook import Notebook\n'), ((18096, 18220), 'neptune.internal.utils.alpha_integration.AlphaChannelWithValueDTO', 'AlphaChannelWithValueDTO', ([], {'channelId': 'channel_id', 'channelName': 'channel_name', 'channelType': 'channel_type.value', 'x': 'None', 'y': 'None'}), '(channelId=channel_id, channelName=channel_name,\n channelType=channel_type.value, x=None, y=None)\n', (18120, 18220), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((20813, 20864), 'neptune.internal.utils.alpha_integration.channel_value_type_to_operation', 'channel_value_type_to_operation', (['channel_value_type'], {}), '(channel_value_type)\n', (20844, 20864), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((22307, 22340), 'neptune.new.internal.operation.AssignBool', 'AssignBool', ([], {'path': 'path', 'value': '(True)'}), '(path=path, value=True)\n', (22317, 22340), False, 'from neptune.new.internal.operation import AssignString, ConfigFloatSeries, LogFloats, AssignBool, LogStrings\n'), ((24329, 24383), 'itertools.groupby', 'groupby', (['report.values', '(lambda value: value.gauge_name)'], {}), '(report.values, lambda value: value.gauge_name)\n', (24336, 24383), False, 'from itertools import groupby\n'), ((25247, 25271), 'os.path.isfile', 'os.path.isfile', (['artifact'], {}), '(artifact)\n', (25261, 25271), False, 'import os\n'), ((26833, 26875), 'neptune.internal.storage.storage_utils.normalize_file_name', 'normalize_file_name', (['qualified_target_name'], {}), '(qualified_target_name)\n', (26852, 26875), False, 'from neptune.internal.storage.storage_utils import normalize_file_name\n'), ((29078, 29114), 'neptune.exceptions.DownloadSourcesException', 'DownloadSourcesException', (['experiment'], {}), '(experiment)\n', (29102, 29114), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((30378, 30400), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (30394, 30400), False, 'import os\n'), ((34468, 34614), 'neptune.exceptions.NeptuneException', 'NeptuneException', (['"""File operations must be handled directly by `_execute_upload_operation`, not by `_execute_operations` function call."""'], {}), "(\n 'File operations must be handled directly by `_execute_upload_operation`, not by `_execute_operations` function call.'\n )\n", (34484, 34614), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((38887, 38912), 'neptune.internal.channels.channels.ChannelType', 'ChannelType', (['channel_type'], {}), '(channel_type)\n', (38898, 38912), False, 'from neptune.internal.channels.channels import ChannelNamespace, ChannelType, ChannelValueType\n'), ((40396, 40406), 'io.StringIO', 'StringIO', ([], {}), '()\n', (40404, 40406), False, 'from io import StringIO\n'), ((43570, 43609), 're.sub', 're.sub', (['"""^http"""', '"""ws"""', 'self.api_address'], {}), "('^http', 'ws', self.api_address)\n", (43576, 43609), False, 'import re\n'), ((47707, 47775), 'requests.Request', 'requests.Request', ([], {'method': '"""POST"""', 'url': 'url', 'data': 'data', 'headers': 'headers'}), "(method='POST', url=url, data=data, headers=headers)\n", (47723, 47775), False, 'import requests\n'), ((49180, 49236), 'requests.Request', 'requests.Request', ([], {'method': '"""GET"""', 'url': 'url', 'headers': 'headers'}), "(method='GET', url=url, headers=headers)\n", (49196, 49236), False, 'import requests\n'), ((5098, 5160), 'os.register_at_fork', 'os.register_at_fork', ([], {'after_in_child': 'self._handle_fork_in_child'}), '(after_in_child=self._handle_fork_in_child)\n', (5117, 5160), False, 'import os\n'), ((6516, 6551), 'neptune.api_exceptions.ProjectNotFound', 'ProjectNotFound', (['project_identifier'], {}), '(project_identifier)\n', (6531, 6551), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((9279, 9330), 'neptune.api_exceptions.ProjectNotFound', 'ProjectNotFound', ([], {'project_identifier': 'project.full_id'}), '(project_identifier=project.full_id)\n', (9294, 9330), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((10734, 10800), 'neptune.api_exceptions.NotebookNotFound', 'NotebookNotFound', ([], {'notebook_id': 'notebook_id', 'project': 'project.full_id'}), '(notebook_id=notebook_id, project=project.full_id)\n', (10750, 10800), False, 'from neptune.api_exceptions import NotebookNotFound\n'), ((11091, 11157), 'neptune.api_exceptions.NotebookNotFound', 'NotebookNotFound', ([], {'notebook_id': 'notebook_id', 'project': 'project.full_id'}), '(notebook_id=notebook_id, project=project.full_id)\n', (11107, 11157), False, 'from neptune.api_exceptions import NotebookNotFound\n'), ((11584, 11650), 'neptune.api_exceptions.NotebookNotFound', 'NotebookNotFound', ([], {'notebook_id': 'notebook_id', 'project': 'project.full_id'}), '(notebook_id=notebook_id, project=project.full_id)\n', (11600, 11650), False, 'from neptune.api_exceptions import NotebookNotFound\n'), ((11834, 11900), 'neptune.api_exceptions.NotebookNotFound', 'NotebookNotFound', ([], {'notebook_id': 'notebook_id', 'project': 'project.full_id'}), '(notebook_id=notebook_id, project=project.full_id)\n', (11850, 11900), False, 'from neptune.api_exceptions import NotebookNotFound\n'), ((12460, 12511), 'neptune.api_exceptions.ProjectNotFound', 'ProjectNotFound', ([], {'project_identifier': 'project.full_id'}), '(project_identifier=project.full_id)\n', (12475, 12511), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((18648, 18673), 'neptune.internal.channels.channels.ChannelType', 'ChannelType', (['channel_type'], {}), '(channel_type)\n', (18659, 18673), False, 'from neptune.internal.channels.channels import ChannelNamespace, ChannelType, ChannelValueType\n'), ((18855, 18876), 'neptune.internal.utils.alpha_integration.AlphaChannelDTO', 'AlphaChannelDTO', (['attr'], {}), '(attr)\n', (18870, 18876), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((19118, 19227), 'neptune.api_exceptions.ExperimentNotFound', 'ExperimentNotFound', ([], {'experiment_short_id': 'experiment.id', 'project_qualified_name': 'experiment._project.full_id'}), '(experiment_short_id=experiment.id,\n project_qualified_name=experiment._project.full_id)\n', (19136, 19227), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((20035, 20060), 'neptune.internal.channels.channels.ChannelType', 'ChannelType', (['channel_type'], {}), '(channel_type)\n', (20046, 20060), False, 'from neptune.internal.channels.channels import ChannelNamespace, ChannelType, ChannelValueType\n'), ((22879, 22988), 'neptune.api_exceptions.ExperimentNotFound', 'ExperimentNotFound', ([], {'experiment_short_id': 'experiment.id', 'project_qualified_name': 'experiment._project.full_id'}), '(experiment_short_id=experiment.id,\n project_qualified_name=experiment._project.full_id)\n', (22897, 22988), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((23735, 23825), 'neptune.new.internal.operation.ConfigFloatSeries', 'ConfigFloatSeries', (['path'], {'min': 'metric.min_value', 'max': 'metric.max_value', 'unit': 'metric.unit'}), '(path, min=metric.min_value, max=metric.max_value, unit=\n metric.unit)\n', (23752, 23825), False, 'from neptune.new.internal.operation import AssignString, ConfigFloatSeries, LogFloats, AssignBool, LogStrings\n'), ((25686, 25709), 'os.path.isdir', 'os.path.isdir', (['artifact'], {}), '(artifact)\n', (25699, 25709), False, 'import os\n'), ((28476, 28550), 'neptune.api_exceptions.PathInExperimentNotFound', 'PathInExperimentNotFound', ([], {'path': 'path', 'exp_identifier': 'experiment.internal_id'}), '(path=path, exp_identifier=experiment.internal_id)\n', (28500, 28550), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((30542, 30596), 'neptune.exceptions.DownloadArtifactUnsupportedException', 'DownloadArtifactUnsupportedException', (['path', 'experiment'], {}), '(path, experiment)\n', (30578, 30596), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((33547, 33566), 'neptune.exceptions.NeptuneException', 'NeptuneException', (['e'], {}), '(e)\n', (33563, 33566), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((35283, 35343), 'neptune.new.exceptions.MetadataInconsistency', 'alpha_exceptions.MetadataInconsistency', (['err.errorDescription'], {}), '(err.errorDescription)\n', (35321, 35343), True, 'from neptune.new import exceptions as alpha_exceptions\n'), ((35437, 35477), 'neptune.api_exceptions.ExperimentOperationErrors', 'ExperimentOperationErrors', ([], {'errors': 'errors'}), '(errors=errors)\n', (35462, 35477), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((35601, 35710), 'neptune.api_exceptions.ExperimentNotFound', 'ExperimentNotFound', ([], {'experiment_short_id': 'experiment.id', 'project_qualified_name': 'experiment._project.full_id'}), '(experiment_short_id=experiment.id,\n project_qualified_name=experiment._project.full_id)\n', (35619, 35710), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((39804, 39913), 'neptune.api_exceptions.ExperimentNotFound', 'ExperimentNotFound', ([], {'experiment_short_id': 'experiment.id', 'project_qualified_name': 'experiment._project.full_id'}), '(experiment_short_id=experiment.id,\n project_qualified_name=experiment._project.full_id)\n', (39822, 39913), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((40627, 40736), 'neptune.api_exceptions.ExperimentNotFound', 'ExperimentNotFound', ([], {'experiment_short_id': 'experiment.id', 'project_qualified_name': 'experiment._project.full_id'}), '(experiment_short_id=experiment.id,\n project_qualified_name=experiment._project.full_id)\n', (40645, 40736), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((43437, 43488), 'neptune.api_exceptions.ProjectNotFound', 'ProjectNotFound', ([], {'project_identifier': 'project.full_id'}), '(project_identifier=project.full_id)\n', (43452, 43488), False, 'from neptune.api_exceptions import ExperimentNotFound, ExperimentOperationErrors, PathInExperimentNotFound, ProjectNotFound\n'), ((13091, 13132), 'neptune.api_exceptions.NotebookNotFound', 'NotebookNotFound', ([], {'notebook_id': 'notebook_id'}), '(notebook_id=notebook_id)\n', (13107, 13132), False, 'from neptune.api_exceptions import NotebookNotFound\n'), ((15036, 15058), 'neptune.internal.utils.alpha_integration.AlphaPropertyDTO', 'AlphaPropertyDTO', (['attr'], {}), '(attr)\n', (15052, 15058), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((15215, 15238), 'neptune.internal.utils.alpha_integration.AlphaParameterDTO', 'AlphaParameterDTO', (['attr'], {}), '(attr)\n', (15232, 15238), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((16320, 16388), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH'], {}), '(alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH)\n', (16347, 16388), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((16543, 16611), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH'], {}), '(alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH)\n', (16570, 16611), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((18969, 19009), 'neptune.internal.utils.alpha_integration.AlphaChannelDTO.is_valid_attribute', 'AlphaChannelDTO.is_valid_attribute', (['attr'], {}), '(attr)\n', (19003, 19009), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((22213, 22224), 'time.time', 'time.time', ([], {}), '()\n', (22222, 22224), False, 'import time\n'), ((22455, 22502), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['MONITORING_TRACEBACK_ATTRIBUTE_PATH'], {}), '(MONITORING_TRACEBACK_ATTRIBUTE_PATH)\n', (22465, 22502), False, 'from neptune.new.internal.utils.paths import parse_path\n'), ((25325, 25351), 'os.path.basename', 'os.path.basename', (['artifact'], {}), '(artifact)\n', (25341, 25351), False, 'import os\n'), ((25980, 26002), 'neptune.exceptions.FileNotFound', 'FileNotFound', (['artifact'], {}), '(artifact)\n', (25992, 26002), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((27740, 27799), 'neptune.exceptions.DeleteArtifactUnsupportedInAlphaException', 'DeleteArtifactUnsupportedInAlphaException', (['path', 'experiment'], {}), '(path, experiment)\n', (27781, 27799), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((34791, 34828), 'neptune.new.internal.utils.paths.path_to_str', 'alpha_path_utils.path_to_str', (['op.path'], {}), '(op.path)\n', (34819, 34828), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((36168, 36236), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SYSTEM_NAME_ATTRIBUTE_PATH'], {}), '(alpha_consts.SYSTEM_NAME_ATTRIBUTE_PATH)\n', (36195, 36236), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((36463, 36538), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SYSTEM_DESCRIPTION_ATTRIBUTE_PATH'], {}), '(alpha_consts.SYSTEM_DESCRIPTION_ATTRIBUTE_PATH)\n', (36490, 36538), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((45880, 45903), 'neptune.internal.utils.alpha_integration.AlphaParameterDTO', 'AlphaParameterDTO', (['attr'], {}), '(attr)\n', (45897, 45903), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((46061, 46083), 'neptune.internal.utils.alpha_integration.AlphaPropertyDTO', 'AlphaPropertyDTO', (['attr'], {}), '(attr)\n', (46077, 46083), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((48199, 48220), 'math.isinf', 'math.isinf', (['parameter'], {}), '(parameter)\n', (48209, 48220), False, 'import math\n'), ((48224, 48245), 'math.isnan', 'math.isnan', (['parameter'], {}), '(parameter)\n', (48234, 48245), False, 'import math\n'), ((15117, 15158), 'neptune.internal.utils.alpha_integration.AlphaPropertyDTO.is_valid_attribute', 'AlphaPropertyDTO.is_valid_attribute', (['attr'], {}), '(attr)\n', (15152, 15158), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((15297, 15339), 'neptune.internal.utils.alpha_integration.AlphaParameterDTO.is_valid_attribute', 'AlphaParameterDTO.is_valid_attribute', (['attr'], {}), '(attr)\n', (15333, 15339), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((25624, 25649), 'os.path.abspath', 'os.path.abspath', (['artifact'], {}), '(artifact)\n', (25639, 25649), False, 'import os\n'), ((26435, 26457), 'neptune.new.internal.utils.base64_encode', 'base64_encode', (['content'], {}), '(content)\n', (26448, 26457), False, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((32010, 32061), 'neptune.new.internal.utils.paths.path_to_str', 'alpha_path_utils.path_to_str', (['upload_operation.path'], {}), '(upload_operation.path)\n', (32038, 32061), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((33410, 33473), 'neptune.exceptions.NeptuneException', 'NeptuneException', (['"""Upload operation in neither File or FileSet"""'], {}), "('Upload operation in neither File or FileSet')\n", (33426, 33473), False, 'from neptune.exceptions import DeleteArtifactUnsupportedInAlphaException, DownloadArtifactUnsupportedException, DownloadArtifactsUnsupportedException, DownloadSourcesException, FileNotFound, NeptuneException\n'), ((37077, 37163), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['f"""{alpha_consts.PARAMETERS_ATTRIBUTE_SPACE}{p_name}"""'], {}), "(\n f'{alpha_consts.PARAMETERS_ATTRIBUTE_SPACE}{p_name}')\n", (37104, 37163), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((37456, 37541), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['f"""{alpha_consts.PROPERTIES_ATTRIBUTE_SPACE}{p_key}"""'], {}), "(f'{alpha_consts.PROPERTIES_ATTRIBUTE_SPACE}{p_key}'\n )\n", (37483, 37541), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((37798, 37866), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH'], {}), '(alpha_consts.SYSTEM_TAGS_ATTRIBUTE_PATH)\n', (37825, 37866), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((38145, 38217), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SYSTEM_HOSTNAME_ATTRIBUTE_PATH'], {}), '(alpha_consts.SYSTEM_HOSTNAME_ATTRIBUTE_PATH)\n', (38172, 38217), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((38498, 38577), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['alpha_consts.SOURCE_CODE_ENTRYPOINT_ATTRIBUTE_PATH'], {}), '(alpha_consts.SOURCE_CODE_ENTRYPOINT_ATTRIBUTE_PATH)\n', (38525, 38577), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((45962, 46004), 'neptune.internal.utils.alpha_integration.AlphaParameterDTO.is_valid_attribute', 'AlphaParameterDTO.is_valid_attribute', (['attr'], {}), '(attr)\n', (45998, 46004), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((46142, 46183), 'neptune.internal.utils.alpha_integration.AlphaPropertyDTO.is_valid_attribute', 'AlphaPropertyDTO.is_valid_attribute', (['attr'], {}), '(attr)\n', (46177, 46183), False, 'from neptune.internal.utils.alpha_integration import AlphaChannelDTO, AlphaChannelWithValueDTO, AlphaParameterDTO, AlphaPropertyDTO, channel_type_to_clear_operation, channel_type_to_operation, channel_value_type_to_operation, deprecated_img_to_alpha_image\n'), ((48284, 48305), 'json.dumps', 'json.dumps', (['parameter'], {}), '(parameter)\n', (48294, 48305), False, 'import json\n'), ((15720, 15798), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['f"""{alpha_consts.PROPERTIES_ATTRIBUTE_SPACE}{key}"""'], {}), "(f'{alpha_consts.PROPERTIES_ATTRIBUTE_SPACE}{key}')\n", (15747, 15798), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((24820, 24883), 'neptune.new.internal.operation.LogFloats.ValueType', 'LogFloats.ValueType', (['value.value'], {'step': 'None', 'ts': 'value.timestamp'}), '(value.value, step=None, ts=value.timestamp)\n', (24839, 24883), False, 'from neptune.new.internal.operation import AssignString, ConfigFloatSeries, LogFloats, AssignBool, LogStrings\n'), ((31293, 31330), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['str_path'], {}), '(str_path)\n', (31320, 31330), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((32553, 32604), 'neptune.new.internal.utils.paths.path_to_str', 'alpha_path_utils.path_to_str', (['upload_operation.path'], {}), '(upload_operation.path)\n', (32581, 32604), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((32633, 32677), 'neptune.new.internal.utils.base64_decode', 'base64_decode', (['upload_operation.file_content'], {}), '(upload_operation.file_content)\n', (32646, 32677), False, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((34850, 34880), 'neptune.new.internal.backends.operation_api_name_visitor.OperationApiNameVisitor', 'AlphaOperationApiNameVisitor', ([], {}), '()\n', (34878, 34880), True, 'from neptune.new.internal.backends.operation_api_name_visitor import OperationApiNameVisitor as AlphaOperationApiNameVisitor\n'), ((34913, 34947), 'neptune.new.internal.backends.operation_api_object_converter.OperationApiObjectConverter', 'AlphaOperationApiObjectConverter', ([], {}), '()\n', (34945, 34947), True, 'from neptune.new.internal.backends.operation_api_object_converter import OperationApiObjectConverter as AlphaOperationApiObjectConverter\n'), ((39127, 39165), 'neptune.new.internal.utils.paths.parse_path', 'alpha_path_utils.parse_path', (['attr_path'], {}), '(attr_path)\n', (39154, 39165), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n'), ((33114, 33165), 'neptune.new.internal.utils.paths.path_to_str', 'alpha_path_utils.path_to_str', (['upload_operation.path'], {}), '(upload_operation.path)\n', (33142, 33165), True, 'from neptune.new.internal.utils import base64_decode, base64_encode, paths as alpha_path_utils\n')]
import os import lightgbm as lgb import neptune from neptunecontrib.monitoring.lightgbm import neptune_monitor from neptunecontrib.versioning.data import log_data_version from neptunecontrib.api.utils import get_filepaths from neptunecontrib.monitoring.reporting import send_binary_classification_report from neptunecontrib.monitoring.utils import pickle_and_send_artifact import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score from src.utils import read_config, check_env_vars from src.models.utils import sample_negative_class from src.features.const import V1_CAT_COLS_FEATURES check_env_vars() CONFIG = read_config(config_path=os.getenv('CONFIG_PATH')) neptune.init(project_qualified_name=CONFIG.project) FEATURES_DATA_PATH = CONFIG.data.features_data_path PREDICTION_DATA_PATH = CONFIG.data.prediction_data_path SAMPLE_SUBMISSION_PATH = CONFIG.data.sample_submission_path FEATURE_NAME = 'v1' MODEL_NAME = 'lgbm' NROWS = None LOG_MODEL = True SEED = 1234 VALIDATION_PARAMS = {'validation_schema': 'holdout', 'validation_fraction': 0.26} MODEL_PARAMS = {'num_leaves': 256, 'min_child_samples': 79, 'objective': 'binary', 'max_depth': 15, 'learning_rate': 0.02, "boosting_type": "gbdt", "subsample_freq": 3, "subsample": 0.9, "bagging_seed": 11, "metric": 'auc', "verbosity": -1, 'reg_alpha': 0.3, 'reg_lambda': 0.3, 'colsample_bytree': 0.9, 'seed': 1234 } TRAINING_PARAMS = {'nrows': NROWS, 'negative_sample_fraction': 1.0, 'negative_sample_seed': SEED, 'num_boosting_rounds': 200, # 5000, 'early_stopping_rounds': 20 # 200 } def fit_predict(train, valid, test, model_params, training_params, fine_tuning=False, log_model=False): X_train = train.drop(['isFraud', 'TransactionDT', 'TransactionID'], axis=1) y_train = train['isFraud'] X_valid = valid.drop(['isFraud', 'TransactionDT', 'TransactionID'], axis=1) y_valid = valid['isFraud'] trn_data = lgb.Dataset(X_train, y_train) val_data = lgb.Dataset(X_valid, y_valid) if fine_tuning: callbacks = None else: callbacks = [neptune_monitor()] clf = lgb.train(model_params, trn_data, training_params['num_boosting_rounds'], feature_name=X_train.columns.tolist(), categorical_feature=V1_CAT_COLS_FEATURES, valid_sets=[trn_data, val_data], early_stopping_rounds=training_params['early_stopping_rounds'], callbacks=callbacks) valid_preds = clf.predict(X_valid, num_iteration=clf.best_iteration) if log_model: pickle_and_send_artifact(clf, 'lightgbm.pkl') if fine_tuning: return valid_preds else: train_preds = clf.predict(X_train, num_iteration=clf.best_iteration) X_test = test.drop(['TransactionDT', 'TransactionID'], axis=1) test_preds = clf.predict(X_test, num_iteration=clf.best_iteration) return train_preds, valid_preds, test_preds def fmt_preds(y_pred): return np.concatenate((1.0 - y_pred.reshape(-1, 1), y_pred.reshape(-1, 1)), axis=1) def main(): print('loading data') train_features_path = os.path.join(FEATURES_DATA_PATH, 'train_features_' + FEATURE_NAME + '.csv') test_features_path = os.path.join(FEATURES_DATA_PATH, 'test_features_' + FEATURE_NAME + '.csv') print('... train') train = pd.read_csv(train_features_path, nrows=TRAINING_PARAMS['nrows']) print('... test') test = pd.read_csv(test_features_path, nrows=TRAINING_PARAMS['nrows']) idx_split = int((1 - VALIDATION_PARAMS['validation_fraction']) * len(train)) train, valid = train[:idx_split], train[idx_split:] train = sample_negative_class(train, fraction=TRAINING_PARAMS['negative_sample_fraction'], seed=TRAINING_PARAMS['negative_sample_seed']) hyperparams = {**MODEL_PARAMS, **TRAINING_PARAMS, **VALIDATION_PARAMS} print('starting experiment') with neptune.create_experiment(name='model training', params=hyperparams, upload_source_files=get_filepaths(), tags=[MODEL_NAME, 'features_{}'.format(FEATURE_NAME), 'training']): print('logging data version') log_data_version(train_features_path, prefix='train_features_') log_data_version(test_features_path, prefix='test_features_') print('training') train_preds, valid_preds, test_preds = fit_predict(train, valid, test, MODEL_PARAMS, TRAINING_PARAMS, log_model=LOG_MODEL) print('logging metrics') train_auc = roc_auc_score(train['isFraud'], train_preds) valid_auc = roc_auc_score(valid['isFraud'], valid_preds) neptune.send_metric('train_auc', train_auc) neptune.send_metric('valid_auc', valid_auc) send_binary_classification_report(valid['isFraud'], fmt_preds(valid_preds), channel_name='valid_classification_report') print('postprocessing predictions') valid_predictions_path = os.path.join(PREDICTION_DATA_PATH, 'valid_prediction_{}_{}.csv'.format(FEATURE_NAME, MODEL_NAME)) test_predictions_path = os.path.join(PREDICTION_DATA_PATH, 'test_prediction_{}_{}.csv'.format(FEATURE_NAME, MODEL_NAME)) submission_path = os.path.join(PREDICTION_DATA_PATH, 'submission_{}_{}.csv'.format(FEATURE_NAME, MODEL_NAME)) submission = pd.read_csv(SAMPLE_SUBMISSION_PATH) valid = pd.concat([valid, pd.DataFrame(valid[["TransactionDT", 'TransactionID']], columns=['prediction'])], axis=1) test = pd.concat([test[["TransactionDT", 'TransactionID']], pd.DataFrame(test_preds, columns=['prediction'])], axis=1) submission['isFraud'] = pd.merge(submission, test, on='TransactionID')['prediction'] valid.to_csv(valid_predictions_path, index=None) test.to_csv(test_predictions_path, index=None) submission.to_csv(submission_path, index=None) neptune.send_artifact(valid_predictions_path) neptune.send_artifact(test_predictions_path) neptune.send_artifact(submission_path) print('experiment finished') if __name__ == '__main__': main()
[ "neptune.send_metric", "neptune.send_artifact", "neptune.init" ]
[((610, 626), 'src.utils.check_env_vars', 'check_env_vars', ([], {}), '()\n', (624, 626), False, 'from src.utils import read_config, check_env_vars\n'), ((687, 738), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': 'CONFIG.project'}), '(project_qualified_name=CONFIG.project)\n', (699, 738), False, 'import neptune\n'), ((2266, 2295), 'lightgbm.Dataset', 'lgb.Dataset', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (2277, 2295), True, 'import lightgbm as lgb\n'), ((2311, 2340), 'lightgbm.Dataset', 'lgb.Dataset', (['X_valid', 'y_valid'], {}), '(X_valid, y_valid)\n', (2322, 2340), True, 'import lightgbm as lgb\n'), ((3498, 3573), 'os.path.join', 'os.path.join', (['FEATURES_DATA_PATH', "('train_features_' + FEATURE_NAME + '.csv')"], {}), "(FEATURES_DATA_PATH, 'train_features_' + FEATURE_NAME + '.csv')\n", (3510, 3573), False, 'import os\n'), ((3599, 3673), 'os.path.join', 'os.path.join', (['FEATURES_DATA_PATH', "('test_features_' + FEATURE_NAME + '.csv')"], {}), "(FEATURES_DATA_PATH, 'test_features_' + FEATURE_NAME + '.csv')\n", (3611, 3673), False, 'import os\n'), ((3710, 3774), 'pandas.read_csv', 'pd.read_csv', (['train_features_path'], {'nrows': "TRAINING_PARAMS['nrows']"}), "(train_features_path, nrows=TRAINING_PARAMS['nrows'])\n", (3721, 3774), True, 'import pandas as pd\n'), ((3809, 3872), 'pandas.read_csv', 'pd.read_csv', (['test_features_path'], {'nrows': "TRAINING_PARAMS['nrows']"}), "(test_features_path, nrows=TRAINING_PARAMS['nrows'])\n", (3820, 3872), True, 'import pandas as pd\n'), ((4024, 4157), 'src.models.utils.sample_negative_class', 'sample_negative_class', (['train'], {'fraction': "TRAINING_PARAMS['negative_sample_fraction']", 'seed': "TRAINING_PARAMS['negative_sample_seed']"}), "(train, fraction=TRAINING_PARAMS[\n 'negative_sample_fraction'], seed=TRAINING_PARAMS['negative_sample_seed'])\n", (4045, 4157), False, 'from src.models.utils import sample_negative_class\n'), ((660, 684), 'os.getenv', 'os.getenv', (['"""CONFIG_PATH"""'], {}), "('CONFIG_PATH')\n", (669, 684), False, 'import os\n'), ((2940, 2985), 'neptunecontrib.monitoring.utils.pickle_and_send_artifact', 'pickle_and_send_artifact', (['clf', '"""lightgbm.pkl"""'], {}), "(clf, 'lightgbm.pkl')\n", (2964, 2985), False, 'from neptunecontrib.monitoring.utils import pickle_and_send_artifact\n'), ((4665, 4728), 'neptunecontrib.versioning.data.log_data_version', 'log_data_version', (['train_features_path'], {'prefix': '"""train_features_"""'}), "(train_features_path, prefix='train_features_')\n", (4681, 4728), False, 'from neptunecontrib.versioning.data import log_data_version\n'), ((4737, 4798), 'neptunecontrib.versioning.data.log_data_version', 'log_data_version', (['test_features_path'], {'prefix': '"""test_features_"""'}), "(test_features_path, prefix='test_features_')\n", (4753, 4798), False, 'from neptunecontrib.versioning.data import log_data_version\n'), ((5070, 5114), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (["train['isFraud']", 'train_preds'], {}), "(train['isFraud'], train_preds)\n", (5083, 5114), False, 'from sklearn.metrics import roc_auc_score\n'), ((5135, 5179), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (["valid['isFraud']", 'valid_preds'], {}), "(valid['isFraud'], valid_preds)\n", (5148, 5179), False, 'from sklearn.metrics import roc_auc_score\n'), ((5188, 5231), 'neptune.send_metric', 'neptune.send_metric', (['"""train_auc"""', 'train_auc'], {}), "('train_auc', train_auc)\n", (5207, 5231), False, 'import neptune\n'), ((5240, 5283), 'neptune.send_metric', 'neptune.send_metric', (['"""valid_auc"""', 'valid_auc'], {}), "('valid_auc', valid_auc)\n", (5259, 5283), False, 'import neptune\n'), ((6028, 6063), 'pandas.read_csv', 'pd.read_csv', (['SAMPLE_SUBMISSION_PATH'], {}), '(SAMPLE_SUBMISSION_PATH)\n', (6039, 6063), True, 'import pandas as pd\n'), ((6635, 6680), 'neptune.send_artifact', 'neptune.send_artifact', (['valid_predictions_path'], {}), '(valid_predictions_path)\n', (6656, 6680), False, 'import neptune\n'), ((6689, 6733), 'neptune.send_artifact', 'neptune.send_artifact', (['test_predictions_path'], {}), '(test_predictions_path)\n', (6710, 6733), False, 'import neptune\n'), ((6742, 6780), 'neptune.send_artifact', 'neptune.send_artifact', (['submission_path'], {}), '(submission_path)\n', (6763, 6780), False, 'import neptune\n'), ((2418, 2435), 'neptunecontrib.monitoring.lightgbm.neptune_monitor', 'neptune_monitor', ([], {}), '()\n', (2433, 2435), False, 'from neptunecontrib.monitoring.lightgbm import neptune_monitor\n'), ((6399, 6445), 'pandas.merge', 'pd.merge', (['submission', 'test'], {'on': '"""TransactionID"""'}), "(submission, test, on='TransactionID')\n", (6407, 6445), True, 'import pandas as pd\n'), ((4499, 4514), 'neptunecontrib.api.utils.get_filepaths', 'get_filepaths', ([], {}), '()\n', (4512, 4514), False, 'from neptunecontrib.api.utils import get_filepaths\n'), ((6099, 6178), 'pandas.DataFrame', 'pd.DataFrame', (["valid[['TransactionDT', 'TransactionID']]"], {'columns': "['prediction']"}), "(valid[['TransactionDT', 'TransactionID']], columns=['prediction'])\n", (6111, 6178), True, 'import pandas as pd\n'), ((6283, 6331), 'pandas.DataFrame', 'pd.DataFrame', (['test_preds'], {'columns': "['prediction']"}), "(test_preds, columns=['prediction'])\n", (6295, 6331), True, 'import pandas as pd\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from faker import Faker import neptune.new as neptune from neptune.new.project import Project from e2e_tests.base import BaseE2ETest from e2e_tests.utils import with_check_if_file_appears fake = Faker() class TestInitRun(BaseE2ETest): # TODO: test all remaining init parameters def test_resuming_run(self, environment): exp = neptune.init(project=environment.project) key = self.gen_key() val = fake.word() exp[key] = val exp.sync() exp.stop() # pylint: disable=protected-access exp2 = neptune.init(run=exp._short_id, project=environment.project) assert exp2[key].fetch() == val def test_custom_run_id(self, environment): custom_run_id = "-".join((fake.word() for _ in range(3))) run = neptune.init(custom_run_id=custom_run_id, project=environment.project) key = self.gen_key() val = fake.word() run[key] = val run.sync() run.stop() exp2 = neptune.init(custom_run_id=custom_run_id, project=environment.project) assert exp2[key].fetch() == val def test_send_source_code(self, environment): exp = neptune.init( source_files="**/*.py", name="E2e init source code", project=environment.project, ) # download sources exp.sync() with with_check_if_file_appears("files.zip"): exp["source_code/files"].download() class TestInitProject(BaseE2ETest): def test_resuming_project(self, environment): exp = neptune.init_project(name=environment.project) key = self.gen_key() val = fake.word() exp[key] = val exp.sync() exp.stop() exp2 = neptune.init_project(name=environment.project) assert exp2[key].fetch() == val def test_init_and_readonly(self, environment): project: Project = neptune.init_project(name=environment.project) key = f"{self.gen_key()}-" + "-".join((fake.word() for _ in range(4))) val = fake.word() project[key] = val project.sync() project.stop() read_only_project = neptune.get_project(name=environment.project) read_only_project.sync() assert set(read_only_project.get_structure()["sys"]) == { "creation_time", "id", "modification_time", "monitoring_time", "name", "ping_time", "running_time", "size", "state", "tags", "visibility", } assert read_only_project[key].fetch() == val
[ "neptune.new.get_project", "neptune.new.init", "neptune.new.init_project" ]
[((794, 801), 'faker.Faker', 'Faker', ([], {}), '()\n', (799, 801), False, 'from faker import Faker\n'), ((943, 984), 'neptune.new.init', 'neptune.init', ([], {'project': 'environment.project'}), '(project=environment.project)\n', (955, 984), True, 'import neptune.new as neptune\n'), ((1162, 1222), 'neptune.new.init', 'neptune.init', ([], {'run': 'exp._short_id', 'project': 'environment.project'}), '(run=exp._short_id, project=environment.project)\n', (1174, 1222), True, 'import neptune.new as neptune\n'), ((1391, 1461), 'neptune.new.init', 'neptune.init', ([], {'custom_run_id': 'custom_run_id', 'project': 'environment.project'}), '(custom_run_id=custom_run_id, project=environment.project)\n', (1403, 1461), True, 'import neptune.new as neptune\n'), ((1596, 1666), 'neptune.new.init', 'neptune.init', ([], {'custom_run_id': 'custom_run_id', 'project': 'environment.project'}), '(custom_run_id=custom_run_id, project=environment.project)\n', (1608, 1666), True, 'import neptune.new as neptune\n'), ((1772, 1871), 'neptune.new.init', 'neptune.init', ([], {'source_files': '"""**/*.py"""', 'name': '"""E2e init source code"""', 'project': 'environment.project'}), "(source_files='**/*.py', name='E2e init source code', project=\n environment.project)\n", (1784, 1871), True, 'import neptune.new as neptune\n'), ((2165, 2211), 'neptune.new.init_project', 'neptune.init_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2185, 2211), True, 'import neptune.new as neptune\n'), ((2346, 2392), 'neptune.new.init_project', 'neptune.init_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2366, 2392), True, 'import neptune.new as neptune\n'), ((2512, 2558), 'neptune.new.init_project', 'neptune.init_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2532, 2558), True, 'import neptune.new as neptune\n'), ((2767, 2812), 'neptune.new.get_project', 'neptune.get_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2786, 2812), True, 'import neptune.new as neptune\n'), ((1974, 2013), 'e2e_tests.utils.with_check_if_file_appears', 'with_check_if_file_appears', (['"""files.zip"""'], {}), "('files.zip')\n", (2000, 2013), False, 'from e2e_tests.utils import with_check_if_file_appears\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=protected-access import os import unittest from mock import patch from neptune.new import ANONYMOUS, init_model_version from neptune.new.attributes import String from neptune.new.envs import API_TOKEN_ENV_NAME, PROJECT_ENV_NAME from neptune.new.exceptions import ( NeptuneException, NeptuneOfflineModeChangeStageException, NeptuneWrongInitParametersException, ) from neptune.new.internal.backends.api_model import ( Attribute, AttributeType, IntAttribute, StringAttribute, ) from neptune.new.internal.backends.neptune_backend_mock import NeptuneBackendMock from neptune.new.internal.container_type import ContainerType from tests.neptune.new.client.abstract_experiment_test_mixin import ( AbstractExperimentTestMixin, ) from tests.neptune.new.utils.api_experiments_factory import api_model, api_model_version AN_API_MODEL = api_model() AN_API_MODEL_VERSION = api_model_version() @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container", new=lambda _, container_id, expected_container_type: AN_API_MODEL if expected_container_type == ContainerType.MODEL else AN_API_MODEL_VERSION, ) @patch("neptune.new.internal.backends.factory.HostedNeptuneBackend", NeptuneBackendMock) class TestClientModelVersion(AbstractExperimentTestMixin, unittest.TestCase): @staticmethod def call_init(**kwargs): return init_model_version(model="PRO-MOD", **kwargs) @classmethod def setUpClass(cls) -> None: os.environ[PROJECT_ENV_NAME] = "organization/project" os.environ[API_TOKEN_ENV_NAME] = ANONYMOUS def test_offline_mode(self): with self.assertRaises(NeptuneException): init_model_version(model="PRO-MOD", mode="offline") @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_attributes", new=lambda _, _uuid, _type: [ Attribute("some/variable", AttributeType.INT), Attribute("sys/model_id", AttributeType.STRING), ], ) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_int_attribute", new=lambda _, _uuid, _type, _path: IntAttribute(42), ) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_string_attribute", new=lambda _, _uuid, _type, _path: StringAttribute("MDL"), ) def test_read_only_mode(self): exp = init_model_version(mode="read-only", version="whatever") with self.assertLogs() as caplog: exp["some/variable"] = 13 exp["some/other_variable"] = 11 self.assertEqual( caplog.output, [ "WARNING:neptune.new.internal.operation_processors.read_only_operation_processor:" "Client in read-only mode, nothing will be saved to server." ], ) self.assertEqual(42, exp["some/variable"].fetch()) self.assertNotIn(str(exp._id), os.listdir(".neptune")) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_attributes", new=lambda _, _uuid, _type: [ Attribute("test", AttributeType.STRING), Attribute("sys/model_id", AttributeType.STRING), ], ) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_string_attribute", new=lambda _, _uuid, _type, _path: StringAttribute("MDL"), ) def test_resume(self): with init_model_version(flush_period=0.5, version="whatever") as exp: self.assertEqual(exp._id, AN_API_MODEL_VERSION.id) self.assertIsInstance(exp.get_structure()["test"], String) def test_sync_mode(self): AbstractExperimentTestMixin.test_sync_mode(self) def test_async_mode(self): AbstractExperimentTestMixin.test_async_mode(self) def test_wrong_parameters(self): with self.assertRaises(NeptuneWrongInitParametersException): init_model_version(version=None, model=None) def test_change_stage(self): exp = self.call_init() exp.change_stage(stage="production") self.assertEqual("production", exp["sys/stage"].fetch()) with self.assertRaises(ValueError): exp.change_stage(stage="wrong_stage") def test_change_stage_of_offline_model_version(self): # this test will be required when we decide that creating model versions # in offline mode is allowed with self.assertRaises(NeptuneException): exp = self.call_init(mode="offline") with self.assertRaises(NeptuneOfflineModeChangeStageException): exp.change_stage(stage="production") def test_name_parameter(self): with self.call_init(name="some_name") as exp: exp.wait() self.assertEqual(exp["sys/name"].fetch(), "some_name")
[ "neptune.new.init_model_version", "neptune.new.internal.backends.api_model.StringAttribute", "neptune.new.internal.backends.api_model.IntAttribute", "neptune.new.internal.backends.api_model.Attribute" ]
[((1474, 1485), 'tests.neptune.new.utils.api_experiments_factory.api_model', 'api_model', ([], {}), '()\n', (1483, 1485), False, 'from tests.neptune.new.utils.api_experiments_factory import api_model, api_model_version\n'), ((1509, 1528), 'tests.neptune.new.utils.api_experiments_factory.api_model_version', 'api_model_version', ([], {}), '()\n', (1526, 1528), False, 'from tests.neptune.new.utils.api_experiments_factory import api_model, api_model_version\n'), ((1532, 1791), 'mock.patch', 'patch', (['"""neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container"""'], {'new': '(lambda _, container_id, expected_container_type: AN_API_MODEL if \n expected_container_type == ContainerType.MODEL else AN_API_MODEL_VERSION)'}), "(\n 'neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container'\n , new=lambda _, container_id, expected_container_type: AN_API_MODEL if \n expected_container_type == ContainerType.MODEL else AN_API_MODEL_VERSION)\n", (1537, 1791), False, 'from mock import patch\n'), ((1797, 1888), 'mock.patch', 'patch', (['"""neptune.new.internal.backends.factory.HostedNeptuneBackend"""', 'NeptuneBackendMock'], {}), "('neptune.new.internal.backends.factory.HostedNeptuneBackend',\n NeptuneBackendMock)\n", (1802, 1888), False, 'from mock import patch\n'), ((2025, 2070), 'neptune.new.init_model_version', 'init_model_version', ([], {'model': '"""PRO-MOD"""'}), "(model='PRO-MOD', **kwargs)\n", (2043, 2070), False, 'from neptune.new import ANONYMOUS, init_model_version\n'), ((3081, 3137), 'neptune.new.init_model_version', 'init_model_version', ([], {'mode': '"""read-only"""', 'version': '"""whatever"""'}), "(mode='read-only', version='whatever')\n", (3099, 3137), False, 'from neptune.new import ANONYMOUS, init_model_version\n'), ((4425, 4473), 'tests.neptune.new.client.abstract_experiment_test_mixin.AbstractExperimentTestMixin.test_sync_mode', 'AbstractExperimentTestMixin.test_sync_mode', (['self'], {}), '(self)\n', (4467, 4473), False, 'from tests.neptune.new.client.abstract_experiment_test_mixin import AbstractExperimentTestMixin\n'), ((4514, 4563), 'tests.neptune.new.client.abstract_experiment_test_mixin.AbstractExperimentTestMixin.test_async_mode', 'AbstractExperimentTestMixin.test_async_mode', (['self'], {}), '(self)\n', (4557, 4563), False, 'from tests.neptune.new.client.abstract_experiment_test_mixin import AbstractExperimentTestMixin\n'), ((2331, 2382), 'neptune.new.init_model_version', 'init_model_version', ([], {'model': '"""PRO-MOD"""', 'mode': '"""offline"""'}), "(model='PRO-MOD', mode='offline')\n", (2349, 2382), False, 'from neptune.new import ANONYMOUS, init_model_version\n'), ((3658, 3680), 'os.listdir', 'os.listdir', (['""".neptune"""'], {}), "('.neptune')\n", (3668, 3680), False, 'import os\n'), ((4187, 4243), 'neptune.new.init_model_version', 'init_model_version', ([], {'flush_period': '(0.5)', 'version': '"""whatever"""'}), "(flush_period=0.5, version='whatever')\n", (4205, 4243), False, 'from neptune.new import ANONYMOUS, init_model_version\n'), ((4683, 4727), 'neptune.new.init_model_version', 'init_model_version', ([], {'version': 'None', 'model': 'None'}), '(version=None, model=None)\n', (4701, 4727), False, 'from neptune.new import ANONYMOUS, init_model_version\n'), ((2821, 2837), 'neptune.new.internal.backends.api_model.IntAttribute', 'IntAttribute', (['(42)'], {}), '(42)\n', (2833, 2837), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute, StringAttribute\n'), ((3002, 3024), 'neptune.new.internal.backends.api_model.StringAttribute', 'StringAttribute', (['"""MDL"""'], {}), "('MDL')\n", (3017, 3024), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute, StringAttribute\n'), ((4117, 4139), 'neptune.new.internal.backends.api_model.StringAttribute', 'StringAttribute', (['"""MDL"""'], {}), "('MDL')\n", (4132, 4139), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute, StringAttribute\n'), ((2542, 2587), 'neptune.new.internal.backends.api_model.Attribute', 'Attribute', (['"""some/variable"""', 'AttributeType.INT'], {}), "('some/variable', AttributeType.INT)\n", (2551, 2587), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute, StringAttribute\n'), ((2601, 2648), 'neptune.new.internal.backends.api_model.Attribute', 'Attribute', (['"""sys/model_id"""', 'AttributeType.STRING'], {}), "('sys/model_id', AttributeType.STRING)\n", (2610, 2648), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute, StringAttribute\n'), ((3841, 3880), 'neptune.new.internal.backends.api_model.Attribute', 'Attribute', (['"""test"""', 'AttributeType.STRING'], {}), "('test', AttributeType.STRING)\n", (3850, 3880), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute, StringAttribute\n'), ((3894, 3941), 'neptune.new.internal.backends.api_model.Attribute', 'Attribute', (['"""sys/model_id"""', 'AttributeType.STRING'], {}), "('sys/model_id', AttributeType.STRING)\n", (3903, 3941), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute, StringAttribute\n')]
import neptune.new as neptune import os import matplotlib.pyplot as plt # sgd 411, 412, 413 # adam 414, 415, 416 token = os.getenv('Neptune_api') run1 = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, run="AR1-439" ) # adam 1 adam1_rate = run1['network_ADAM/learning_rate'].fetch_values() adam1_weight = run1['network_ADAM/parameters/optimizer_weight_decay'].fetch() adam1_tp = run1['network_ADAM/matrix/val_tp_pr_file'].fetch_values() adam1_fp = run1['network_ADAM/matrix/val_fp_pr_file'].fetch_values() adam1_tn = run1['network_ADAM/matrix/val_tn_pr_file'].fetch_values() adam1_fn = run1['network_ADAM/matrix/val_fn_pr_file'].fetch_values() adam1_acc = run1['network_ADAM/val_acc_pr_file'].fetch_values() adam1_loss = run1['network_ADAM/validation_loss_pr_file'].fetch_values() adam1_smloss = run1['network_ADAM/smooth_val_loss_pr_file'].fetch_values() token = os.getenv('Neptune_api') run2 = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, run="AR1-440" ) # adam 2 adam2_rate = run2['network_ADAM/learning_rate'].fetch_values() adam2_weight = run2['network_ADAM/parameters/optimizer_weight_decay'].fetch() adam2_tp = run2['network_ADAM/matrix/val_tp_pr_file'].fetch_values() adam2_fp = run2['network_ADAM/matrix/val_fp_pr_file'].fetch_values() adam2_tn = run2['network_ADAM/matrix/val_tn_pr_file'].fetch_values() adam2_fn = run2['network_ADAM/matrix/val_fn_pr_file'].fetch_values() adam2_acc = run2['network_ADAM/val_acc_pr_file'].fetch_values() adam2_loss = run2['network_ADAM/validation_loss_pr_file'].fetch_values() adam2_smloss = run2['network_ADAM/smooth_val_loss_pr_file'].fetch_values() token = os.getenv('Neptune_api') run3 = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, run="AR1-441" ) # adam 3 adam3_rate = run3['network_ADAM/learning_rate'].fetch_values() adam3_weight = run3['network_ADAM/parameters/optimizer_weight_decay'].fetch() adam3_tp = run3['network_ADAM/matrix/val_tp_pr_file'].fetch_values() adam3_fp = run3['network_ADAM/matrix/val_fp_pr_file'].fetch_values() adam3_tn = run3['network_ADAM/matrix/val_tn_pr_file'].fetch_values() adam3_fn = run3['network_ADAM/matrix/val_fn_pr_file'].fetch_values() adam3_acc = run3['network_ADAM/val_acc_pr_file'].fetch_values() adam3_loss = run3['network_ADAM/validation_loss_pr_file'].fetch_values() adam3_smloss = run3['network_ADAM/smooth_val_loss_pr_file'].fetch_values() run1.stop() run2.stop() run3.stop() loss_y_range = [0.55, 0.85] momentum_y_range = [0.55, 1] acc_y_range = [-0.1, 1.1] lr_range = [-0.0001, 0.02] fig, ((ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9)) = plt.subplots(3, 3) ax1.set_title(f'ADAM optimizor with weight_decay of {adam1_weight}') ax1.plot(adam1_rate["value"]) ax1.set_ylim(lr_range) ax4.plot(adam1_tp["value"], label = "tp", color = "blue") ax4.plot(adam1_fp["value"], label = "fp", color = "gray") ax4.plot(adam1_tn["value"], label = "tn", color = "green") ax4.plot(adam1_fn["value"], label = "fn", color = "black") ax4.plot(adam1_acc["value"], label = "acc", color = "orange") ax4.set_ylim(acc_y_range) ax7.plot(adam1_loss["value"]) ax7.plot(adam1_smloss["value"]) ax7.set_ylim(loss_y_range) ax2.set_title(f'ADAM optimizor with weight_decay of {adam2_weight}') ax2.plot(adam2_rate["value"]) ax2.set_ylim(lr_range) ax5.plot(adam2_tp["value"], label = "tp", color = "blue") ax5.plot(adam2_fp["value"], label = "fp", color = "gray") ax5.plot(adam2_tn["value"], label = "tn", color = "green") ax5.plot(adam2_fn["value"], label = "fn", color = "black") ax5.plot(adam2_acc["value"], label = "acc", color = "orange") ax5.set_ylim(acc_y_range) ax8.plot(adam2_loss["value"]) ax8.plot(adam2_smloss["value"]) ax8.set_ylim(loss_y_range) ax3.set_title(f'ADAM optimizor with weight_decay of {adam3_weight}') ax3.plot(adam3_rate["value"]) ax3.set_ylim(lr_range) ax6.plot(adam3_tp["value"], label = "tp", color = "blue") ax6.plot(adam3_fp["value"], label = "fp", color = "gray") ax6.plot(adam3_tn["value"], label = "tn", color = "green") ax6.plot(adam3_fn["value"], label = "fn", color = "black") ax6.plot(adam3_acc["value"], label = "acc", color = "orange") ax6.set_ylim(acc_y_range) ax9.plot(adam3_loss["value"]) ax9.plot(adam3_smloss["value"]) ax9.set_ylim(loss_y_range) fig.tight_layout(pad=2.0) plt.show()
[ "neptune.new.init" ]
[((124, 148), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (133, 148), False, 'import os\n'), ((156, 241), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token', 'run': '"""AR1-439"""'}), "(project='NTLAB/artifact-rej-scalp', api_token=token, run='AR1-439'\n )\n", (168, 241), True, 'import neptune.new as neptune\n'), ((900, 924), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (909, 924), False, 'import os\n'), ((932, 1017), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token', 'run': '"""AR1-440"""'}), "(project='NTLAB/artifact-rej-scalp', api_token=token, run='AR1-440'\n )\n", (944, 1017), True, 'import neptune.new as neptune\n'), ((1677, 1701), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (1686, 1701), False, 'import os\n'), ((1709, 1794), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token', 'run': '"""AR1-441"""'}), "(project='NTLAB/artifact-rej-scalp', api_token=token, run='AR1-441'\n )\n", (1721, 1794), True, 'import neptune.new as neptune\n'), ((2656, 2674), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(3)'], {}), '(3, 3)\n', (2668, 2674), True, 'import matplotlib.pyplot as plt\n'), ((4314, 4324), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4322, 4324), True, 'import matplotlib.pyplot as plt\n')]
import hashlib import os import tempfile import matplotlib.pyplot as plt import neptune import numpy as np import optuna import tensorflow as tf from tensorflow import keras def log_data(logs): neptune.log_metric('epoch_accuracy', logs['accuracy']) neptune.log_metric('epoch_loss', logs['loss']) def train_evaluate(params): def lr_scheduler(epoch): if epoch < 20: new_lr = params['learning_rate'] else: new_lr = params['learning_rate'] * np.exp(0.05 * (20 - epoch)) neptune.log_metric('learning_rate', new_lr) return new_lr # clear session tf.keras.backend.clear_session() # create experiment neptune.create_experiment(name='optuna_example', tags=['optuna'], upload_source_files=['optuna-example.py', 'requirements.txt'], params=params) neptune.set_property('train_images_version', hashlib.md5(train_images).hexdigest()) neptune.set_property('train_labels_version', hashlib.md5(train_labels).hexdigest()) neptune.set_property('test_images_version', hashlib.md5(test_images).hexdigest()) neptune.set_property('test_labels_version', hashlib.md5(test_labels).hexdigest()) neptune.set_property('class_names', class_names) for j, class_name in enumerate(class_names): plt.figure(figsize=(10, 10)) label_ = np.where(train_labels == j) for i in range(9): plt.subplot(3, 3, i + 1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[label_[0][i]], cmap=plt.cm.binary) plt.xlabel(class_names[j]) neptune.log_image('example_images', plt.gcf()) plt.close('all') # model model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(params['dense_units'], activation=params['activation']), keras.layers.Dropout(params['dropout']), keras.layers.Dense(params['dense_units'], activation=params['activation']), keras.layers.Dropout(params['dropout']), keras.layers.Dense(params['dense_units'], activation=params['activation']), keras.layers.Dropout(params['dropout']), keras.layers.Dense(10, activation='softmax') ]) if params['optimizer'] == 'Adam': optimizer = tf.keras.optimizers.Adam( learning_rate=params['learning_rate'], ) elif params['optimizer'] == 'Nadam': optimizer = tf.keras.optimizers.Nadam( learning_rate=params['learning_rate'], ) elif params['optimizer'] == 'SGD': optimizer = tf.keras.optimizers.SGD( learning_rate=params['learning_rate'], ) model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy']) # log model summary model.summary(print_fn=lambda x: neptune.log_text('model_summary', x)) # train model model.fit(train_images, train_labels, batch_size=params['batch_size'], epochs=params['n_epochs'], shuffle=params['shuffle'], callbacks=[keras.callbacks.LambdaCallback(on_epoch_end=lambda epoch, logs: log_data(logs)), keras.callbacks.EarlyStopping(patience=params['early_stopping'], monitor='accuracy', restore_best_weights=True), keras.callbacks.LearningRateScheduler(lr_scheduler)] ) # log model weights with tempfile.TemporaryDirectory(dir='.') as d: prefix = os.path.join(d, 'model_weights') model.save_weights(os.path.join(prefix, 'model')) for item in os.listdir(prefix): neptune.log_artifact(os.path.join(prefix, item), os.path.join('model_weights', item)) # evaluate model eval_metrics = model.evaluate(test_images, test_labels, verbose=0) for j, metric in enumerate(eval_metrics): neptune.log_metric('eval_' + model.metrics_names[j], metric) if model.metrics_names[j] == 'accuracy': score = metric neptune.stop() return score def objective(trial): optuna_params = {'batch_size': trial.suggest_categorical('batch_size', [32, 64]), 'activation': trial.suggest_categorical('activation', ['relu', 'elu']), 'learning_rate': trial.suggest_loguniform('learning_rate', 0.0001, 0.1), 'optimizer': trial.suggest_categorical('optimizer', ['Adam', 'Nadam', 'SGD']), 'dense_units': trial.suggest_categorical('dense_units', [16, 32, 64, 128]), 'dropout': trial.suggest_uniform('dropout', 0, 0.5), } PARAMS = {**optuna_params, **STATIC_PARAMS} return train_evaluate(PARAMS) # static params STATIC_PARAMS = {'n_epochs': 100, 'shuffle': True, 'early_stopping': 10, } # dataset fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() train_images = train_images / 255.0 test_images = test_images / 255.0 class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # select project neptune.init('USERNAME/example-project') # make optuna study study = optuna.create_study(study_name='classification', direction='maximize', storage='sqlite:///classification.db', load_if_exists=True) study.optimize(objective, n_trials=100) # run experiment that collects study visuals neptune.create_experiment(name='optuna_summary', tags=['optuna', 'optuna-summary'], upload_source_files=['optuna-example.py', 'requirements.txt']) neptune.log_metric('optuna_best_score', study.best_value) neptune.set_property('optuna_best_parameters', study.best_params) neptune.log_artifact('classification.db', 'classification.db') neptune.stop()
[ "neptune.log_metric", "neptune.create_experiment", "neptune.set_property", "neptune.init", "neptune.log_text", "neptune.stop", "neptune.log_artifact" ]
[((5519, 5559), 'neptune.init', 'neptune.init', (['"""USERNAME/example-project"""'], {}), "('USERNAME/example-project')\n", (5531, 5559), False, 'import neptune\n'), ((5589, 5723), 'optuna.create_study', 'optuna.create_study', ([], {'study_name': '"""classification"""', 'direction': '"""maximize"""', 'storage': '"""sqlite:///classification.db"""', 'load_if_exists': '(True)'}), "(study_name='classification', direction='maximize',\n storage='sqlite:///classification.db', load_if_exists=True)\n", (5608, 5723), False, 'import optuna\n'), ((5890, 6044), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""optuna_summary"""', 'tags': "['optuna', 'optuna-summary']", 'upload_source_files': "['optuna-example.py', 'requirements.txt']"}), "(name='optuna_summary', tags=['optuna',\n 'optuna-summary'], upload_source_files=['optuna-example.py',\n 'requirements.txt'])\n", (5915, 6044), False, 'import neptune\n'), ((6089, 6146), 'neptune.log_metric', 'neptune.log_metric', (['"""optuna_best_score"""', 'study.best_value'], {}), "('optuna_best_score', study.best_value)\n", (6107, 6146), False, 'import neptune\n'), ((6147, 6212), 'neptune.set_property', 'neptune.set_property', (['"""optuna_best_parameters"""', 'study.best_params'], {}), "('optuna_best_parameters', study.best_params)\n", (6167, 6212), False, 'import neptune\n'), ((6213, 6275), 'neptune.log_artifact', 'neptune.log_artifact', (['"""classification.db"""', '"""classification.db"""'], {}), "('classification.db', 'classification.db')\n", (6233, 6275), False, 'import neptune\n'), ((6276, 6290), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (6288, 6290), False, 'import neptune\n'), ((201, 255), 'neptune.log_metric', 'neptune.log_metric', (['"""epoch_accuracy"""', "logs['accuracy']"], {}), "('epoch_accuracy', logs['accuracy'])\n", (219, 255), False, 'import neptune\n'), ((260, 306), 'neptune.log_metric', 'neptune.log_metric', (['"""epoch_loss"""', "logs['loss']"], {}), "('epoch_loss', logs['loss'])\n", (278, 306), False, 'import neptune\n'), ((623, 655), 'tensorflow.keras.backend.clear_session', 'tf.keras.backend.clear_session', ([], {}), '()\n', (653, 655), True, 'import tensorflow as tf\n'), ((685, 837), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': '"""optuna_example"""', 'tags': "['optuna']", 'upload_source_files': "['optuna-example.py', 'requirements.txt']", 'params': 'params'}), "(name='optuna_example', tags=['optuna'],\n upload_source_files=['optuna-example.py', 'requirements.txt'], params=\n params)\n", (710, 837), False, 'import neptune\n'), ((1272, 1320), 'neptune.set_property', 'neptune.set_property', (['"""class_names"""', 'class_names'], {}), "('class_names', class_names)\n", (1292, 1320), False, 'import neptune\n'), ((4305, 4319), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (4317, 4319), False, 'import neptune\n'), ((532, 575), 'neptune.log_metric', 'neptune.log_metric', (['"""learning_rate"""', 'new_lr'], {}), "('learning_rate', new_lr)\n", (550, 575), False, 'import neptune\n'), ((1379, 1407), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (1389, 1407), True, 'import matplotlib.pyplot as plt\n'), ((1425, 1452), 'numpy.where', 'np.where', (['(train_labels == j)'], {}), '(train_labels == j)\n', (1433, 1452), True, 'import numpy as np\n'), ((1772, 1788), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (1781, 1788), True, 'import matplotlib.pyplot as plt\n'), ((2403, 2466), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': "params['learning_rate']"}), "(learning_rate=params['learning_rate'])\n", (2427, 2466), True, 'import tensorflow as tf\n'), ((3694, 3730), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {'dir': '"""."""'}), "(dir='.')\n", (3721, 3730), False, 'import tempfile\n'), ((3754, 3786), 'os.path.join', 'os.path.join', (['d', '"""model_weights"""'], {}), "(d, 'model_weights')\n", (3766, 3786), False, 'import os\n'), ((3865, 3883), 'os.listdir', 'os.listdir', (['prefix'], {}), '(prefix)\n', (3875, 3883), False, 'import os\n'), ((4163, 4223), 'neptune.log_metric', 'neptune.log_metric', (["('eval_' + model.metrics_names[j])", 'metric'], {}), "('eval_' + model.metrics_names[j], metric)\n", (4181, 4223), False, 'import neptune\n'), ((1492, 1516), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(3)', '(i + 1)'], {}), '(3, 3, i + 1)\n', (1503, 1516), True, 'import matplotlib.pyplot as plt\n'), ((1529, 1543), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (1539, 1543), True, 'import matplotlib.pyplot as plt\n'), ((1556, 1570), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (1566, 1570), True, 'import matplotlib.pyplot as plt\n'), ((1583, 1598), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (1591, 1598), True, 'import matplotlib.pyplot as plt\n'), ((1611, 1669), 'matplotlib.pyplot.imshow', 'plt.imshow', (['train_images[label_[0][i]]'], {'cmap': 'plt.cm.binary'}), '(train_images[label_[0][i]], cmap=plt.cm.binary)\n', (1621, 1669), True, 'import matplotlib.pyplot as plt\n'), ((1682, 1708), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['class_names[j]'], {}), '(class_names[j])\n', (1692, 1708), True, 'import matplotlib.pyplot as plt\n'), ((1753, 1762), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (1760, 1762), True, 'import matplotlib.pyplot as plt\n'), ((1841, 1883), 'tensorflow.keras.layers.Flatten', 'keras.layers.Flatten', ([], {'input_shape': '(28, 28)'}), '(input_shape=(28, 28))\n', (1861, 1883), False, 'from tensorflow import keras\n'), ((1893, 1967), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (["params['dense_units']"], {'activation': "params['activation']"}), "(params['dense_units'], activation=params['activation'])\n", (1911, 1967), False, 'from tensorflow import keras\n'), ((1977, 2016), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (["params['dropout']"], {}), "(params['dropout'])\n", (1997, 2016), False, 'from tensorflow import keras\n'), ((2026, 2100), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (["params['dense_units']"], {'activation': "params['activation']"}), "(params['dense_units'], activation=params['activation'])\n", (2044, 2100), False, 'from tensorflow import keras\n'), ((2110, 2149), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (["params['dropout']"], {}), "(params['dropout'])\n", (2130, 2149), False, 'from tensorflow import keras\n'), ((2159, 2233), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (["params['dense_units']"], {'activation': "params['activation']"}), "(params['dense_units'], activation=params['activation'])\n", (2177, 2233), False, 'from tensorflow import keras\n'), ((2243, 2282), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (["params['dropout']"], {}), "(params['dropout'])\n", (2263, 2282), False, 'from tensorflow import keras\n'), ((2292, 2336), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(10)'], {'activation': '"""softmax"""'}), "(10, activation='softmax')\n", (2310, 2336), False, 'from tensorflow import keras\n'), ((2551, 2615), 'tensorflow.keras.optimizers.Nadam', 'tf.keras.optimizers.Nadam', ([], {'learning_rate': "params['learning_rate']"}), "(learning_rate=params['learning_rate'])\n", (2576, 2615), True, 'import tensorflow as tf\n'), ((3814, 3843), 'os.path.join', 'os.path.join', (['prefix', '"""model"""'], {}), "(prefix, 'model')\n", (3826, 3843), False, 'import os\n'), ((495, 522), 'numpy.exp', 'np.exp', (['(0.05 * (20 - epoch))'], {}), '(0.05 * (20 - epoch))\n', (501, 522), True, 'import numpy as np\n'), ((969, 994), 'hashlib.md5', 'hashlib.md5', (['train_images'], {}), '(train_images)\n', (980, 994), False, 'import hashlib\n'), ((1057, 1082), 'hashlib.md5', 'hashlib.md5', (['train_labels'], {}), '(train_labels)\n', (1068, 1082), False, 'import hashlib\n'), ((1144, 1168), 'hashlib.md5', 'hashlib.md5', (['test_images'], {}), '(test_images)\n', (1155, 1168), False, 'import hashlib\n'), ((1230, 1254), 'hashlib.md5', 'hashlib.md5', (['test_labels'], {}), '(test_labels)\n', (1241, 1254), False, 'import hashlib\n'), ((2698, 2760), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'learning_rate': "params['learning_rate']"}), "(learning_rate=params['learning_rate'])\n", (2721, 2760), True, 'import tensorflow as tf\n'), ((2984, 3020), 'neptune.log_text', 'neptune.log_text', (['"""model_summary"""', 'x'], {}), "('model_summary', x)\n", (3000, 3020), False, 'import neptune\n'), ((3343, 3459), 'tensorflow.keras.callbacks.EarlyStopping', 'keras.callbacks.EarlyStopping', ([], {'patience': "params['early_stopping']", 'monitor': '"""accuracy"""', 'restore_best_weights': '(True)'}), "(patience=params['early_stopping'], monitor=\n 'accuracy', restore_best_weights=True)\n", (3372, 3459), False, 'from tensorflow import keras\n'), ((3591, 3642), 'tensorflow.keras.callbacks.LearningRateScheduler', 'keras.callbacks.LearningRateScheduler', (['lr_scheduler'], {}), '(lr_scheduler)\n', (3628, 3642), False, 'from tensorflow import keras\n'), ((3918, 3944), 'os.path.join', 'os.path.join', (['prefix', 'item'], {}), '(prefix, item)\n', (3930, 3944), False, 'import os\n'), ((3979, 4014), 'os.path.join', 'os.path.join', (['"""model_weights"""', 'item'], {}), "('model_weights', item)\n", (3991, 4014), False, 'import os\n')]
import torch import torch.nn as nn from torch.distributions import Categorical import numpy as np import gym import lolgym.envs from pylol.lib import actions, features, point from pylol.lib import point from absl import flags FLAGS = flags.FLAGS _NO_OP = [actions.FUNCTIONS.no_op.id] _MOVE = [actions.FUNCTIONS.move.id] _SPELL = [actions.FUNCTIONS.spell.id] import gym from gym.spaces import Box, Tuple, Discrete, Dict, MultiDiscrete from dotenv import dotenv_values import neptune.new as neptune from absl import flags from absl import app FLAGS = flags.FLAGS flags.DEFINE_string("config_dirs", "/mnt/c/Users/win8t/Desktop/pylol/config.txt", "Path to file containing GameServer and LoL Client directories") flags.DEFINE_string("host", "192.168.0.16", "Host IP for GameServer, LoL Client and Redis") flags.DEFINE_integer("epochs", 50, "Number of episodes to run the experiment for") flags.DEFINE_float("step_multiplier", 1.0, "Run game server x times faster than real-time") flags.DEFINE_bool("run_client", False, "Controls whether the game client is run or not") flags.DEFINE_integer("max_steps", 25, "Maximum number of steps per episode") # (Optional) Initialises Neptune.ai logging log = False config = dotenv_values(".env") if "NEPTUNE_PROJECT" in config and "NEPTUNE_TOKEN" in config: if config["NEPTUNE_PROJECT"] and config["NEPTUNE_TOKEN"]: run = neptune.init( project=config["NEPTUNE_PROJECT"], api_token=config["NEPTUNE_TOKEN"]) log = True # Use GPU if available if (torch.cuda.is_available()): device = torch.device("cuda:0") torch.cuda.empty_cache() print("Device set to:", torch.cuda.get_device_name(device)) else: device = torch.device("cpu") print("Device set to: CPU") class RolloutBuffer(object): def __init__(self): self.actions = [] self.states = [] self.logprobs = [] self.rewards = [] self.is_terminals = [] def clear(self): del self.actions[:] del self.states[:] del self.logprobs[:] del self.rewards[:] del self.is_terminals[:] class ActorCritic(nn.Module): def __init__(self, state_dim, action_dim): super(ActorCritic, self).__init__() self.actor = nn.Sequential( nn.Linear(state_dim.shape[0], 1), nn.Tanh(), nn.Linear(1, action_dim.n), nn.Softmax(dim=-1) ) self.critic = nn.Sequential( nn.Linear(state_dim.shape[0], 1), nn.Tanh(), nn.Linear(1, 1) ) def act(self, state): action_probs = self.actor(state) dist = Categorical(action_probs) action = dist.sample() action_logprob = dist.log_prob(action) action = action.detach() action_logprob = action_logprob.detach() if log: if action == 0: run['action_left_logprob'].log(action_logprob) else: run['action_right_logprob'].log(action_logprob) return action.detach(), action_logprob.detach() def eval(self, state, action): action_probs = self.actor(state) dist = Categorical(action_probs) action_logprob = dist.log_prob(action) dist_entropy = dist.entropy() state_values = self.critic(state) return action_logprob, dist_entropy, state_values class PPO(object): def __init__(self, state_dim, action_dim, lr_actor, lr_critic, gamma, K_epochs, eps_clip): self.gamma = gamma self.eps_clip = eps_clip self.K_epochs = K_epochs self.buffer = RolloutBuffer() self.policy = ActorCritic(state_dim, action_dim).to(device) self.optimizer = torch.optim.Adam([ {'params': self.policy.actor.parameters(), 'lr': lr_actor}, {'params': self.policy.critic.parameters(), 'lr': lr_critic} ]) self.policy_old = ActorCritic(state_dim, action_dim).to(device) self.policy_old.load_state_dict(self.policy.state_dict()) self.MseLoss = nn.MSELoss() def forward(self): raise NotImplementedError def act(self, state): with torch.no_grad(): state = torch.FloatTensor(state).to(device) action, action_logprob = self.policy_old.act(state) self.buffer.states.append(state) self.buffer.actions.append(action) self.buffer.logprobs.append(action_logprob) return action.item() def update(self): # Monte Carlo estimate of rewards rews = [] discounted_rew = 0 for rew, is_terminal in zip(reversed(self.buffer.rewards), reversed(self.buffer.is_terminals)): if is_terminal: discounted_rew = 0 discounted_rew = rew + (self.gamma + discounted_rew) rews.insert(0, discounted_rew) # Normalizing the rewards rews = torch.tensor(rews, dtype=torch.float32).to(device) rews = (rews - rews.mean()) / (rews.std() + 1e-7) # Convert list to tensor old_states = torch.squeeze(torch.stack(self.buffer.states, dim=0)).detach().to(device) old_actions = torch.squeeze(torch.stack(self.buffer.actions, dim=0)).detach().to(device) old_logprobs = torch.squeeze(torch.stack(self.buffer.logprobs, dim=0)).detach().to(device) old_states = torch.unsqueeze(old_states, 1) print('[UPDATE] old_states:', old_states, old_states.shape) # Optimize policy for K epochs for _ in range(self.K_epochs): # Eval old actions and values logprobs, state_values, dist_entropy = self.policy.eval(old_states, old_actions) # Match state_values tensor dims with rews tensor state_values = torch.squeeze(state_values) # Find the ratio (pi_theta / pi_theta__old) ratios = torch.exp(logprobs - old_logprobs.detach()) # Finding surrogate loss advantages = rews - state_values.detach() surr1 = ratios * advantages surr2 = torch.clamp(ratios, 1-self.eps_clip, 1+self.eps_clip) * advantages # Final loss of clipped objective PPO loss = -torch.min(surr1, surr2) + 0.5 * self.MseLoss(state_values, rews) - 0.01 * dist_entropy if log: run["policy_loss"].log(loss.mean()) # Take gradient step self.optimizer.zero_grad() loss.mean().backward() self.optimizer.step() # Copy new weights into old policy self.policy_old.load_state_dict(self.policy.state_dict()) # Clear buffer self.buffer.clear() def save(self, checkpoint_path): torch.save(self.policy_old.state_dict(), checkpoint_path) def load(self, checkpoint_path): self.policy_old.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage)) self.policy.load_state_dict(torch.load(checkpoint_path, map_location=lambda storage, loc: storage)) def convert_action(raw_obs, act): act_x = 8 if act else 0 act_y = 4 target_pos = point.Point(raw_obs[0].observation["me_unit"].position_x, raw_obs[0].observation["me_unit"].position_y) act = [ [1, point.Point(act_x, act_y)], _NO_OP # _SPELL + [[0], target_pos] ] return act def test(host, epochs, max_steps, obs_space, act_space, lr_actor, lr_critic, model_path): # Initialize gym environment env_name = "LoLGame-v0" env = gym.make(env_name) env.settings["map_name"] = "Old Summoners Rift" env.settings["human_observer"] = FLAGS.run_client # Set to true to run league client env.settings["host"] = host # Set this using "hostname -i" ip on Linux env.settings["players"] = "Ezreal.BLUE,Ezreal.PURPLE" env.settings["config_path"] = FLAGS.config_dirs env.settings["step_multiplier"] = FLAGS.step_multiplier # Initialize actor-critic agent eps_clip = 0.2 gamma = 0.99 K_epochs = 1 # Originaly 80 agent = PPO(obs_space, act_space, lr_actor, lr_critic, gamma, K_epochs, eps_clip) # Load pre-trained model agent.load(model_path) total_steps = 0 for epoch in range(epochs): obs = env.reset() env.teleport(1, point.Point(7100.0, 7000.0)) env.teleport(2, point.Point(7500.0, 7000.0)) raw_obs = obs obs = np.array(raw_obs[0].observation["enemy_unit"].distance_to_me)[None] rews = [] steps = 0 while True: steps += 1 total_steps += 1 # Select action with policy act = agent.act(obs[None]) # NOTE: arr[None] wraps arr in another [] act = convert_action(raw_obs, act) obs, rew, done, _ = env.step(act) raw_obs = obs obs = np.array(raw_obs[0].observation["enemy_unit"].distance_to_me)[None] # Extract distance from rews #rews = [ob[0] / 1000.0 for ob in obs] rew = +(raw_obs[0].observation["enemy_unit"].distance_to_me / 1000.0) rews.append(rew) # Break if episode is over if any(done) or steps == max_steps: # Announce episode number and rew env.broadcast_msg(f"episode No: {epoch}, rew: {sum(rews)}") # Break break rews = [] # Close environment env.close() def train(host, epochs, max_steps, obs_space, act_space, lr_actor, lr_critic): # Initialize gym environment env_name = "LoLGame-v0" env = gym.make(env_name) env.settings["map_name"] = "Old Summoners Rift" env.settings["human_observer"] = FLAGS.run_client # Set to true to run league client env.settings["host"] = host # Set this using "hostname -i" ip on Linux env.settings["players"] = "Ezreal.BLUE,Ezreal.PURPLE" env.settings["config_path"] = FLAGS.config_dirs env.settings["step_multiplier"] = FLAGS.step_multiplier # Initialize actor-critic agent eps_clip = 0.2 gamma = 0.99 K_epochs = 80 # K_epochs = 1 # Originaly 80 agent = PPO(obs_space, act_space, lr_actor, lr_critic, gamma, K_epochs, eps_clip) run["K_epochs"] = K_epochs # Training process update_step = max_steps * 1 # Random seed random_seed = 0 if random_seed: torch.manual_seed(random_seed) env.seed(random_seed) np.random.seed(random_seed) # Checkpoint checkpoint_path = "PPO_{}_{}_.pth".format(env_name, random_seed) total_steps = 0 for epoch in range(FLAGS.epochs): steps = 0 obs = env.reset() env.teleport(1, point.Point(7100.0, 7000.0)) env.teleport(2, point.Point(7500.0, 7000.0)) raw_obs = obs obs = np.array(raw_obs[0].observation["enemy_unit"].distance_to_me)[None] print(f'obs: {epoch}, step: 0') rews = [] steps = 0 while True: steps += 1 total_steps += 1 print(f'obs: {epoch}, step: {steps}') # Select action with policy act = agent.act(obs[None]) # NOTE: arr[None] wraps arr in another [] act = convert_action(raw_obs, act) obs, rew, done, _ = env.step(act) raw_obs = obs obs = np.array(raw_obs[0].observation["enemy_unit"].distance_to_me)[None] # Extract distance from rews #rews = [ob[0] / 1000.0 for ob in obs] rew = +(raw_obs[0].observation["enemy_unit"].distance_to_me / 1000.0) rews.append(rew) # Saving reward and is_terminals agent.buffer.rewards.append(rew) agent.buffer.is_terminals.append(done[0]) # Update PPO agent if total_steps % update_step == 0: agent.update() agent.save(checkpoint_path) # Break if episode is over if any(done) or steps == max_steps: # Announce episode number and rew env.broadcast_msg(f"episode No: {epoch}, rew: {sum(rews)}") if log: run["reward"].log(sum(rews)) # Break break rews = [] # Close environment env.close() def main(unused_argv): obs_space = Box(low=0, high=24000, shape=(1,), dtype=np.float32) act_space = Discrete(2) # lr_actor = 0.0003 lr_actor = 0.003 #lr_critic = 0.001 lr_critic = 0.01 if log: run["lr_actor"] = lr_actor run["lr_critic"] = lr_critic host = FLAGS.host epochs = FLAGS.epochs max_steps = FLAGS.max_steps # Checkpoint train(host, epochs, max_steps, obs_space, act_space, lr_actor, lr_critic) # checkpoint_path = "PPO_LoLGame-v0_0_200epochs.pth" # test(host, epochs, max_steps, obs_space, act_space, lr_actor, lr_critic, checkpoint_path) def entry_point(): app.run(main) if __name__ == "__main__": app.run(main)
[ "neptune.new.init" ]
[((595, 749), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""config_dirs"""', '"""/mnt/c/Users/win8t/Desktop/pylol/config.txt"""', '"""Path to file containing GameServer and LoL Client directories"""'], {}), "('config_dirs',\n '/mnt/c/Users/win8t/Desktop/pylol/config.txt',\n 'Path to file containing GameServer and LoL Client directories')\n", (614, 749), False, 'from absl import flags\n'), ((743, 838), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""host"""', '"""192.168.0.16"""', '"""Host IP for GameServer, LoL Client and Redis"""'], {}), "('host', '192.168.0.16',\n 'Host IP for GameServer, LoL Client and Redis')\n", (762, 838), False, 'from absl import flags\n'), ((836, 922), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""epochs"""', '(50)', '"""Number of episodes to run the experiment for"""'], {}), "('epochs', 50,\n 'Number of episodes to run the experiment for')\n", (856, 922), False, 'from absl import flags\n'), ((920, 1015), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""step_multiplier"""', '(1.0)', '"""Run game server x times faster than real-time"""'], {}), "('step_multiplier', 1.0,\n 'Run game server x times faster than real-time')\n", (938, 1015), False, 'from absl import flags\n'), ((1013, 1105), 'absl.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""run_client"""', '(False)', '"""Controls whether the game client is run or not"""'], {}), "('run_client', False,\n 'Controls whether the game client is run or not')\n", (1030, 1105), False, 'from absl import flags\n'), ((1103, 1179), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""max_steps"""', '(25)', '"""Maximum number of steps per episode"""'], {}), "('max_steps', 25, 'Maximum number of steps per episode')\n", (1123, 1179), False, 'from absl import flags\n'), ((1250, 1271), 'dotenv.dotenv_values', 'dotenv_values', (['""".env"""'], {}), "('.env')\n", (1263, 1271), False, 'from dotenv import dotenv_values\n'), ((1574, 1599), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1597, 1599), False, 'import torch\n'), ((1616, 1638), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (1628, 1638), False, 'import torch\n'), ((1644, 1668), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (1666, 1668), False, 'import torch\n'), ((1755, 1774), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1767, 1774), False, 'import torch\n'), ((7375, 7483), 'pylol.lib.point.Point', 'point.Point', (["raw_obs[0].observation['me_unit'].position_x", "raw_obs[0].observation['me_unit'].position_y"], {}), "(raw_obs[0].observation['me_unit'].position_x, raw_obs[0].\n observation['me_unit'].position_y)\n", (7386, 7483), False, 'from pylol.lib import point\n'), ((7803, 7821), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (7811, 7821), False, 'import gym\n'), ((9941, 9959), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (9949, 9959), False, 'import gym\n'), ((12780, 12832), 'gym.spaces.Box', 'Box', ([], {'low': '(0)', 'high': '(24000)', 'shape': '(1,)', 'dtype': 'np.float32'}), '(low=0, high=24000, shape=(1,), dtype=np.float32)\n', (12783, 12832), False, 'from gym.spaces import Box, Tuple, Discrete, Dict, MultiDiscrete\n'), ((12850, 12861), 'gym.spaces.Discrete', 'Discrete', (['(2)'], {}), '(2)\n', (12858, 12861), False, 'from gym.spaces import Box, Tuple, Discrete, Dict, MultiDiscrete\n'), ((13420, 13433), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (13427, 13433), False, 'from absl import app\n'), ((13469, 13482), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (13476, 13482), False, 'from absl import app\n'), ((1413, 1500), 'neptune.new.init', 'neptune.init', ([], {'project': "config['NEPTUNE_PROJECT']", 'api_token': "config['NEPTUNE_TOKEN']"}), "(project=config['NEPTUNE_PROJECT'], api_token=config[\n 'NEPTUNE_TOKEN'])\n", (1425, 1500), True, 'import neptune.new as neptune\n'), ((1698, 1732), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', (['device'], {}), '(device)\n', (1724, 1732), False, 'import torch\n'), ((2735, 2760), 'torch.distributions.Categorical', 'Categorical', (['action_probs'], {}), '(action_probs)\n', (2746, 2760), False, 'from torch.distributions import Categorical\n'), ((3280, 3305), 'torch.distributions.Categorical', 'Categorical', (['action_probs'], {}), '(action_probs)\n', (3291, 3305), False, 'from torch.distributions import Categorical\n'), ((4201, 4213), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (4211, 4213), True, 'import torch.nn as nn\n'), ((5554, 5584), 'torch.unsqueeze', 'torch.unsqueeze', (['old_states', '(1)'], {}), '(old_states, 1)\n', (5569, 5584), False, 'import torch\n'), ((10730, 10760), 'torch.manual_seed', 'torch.manual_seed', (['random_seed'], {}), '(random_seed)\n', (10747, 10760), False, 'import torch\n'), ((10801, 10828), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (10815, 10828), True, 'import numpy as np\n'), ((2357, 2389), 'torch.nn.Linear', 'nn.Linear', (['state_dim.shape[0]', '(1)'], {}), '(state_dim.shape[0], 1)\n', (2366, 2389), True, 'import torch.nn as nn\n'), ((2404, 2413), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (2411, 2413), True, 'import torch.nn as nn\n'), ((2428, 2454), 'torch.nn.Linear', 'nn.Linear', (['(1)', 'action_dim.n'], {}), '(1, action_dim.n)\n', (2437, 2454), True, 'import torch.nn as nn\n'), ((2469, 2487), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (2479, 2487), True, 'import torch.nn as nn\n'), ((2550, 2582), 'torch.nn.Linear', 'nn.Linear', (['state_dim.shape[0]', '(1)'], {}), '(state_dim.shape[0], 1)\n', (2559, 2582), True, 'import torch.nn as nn\n'), ((2597, 2606), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (2604, 2606), True, 'import torch.nn as nn\n'), ((2621, 2636), 'torch.nn.Linear', 'nn.Linear', (['(1)', '(1)'], {}), '(1, 1)\n', (2630, 2636), True, 'import torch.nn as nn\n'), ((4322, 4337), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4335, 4337), False, 'import torch\n'), ((5966, 5993), 'torch.squeeze', 'torch.squeeze', (['state_values'], {}), '(state_values)\n', (5979, 5993), False, 'import torch\n'), ((7095, 7165), 'torch.load', 'torch.load', (['checkpoint_path'], {'map_location': '(lambda storage, loc: storage)'}), '(checkpoint_path, map_location=lambda storage, loc: storage)\n', (7105, 7165), False, 'import torch\n'), ((7204, 7274), 'torch.load', 'torch.load', (['checkpoint_path'], {'map_location': '(lambda storage, loc: storage)'}), '(checkpoint_path, map_location=lambda storage, loc: storage)\n', (7214, 7274), False, 'import torch\n'), ((7538, 7563), 'pylol.lib.point.Point', 'point.Point', (['act_x', 'act_y'], {}), '(act_x, act_y)\n', (7549, 7563), False, 'from pylol.lib import point\n'), ((8591, 8618), 'pylol.lib.point.Point', 'point.Point', (['(7100.0)', '(7000.0)'], {}), '(7100.0, 7000.0)\n', (8602, 8618), False, 'from pylol.lib import point\n'), ((8645, 8672), 'pylol.lib.point.Point', 'point.Point', (['(7500.0)', '(7000.0)'], {}), '(7500.0, 7000.0)\n', (8656, 8672), False, 'from pylol.lib import point\n'), ((8722, 8783), 'numpy.array', 'np.array', (["raw_obs[0].observation['enemy_unit'].distance_to_me"], {}), "(raw_obs[0].observation['enemy_unit'].distance_to_me)\n", (8730, 8783), True, 'import numpy as np\n'), ((11064, 11091), 'pylol.lib.point.Point', 'point.Point', (['(7100.0)', '(7000.0)'], {}), '(7100.0, 7000.0)\n', (11075, 11091), False, 'from pylol.lib import point\n'), ((11118, 11145), 'pylol.lib.point.Point', 'point.Point', (['(7500.0)', '(7000.0)'], {}), '(7500.0, 7000.0)\n', (11129, 11145), False, 'from pylol.lib import point\n'), ((11195, 11256), 'numpy.array', 'np.array', (["raw_obs[0].observation['enemy_unit'].distance_to_me"], {}), "(raw_obs[0].observation['enemy_unit'].distance_to_me)\n", (11203, 11256), True, 'import numpy as np\n'), ((5090, 5129), 'torch.tensor', 'torch.tensor', (['rews'], {'dtype': 'torch.float32'}), '(rews, dtype=torch.float32)\n', (5102, 5129), False, 'import torch\n'), ((6276, 6333), 'torch.clamp', 'torch.clamp', (['ratios', '(1 - self.eps_clip)', '(1 + self.eps_clip)'], {}), '(ratios, 1 - self.eps_clip, 1 + self.eps_clip)\n', (6287, 6333), False, 'import torch\n'), ((9174, 9235), 'numpy.array', 'np.array', (["raw_obs[0].observation['enemy_unit'].distance_to_me"], {}), "(raw_obs[0].observation['enemy_unit'].distance_to_me)\n", (9182, 9235), True, 'import numpy as np\n'), ((11741, 11802), 'numpy.array', 'np.array', (["raw_obs[0].observation['enemy_unit'].distance_to_me"], {}), "(raw_obs[0].observation['enemy_unit'].distance_to_me)\n", (11749, 11802), True, 'import numpy as np\n'), ((4360, 4384), 'torch.FloatTensor', 'torch.FloatTensor', (['state'], {}), '(state)\n', (4377, 4384), False, 'import torch\n'), ((6417, 6440), 'torch.min', 'torch.min', (['surr1', 'surr2'], {}), '(surr1, surr2)\n', (6426, 6440), False, 'import torch\n'), ((5272, 5310), 'torch.stack', 'torch.stack', (['self.buffer.states'], {'dim': '(0)'}), '(self.buffer.states, dim=0)\n', (5283, 5310), False, 'import torch\n'), ((5369, 5408), 'torch.stack', 'torch.stack', (['self.buffer.actions'], {'dim': '(0)'}), '(self.buffer.actions, dim=0)\n', (5380, 5408), False, 'import torch\n'), ((5468, 5508), 'torch.stack', 'torch.stack', (['self.buffer.logprobs'], {'dim': '(0)'}), '(self.buffer.logprobs, dim=0)\n', (5479, 5508), False, 'import torch\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import re import os from typing import Optional, List, Dict from bravado.client import SwaggerClient from bravado.exception import ( HTTPNotFound, HTTPBadRequest, HTTPConflict, HTTPForbidden, HTTPUnprocessableEntity, ) from neptune.patterns import PROJECT_QUALIFIED_NAME_PATTERN from neptune.new.envs import API_TOKEN_ENV_NAME from neptune.new.internal.utils import verify_type from neptune.new.internal.credentials import Credentials from neptune.new.internal.backends.hosted_client import ( create_backend_client, create_http_client_with_auth, DEFAULT_REQUEST_KWARGS, ) from neptune.new.internal.backends.utils import ( with_api_exceptions_handler, ssl_verify, parse_validation_errors, ) from neptune.management.internal.utils import normalize_project_name from neptune.management.internal.types import * from neptune.management.exceptions import ( AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached, ) from neptune.management.internal.dto import ( ProjectVisibilityDTO, ProjectMemberRoleDTO, WorkspaceMemberRoleDTO, ) def _get_token(api_token: Optional[str] = None) -> str: return api_token or os.getenv(API_TOKEN_ENV_NAME) def _get_backend_client(api_token: Optional[str] = None) -> SwaggerClient: credentials = Credentials.from_token(api_token=_get_token(api_token=api_token)) http_client, client_config = create_http_client_with_auth( credentials=credentials, ssl_verify=ssl_verify(), proxies={} ) return create_backend_client(client_config=client_config, http_client=http_client) @with_api_exceptions_handler def get_project_list(api_token: Optional[str] = None) -> List[str]: """Get a list of projects you have access to. Args: api_token(str, optional): User’s API token. Defaults to `None`. If `None`, the value of `NEPTUNE_API_TOKEN` environment variable will be taken. .. note:: It is strongly recommended to use `NEPTUNE_API_TOKEN` environment variable rather than placing your API token in plain text in your source code. Returns: ``List[str]``: list of project names of a format 'WORKSPACE/PROJECT' Examples: >>> from neptune import management >>> management.get_project_list() You may also want to check `management API reference`_. .. _management API reference: https://docs.neptune.ai/api-reference/management """ verify_type("api_token", api_token, (str, type(None))) backend_client = _get_backend_client(api_token=api_token) params = { "userRelation": "viewerOrHigher", "sortBy": ["lastViewed"], **DEFAULT_REQUEST_KWARGS, } projects = backend_client.api.listProjects(**params).response().result.entries return [ normalize_project_name(name=project.name, workspace=project.organizationName) for project in projects ] @with_api_exceptions_handler def create_project( name: str, key: str, workspace: Optional[str] = None, visibility: str = ProjectVisibility.PRIVATE, description: Optional[str] = None, api_token: Optional[str] = None, ) -> str: """Creates a new project in your Neptune workspace. Args: name(str): The name of the project in Neptune in the format 'WORKSPACE/PROJECT'. If workspace argument was set, it should only contain 'PROJECT' instead of 'WORKSPACE/PROJECT'. key(str): Project identifier. It has to be contain 1-10 upper case letters or numbers. For example, 'GOOD5' workspace(str, optional): Name of your Neptune workspace. If you specify it, change the format of the name argument to 'PROJECT' instead of 'WORKSPACE/PROJECT'. If 'None' it will be parsed from the `name` argument. visibility(str, optional): level of visibility you want your project to have. Can be set to: - 'pub' for public projects - 'priv' for private projects If 'None' it will be set to 'priv' description(str, optional): Project description. If 'None', it will be left empty. api_token(str, optional): User’s API token. Defaults to `None`. If `None`, the value of `NEPTUNE_API_TOKEN` environment variable will be taken. .. note:: It is strongly recommended to use `NEPTUNE_API_TOKEN` environment variable rather than placing your API token in plain text in your source code. Returns: ``str``: name of the new project you created. Examples: >>> from neptune import management >>> management.create_project(name="awesome-team/amazing-project", ... key="AMA", ... visibility="pub") You may also want to check `management API reference`_. .. _management API reference: https://docs.neptune.ai/api-reference/management """ verify_type("name", name, str) verify_type("key", key, str) verify_type("workspace", workspace, (str, type(None))) verify_type("visibility", visibility, str) verify_type("description", description, (str, type(None))) verify_type("api_token", api_token, (str, type(None))) backend_client = _get_backend_client(api_token=api_token) project_identifier = normalize_project_name(name=name, workspace=workspace) project_spec = re.search(PROJECT_QUALIFIED_NAME_PATTERN, project_identifier) workspace, name = project_spec["workspace"], project_spec["project"] try: workspaces = ( backend_client.api.listOrganizations(**DEFAULT_REQUEST_KWARGS) .response() .result ) workspace_name_to_id = {f"{f.name}": f.id for f in workspaces} except HTTPNotFound: raise WorkspaceNotFound(workspace=workspace) if workspace not in workspace_name_to_id: raise WorkspaceNotFound(workspace=workspace) params = { "projectToCreate": { "name": name, "description": description, "projectKey": key, "organizationId": workspace_name_to_id[workspace], "visibility": ProjectVisibilityDTO.from_str(visibility).value, }, **DEFAULT_REQUEST_KWARGS, } try: response = backend_client.api.createProject(**params).response() return normalize_project_name( name=response.result.name, workspace=response.result.organizationName ) except HTTPBadRequest as e: validation_errors = parse_validation_errors(error=e) if "ERR_NOT_UNIQUE" in validation_errors: raise ProjectAlreadyExists(name=project_identifier) from e raise BadRequestException(validation_errors=validation_errors) except HTTPUnprocessableEntity as e: raise ProjectsLimitReached() from e @with_api_exceptions_handler def delete_project( name: str, workspace: Optional[str] = None, api_token: Optional[str] = None ): """Deletes a project from your Neptune workspace. Args: name(str): The name of the project in Neptune in the format 'WORKSPACE/PROJECT'. If workspace argument was set, it should only contain 'PROJECT' instead of 'WORKSPACE/PROJECT'. workspace(str, optional): Name of your Neptune workspace. If you specify it, change the format of the name argument to 'PROJECT' instead of 'WORKSPACE/PROJECT'. If 'None' it will be parsed from the name argument. api_token(str, optional): User’s API token. Defaults to `None`. If `None`, the value of `NEPTUNE_API_TOKEN` environment variable will be taken. .. note:: It is strongly recommended to use `NEPTUNE_API_TOKEN` environment variable rather than placing your API token in plain text in your source code. Examples: >>> from neptune import management >>> management.delete_project(name="awesome-team/amazing-project") You may also want to check `management API reference`_. .. _management API reference: https://docs.neptune.ai/api-reference/management """ verify_type("name", name, str) verify_type("workspace", workspace, (str, type(None))) verify_type("api_token", api_token, (str, type(None))) backend_client = _get_backend_client(api_token=api_token) project_identifier = normalize_project_name(name=name, workspace=workspace) params = {"projectIdentifier": project_identifier, **DEFAULT_REQUEST_KWARGS} try: backend_client.api.deleteProject(**params).response() except HTTPNotFound as e: raise ProjectNotFound(name=project_identifier) from e except HTTPForbidden as e: raise AccessRevokedOnDeletion(name=project_identifier) from e @with_api_exceptions_handler def add_project_member( name: str, username: str, role: str, workspace: Optional[str] = None, api_token: Optional[str] = None, ): """Adds member to the Neptune project. Args: name(str): The name of the project in Neptune in the format 'WORKSPACE/PROJECT'. If workspace argument was set, it should only contain 'PROJECT' instead of 'WORKSPACE/PROJECT'. username(str): Name of the user you want to add to the project. role(str): level of permissions the user should have in a project. Can be set to: - 'viewer': can only view project content and members - 'contributor': can view and edit project content and only view members - 'owner': can view and edit project content and members For more information, see `user roles in a project docs`_. workspace(str, optional): Name of your Neptune workspace. If you specify it, change the format of the name argument to 'PROJECT' instead of 'WORKSPACE/PROJECT'. If 'None' it will be parsed from the name argument. api_token(str, optional): User’s API token. Defaults to `None`. If `None`, the value of `NEPTUNE_API_TOKEN` environment variable will be taken. .. note:: It is strongly recommended to use `NEPTUNE_API_TOKEN` environment variable rather than placing your API token in plain text in your source code. Examples: >>> from neptune import management >>> management.add_project_member(name="awesome-team/amazing-project", ... username="johny", ... role="contributor") You may also want to check `management API reference`_. .. _management API reference: https://docs.neptune.ai/api-reference/management .. _user roles in a project docs: https://docs.neptune.ai/administration/user-management#roles-in-a-project """ verify_type("name", name, str) verify_type("username", username, str) verify_type("role", role, str) verify_type("workspace", workspace, (str, type(None))) verify_type("api_token", api_token, (str, type(None))) backend_client = _get_backend_client(api_token=api_token) project_identifier = normalize_project_name(name=name, workspace=workspace) params = { "projectIdentifier": project_identifier, "member": { "userId": username, "role": ProjectMemberRoleDTO.from_str(role).value, }, **DEFAULT_REQUEST_KWARGS, } try: backend_client.api.addProjectMember(**params).response() except HTTPNotFound as e: raise ProjectNotFound(name=project_identifier) from e except HTTPConflict as e: raise UserAlreadyHasAccess(user=username, project=project_identifier) from e @with_api_exceptions_handler def get_project_member_list( name: str, workspace: Optional[str] = None, api_token: Optional[str] = None ) -> Dict[str, str]: """Get a list of members for a project. Args: name(str): The name of the project in Neptune in the format 'WORKSPACE/PROJECT'. If workspace argument was set it should only contain 'PROJECT' instead of 'WORKSPACE/PROJECT'. workspace(str, optional): Name of your Neptune workspace. If you specify change the format of the name argument to 'PROJECT' instead of 'WORKSPACE/PROJECT'. If 'None' it will be parsed from the name argument. api_token(str, optional): User’s API token. Defaults to `None`. If `None`, the value of `NEPTUNE_API_TOKEN` environment variable will be taken. .. note:: It is strongly recommended to use `NEPTUNE_API_TOKEN` environment variable rather than placing your API token in plain text in your source code. Returns: ``Dict[str, str]``: Dictionary with usernames as keys and ProjectMemberRoles ('owner', 'contributor', 'viewer') as values. Examples: >>> from neptune import management >>> management.get_project_member_list(name="awesome-team/amazing-project") You may also want to check `management API reference`_. .. _management API reference: https://docs.neptune.ai/api-reference/management """ verify_type("name", name, str) verify_type("workspace", workspace, (str, type(None))) verify_type("api_token", api_token, (str, type(None))) backend_client = _get_backend_client(api_token=api_token) project_identifier = normalize_project_name(name=name, workspace=workspace) params = {"projectIdentifier": project_identifier, **DEFAULT_REQUEST_KWARGS} try: result = backend_client.api.listProjectMembers(**params).response().result return { f"{m.registeredMemberInfo.username}": ProjectMemberRoleDTO.to_domain(m.role) for m in result } except HTTPNotFound as e: raise ProjectNotFound(name=project_identifier) from e @with_api_exceptions_handler def remove_project_member( name: str, username: str, workspace: Optional[str] = None, api_token: Optional[str] = None, ): """Removes member from the Neptune project. Args: name(str): The name of the project in Neptune in the format 'WORKSPACE/PROJECT'. If workspace argument was set, it should only contain 'PROJECT' instead of 'WORKSPACE/PROJECT'. username(str): name of the user you want to remove from the project. workspace(str, optional): Name of your Neptune workspace. If you specify change the format of the name argument to 'PROJECT' instead of 'WORKSPACE/PROJECT'. If 'None' it will be parsed from the name argument. api_token(str, optional): User’s API token. Defaults to `None`. If `None`, the value of `NEPTUNE_API_TOKEN` environment variable will be taken. .. note:: It is strongly recommended to use `NEPTUNE_API_TOKEN` environment variable rather than placing your API token in plain text in your source code. Examples: >>> from neptune import management >>> management.remove_project_member(name="awesome-team/amazing-project", ... username="johny") You may also want to check `management API reference`_. .. _management API reference: https://docs.neptune.ai/api-reference/management """ verify_type("name", name, str) verify_type("username", username, str) verify_type("workspace", workspace, (str, type(None))) verify_type("api_token", api_token, (str, type(None))) backend_client = _get_backend_client(api_token=api_token) project_identifier = normalize_project_name(name=name, workspace=workspace) params = { "projectIdentifier": project_identifier, "userId": username, **DEFAULT_REQUEST_KWARGS, } try: backend_client.api.deleteProjectMember(**params).response() except HTTPNotFound as e: raise ProjectNotFound(name=project_identifier) from e except HTTPUnprocessableEntity as e: raise UserNotExistsOrWithoutAccess( user=username, project=project_identifier ) from e except HTTPForbidden as e: raise AccessRevokedOnMemberRemoval( user=username, project=project_identifier ) from e @with_api_exceptions_handler def get_workspace_member_list( name: str, api_token: Optional[str] = None ) -> Dict[str, str]: """Get a list of members of a workspace. Args: name(str, optional): Name of your Neptune workspace. api_token(str, optional): User’s API token. Defaults to `None`. If `None`, the value of `NEPTUNE_API_TOKEN` environment variable will be taken. .. note:: It is strongly recommended to use `NEPTUNE_API_TOKEN` environment variable rather than placing your API token in plain text in your source code. Returns: ``Dict[str, str]``: Dictionary with usernames as keys and `WorkspaceMemberRole` ('member', 'admin') as values. Examples: >>> from neptune import management >>> management.get_workspace_member_list(name="awesome-team") You may also want to check `management API reference`_. .. _management API reference: https://docs.neptune.ai/api-reference/management """ verify_type("name", name, str) verify_type("api_token", api_token, (str, type(None))) backend_client = _get_backend_client(api_token=api_token) params = {"organizationIdentifier": name, **DEFAULT_REQUEST_KWARGS} try: result = backend_client.api.listOrganizationMembers(**params).response().result return { f"{m.registeredMemberInfo.username}": WorkspaceMemberRoleDTO.to_domain( m.role ) for m in result } except HTTPNotFound as e: raise WorkspaceNotFound(workspace=name) from e
[ "neptune.new.internal.backends.utils.ssl_verify", "neptune.management.exceptions.BadRequestException", "neptune.management.internal.dto.ProjectVisibilityDTO.from_str", "neptune.management.exceptions.ProjectsLimitReached", "neptune.new.internal.backends.hosted_client.create_backend_client", "neptune.manage...
[((2289, 2364), 'neptune.new.internal.backends.hosted_client.create_backend_client', 'create_backend_client', ([], {'client_config': 'client_config', 'http_client': 'http_client'}), '(client_config=client_config, http_client=http_client)\n', (2310, 2364), False, 'from neptune.new.internal.backends.hosted_client import create_backend_client, create_http_client_with_auth, DEFAULT_REQUEST_KWARGS\n'), ((5776, 5806), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""name"""', 'name', 'str'], {}), "('name', name, str)\n", (5787, 5806), False, 'from neptune.new.internal.utils import verify_type\n'), ((5811, 5839), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""key"""', 'key', 'str'], {}), "('key', key, str)\n", (5822, 5839), False, 'from neptune.new.internal.utils import verify_type\n'), ((5903, 5945), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""visibility"""', 'visibility', 'str'], {}), "('visibility', visibility, str)\n", (5914, 5945), False, 'from neptune.new.internal.utils import verify_type\n'), ((6156, 6210), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'name', 'workspace': 'workspace'}), '(name=name, workspace=workspace)\n', (6178, 6210), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((6231, 6292), 're.search', 're.search', (['PROJECT_QUALIFIED_NAME_PATTERN', 'project_identifier'], {}), '(PROJECT_QUALIFIED_NAME_PATTERN, project_identifier)\n', (6240, 6292), False, 'import re\n'), ((8989, 9019), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""name"""', 'name', 'str'], {}), "('name', name, str)\n", (9000, 9019), False, 'from neptune.new.internal.utils import verify_type\n'), ((9226, 9280), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'name', 'workspace': 'workspace'}), '(name=name, workspace=workspace)\n', (9248, 9280), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((11674, 11704), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""name"""', 'name', 'str'], {}), "('name', name, str)\n", (11685, 11704), False, 'from neptune.new.internal.utils import verify_type\n'), ((11709, 11747), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""username"""', 'username', 'str'], {}), "('username', username, str)\n", (11720, 11747), False, 'from neptune.new.internal.utils import verify_type\n'), ((11752, 11782), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""role"""', 'role', 'str'], {}), "('role', role, str)\n", (11763, 11782), False, 'from neptune.new.internal.utils import verify_type\n'), ((11989, 12043), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'name', 'workspace': 'workspace'}), '(name=name, workspace=workspace)\n', (12011, 12043), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((14027, 14057), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""name"""', 'name', 'str'], {}), "('name', name, str)\n", (14038, 14057), False, 'from neptune.new.internal.utils import verify_type\n'), ((14264, 14318), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'name', 'workspace': 'workspace'}), '(name=name, workspace=workspace)\n', (14286, 14318), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((16199, 16229), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""name"""', 'name', 'str'], {}), "('name', name, str)\n", (16210, 16229), False, 'from neptune.new.internal.utils import verify_type\n'), ((16234, 16272), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""username"""', 'username', 'str'], {}), "('username', username, str)\n", (16245, 16272), False, 'from neptune.new.internal.utils import verify_type\n'), ((16479, 16533), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'name', 'workspace': 'workspace'}), '(name=name, workspace=workspace)\n', (16501, 16533), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((18169, 18199), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""name"""', 'name', 'str'], {}), "('name', name, str)\n", (18180, 18199), False, 'from neptune.new.internal.utils import verify_type\n'), ((1949, 1978), 'os.getenv', 'os.getenv', (['API_TOKEN_ENV_NAME'], {}), '(API_TOKEN_ENV_NAME)\n', (1958, 1978), False, 'import os\n'), ((3594, 3671), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'project.name', 'workspace': 'project.organizationName'}), '(name=project.name, workspace=project.organizationName)\n', (3616, 3671), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((6738, 6776), 'neptune.management.exceptions.WorkspaceNotFound', 'WorkspaceNotFound', ([], {'workspace': 'workspace'}), '(workspace=workspace)\n', (6755, 6776), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((7206, 7304), 'neptune.management.internal.utils.normalize_project_name', 'normalize_project_name', ([], {'name': 'response.result.name', 'workspace': 'response.result.organizationName'}), '(name=response.result.name, workspace=response.result\n .organizationName)\n', (7228, 7304), False, 'from neptune.management.internal.utils import normalize_project_name\n'), ((2247, 2259), 'neptune.new.internal.backends.utils.ssl_verify', 'ssl_verify', ([], {}), '()\n', (2257, 2259), False, 'from neptune.new.internal.backends.utils import with_api_exceptions_handler, ssl_verify, parse_validation_errors\n'), ((6638, 6676), 'neptune.management.exceptions.WorkspaceNotFound', 'WorkspaceNotFound', ([], {'workspace': 'workspace'}), '(workspace=workspace)\n', (6655, 6676), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((7382, 7414), 'neptune.new.internal.backends.utils.parse_validation_errors', 'parse_validation_errors', ([], {'error': 'e'}), '(error=e)\n', (7405, 7414), False, 'from neptune.new.internal.backends.utils import with_api_exceptions_handler, ssl_verify, parse_validation_errors\n'), ((7550, 7606), 'neptune.management.exceptions.BadRequestException', 'BadRequestException', ([], {'validation_errors': 'validation_errors'}), '(validation_errors=validation_errors)\n', (7569, 7606), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((7662, 7684), 'neptune.management.exceptions.ProjectsLimitReached', 'ProjectsLimitReached', ([], {}), '()\n', (7682, 7684), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((9479, 9519), 'neptune.management.exceptions.ProjectNotFound', 'ProjectNotFound', ([], {'name': 'project_identifier'}), '(name=project_identifier)\n', (9494, 9519), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((9572, 9620), 'neptune.management.exceptions.AccessRevokedOnDeletion', 'AccessRevokedOnDeletion', ([], {'name': 'project_identifier'}), '(name=project_identifier)\n', (9595, 9620), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((12394, 12434), 'neptune.management.exceptions.ProjectNotFound', 'ProjectNotFound', ([], {'name': 'project_identifier'}), '(name=project_identifier)\n', (12409, 12434), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((12486, 12549), 'neptune.management.exceptions.UserAlreadyHasAccess', 'UserAlreadyHasAccess', ([], {'user': 'username', 'project': 'project_identifier'}), '(user=username, project=project_identifier)\n', (12506, 12549), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((14561, 14599), 'neptune.management.internal.dto.ProjectMemberRoleDTO.to_domain', 'ProjectMemberRoleDTO.to_domain', (['m.role'], {}), '(m.role)\n', (14591, 14599), False, 'from neptune.management.internal.dto import ProjectVisibilityDTO, ProjectMemberRoleDTO, WorkspaceMemberRoleDTO\n'), ((14682, 14722), 'neptune.management.exceptions.ProjectNotFound', 'ProjectNotFound', ([], {'name': 'project_identifier'}), '(name=project_identifier)\n', (14697, 14722), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((16789, 16829), 'neptune.management.exceptions.ProjectNotFound', 'ProjectNotFound', ([], {'name': 'project_identifier'}), '(name=project_identifier)\n', (16804, 16829), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((16892, 16963), 'neptune.management.exceptions.UserNotExistsOrWithoutAccess', 'UserNotExistsOrWithoutAccess', ([], {'user': 'username', 'project': 'project_identifier'}), '(user=username, project=project_identifier)\n', (16920, 16963), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((17038, 17109), 'neptune.management.exceptions.AccessRevokedOnMemberRemoval', 'AccessRevokedOnMemberRemoval', ([], {'user': 'username', 'project': 'project_identifier'}), '(user=username, project=project_identifier)\n', (17066, 17109), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((18560, 18600), 'neptune.management.internal.dto.WorkspaceMemberRoleDTO.to_domain', 'WorkspaceMemberRoleDTO.to_domain', (['m.role'], {}), '(m.role)\n', (18592, 18600), False, 'from neptune.management.internal.dto import ProjectVisibilityDTO, ProjectMemberRoleDTO, WorkspaceMemberRoleDTO\n'), ((18713, 18746), 'neptune.management.exceptions.WorkspaceNotFound', 'WorkspaceNotFound', ([], {'workspace': 'name'}), '(workspace=name)\n', (18730, 18746), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((7008, 7049), 'neptune.management.internal.dto.ProjectVisibilityDTO.from_str', 'ProjectVisibilityDTO.from_str', (['visibility'], {}), '(visibility)\n', (7037, 7049), False, 'from neptune.management.internal.dto import ProjectVisibilityDTO, ProjectMemberRoleDTO, WorkspaceMemberRoleDTO\n'), ((7483, 7528), 'neptune.management.exceptions.ProjectAlreadyExists', 'ProjectAlreadyExists', ([], {'name': 'project_identifier'}), '(name=project_identifier)\n', (7503, 7528), False, 'from neptune.management.exceptions import AccessRevokedOnDeletion, AccessRevokedOnMemberRemoval, ProjectAlreadyExists, ProjectNotFound, UserNotExistsOrWithoutAccess, WorkspaceNotFound, UserAlreadyHasAccess, BadRequestException, ProjectsLimitReached\n'), ((12181, 12216), 'neptune.management.internal.dto.ProjectMemberRoleDTO.from_str', 'ProjectMemberRoleDTO.from_str', (['role'], {}), '(role)\n', (12210, 12216), False, 'from neptune.management.internal.dto import ProjectVisibilityDTO, ProjectMemberRoleDTO, WorkspaceMemberRoleDTO\n')]
import os import re import string from typing import Tuple import flytekit from flytekit import task, workflow, Secret, Resources from flytekit.types.directory import FlyteDirectory from flytekitplugins.kftensorflow import TfJob import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras import losses from tensorflow.python.data.ops.dataset_ops import BatchDataset from tensorflow.keras.layers.experimental.preprocessing import TextVectorization import neptune.new as neptune from neptune.new.integrations.tensorflow_keras import NeptuneCallback from dataclasses import dataclass from dataclasses_json import dataclass_json SECRET_NAME = "user_secret" SECRET_GROUP = "user-info" MODEL_FILE_PATH = "saved_model/" resources = Resources( gpu="2", mem="10Gi", storage="10Gi", ephemeral_storage="500Mi" ) @dataclass_json @dataclass class Hyperparameters(object): batch_size_per_replica: int = 64 seed: int = 10000 epochs: int = 10 max_features: int = 1000 sequence_length: int = 4 embedding_dim: int = 16 class Dataset: def __init__(self, train_data: BatchDataset, val_data: BatchDataset, test_data: BatchDataset): self.train_data = train_data self.val_data = val_data self.test_data = test_data def custom_standardization(input_data: str): lowercase = tf.strings.lower(input_data) stripped_html = tf.strings.regex_replace(lowercase, '<br />', ' ') return tf.strings.regex_replace( stripped_html, '[%s]' % re.escape(string.punctuation), '') class VectorizedLayer: def __init__(self, max_features: int, sequence_length: int): self.vectorized_layer = TextVectorization( standardize=custom_standardization, max_tokens=max_features, output_mode='int', output_sequence_length=sequence_length) def vectorized_text(self, text: str, label: str): text = tf.expand_dims(text, -1) return self.vectorize_layer(text), label def get_dataset(data_dir: FlyteDirectory, hyperparameters: Hyperparameters) -> Dataset: raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory( os.path.join(os.path.dirname(data_dir.path), 'train'), batch_size=hyperparameters.batch_size_per_replica, validation_split=0.2, subset='training', seed=hyperparameters.seed ) raw_val_ds = tf.keras.preprocessing.text_dataset_from_directory( os.path.join(os.path.dirname(data_dir.path), 'train'), batch_size=hyperparameters.batch_size_per_replica, validation_split=0.2, subset='validation', seed=hyperparameters.seed ) raw_test_ds = tf.keras.preprocessing.text_dataset_from_directory( str(os.path.join(os.path.dirname(data_dir.path), 'test')), batch_size=hyperparameters.batch_size_per_replica ) return Dataset(raw_train_ds, raw_val_ds, raw_test_ds) @task( retries=2, cache=True, cache_version="1.0", ) def download_dataset(uri: str) -> Dataset: data = tf.keras.utils.get_file( "aclImdb_v1", uri, untar=True, cache_dir='.', cache_subdir='') return FlyteDirectory(path=os.path.join(os.path.dirname(data), "aclImdb_v1")) @task( retries=2, cache=True, cache_version="1.0", ) def prepare_dataset(data_dir: FlyteDirectory, hyperparameters: Hyperparameters) -> (VectorizedLayer, Dataset): data_set = get_dataset(data_dir=data_dir, hyperparameters=hyperparameters) train_text = data_set.train_data.map(lambda x, y: x) vectorized_layer = VectorizedLayer(max_features=hyperparameters.max_features, sequence_length=hyperparameters.sequence_length) vectorized_layer.adapt(train_text) data_set.train_data = data_set.train_data.map(vectorized_layer.vectorized_text) data_set.val_data = data_set.val_data.map(vectorized_layer.vectorized_text) data_set.test_data = data_set.test_data.map(vectorized_layer.vectorized_text) autotune = tf.data.AUTOTUNE data_set.train_data = data_set.train_data.cache().prefetch(buffer_size=autotune) data_set.val_data = data_set.val_data.cache().prefetch(buffer_size=autotune) data_set.test_data = data_set.test_data.cache().prefetch(buffer_size=autotune) return vectorized_layer, data_set @task( task_config=TfJob(num_workers=2, num_ps_replicas=1, num_chief_replicas=1), retries=2, secret_requests=[Secret(group=SECRET_GROUP, key=SECRET_NAME)], cache=True, cache_version="1.0", requests=resources, limits=resources, ) def create_model(data_set: Dataset, hyperparameters: Hyperparameters, vectorized_layer: VectorizedLayer) \ -> Tuple[tf.keras.Model, FlyteDirectory]: working_dir = flytekit.current_context().working_directory checkpoint_dir = "training_checkpoints" checkpoint_prefix = os.path.join(working_dir, checkpoint_dir, "ckpt_{epoch}") run = neptune.init( project="evalsocket/flyte-pipeline", api_token=flytekit.current_context().secrets.get(SECRET_GROUP, SECRET_NAME), ) params = {"max_features": hyperparameters.max_features, "optimizer": "Adam", "epochs": hyperparameters.epochs, "embedding_dim": hyperparameters.embedding_dim} run["parameters"] = params callbacks = [ tf.keras.callbacks.TensorBoard(log_dir="./logs"), tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_prefix, save_weights_only=True ), NeptuneCallback(run=run, base_namespace="training"), ] model = tf.keras.Sequential([ layers.Embedding(hyperparameters.max_features + 1, hyperparameters.embedding_dim), layers.Dropout(0.2), layers.GlobalAveragePooling1D(), layers.Dropout(0.2), layers.Dense(1)]) model.compile(loss=losses.BinaryCrossentropy(from_logits=True), optimizer='adam', metrics=tf.metrics.BinaryAccuracy(threshold=0.0)) _ = model.fit( data_set.train_data, validation_data=data_set.val_data, epochs=hyperparameters.epochs, callbacks=callbacks, ) model.save(MODEL_FILE_PATH, save_format="tf") export_model = tf.keras.Sequential([ vectorized_layer, model, layers.Activation('sigmoid') ]) export_model.compile( loss=losses.BinaryCrossentropy(from_logits=False), optimizer="adam", metrics=['accuracy']) eval_metrics = export_model.evaluate(data_set.test_data) for j, metric in enumerate(eval_metrics): run["eval/{}".format(model.metrics_names[j])] = metric return model, FlyteDirectory(path=os.path.join(working_dir, checkpoint_dir)) @workflow def train_and_export(uri: str, hyperparameters: Hyperparameters = Hyperparameters()) \ -> Tuple[tf.keras.Model, FlyteDirectory]: data = download_dataset(uri=uri) vectorized_layer, data_set = prepare_dataset( data_dir=data, hyperparameters=hyperparameters) model, checkpoint = create_model(data_set=data_set, hyperparameters=hyperparameters, vectorized_layer=vectorized_layer) return model, checkpoint if __name__ == "__main__": print(f"Running {__file__} main...") print( f"Running chain_tasks_wf()... {train_and_export(uri='https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz')}")
[ "neptune.new.integrations.tensorflow_keras.NeptuneCallback" ]
[((750, 823), 'flytekit.Resources', 'Resources', ([], {'gpu': '"""2"""', 'mem': '"""10Gi"""', 'storage': '"""10Gi"""', 'ephemeral_storage': '"""500Mi"""'}), "(gpu='2', mem='10Gi', storage='10Gi', ephemeral_storage='500Mi')\n", (759, 823), False, 'from flytekit import task, workflow, Secret, Resources\n'), ((2930, 2978), 'flytekit.task', 'task', ([], {'retries': '(2)', 'cache': '(True)', 'cache_version': '"""1.0"""'}), "(retries=2, cache=True, cache_version='1.0')\n", (2934, 2978), False, 'from flytekit import task, workflow, Secret, Resources\n'), ((3261, 3309), 'flytekit.task', 'task', ([], {'retries': '(2)', 'cache': '(True)', 'cache_version': '"""1.0"""'}), "(retries=2, cache=True, cache_version='1.0')\n", (3265, 3309), False, 'from flytekit import task, workflow, Secret, Resources\n'), ((1340, 1368), 'tensorflow.strings.lower', 'tf.strings.lower', (['input_data'], {}), '(input_data)\n', (1356, 1368), True, 'import tensorflow as tf\n'), ((1389, 1439), 'tensorflow.strings.regex_replace', 'tf.strings.regex_replace', (['lowercase', '"""<br />"""', '""" """'], {}), "(lowercase, '<br />', ' ')\n", (1413, 1439), True, 'import tensorflow as tf\n'), ((3048, 3138), 'tensorflow.keras.utils.get_file', 'tf.keras.utils.get_file', (['"""aclImdb_v1"""', 'uri'], {'untar': '(True)', 'cache_dir': '"""."""', 'cache_subdir': '""""""'}), "('aclImdb_v1', uri, untar=True, cache_dir='.',\n cache_subdir='')\n", (3071, 3138), True, 'import tensorflow as tf\n'), ((4897, 4954), 'os.path.join', 'os.path.join', (['working_dir', 'checkpoint_dir', '"""ckpt_{epoch}"""'], {}), "(working_dir, checkpoint_dir, 'ckpt_{epoch}')\n", (4909, 4954), False, 'import os\n'), ((1666, 1808), 'tensorflow.keras.layers.experimental.preprocessing.TextVectorization', 'TextVectorization', ([], {'standardize': 'custom_standardization', 'max_tokens': 'max_features', 'output_mode': '"""int"""', 'output_sequence_length': 'sequence_length'}), "(standardize=custom_standardization, max_tokens=\n max_features, output_mode='int', output_sequence_length=sequence_length)\n", (1683, 1808), False, 'from tensorflow.keras.layers.experimental.preprocessing import TextVectorization\n'), ((1923, 1947), 'tensorflow.expand_dims', 'tf.expand_dims', (['text', '(-1)'], {}), '(text, -1)\n', (1937, 1947), True, 'import tensorflow as tf\n'), ((4784, 4810), 'flytekit.current_context', 'flytekit.current_context', ([], {}), '()\n', (4808, 4810), False, 'import flytekit\n'), ((5352, 5400), 'tensorflow.keras.callbacks.TensorBoard', 'tf.keras.callbacks.TensorBoard', ([], {'log_dir': '"""./logs"""'}), "(log_dir='./logs')\n", (5382, 5400), True, 'import tensorflow as tf\n'), ((5410, 5500), 'tensorflow.keras.callbacks.ModelCheckpoint', 'tf.keras.callbacks.ModelCheckpoint', ([], {'filepath': 'checkpoint_prefix', 'save_weights_only': '(True)'}), '(filepath=checkpoint_prefix,\n save_weights_only=True)\n', (5444, 5500), True, 'import tensorflow as tf\n'), ((5528, 5579), 'neptune.new.integrations.tensorflow_keras.NeptuneCallback', 'NeptuneCallback', ([], {'run': 'run', 'base_namespace': '"""training"""'}), "(run=run, base_namespace='training')\n", (5543, 5579), False, 'from neptune.new.integrations.tensorflow_keras import NeptuneCallback\n'), ((4375, 4436), 'flytekitplugins.kftensorflow.TfJob', 'TfJob', ([], {'num_workers': '(2)', 'num_ps_replicas': '(1)', 'num_chief_replicas': '(1)'}), '(num_workers=2, num_ps_replicas=1, num_chief_replicas=1)\n', (4380, 4436), False, 'from flytekitplugins.kftensorflow import TfJob\n'), ((1509, 1538), 're.escape', 're.escape', (['string.punctuation'], {}), '(string.punctuation)\n', (1518, 1538), False, 'import re\n'), ((2179, 2209), 'os.path.dirname', 'os.path.dirname', (['data_dir.path'], {}), '(data_dir.path)\n', (2194, 2209), False, 'import os\n'), ((2467, 2497), 'os.path.dirname', 'os.path.dirname', (['data_dir.path'], {}), '(data_dir.path)\n', (2482, 2497), False, 'import os\n'), ((5630, 5716), 'tensorflow.keras.layers.Embedding', 'layers.Embedding', (['(hyperparameters.max_features + 1)', 'hyperparameters.embedding_dim'], {}), '(hyperparameters.max_features + 1, hyperparameters.\n embedding_dim)\n', (5646, 5716), False, 'from tensorflow.keras import layers\n'), ((5721, 5740), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['(0.2)'], {}), '(0.2)\n', (5735, 5740), False, 'from tensorflow.keras import layers\n'), ((5750, 5781), 'tensorflow.keras.layers.GlobalAveragePooling1D', 'layers.GlobalAveragePooling1D', ([], {}), '()\n', (5779, 5781), False, 'from tensorflow.keras import layers\n'), ((5791, 5810), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['(0.2)'], {}), '(0.2)\n', (5805, 5810), False, 'from tensorflow.keras import layers\n'), ((5820, 5835), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(1)'], {}), '(1)\n', (5832, 5835), False, 'from tensorflow.keras import layers\n'), ((5861, 5904), 'tensorflow.keras.losses.BinaryCrossentropy', 'losses.BinaryCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (5886, 5904), False, 'from tensorflow.keras import losses\n'), ((5968, 6008), 'tensorflow.metrics.BinaryAccuracy', 'tf.metrics.BinaryAccuracy', ([], {'threshold': '(0.0)'}), '(threshold=0.0)\n', (5993, 6008), True, 'import tensorflow as tf\n'), ((6317, 6345), 'tensorflow.keras.layers.Activation', 'layers.Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (6334, 6345), False, 'from tensorflow.keras import layers\n'), ((6393, 6437), 'tensorflow.keras.losses.BinaryCrossentropy', 'losses.BinaryCrossentropy', ([], {'from_logits': '(False)'}), '(from_logits=False)\n', (6418, 6437), False, 'from tensorflow.keras import losses\n'), ((4474, 4517), 'flytekit.Secret', 'Secret', ([], {'group': 'SECRET_GROUP', 'key': 'SECRET_NAME'}), '(group=SECRET_GROUP, key=SECRET_NAME)\n', (4480, 4517), False, 'from flytekit import task, workflow, Secret, Resources\n'), ((2762, 2792), 'os.path.dirname', 'os.path.dirname', (['data_dir.path'], {}), '(data_dir.path)\n', (2777, 2792), False, 'import os\n'), ((3220, 3241), 'os.path.dirname', 'os.path.dirname', (['data'], {}), '(data)\n', (3235, 3241), False, 'import os\n'), ((6690, 6731), 'os.path.join', 'os.path.join', (['working_dir', 'checkpoint_dir'], {}), '(working_dir, checkpoint_dir)\n', (6702, 6731), False, 'import os\n'), ((5043, 5069), 'flytekit.current_context', 'flytekit.current_context', ([], {}), '()\n', (5067, 5069), False, 'import flytekit\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import imghdr import os import pathlib from typing import List, Optional, Iterable from neptune.new.internal.utils import base64_encode from neptune.new.exceptions import FileNotFound, OperationNotSupported from neptune.new.types import File from neptune.new.types.series.file_series import FileSeries as FileSeriesVal from neptune.new.internal.operation import ( ImageValue, LogImages, ClearImageLog, Operation, ) from neptune.new.attributes.series.series import Series from neptune.utils import split_to_chunks Val = FileSeriesVal Data = File class FileSeries(Series[Val, Data]): def _get_log_operations_from_value( self, value: Val, step: Optional[float], timestamp: float ) -> List[Operation]: values = [ LogImages.ValueType( ImageValue( data=self._get_base64_image_content(val), name=value.name, description=value.description, ), step=step, ts=timestamp, ) for val in value.values ] return [LogImages(self._path, chunk) for chunk in split_to_chunks(values, 1)] def _get_clear_operation(self) -> Operation: return ClearImageLog(self._path) def _data_to_value(self, values: Iterable, **kwargs) -> Val: return FileSeriesVal(values, **kwargs) def _is_value_type(self, value) -> bool: return isinstance(value, FileSeriesVal) @staticmethod def _get_base64_image_content(file: File) -> str: if file.path is not None: if not os.path.exists(file.path): raise FileNotFound(file.path) with open(file.path, "rb") as image_file: file = File.from_stream(image_file) ext = imghdr.what("", h=file.content) if not ext: raise OperationNotSupported( "FileSeries supports only image files for now. " "Other file types will be implemented in future." ) return base64_encode(file.content) def download(self, destination: Optional[str]): target_dir = self._get_destination(destination) item_count = self._backend.get_image_series_values( self._container_id, self._container_type, self._path, 0, 1 ).totalItemCount for i in range(0, item_count): self._backend.download_file_series_by_index( self._container_id, self._container_type, self._path, i, target_dir ) def download_last(self, destination: Optional[str]): target_dir = self._get_destination(destination) item_count = self._backend.get_image_series_values( self._container_id, self._container_type, self._path, 0, 1 ).totalItemCount if item_count > 0: self._backend.download_file_series_by_index( self._container_id, self._container_type, self._path, item_count - 1, target_dir, ) else: raise ValueError("Unable to download last file - series is empty") def _get_destination(self, destination: Optional[str]): target_dir = destination if destination is None: target_dir = os.path.join("neptune", self._path[-1]) pathlib.Path(os.path.abspath(target_dir)).mkdir(parents=True, exist_ok=True) return target_dir
[ "neptune.new.types.series.file_series.FileSeries", "neptune.new.internal.operation.ClearImageLog", "neptune.new.internal.utils.base64_encode", "neptune.utils.split_to_chunks", "neptune.new.exceptions.FileNotFound", "neptune.new.internal.operation.LogImages", "neptune.new.exceptions.OperationNotSupported...
[((1850, 1875), 'neptune.new.internal.operation.ClearImageLog', 'ClearImageLog', (['self._path'], {}), '(self._path)\n', (1863, 1875), False, 'from neptune.new.internal.operation import ImageValue, LogImages, ClearImageLog, Operation\n'), ((1957, 1988), 'neptune.new.types.series.file_series.FileSeries', 'FileSeriesVal', (['values'], {}), '(values, **kwargs)\n', (1970, 1988), True, 'from neptune.new.types.series.file_series import FileSeries as FileSeriesVal\n'), ((2403, 2434), 'imghdr.what', 'imghdr.what', (['""""""'], {'h': 'file.content'}), "('', h=file.content)\n", (2414, 2434), False, 'import imghdr\n'), ((2657, 2684), 'neptune.new.internal.utils.base64_encode', 'base64_encode', (['file.content'], {}), '(file.content)\n', (2670, 2684), False, 'from neptune.new.internal.utils import base64_encode\n'), ((1715, 1743), 'neptune.new.internal.operation.LogImages', 'LogImages', (['self._path', 'chunk'], {}), '(self._path, chunk)\n', (1724, 1743), False, 'from neptune.new.internal.operation import ImageValue, LogImages, ClearImageLog, Operation\n'), ((2473, 2601), 'neptune.new.exceptions.OperationNotSupported', 'OperationNotSupported', (['"""FileSeries supports only image files for now. Other file types will be implemented in future."""'], {}), "(\n 'FileSeries supports only image files for now. Other file types will be implemented in future.'\n )\n", (2494, 2601), False, 'from neptune.new.exceptions import FileNotFound, OperationNotSupported\n'), ((3918, 3957), 'os.path.join', 'os.path.join', (['"""neptune"""', 'self._path[-1]'], {}), "('neptune', self._path[-1])\n", (3930, 3957), False, 'import os\n'), ((1757, 1783), 'neptune.utils.split_to_chunks', 'split_to_chunks', (['values', '(1)'], {}), '(values, 1)\n', (1772, 1783), False, 'from neptune.utils import split_to_chunks\n'), ((2209, 2234), 'os.path.exists', 'os.path.exists', (['file.path'], {}), '(file.path)\n', (2223, 2234), False, 'import os\n'), ((2258, 2281), 'neptune.new.exceptions.FileNotFound', 'FileNotFound', (['file.path'], {}), '(file.path)\n', (2270, 2281), False, 'from neptune.new.exceptions import FileNotFound, OperationNotSupported\n'), ((2359, 2387), 'neptune.new.types.File.from_stream', 'File.from_stream', (['image_file'], {}), '(image_file)\n', (2375, 2387), False, 'from neptune.new.types import File\n'), ((3979, 4006), 'os.path.abspath', 'os.path.abspath', (['target_dir'], {}), '(target_dir)\n', (3994, 4006), False, 'import os\n')]
# # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import neptune.new as neptune from e2e_tests.base import AVAILABLE_CONTAINERS, BaseE2ETest, fake from e2e_tests.utils import ( initialize_container, reinitialize_container, with_check_if_file_appears, ) from neptune.new.exceptions import NeptuneModelKeyAlreadyExistsError from neptune.new.metadata_containers import Model from neptune.new.project import Project class TestInitRun(BaseE2ETest): def test_custom_run_id(self, environment): custom_run_id = "-".join((fake.word() for _ in range(3))) run = neptune.init_run(custom_run_id=custom_run_id, project=environment.project) key = self.gen_key() val = fake.word() run[key] = val run.sync() run.stop() exp2 = neptune.init_run(custom_run_id=custom_run_id, project=environment.project) assert exp2[key].fetch() == val def test_send_source_code(self, environment): exp = neptune.init_run( source_files="**/*.py", name="E2e init source code", project=environment.project, ) # download sources exp.sync() with with_check_if_file_appears("files.zip"): exp["source_code/files"].download() class TestInitProject(BaseE2ETest): def test_resuming_project(self, environment): exp = neptune.init_project(name=environment.project) key = self.gen_key() val = fake.word() exp[key] = val exp.sync() exp.stop() exp2 = neptune.init_project(name=environment.project) assert exp2[key].fetch() == val def test_init_and_readonly(self, environment): project: Project = neptune.init_project(name=environment.project) key = f"{self.gen_key()}-" + "-".join((fake.word() for _ in range(4))) val = fake.word() project[key] = val project.sync() project.stop() read_only_project = neptune.get_project(name=environment.project) read_only_project.sync() assert set(read_only_project.get_structure()["sys"]) == { "creation_time", "id", "modification_time", "monitoring_time", "name", "ping_time", "running_time", "size", "state", "tags", "visibility", } assert read_only_project[key].fetch() == val class TestInitModel(BaseE2ETest): @pytest.mark.parametrize("container", ["model"], indirect=True) def test_fail_reused_model_key(self, container: Model, environment): with pytest.raises(NeptuneModelKeyAlreadyExistsError): model_key = container["sys/id"].fetch().split("-")[1] neptune.init_model(key=model_key, project=environment.project) class TestReinitialization(BaseE2ETest): @pytest.mark.parametrize("container_type", AVAILABLE_CONTAINERS) def test_resuming_container(self, container_type, environment): container = initialize_container(container_type=container_type, project=environment.project) sys_id = container["sys/id"].fetch() key = self.gen_key() val = fake.word() container[key] = val container.sync() container.stop() reinitialized = reinitialize_container( sys_id=sys_id, container_type=container.container_type.value, project=environment.project, ) assert reinitialized[key].fetch() == val
[ "neptune.new.get_project", "neptune.new.init_project", "neptune.new.init_run", "neptune.new.init_model" ]
[((3055, 3117), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""container"""', "['model']"], {'indirect': '(True)'}), "('container', ['model'], indirect=True)\n", (3078, 3117), False, 'import pytest\n'), ((3443, 3506), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""container_type"""', 'AVAILABLE_CONTAINERS'], {}), "('container_type', AVAILABLE_CONTAINERS)\n", (3466, 3506), False, 'import pytest\n'), ((1146, 1220), 'neptune.new.init_run', 'neptune.init_run', ([], {'custom_run_id': 'custom_run_id', 'project': 'environment.project'}), '(custom_run_id=custom_run_id, project=environment.project)\n', (1162, 1220), True, 'import neptune.new as neptune\n'), ((1265, 1276), 'e2e_tests.base.fake.word', 'fake.word', ([], {}), '()\n', (1274, 1276), False, 'from e2e_tests.base import AVAILABLE_CONTAINERS, BaseE2ETest, fake\n'), ((1355, 1429), 'neptune.new.init_run', 'neptune.init_run', ([], {'custom_run_id': 'custom_run_id', 'project': 'environment.project'}), '(custom_run_id=custom_run_id, project=environment.project)\n', (1371, 1429), True, 'import neptune.new as neptune\n'), ((1535, 1637), 'neptune.new.init_run', 'neptune.init_run', ([], {'source_files': '"""**/*.py"""', 'name': '"""E2e init source code"""', 'project': 'environment.project'}), "(source_files='**/*.py', name='E2e init source code',\n project=environment.project)\n", (1551, 1637), True, 'import neptune.new as neptune\n'), ((1932, 1978), 'neptune.new.init_project', 'neptune.init_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (1952, 1978), True, 'import neptune.new as neptune\n'), ((2023, 2034), 'e2e_tests.base.fake.word', 'fake.word', ([], {}), '()\n', (2032, 2034), False, 'from e2e_tests.base import AVAILABLE_CONTAINERS, BaseE2ETest, fake\n'), ((2113, 2159), 'neptune.new.init_project', 'neptune.init_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2133, 2159), True, 'import neptune.new as neptune\n'), ((2279, 2325), 'neptune.new.init_project', 'neptune.init_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2299, 2325), True, 'import neptune.new as neptune\n'), ((2420, 2431), 'e2e_tests.base.fake.word', 'fake.word', ([], {}), '()\n', (2429, 2431), False, 'from e2e_tests.base import AVAILABLE_CONTAINERS, BaseE2ETest, fake\n'), ((2534, 2579), 'neptune.new.get_project', 'neptune.get_project', ([], {'name': 'environment.project'}), '(name=environment.project)\n', (2553, 2579), True, 'import neptune.new as neptune\n'), ((3595, 3680), 'e2e_tests.utils.initialize_container', 'initialize_container', ([], {'container_type': 'container_type', 'project': 'environment.project'}), '(container_type=container_type, project=environment.project\n )\n', (3615, 3680), False, 'from e2e_tests.utils import initialize_container, reinitialize_container, with_check_if_file_appears\n'), ((3765, 3776), 'e2e_tests.base.fake.word', 'fake.word', ([], {}), '()\n', (3774, 3776), False, 'from e2e_tests.base import AVAILABLE_CONTAINERS, BaseE2ETest, fake\n'), ((3881, 3999), 'e2e_tests.utils.reinitialize_container', 'reinitialize_container', ([], {'sys_id': 'sys_id', 'container_type': 'container.container_type.value', 'project': 'environment.project'}), '(sys_id=sys_id, container_type=container.\n container_type.value, project=environment.project)\n', (3903, 3999), False, 'from e2e_tests.utils import initialize_container, reinitialize_container, with_check_if_file_appears\n'), ((1741, 1780), 'e2e_tests.utils.with_check_if_file_appears', 'with_check_if_file_appears', (['"""files.zip"""'], {}), "('files.zip')\n", (1767, 1780), False, 'from e2e_tests.utils import initialize_container, reinitialize_container, with_check_if_file_appears\n'), ((3204, 3252), 'pytest.raises', 'pytest.raises', (['NeptuneModelKeyAlreadyExistsError'], {}), '(NeptuneModelKeyAlreadyExistsError)\n', (3217, 3252), False, 'import pytest\n'), ((3332, 3394), 'neptune.new.init_model', 'neptune.init_model', ([], {'key': 'model_key', 'project': 'environment.project'}), '(key=model_key, project=environment.project)\n', (3350, 3394), True, 'import neptune.new as neptune\n'), ((1100, 1111), 'e2e_tests.base.fake.word', 'fake.word', ([], {}), '()\n', (1109, 1111), False, 'from e2e_tests.base import AVAILABLE_CONTAINERS, BaseE2ETest, fake\n'), ((2374, 2385), 'e2e_tests.base.fake.word', 'fake.word', ([], {}), '()\n', (2383, 2385), False, 'from e2e_tests.base import AVAILABLE_CONTAINERS, BaseE2ETest, fake\n')]
import neptune.new as neptune data_version = "5b49383080a7edfe4ef72dc359112d3c" base_namespace = "production" # (neptune) fetch project project = neptune.get_project(name="common/project-tabular-data") # (neptune) find best run for given data version best_run_df = project.fetch_runs_table(tag="best-finetuned").to_pandas() best_run_df = best_run_df[best_run_df["data/train/version"] == data_version] best_run_id = best_run_df["sys/id"].values[0] # (neptune) resume this run run = neptune.init( project="common/project-tabular-data", run=best_run_id, capture_hardware_metrics=False, ) # (neptune) download model from the run run["model_training/pickled_model"].download("xgb.model") # here goes deploying logic # (neptune) log model version that is now in prod in_prod_run_df = project.fetch_runs_table(tag="in-prod").to_pandas() in_prod_run_df = in_prod_run_df[in_prod_run_df["data/train/version"] == data_version] in_prod_run_id = in_prod_run_df["sys/id"].values[0] # (neptune) resume in-prod run run_in_prod = neptune.init( project="common/project-tabular-data", run=in_prod_run_id, capture_hardware_metrics=False, ) # increment model version model_version = run_in_prod[f"{base_namespace}/model_version"].fetch() run[f"{base_namespace}/model_version"] = "xgb-{}".format(int(model_version.split("-")[-1]) + 1) # (neptune) move "in-prod" tag to the new run run_in_prod["sys/tags"].remove("in-prod") run["sys/tags"].add("in-prod")
[ "neptune.new.get_project", "neptune.new.init" ]
[((148, 203), 'neptune.new.get_project', 'neptune.get_project', ([], {'name': '"""common/project-tabular-data"""'}), "(name='common/project-tabular-data')\n", (167, 203), True, 'import neptune.new as neptune\n'), ((485, 589), 'neptune.new.init', 'neptune.init', ([], {'project': '"""common/project-tabular-data"""', 'run': 'best_run_id', 'capture_hardware_metrics': '(False)'}), "(project='common/project-tabular-data', run=best_run_id,\n capture_hardware_metrics=False)\n", (497, 589), True, 'import neptune.new as neptune\n'), ((1033, 1140), 'neptune.new.init', 'neptune.init', ([], {'project': '"""common/project-tabular-data"""', 'run': 'in_prod_run_id', 'capture_hardware_metrics': '(False)'}), "(project='common/project-tabular-data', run=in_prod_run_id,\n capture_hardware_metrics=False)\n", (1045, 1140), True, 'import neptune.new as neptune\n')]
import neptune.new as neptune import time from metrics import calculate_counter, calculate_classification, calculate_counter135 from models.shapes_classifier import ShapesClassifier from models.shapes_counter import ShapesCounter, ShapesCounter135 tracked_values = ['train/loss', 'train/acc', 'validation/loss', 'validation/acc', 'train/batch_loss'] NEPTUNE = False npt_run = None hist_run = {key: [] for key in tracked_values} def setup_neptune(model): global NEPTUNE, npt_run NEPTUNE = True npt_run = neptune.init(project='uw-niedziol/dl-shapes', source_files=['*.py', 'models/*.py', 'datasets/*.py'], tags=[model]) def upload_file(file): global npt_run npt_run['hist'].upload(file) def log_values(key, value): if NEPTUNE: npt_run[key].log(value) hist_run[key].append(value.detach().item()) def calculate_accuracy(model, outputs, labels): if isinstance(model, ShapesClassifier): return calculate_classification(outputs, labels) elif isinstance(model, ShapesCounter): return calculate_counter(outputs, labels) elif isinstance(model, ShapesCounter135): return calculate_counter135(outputs, labels) else: raise ValueError('Unknown model') def train_and_evaluate_model( model, criterion, optimizer, train_loader, train_set, val_loader, val_set, device, num_epochs=10, save_every_nth_all=1, save_every_nth_batch_loss=50 ): try: for epoch in range(num_epochs): epoch_start = time.time() print('Epoch {}/{}'.format(epoch + 1, num_epochs)) print('-' * 10) # training phase model.train() running_loss_train = 0.0 running_corrects_train = 0.0 i = 0 for inputs, labels in train_loader: inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() running_loss_train += loss.detach() if epoch % save_every_nth_all == 0: running_corrects_train += calculate_accuracy(model, outputs, labels).detach() if i % save_every_nth_batch_loss == 0: log_values('train/batch_loss', loss) i += 1 epoch_loss_train = running_loss_train / len(train_set) log_values('train/loss', epoch_loss_train) print(f'[TRAIN] loss: {epoch_loss_train}') # exit() if epoch % save_every_nth_all == 0: epoch_acc_train = running_corrects_train / len(train_set) log_values('train/acc', epoch_acc_train) print(f'[TRAIN] accuracy: {epoch_acc_train}') # evaluating phase model.eval() running_loss_val = 0.0 running_corrects_val = 0.0 for inputs, labels in val_loader: inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) loss = criterion(outputs, labels) running_loss_val += loss.detach() if epoch % save_every_nth_all == 0: running_corrects_val += calculate_accuracy(model, outputs, labels) epoch_loss_test = running_loss_val / len(val_set) log_values('validation/loss', epoch_loss_test) print(f'[TEST] loss: {epoch_loss_test}') if epoch % save_every_nth_all == 0: epoch_acc_test = running_corrects_val / len(val_set) log_values('validation/acc', epoch_acc_test) print(f'[TEST] accuracy: {epoch_acc_test}') epoch_end = time.time() print(f"Epoch elapsed time = {epoch_end - epoch_start}\n") except KeyboardInterrupt: print('Interrupt') pass return hist_run
[ "neptune.new.init" ]
[((593, 711), 'neptune.new.init', 'neptune.init', ([], {'project': '"""uw-niedziol/dl-shapes"""', 'source_files': "['*.py', 'models/*.py', 'datasets/*.py']", 'tags': '[model]'}), "(project='uw-niedziol/dl-shapes', source_files=['*.py',\n 'models/*.py', 'datasets/*.py'], tags=[model])\n", (605, 711), True, 'import neptune.new as neptune\n'), ((1076, 1117), 'metrics.calculate_classification', 'calculate_classification', (['outputs', 'labels'], {}), '(outputs, labels)\n', (1100, 1117), False, 'from metrics import calculate_counter, calculate_classification, calculate_counter135\n'), ((1176, 1210), 'metrics.calculate_counter', 'calculate_counter', (['outputs', 'labels'], {}), '(outputs, labels)\n', (1193, 1210), False, 'from metrics import calculate_counter, calculate_classification, calculate_counter135\n'), ((1709, 1720), 'time.time', 'time.time', ([], {}), '()\n', (1718, 1720), False, 'import time\n'), ((4065, 4076), 'time.time', 'time.time', ([], {}), '()\n', (4074, 4076), False, 'import time\n'), ((1272, 1309), 'metrics.calculate_counter135', 'calculate_counter135', (['outputs', 'labels'], {}), '(outputs, labels)\n', (1292, 1309), False, 'from metrics import calculate_counter, calculate_classification, calculate_counter135\n')]
import neptune.new as neptune import os from GTApack.GTA_hotloader import GTA_hotloader from GTApack.GTA_antihot import GTA_antihot from GTApack.GTA_Unet import GTA_Unet from GTApack.GTA_prop_to_hot import GTA_prop_to_hot from GTApack.GTA_tester import GTA_tester from torchvision import datasets, transforms from torch.optim import SGD, Adam from torch.optim.lr_scheduler import (ReduceLROnPlateau, CyclicLR, CosineAnnealingLR) from torch.utils.data import DataLoader, random_split import torch.nn.functional as F import torch.nn as nn import torch import numpy as np import time from neptune.new.types import File import matplotlib.pyplot as plt device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) # Set up the datasets np.random.seed(42) val_set, train_set = torch.utils.data.random_split( np.random.randint(low = 1, high = 4962, size = 100), [20, 80], generator=torch.Generator().manual_seed(42)) test_val_set = np.random.randint(low = 1, high = 856, size = 20) # 100 valload = GTA_hotloader(path = "C:/Users/Marc/Desktop/Billeder/train/", width = 400, height = 300, ind = val_set, device = device) trainload = GTA_hotloader(path = "C:/Users/Marc/Desktop/Billeder/train/", width = 400, height = 300, ind = train_set, device = device) testload = GTA_hotloader(path = "C:/Users/Marc/Desktop/Billeder/test-val/", width = 400, height = 300, ind = test_val_set, device = device) batch_size = 1 # Set up the dataloaders: valloader = torch.utils.data.DataLoader(valload, batch_size=batch_size, shuffle=True, num_workers=0) trainloader = torch.utils.data.DataLoader(trainload, batch_size=batch_size, shuffle=True, num_workers=0) testloader = torch.utils.data.DataLoader(testload, batch_size=batch_size, shuffle=True, num_workers=0) token = os.getenv('Neptune_api') run = neptune.init( project="Deep-Learning-test/Deep-Learning-Test", api_token=token, ) nEpoch = 61 # Network with cycl params = {"optimizer":"SGD", "optimizer_momentum": 0.7, "optimizer_learning_rate": 0.001, "loss_function":"MSEloss", "model":"GTA_Unet", "scheduler":"CyclicLR", "scheduler_base_lr":0.001, "scheduler_max_lr":1.25, "scheduler_step_size_up":10} run[f"network_cycl1/parameters"] = params lossFunc = nn.MSELoss() model = GTA_Unet(n_channels = 3, n_classes = 9).to(device) optimizer = SGD(model.parameters(), lr=0.001, momentum=0.7) scheduler = CyclicLR(optimizer, base_lr=0.001, max_lr=1, step_size_up=10) valid_loss, train_loss = [], [] avg_train_loss, avg_valid_loss = [], [] for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_cycl1/learning_rate"].log(optimizer.param_groups[0]['lr']) for img, lab in trainloader: y_pred = model(img) model.zero_grad() loss = lossFunc(y_pred, lab) loss.backward() optimizer.step() train_loss.append(loss.item()) avg_train_loss.append(w := (np.mean(np.array(train_loss)))) run[f"network_cycl1/train_loss"].log(w) train_loss = [] for img, lab in valloader: y_pred = model(img) loss = lossFunc(y_pred, lab) valid_loss.append(loss.item()) val_acc_per_pic = np.mean(GTA_tester(model, valloader, p = False)) run[f"network_cycl1/validation_mean_acc"].log(val_acc_per_pic) avg_valid_loss.append(w := (np.mean(np.array(valid_loss)))) run[f"network_cycl1/validation_loss"].log(w) valid_loss = [] scheduler.step() torch.save(model.state_dict(), "C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl1.pt") run[f"network_cycl1/network_weights"].upload(File("C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl1.pt")) test_acc_per_pic = GTA_tester(model, testloader) print(np.mean(test_acc_per_pic)) run[f"network_cycl1/test_accuracy_per_pic"].log(test_acc_per_pic) run[f"network_cycl1/mean_test_accuracy"].log(np.mean(test_acc_per_pic)) params = {"optimizer":"SGD", "optimizer_momentum": 0.9, "optimizer_learning_rate": 0.001, "loss_function":"MSEloss", "model":"GTA_Unet", "scheduler":"CyclicLR", "scheduler_base_lr":0.001, "scheduler_max_lr":1.25, "scheduler_step_size_up":10} run[f"network_cycl2/parameters"] = params lossFunc = nn.MSELoss() model = GTA_Unet(n_channels = 3, n_classes = 9).to(device) optimizer = SGD(model.parameters(), lr=0.001, momentum=0.9) scheduler = CyclicLR(optimizer, base_lr=0.001, max_lr=1, step_size_up=10) valid_loss, train_loss = [], [] avg_train_loss, avg_valid_loss = [], [] for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_cycl2/learning_rate"].log(optimizer.param_groups[0]['lr']) for img, lab in trainloader: y_pred = model(img) model.zero_grad() loss = lossFunc(y_pred, lab) loss.backward() optimizer.step() train_loss.append(loss.item()) avg_train_loss.append(w := (np.mean(np.array(train_loss)))) run[f"network_cycl2/train_loss"].log(w) train_loss = [] for img, lab in valloader: y_pred = model(img) loss = lossFunc(y_pred, lab) valid_loss.append(loss.item()) val_acc_per_pic = np.mean(GTA_tester(model, valloader, p = False)) run[f"network_cycl2/validation_mean_acc"].log(val_acc_per_pic) avg_valid_loss.append(w := (np.mean(np.array(valid_loss)))) run[f"network_cycl2/validation_loss"].log(w) valid_loss = [] scheduler.step() torch.save(model.state_dict(), "C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl2.pt") run[f"network_cycl2/network_weights"].upload(File("C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl2.pt")) test_acc_per_pic = GTA_tester(model, testloader) print(np.mean(test_acc_per_pic)) run[f"network_cycl2/test_accuracy_per_pic"].log(test_acc_per_pic) run[f"network_cycl2/mean_test_accuracy"].log(np.mean(test_acc_per_pic)) params = {"optimizer":"SGD", "optimizer_momentum": 0.99, "optimizer_learning_rate": 0.001, "loss_function":"MSEloss", "model":"GTA_Unet", "scheduler":"CyclicLR", "scheduler_base_lr":0.001, "scheduler_max_lr":1.25, "scheduler_step_size_up":10} run[f"network_cycl3/parameters"] = params lossFunc = nn.MSELoss() model = GTA_Unet(n_channels = 3, n_classes = 9).to(device) optimizer = SGD(model.parameters(), lr=0.001, momentum=0.99) scheduler = CyclicLR(optimizer, base_lr=0.001, max_lr=1, step_size_up=10) valid_loss, train_loss = [], [] avg_train_loss, avg_valid_loss = [], [] for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_cycl3/learning_rate"].log(optimizer.param_groups[0]['lr']) for img, lab in trainloader: y_pred = model(img) model.zero_grad() loss = lossFunc(y_pred, lab) loss.backward() optimizer.step() train_loss.append(loss.item()) avg_train_loss.append(w := (np.mean(np.array(train_loss)))) run[f"network_cycl3/train_loss"].log(w) train_loss = [] for img, lab in valloader: y_pred = model(img) loss = lossFunc(y_pred, lab) valid_loss.append(loss.item()) val_acc_per_pic = np.mean(GTA_tester(model, valloader, p = False)) run[f"network_cycl3/validation_mean_acc"].log(val_acc_per_pic) avg_valid_loss.append(w := (np.mean(np.array(valid_loss)))) run[f"network_cycl3/validation_loss"].log(w) valid_loss = [] scheduler.step() torch.save(model.state_dict(), "C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl3.pt") run[f"network_cycl3/network_weights"].upload(File("C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl3.pt")) test_acc_per_pic = GTA_tester(model, testloader) print(np.mean(test_acc_per_pic)) run[f"network_cycl3/test_accuracy_per_pic"].log(test_acc_per_pic) run[f"network_cycl3/mean_test_accuracy"].log(np.mean(test_acc_per_pic))
[ "neptune.new.init", "neptune.new.types.File" ]
[((797, 815), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (811, 815), True, 'import numpy as np\n'), ((1078, 1121), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(856)', 'size': '(20)'}), '(low=1, high=856, size=20)\n', (1095, 1121), True, 'import numpy as np\n'), ((1147, 1261), 'GTApack.GTA_hotloader.GTA_hotloader', 'GTA_hotloader', ([], {'path': '"""C:/Users/Marc/Desktop/Billeder/train/"""', 'width': '(400)', 'height': '(300)', 'ind': 'val_set', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/Billeder/train/', width=400,\n height=300, ind=val_set, device=device)\n", (1160, 1261), False, 'from GTApack.GTA_hotloader import GTA_hotloader\n'), ((1329, 1445), 'GTApack.GTA_hotloader.GTA_hotloader', 'GTA_hotloader', ([], {'path': '"""C:/Users/Marc/Desktop/Billeder/train/"""', 'width': '(400)', 'height': '(300)', 'ind': 'train_set', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/Billeder/train/', width=400,\n height=300, ind=train_set, device=device)\n", (1342, 1445), False, 'from GTApack.GTA_hotloader import GTA_hotloader\n'), ((1512, 1634), 'GTApack.GTA_hotloader.GTA_hotloader', 'GTA_hotloader', ([], {'path': '"""C:/Users/Marc/Desktop/Billeder/test-val/"""', 'width': '(400)', 'height': '(300)', 'ind': 'test_val_set', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/Billeder/test-val/', width=400,\n height=300, ind=test_val_set, device=device)\n", (1525, 1634), False, 'from GTApack.GTA_hotloader import GTA_hotloader\n'), ((1744, 1836), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['valload'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(valload, batch_size=batch_size, shuffle=True,\n num_workers=0)\n', (1771, 1836), False, 'import torch\n'), ((1974, 2068), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainload'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(trainload, batch_size=batch_size, shuffle=True,\n num_workers=0)\n', (2001, 2068), False, 'import torch\n'), ((2205, 2298), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['testload'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(testload, batch_size=batch_size, shuffle=True,\n num_workers=0)\n', (2232, 2298), False, 'import torch\n'), ((2431, 2455), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (2440, 2455), False, 'import os\n'), ((2463, 2541), 'neptune.new.init', 'neptune.init', ([], {'project': '"""Deep-Learning-test/Deep-Learning-Test"""', 'api_token': 'token'}), "(project='Deep-Learning-test/Deep-Learning-Test', api_token=token)\n", (2475, 2541), True, 'import neptune.new as neptune\n'), ((2926, 2938), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2936, 2938), True, 'import torch.nn as nn\n'), ((3071, 3132), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.001)', 'max_lr': '(1)', 'step_size_up': '(10)'}), '(optimizer, base_lr=0.001, max_lr=1, step_size_up=10)\n', (3079, 3132), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau, CyclicLR, CosineAnnealingLR\n'), ((4361, 4390), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'testloader'], {}), '(model, testloader)\n', (4371, 4390), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((4906, 4918), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (4916, 4918), True, 'import torch.nn as nn\n'), ((5051, 5112), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.001)', 'max_lr': '(1)', 'step_size_up': '(10)'}), '(optimizer, base_lr=0.001, max_lr=1, step_size_up=10)\n', (5059, 5112), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau, CyclicLR, CosineAnnealingLR\n'), ((6341, 6370), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'testloader'], {}), '(model, testloader)\n', (6351, 6370), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((6887, 6899), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (6897, 6899), True, 'import torch.nn as nn\n'), ((7033, 7094), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.001)', 'max_lr': '(1)', 'step_size_up': '(10)'}), '(optimizer, base_lr=0.001, max_lr=1, step_size_up=10)\n', (7041, 7094), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau, CyclicLR, CosineAnnealingLR\n'), ((8323, 8352), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'testloader'], {}), '(model, testloader)\n', (8333, 8352), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((897, 942), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(4962)', 'size': '(100)'}), '(low=1, high=4962, size=100)\n', (914, 942), True, 'import numpy as np\n'), ((4270, 4339), 'neptune.new.types.File', 'File', (['"""C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl1.pt"""'], {}), "('C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl1.pt')\n", (4274, 4339), False, 'from neptune.new.types import File\n'), ((4397, 4422), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (4404, 4422), True, 'import numpy as np\n'), ((4536, 4561), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (4543, 4561), True, 'import numpy as np\n'), ((6250, 6319), 'neptune.new.types.File', 'File', (['"""C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl2.pt"""'], {}), "('C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl2.pt')\n", (6254, 6319), False, 'from neptune.new.types import File\n'), ((6377, 6402), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (6384, 6402), True, 'import numpy as np\n'), ((6516, 6541), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (6523, 6541), True, 'import numpy as np\n'), ((8232, 8301), 'neptune.new.types.File', 'File', (['"""C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl3.pt"""'], {}), "('C:/Users/Marc/Desktop/Billeder/params/moment/network_cycl3.pt')\n", (8236, 8301), False, 'from neptune.new.types import File\n'), ((8359, 8384), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (8366, 8384), True, 'import numpy as np\n'), ((8498, 8523), 'numpy.mean', 'np.mean', (['test_acc_per_pic'], {}), '(test_acc_per_pic)\n', (8505, 8523), True, 'import numpy as np\n'), ((721, 746), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (744, 746), False, 'import torch\n'), ((2947, 2982), 'GTApack.GTA_Unet.GTA_Unet', 'GTA_Unet', ([], {'n_channels': '(3)', 'n_classes': '(9)'}), '(n_channels=3, n_classes=9)\n', (2955, 2982), False, 'from GTApack.GTA_Unet import GTA_Unet\n'), ((3863, 3900), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'valloader'], {'p': '(False)'}), '(model, valloader, p=False)\n', (3873, 3900), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((4927, 4962), 'GTApack.GTA_Unet.GTA_Unet', 'GTA_Unet', ([], {'n_channels': '(3)', 'n_classes': '(9)'}), '(n_channels=3, n_classes=9)\n', (4935, 4962), False, 'from GTApack.GTA_Unet import GTA_Unet\n'), ((5843, 5880), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'valloader'], {'p': '(False)'}), '(model, valloader, p=False)\n', (5853, 5880), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((6908, 6943), 'GTApack.GTA_Unet.GTA_Unet', 'GTA_Unet', ([], {'n_channels': '(3)', 'n_classes': '(9)'}), '(n_channels=3, n_classes=9)\n', (6916, 6943), False, 'from GTApack.GTA_Unet import GTA_Unet\n'), ((7825, 7862), 'GTApack.GTA_tester.GTA_tester', 'GTA_tester', (['model', 'valloader'], {'p': '(False)'}), '(model, valloader, p=False)\n', (7835, 7862), False, 'from GTApack.GTA_tester import GTA_tester\n'), ((1026, 1043), 'torch.Generator', 'torch.Generator', ([], {}), '()\n', (1041, 1043), False, 'import torch\n'), ((3608, 3628), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (3616, 3628), True, 'import numpy as np\n'), ((4012, 4032), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (4020, 4032), True, 'import numpy as np\n'), ((5588, 5608), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (5596, 5608), True, 'import numpy as np\n'), ((5992, 6012), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (6000, 6012), True, 'import numpy as np\n'), ((7570, 7590), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (7578, 7590), True, 'import numpy as np\n'), ((7974, 7994), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (7982, 7994), True, 'import numpy as np\n')]
# # Copyright (c) 2016, deepsense.io # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from future.builtins import object from neptune.internal.cli.commands.command_names import CommandNames from neptune.internal.cli.commands.data.download import DataDownload from neptune.internal.cli.commands.data.list import DataList from neptune.internal.cli.commands.data.remove import DataRemove from neptune.internal.cli.commands.data.upload import DataUpload from neptune.internal.cli.commands.experiment.ls.formatting import RowFactory from neptune.internal.cli.commands.experiment.ls.ls_command import NeptuneExperimentLs from neptune.internal.cli.commands.framework import ( CommandExecutionContext, HandleCommandErrors, NeptuneCommandAdapter ) from neptune.internal.cli.commands.listing.table_formatting import ( AsciiTableFactory, ENTRY_DEFAULT_FIELDS, LeaderboardRowFormatter ) from neptune.internal.cli.commands.experiment.abort.abort_command import NeptuneExperimentAbort from neptune.internal.cli.commands.project_activate import ProjectActivate from neptune.internal.cli.commands.session import ( NeptuneLocalLogin, NeptuneLogout, NeptuneManualLogin, NeptuneApiToken) from neptune.internal.common.api.keycloak_api_service import KeycloakApiConfig, KeycloakApiService from neptune.internal.common.api.short_id_converter import ShortIdConverter from neptune.internal.common.config.job_config import ConfigKeys from neptune.internal.common.config.neptune_config import load_bool_env from neptune.internal.common.parsers.common_parameters_configurator import CommonParametersConfigurator from neptune.internal.common.parsers.type_mapper import TypeMapper from neptune.internal.common.utils.browser import ( NullBrowser, SilentBrowser, is_able_to_open_socket, is_webbrowser_operable ) class NeptuneCommandFactory(object): def __init__(self, config, api_service, keycloak_api_service, neptune_exec_factory, neptune_run_factory, neptune_notebook_factory, utilities_service, offline_token_storage_service, session): self._config = config self._api_service = api_service self._keycloak_api_service = keycloak_api_service self._neptune_exec_factory = neptune_exec_factory self._neptune_notebook_factory = neptune_notebook_factory self._neptune_run_factory = neptune_run_factory self._utilities_service = utilities_service self._offline_token_storage_service = offline_token_storage_service self.session = session def create_command(self, arguments): known_args = arguments.known_args name = known_args.command_to_run subcommand_name = known_args.subcommand if 'subcommand' in known_args else None if name == CommandNames.ACCOUNT and subcommand_name == CommandNames.LOGIN: keycloak_api_config = KeycloakApiConfig( auth_url=known_args.url if known_args.url else 'https://auth.neptune.ml' ) open_webbrowser = getattr(known_args, "open-webbrowser", None) should_open_browser = TypeMapper.to_bool(open_webbrowser if open_webbrowser is not None else "true") if not load_bool_env('NEPTUNE_MANUAL_LOGIN', default=False) and \ is_webbrowser_operable() and \ is_able_to_open_socket() and \ should_open_browser: return NeptuneLocalLogin( self._config, KeycloakApiService(keycloak_api_config), self._offline_token_storage_service, self._api_service, webbrowser=SilentBrowser()) else: if load_bool_env('NEPTUNE_OPEN_AUTH_URL') and is_webbrowser_operable() and should_open_browser: webbrowser = SilentBrowser() else: webbrowser = NullBrowser() _login_address = keycloak_api_config.manual_login_url return NeptuneManualLogin( config=self._config, auth_code_url=_login_address, keycloak_service=KeycloakApiService(keycloak_api_config), token_storage=self._offline_token_storage_service, api_service=self._api_service, webbrowser=webbrowser) elif name == CommandNames.ACCOUNT and subcommand_name == CommandNames.LOGOUT: return NeptuneLogout(token_storage=self._offline_token_storage_service) elif name == CommandNames.ACCOUNT and subcommand_name == CommandNames.API_TOKEN: subcommand_subname = known_args.subsubcommand if 'subsubcommand' in known_args else None if subcommand_subname in [CommandNames.GET]: return NeptuneApiToken(config=self._config, api_service=self._api_service) ctx = CommandExecutionContext( api_service=self._api_service, config=self._config, session=self.session) if name == CommandNames.EXEC: return self._neptune_exec_factory.create(experiment_id=known_args.experiment_id, environment=self._config.environment) elif name in CommandNames.EXPERIMENT_CMDS and subcommand_name == CommandNames.SEND_NOTEBOOK: return self._neptune_notebook_factory.create(inputs=self._config.input, environment=self._config.environment, worker=self._config.worker) elif (name in CommandNames.EXPERIMENT_CMDS and subcommand_name == CommandNames.SEND)\ or name == CommandNames.SEND: return self._neptune_run_factory.create( is_local=False, inputs=self._config.input, neptune_exec_factory=self._neptune_exec_factory, environment=self._config.environment, worker=self._config.worker ) elif (name in CommandNames.EXPERIMENT_CMDS and subcommand_name == CommandNames.RUN)\ or name == CommandNames.RUN: return self._neptune_run_factory.create( is_local=True, inputs=self._config.input, neptune_exec_factory=self._neptune_exec_factory, environment=self._config.environment, worker=None ) elif name in CommandNames.EXPERIMENT_CMDS and subcommand_name == CommandNames.ABORT: return NeptuneExperimentAbort( config=self._config, api_service=self._api_service, short_id_converter=ShortIdConverter(self._api_service), organization_name=self._config.organization_name, project_name=self._config.project_name ) elif name in CommandNames.EXPERIMENT_CMDS and subcommand_name == CommandNames.LIST: return NeptuneCommandAdapter( HandleCommandErrors( NeptuneExperimentLs( row_factory=RowFactory( formatter=LeaderboardRowFormatter(), fields=ENTRY_DEFAULT_FIELDS, table_factory=AsciiTableFactory) ) ), ctx=ctx) elif name == CommandNames.DATA and subcommand_name == CommandNames.UPLOAD: return DataUpload( config=self._config, api_service=self._api_service, organization_name=self._config.organization_name, project_name=self._config.project_name, path=known_args.path, recursive=known_args.recursive, destination=known_args.destination) elif name == CommandNames.DATA and subcommand_name == CommandNames.LS: return DataList( config=self._config, api_service=self._api_service, organization_name=self._config.organization_name, project_name=self._config.project_name, path=known_args.path, recursive=known_args.recursive) elif name == CommandNames.DATA and subcommand_name == CommandNames.RM: return DataRemove( config=self._config, api_service=self._api_service, organization_name=self._config.organization_name, project_name=self._config.project_name, path=known_args.path, recursive=known_args.recursive) elif name == CommandNames.DATA and subcommand_name == CommandNames.DOWNLOAD: return DataDownload( config=self._config, api_service=self._api_service, session=self.session, organization_name=self._config.organization_name, project_name=self._config.project_name, path=known_args.path, recursive=known_args.recursive, destination=known_args.destination) elif name == CommandNames.PROJECT and subcommand_name == CommandNames.ACTIVATE: profile = getattr(arguments.known_args, ConfigKeys.PROFILE, CommonParametersConfigurator.DEFAULT_PROFILE) return NeptuneCommandAdapter( HandleCommandErrors( ProjectActivate( api_service=self._api_service, organization_name=self._config.organization_name, project_name=self._config.project_name, profile=profile ) ), ctx) else: raise ValueError(u'Unknown command: neptune {}'.format(name))
[ "neptune.internal.common.utils.browser.SilentBrowser", "neptune.internal.common.utils.browser.NullBrowser", "neptune.internal.common.config.neptune_config.load_bool_env", "neptune.internal.cli.commands.data.upload.DataUpload", "neptune.internal.cli.commands.data.remove.DataRemove", "neptune.internal.cli.c...
[((5445, 5546), 'neptune.internal.cli.commands.framework.CommandExecutionContext', 'CommandExecutionContext', ([], {'api_service': 'self._api_service', 'config': 'self._config', 'session': 'self.session'}), '(api_service=self._api_service, config=self._config,\n session=self.session)\n', (5468, 5546), False, 'from neptune.internal.cli.commands.framework import CommandExecutionContext, HandleCommandErrors, NeptuneCommandAdapter\n'), ((3410, 3505), 'neptune.internal.common.api.keycloak_api_service.KeycloakApiConfig', 'KeycloakApiConfig', ([], {'auth_url': "(known_args.url if known_args.url else 'https://auth.neptune.ml')"}), "(auth_url=known_args.url if known_args.url else\n 'https://auth.neptune.ml')\n", (3427, 3505), False, 'from neptune.internal.common.api.keycloak_api_service import KeycloakApiConfig, KeycloakApiService\n'), ((3642, 3720), 'neptune.internal.common.parsers.type_mapper.TypeMapper.to_bool', 'TypeMapper.to_bool', (["(open_webbrowser if open_webbrowser is not None else 'true')"], {}), "(open_webbrowser if open_webbrowser is not None else 'true')\n", (3660, 3720), False, 'from neptune.internal.common.parsers.type_mapper import TypeMapper\n'), ((3819, 3843), 'neptune.internal.common.utils.browser.is_webbrowser_operable', 'is_webbrowser_operable', ([], {}), '()\n', (3841, 3843), False, 'from neptune.internal.common.utils.browser import NullBrowser, SilentBrowser, is_able_to_open_socket, is_webbrowser_operable\n'), ((3870, 3894), 'neptune.internal.common.utils.browser.is_able_to_open_socket', 'is_able_to_open_socket', ([], {}), '()\n', (3892, 3894), False, 'from neptune.internal.common.utils.browser import NullBrowser, SilentBrowser, is_able_to_open_socket, is_webbrowser_operable\n'), ((5027, 5091), 'neptune.internal.cli.commands.session.NeptuneLogout', 'NeptuneLogout', ([], {'token_storage': 'self._offline_token_storage_service'}), '(token_storage=self._offline_token_storage_service)\n', (5040, 5091), False, 'from neptune.internal.cli.commands.session import NeptuneLocalLogin, NeptuneLogout, NeptuneManualLogin, NeptuneApiToken\n'), ((3740, 3792), 'neptune.internal.common.config.neptune_config.load_bool_env', 'load_bool_env', (['"""NEPTUNE_MANUAL_LOGIN"""'], {'default': '(False)'}), "('NEPTUNE_MANUAL_LOGIN', default=False)\n", (3753, 3792), False, 'from neptune.internal.common.config.neptune_config import load_bool_env\n'), ((4039, 4078), 'neptune.internal.common.api.keycloak_api_service.KeycloakApiService', 'KeycloakApiService', (['keycloak_api_config'], {}), '(keycloak_api_config)\n', (4057, 4078), False, 'from neptune.internal.common.api.keycloak_api_service import KeycloakApiConfig, KeycloakApiService\n'), ((4261, 4299), 'neptune.internal.common.config.neptune_config.load_bool_env', 'load_bool_env', (['"""NEPTUNE_OPEN_AUTH_URL"""'], {}), "('NEPTUNE_OPEN_AUTH_URL')\n", (4274, 4299), False, 'from neptune.internal.common.config.neptune_config import load_bool_env\n'), ((4304, 4328), 'neptune.internal.common.utils.browser.is_webbrowser_operable', 'is_webbrowser_operable', ([], {}), '()\n', (4326, 4328), False, 'from neptune.internal.common.utils.browser import NullBrowser, SilentBrowser, is_able_to_open_socket, is_webbrowser_operable\n'), ((4387, 4402), 'neptune.internal.common.utils.browser.SilentBrowser', 'SilentBrowser', ([], {}), '()\n', (4400, 4402), False, 'from neptune.internal.common.utils.browser import NullBrowser, SilentBrowser, is_able_to_open_socket, is_webbrowser_operable\n'), ((4458, 4471), 'neptune.internal.common.utils.browser.NullBrowser', 'NullBrowser', ([], {}), '()\n', (4469, 4471), False, 'from neptune.internal.common.utils.browser import NullBrowser, SilentBrowser, is_able_to_open_socket, is_webbrowser_operable\n'), ((4207, 4222), 'neptune.internal.common.utils.browser.SilentBrowser', 'SilentBrowser', ([], {}), '()\n', (4220, 4222), False, 'from neptune.internal.common.utils.browser import NullBrowser, SilentBrowser, is_able_to_open_socket, is_webbrowser_operable\n'), ((4715, 4754), 'neptune.internal.common.api.keycloak_api_service.KeycloakApiService', 'KeycloakApiService', (['keycloak_api_config'], {}), '(keycloak_api_config)\n', (4733, 4754), False, 'from neptune.internal.common.api.keycloak_api_service import KeycloakApiConfig, KeycloakApiService\n'), ((5362, 5429), 'neptune.internal.cli.commands.session.NeptuneApiToken', 'NeptuneApiToken', ([], {'config': 'self._config', 'api_service': 'self._api_service'}), '(config=self._config, api_service=self._api_service)\n', (5377, 5429), False, 'from neptune.internal.cli.commands.session import NeptuneLocalLogin, NeptuneLogout, NeptuneManualLogin, NeptuneApiToken\n'), ((7297, 7332), 'neptune.internal.common.api.short_id_converter.ShortIdConverter', 'ShortIdConverter', (['self._api_service'], {}), '(self._api_service)\n', (7313, 7332), False, 'from neptune.internal.common.api.short_id_converter import ShortIdConverter\n'), ((8082, 8338), 'neptune.internal.cli.commands.data.upload.DataUpload', 'DataUpload', ([], {'config': 'self._config', 'api_service': 'self._api_service', 'organization_name': 'self._config.organization_name', 'project_name': 'self._config.project_name', 'path': 'known_args.path', 'recursive': 'known_args.recursive', 'destination': 'known_args.destination'}), '(config=self._config, api_service=self._api_service,\n organization_name=self._config.organization_name, project_name=self.\n _config.project_name, path=known_args.path, recursive=known_args.\n recursive, destination=known_args.destination)\n', (8092, 8338), False, 'from neptune.internal.cli.commands.data.upload import DataUpload\n'), ((8536, 8749), 'neptune.internal.cli.commands.data.list.DataList', 'DataList', ([], {'config': 'self._config', 'api_service': 'self._api_service', 'organization_name': 'self._config.organization_name', 'project_name': 'self._config.project_name', 'path': 'known_args.path', 'recursive': 'known_args.recursive'}), '(config=self._config, api_service=self._api_service,\n organization_name=self._config.organization_name, project_name=self.\n _config.project_name, path=known_args.path, recursive=known_args.recursive)\n', (8544, 8749), False, 'from neptune.internal.cli.commands.data.list import DataList\n'), ((8936, 9151), 'neptune.internal.cli.commands.data.remove.DataRemove', 'DataRemove', ([], {'config': 'self._config', 'api_service': 'self._api_service', 'organization_name': 'self._config.organization_name', 'project_name': 'self._config.project_name', 'path': 'known_args.path', 'recursive': 'known_args.recursive'}), '(config=self._config, api_service=self._api_service,\n organization_name=self._config.organization_name, project_name=self.\n _config.project_name, path=known_args.path, recursive=known_args.recursive)\n', (8946, 9151), False, 'from neptune.internal.cli.commands.data.remove import DataRemove\n'), ((9344, 9624), 'neptune.internal.cli.commands.data.download.DataDownload', 'DataDownload', ([], {'config': 'self._config', 'api_service': 'self._api_service', 'session': 'self.session', 'organization_name': 'self._config.organization_name', 'project_name': 'self._config.project_name', 'path': 'known_args.path', 'recursive': 'known_args.recursive', 'destination': 'known_args.destination'}), '(config=self._config, api_service=self._api_service, session=\n self.session, organization_name=self._config.organization_name,\n project_name=self._config.project_name, path=known_args.path, recursive\n =known_args.recursive, destination=known_args.destination)\n', (9356, 9624), False, 'from neptune.internal.cli.commands.data.download import DataDownload\n'), ((7768, 7793), 'neptune.internal.cli.commands.listing.table_formatting.LeaderboardRowFormatter', 'LeaderboardRowFormatter', ([], {}), '()\n', (7791, 7793), False, 'from neptune.internal.cli.commands.listing.table_formatting import AsciiTableFactory, ENTRY_DEFAULT_FIELDS, LeaderboardRowFormatter\n'), ((10105, 10267), 'neptune.internal.cli.commands.project_activate.ProjectActivate', 'ProjectActivate', ([], {'api_service': 'self._api_service', 'organization_name': 'self._config.organization_name', 'project_name': 'self._config.project_name', 'profile': 'profile'}), '(api_service=self._api_service, organization_name=self.\n _config.organization_name, project_name=self._config.project_name,\n profile=profile)\n', (10120, 10267), False, 'from neptune.internal.cli.commands.project_activate import ProjectActivate\n')]
# -*- coding: utf-8 -*- # # Copyright (c) 2017, deepsense.io # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging import time from functools import wraps from enum import Enum from future.utils import raise_from, iteritems from oauthlib.oauth2.rfc6749.errors import InvalidGrantError from neptune.generated.swagger_client.rest import ApiException from neptune.internal.common.api.exceptions import ( NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException) from neptune.internal.common.utils.time import compute_delay logger = logging.getLogger(__name__) ERROR_CODES_TO_RETRY = [0, 408, 500, 502, 503, 504] MAX_RETRY_DELAY = 128 REQUESTS_TIMEOUT = 13 class APIErrorCodes(int, Enum): OK = 200 MOVED = 302 CLIENT_ERROR = 400 UNAUTHORIZED = 401 PAYMENT_REQUIRED = 402 FORBIDDEN = 403 NOT_FOUND = 404 TIMEOUT = 408 PRECONDITION_FAILED = 412 UNPROCESSABLE_ENTITY = 422 def swagger_model_to_json(model): """ For Python, Swagger model properties are written in underscore_case. Model has to_dict() method, which converts the properties to JSON directly, preserving the underscore_case. The server expects camelCased properties. The mapping between different conventions is stored in Model.attribute_map property, but there is no method in the model to perform the conversion. :param model: Swagger model. :return: The model converted to JSON with renamed parameters, ready to be sent in a request. """ result = {} for attr, _ in iteritems(model.swagger_types): value = getattr(model, attr) json_attr_name = model.attribute_map[attr] if isinstance(value, list): result[json_attr_name] = [ swagger_model_to_json(x) if hasattr(x, "to_dict") else x for x in value] elif hasattr(value, "to_dict"): result[json_attr_name] = swagger_model_to_json(value) elif isinstance(value, dict): result[json_attr_name] = dict([ (item[0], swagger_model_to_json(item[1])) if hasattr(item[1], "to_dict") else item for item in iteritems(value)]) else: result[json_attr_name] = value return result def retry_request(fun): def retry_loop(*args, **kwargs): attempt = 1 while True: try: if attempt > 1: logger.info(u"Request failed. Retrying...") result = fun(*args, **kwargs) if attempt > 1: logger.info(u"Request succeeded!") return result except NeptuneServerResponseErrorException as response_error: if response_error.status not in ERROR_CODES_TO_RETRY: logger.info(response_error) raise response_error logger.debug(response_error) except NeptuneRefreshTokenExpiredException as exc: logger.debug(exc) raise exc except NeptuneServerRequestFailedException as exc: logger.debug(exc) delay = compute_delay(attempt, MAX_RETRY_DELAY) logger.info("Attempt #%d to call %s failed. Next try in %ds.", attempt, fun.__name__, delay) time.sleep(delay) attempt += 1 return retry_loop def log_exceptions(skip_error_codes): def wrap(func): def func_wrapper(*args, **kwargs): func_wrapper.__name__ = func.__name__ def log_exception(exc): logger.error('Failed to call ' + func.__name__) logger.exception(exc) try: return func(*args, **kwargs) except (NeptuneEntityNotFoundException, NeptuneValidationException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneRefreshTokenExpiredException, NeptuneServerRequestFailedException, NeptunePaymentRequiredException): raise except NeptuneServerResponseErrorException as exc: if exc.status not in skip_error_codes: log_exception(exc) raise except Exception as exc: log_exception(exc) raise return func_wrapper return wrap def wrap_exceptions(func): """ Wraps service exceptions as NeptuneException. In case of ApiException(302) from proxy - which means login page redirect, exception is mapped to ApiException(401) - unauthorized. """ @wraps(func) def func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ApiException as exc: if exc.status == APIErrorCodes.PAYMENT_REQUIRED: raise NeptunePaymentRequiredException(exc.status, exc) elif exc.status == APIErrorCodes.NOT_FOUND: raise NeptuneEntityNotFoundException(exc.status, exc) elif exc.status == APIErrorCodes.UNPROCESSABLE_ENTITY: raise NeptuneUnprocessableEntityException(exc.status, exc) elif exc.status == APIErrorCodes.CLIENT_ERROR: if u'validationError' in exc.body: raise NeptuneValidationException(exc) else: raise NeptuneBadClientRequest(exc.status, exc) elif exc.status == APIErrorCodes.TIMEOUT: raise ServerTimedOutException(exc.status, exc) else: raise NeptuneServerResponseErrorException(exc.status, exc) except InvalidGrantError as err: logger.debug(err) if err.description == u'Stale refresh token': raise NeptuneRefreshTokenExpiredException() elif err.description == u'Client session not active': raise NeptuneRefreshTokenExpiredException() else: raise_from(NeptuneServerRequestFailedException(err), err) except Exception as exc: raise_from(NeptuneServerRequestFailedException(exc), exc) return func_wrapper def handle_warning(func): def headers_handler(headers): if u'Warning' in headers: print(headers.get(u"Warning").replace(u"299 -", u"WARNING:")) @wraps(func) def func_wrapper(*args, **kwargs): return func(*args, **dict(kwargs, headers_handler=headers_handler)) return func_wrapper class WithLoggedExceptions(object): CODES_SKIPPED_BY_DEFAULT = [APIErrorCodes.FORBIDDEN, APIErrorCodes.UNAUTHORIZED, APIErrorCodes.UNPROCESSABLE_ENTITY, APIErrorCodes.CLIENT_ERROR] def __init__(self, obj, skipped_error_codes=None): self._obj = obj self._skipped_error_codes = skipped_error_codes or {} def __getattr__(self, name): method = getattr(self._obj, name) error_codes = self.CODES_SKIPPED_BY_DEFAULT if name in self._skipped_error_codes: error_codes = error_codes + self._skipped_error_codes[name] return log_exceptions(skip_error_codes=error_codes)(method) class WithRetries(object): def __init__(self, obj, omit=None): self._obj = obj self._omitted = omit or [] def __getattr__(self, name): method = getattr(self._obj, name) if name in self._omitted: return method else: return retry_request(method) class WithWrappedExceptions(object): def __init__(self, obj): self._obj = obj def __getattr__(self, name): method = getattr(self._obj, name) return wrap_exceptions(method) class WithWarningHandler(object): def __init__(self, obj): self._obj = obj def __getattr__(self, name): method = getattr(self._obj, name) return handle_warning(method)
[ "neptune.internal.common.api.exceptions.NeptuneUnprocessableEntityException", "neptune.internal.common.api.exceptions.ServerTimedOutException", "neptune.internal.common.api.exceptions.NeptuneEntityNotFoundException", "neptune.internal.common.api.exceptions.NeptuneServerRequestFailedException", "neptune.inte...
[((1346, 1373), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1363, 1373), False, 'import logging\n'), ((2327, 2357), 'future.utils.iteritems', 'iteritems', (['model.swagger_types'], {}), '(model.swagger_types)\n', (2336, 2357), False, 'from future.utils import raise_from, iteritems\n'), ((5394, 5405), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (5399, 5405), False, 'from functools import wraps\n'), ((7113, 7124), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (7118, 7124), False, 'from functools import wraps\n'), ((3935, 3974), 'neptune.internal.common.utils.time.compute_delay', 'compute_delay', (['attempt', 'MAX_RETRY_DELAY'], {}), '(attempt, MAX_RETRY_DELAY)\n', (3948, 3974), False, 'from neptune.internal.common.utils.time import compute_delay\n'), ((4116, 4133), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (4126, 4133), False, 'import time\n'), ((5619, 5667), 'neptune.internal.common.api.exceptions.NeptunePaymentRequiredException', 'NeptunePaymentRequiredException', (['exc.status', 'exc'], {}), '(exc.status, exc)\n', (5650, 5667), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((6554, 6591), 'neptune.internal.common.api.exceptions.NeptuneRefreshTokenExpiredException', 'NeptuneRefreshTokenExpiredException', ([], {}), '()\n', (6589, 6591), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((6866, 6906), 'neptune.internal.common.api.exceptions.NeptuneServerRequestFailedException', 'NeptuneServerRequestFailedException', (['exc'], {}), '(exc)\n', (6901, 6906), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((5746, 5793), 'neptune.internal.common.api.exceptions.NeptuneEntityNotFoundException', 'NeptuneEntityNotFoundException', (['exc.status', 'exc'], {}), '(exc.status, exc)\n', (5776, 5793), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((6680, 6717), 'neptune.internal.common.api.exceptions.NeptuneRefreshTokenExpiredException', 'NeptuneRefreshTokenExpiredException', ([], {}), '()\n', (6715, 6717), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((5883, 5935), 'neptune.internal.common.api.exceptions.NeptuneUnprocessableEntityException', 'NeptuneUnprocessableEntityException', (['exc.status', 'exc'], {}), '(exc.status, exc)\n', (5918, 5935), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((6763, 6803), 'neptune.internal.common.api.exceptions.NeptuneServerRequestFailedException', 'NeptuneServerRequestFailedException', (['err'], {}), '(err)\n', (6798, 6803), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((2942, 2958), 'future.utils.iteritems', 'iteritems', (['value'], {}), '(value)\n', (2951, 2958), False, 'from future.utils import raise_from, iteritems\n'), ((6072, 6103), 'neptune.internal.common.api.exceptions.NeptuneValidationException', 'NeptuneValidationException', (['exc'], {}), '(exc)\n', (6098, 6103), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((6152, 6192), 'neptune.internal.common.api.exceptions.NeptuneBadClientRequest', 'NeptuneBadClientRequest', (['exc.status', 'exc'], {}), '(exc.status, exc)\n', (6175, 6192), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((6269, 6309), 'neptune.internal.common.api.exceptions.ServerTimedOutException', 'ServerTimedOutException', (['exc.status', 'exc'], {}), '(exc.status, exc)\n', (6292, 6309), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n'), ((6350, 6402), 'neptune.internal.common.api.exceptions.NeptuneServerResponseErrorException', 'NeptuneServerResponseErrorException', (['exc.status', 'exc'], {}), '(exc.status, exc)\n', (6385, 6402), False, 'from neptune.internal.common.api.exceptions import NeptuneEntityNotFoundException, NeptuneServerRequestFailedException, NeptuneServerResponseErrorException, NeptuneRefreshTokenExpiredException, NeptuneUnprocessableEntityException, NeptuneBadClientRequest, ServerTimedOutException, NeptuneValidationException, NeptunePaymentRequiredException\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import Optional, TYPE_CHECKING, Union, Iterable from neptune.new.attributes import File from neptune.new.attributes.file_set import FileSet from neptune.new.attributes.series import FileSeries from neptune.new.attributes.series.float_series import FloatSeries from neptune.new.attributes.series.string_series import StringSeries from neptune.new.attributes.sets.string_set import StringSet from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, \ is_float_like, is_string_like from neptune.new.internal.utils.paths import join_paths, parse_path from neptune.new.types.atoms.file import File as FileVal if TYPE_CHECKING: from neptune.new.run import Run class Handler: def __init__(self, run: 'Run', path: str): super().__init__() self._run = run self._path = path def __getitem__(self, path: str) -> 'Handler': return Handler(self._run, join_paths(self._path, path)) def __setitem__(self, key: str, value) -> None: self[key].assign(value) def __getattr__(self, attribute_name): attr = self._run.get_attribute(self._path) if attr: return getattr(attr, attribute_name) else: raise AttributeError() def assign(self, value, wait: bool = False) -> None: if not isinstance(value, dict): return self._assign_impl(value, wait) for key, value in value.items(): self[key].assign(value, wait) def _assign_impl(self, value, wait: bool = False) -> None: with self._run.lock(): attr = self._run.get_attribute(self._path) if attr: attr.assign(value, wait) else: self._run.define(self._path, value, wait) def upload(self, value, wait: bool = False) -> None: value = FileVal.create_from(value) with self._run.lock(): attr = self._run.get_attribute(self._path) if not attr: attr = File(self._run, parse_path(self._path)) attr.upload(value, wait) self._run.set_attribute(self._path, attr) else: attr.upload(value, wait) def upload_files(self, value: Union[str, Iterable[str]], wait: bool = False) -> None: if is_collection(value): verify_collection_type("value", value, str) else: verify_type("value", value, str) with self._run.lock(): attr = self._run.get_attribute(self._path) if not attr: attr = FileSet(self._run, parse_path(self._path)) attr.upload_files(value, wait) self._run.set_attribute(self._path, attr) else: attr.upload_files(value, wait) def log(self, value, step: Optional[float] = None, timestamp: Optional[float] = None, wait: bool = False, **kwargs) -> None: verify_type("step", step, (int, float, type(None))) verify_type("timestamp", timestamp, (int, float, type(None))) with self._run.lock(): attr = self._run.get_attribute(self._path) if not attr: if is_collection(value): if value: first_value = next(iter(value)) else: raise ValueError("Cannot deduce value type: `value` cannot be empty") else: first_value = value if is_float(first_value): attr = FloatSeries(self._run, parse_path(self._path)) elif is_string(first_value): attr = StringSeries(self._run, parse_path(self._path)) elif FileVal.is_convertable(first_value): attr = FileSeries(self._run, parse_path(self._path)) elif is_float_like(first_value): attr = FloatSeries(self._run, parse_path(self._path)) elif is_string_like(first_value): attr = StringSeries(self._run, parse_path(self._path)) else: raise TypeError("Value of unsupported type {}".format(type(first_value))) attr.log(value, step=step, timestamp=timestamp, wait=wait, **kwargs) self._run.set_attribute(self._path, attr) else: attr.log(value, step=step, timestamp=timestamp, wait=wait, **kwargs) def add(self, values: Union[str, Iterable[str]], wait: bool = False) -> None: verify_type("values", values, (str, Iterable)) with self._run.lock(): attr = self._run.get_attribute(self._path) if not attr: attr = StringSet(self._run, parse_path(self._path)) attr.add(values, wait) self._run.set_attribute(self._path, attr) else: attr.add(values, wait) def pop(self, path: str, wait: bool = False) -> None: verify_type("path", path, str) self._run.pop(join_paths(self._path, path), wait) def __delitem__(self, path) -> None: self.pop(path)
[ "neptune.new.internal.utils.verify_collection_type", "neptune.new.internal.utils.paths.parse_path", "neptune.new.internal.utils.is_float_like", "neptune.new.internal.utils.is_float", "neptune.new.types.atoms.file.File.is_convertable", "neptune.new.internal.utils.is_string", "neptune.new.internal.utils.i...
[((2473, 2499), 'neptune.new.types.atoms.file.File.create_from', 'FileVal.create_from', (['value'], {}), '(value)\n', (2492, 2499), True, 'from neptune.new.types.atoms.file import File as FileVal\n'), ((2935, 2955), 'neptune.new.internal.utils.is_collection', 'is_collection', (['value'], {}), '(value)\n', (2948, 2955), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((5231, 5277), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""values"""', 'values', '(str, Iterable)'], {}), "('values', values, (str, Iterable))\n", (5242, 5277), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((5678, 5708), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""path"""', 'path', 'str'], {}), "('path', path, str)\n", (5689, 5708), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((1555, 1583), 'neptune.new.internal.utils.paths.join_paths', 'join_paths', (['self._path', 'path'], {}), '(self._path, path)\n', (1565, 1583), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((2969, 3012), 'neptune.new.internal.utils.verify_collection_type', 'verify_collection_type', (['"""value"""', 'value', 'str'], {}), "('value', value, str)\n", (2991, 3012), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((3039, 3071), 'neptune.new.internal.utils.verify_type', 'verify_type', (['"""value"""', 'value', 'str'], {}), "('value', value, str)\n", (3050, 3071), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((5731, 5759), 'neptune.new.internal.utils.paths.join_paths', 'join_paths', (['self._path', 'path'], {}), '(self._path, path)\n', (5741, 5759), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((3871, 3891), 'neptune.new.internal.utils.is_collection', 'is_collection', (['value'], {}), '(value)\n', (3884, 3891), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((4181, 4202), 'neptune.new.internal.utils.is_float', 'is_float', (['first_value'], {}), '(first_value)\n', (4189, 4202), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((2651, 2673), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (2661, 2673), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((3226, 3248), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (3236, 3248), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((4299, 4321), 'neptune.new.internal.utils.is_string', 'is_string', (['first_value'], {}), '(first_value)\n', (4308, 4321), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((5433, 5455), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (5443, 5455), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((4254, 4276), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (4264, 4276), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((4419, 4454), 'neptune.new.types.atoms.file.File.is_convertable', 'FileVal.is_convertable', (['first_value'], {}), '(first_value)\n', (4441, 4454), True, 'from neptune.new.types.atoms.file import File as FileVal\n'), ((4374, 4396), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (4384, 4396), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((4550, 4576), 'neptune.new.internal.utils.is_float_like', 'is_float_like', (['first_value'], {}), '(first_value)\n', (4563, 4576), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((4505, 4527), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (4515, 4527), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((4673, 4700), 'neptune.new.internal.utils.is_string_like', 'is_string_like', (['first_value'], {}), '(first_value)\n', (4687, 4700), False, 'from neptune.new.internal.utils import verify_type, is_collection, verify_collection_type, is_float, is_string, is_float_like, is_string_like\n'), ((4628, 4650), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (4638, 4650), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n'), ((4753, 4775), 'neptune.new.internal.utils.paths.parse_path', 'parse_path', (['self._path'], {}), '(self._path)\n', (4763, 4775), False, 'from neptune.new.internal.utils.paths import join_paths, parse_path\n')]
import neptune.new as neptune # download runs table from Neptune my_project = neptune.get_project(name="common/colab-test-run", api_token="<PASSWORD>") run_df = my_project.fetch_runs_table(tag=["advanced"]).to_pandas() run_df.head() # resume run run = neptune.init(project="common/colab-test-run", api_token="<PASSWORD>", run="COL-7") # update run parameters batch_size = run["parameters/batch_size"].fetch() last_batch_acc = run["batch/accuracy"].fetch_last() print("batch_size: {}".format(batch_size)) print("last_batch_acc: {}".format(last_batch_acc)) # download model from run run["model"].download()
[ "neptune.new.get_project", "neptune.new.init" ]
[((79, 152), 'neptune.new.get_project', 'neptune.get_project', ([], {'name': '"""common/colab-test-run"""', 'api_token': '"""<PASSWORD>"""'}), "(name='common/colab-test-run', api_token='<PASSWORD>')\n", (98, 152), True, 'import neptune.new as neptune\n'), ((254, 341), 'neptune.new.init', 'neptune.init', ([], {'project': '"""common/colab-test-run"""', 'api_token': '"""<PASSWORD>"""', 'run': '"""COL-7"""'}), "(project='common/colab-test-run', api_token='<PASSWORD>', run=\n 'COL-7')\n", (266, 341), True, 'import neptune.new as neptune\n')]
# # Copyright (c) 2022, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=protected-access import os import unittest from mock import patch from neptune.new import ANONYMOUS, Run, get_last_run, init_run from neptune.new.attributes.atoms import String from neptune.new.envs import API_TOKEN_ENV_NAME, PROJECT_ENV_NAME from neptune.new.exceptions import MissingFieldException, NeptuneUninitializedException from neptune.new.internal.backends.api_model import ( Attribute, AttributeType, IntAttribute, ) from neptune.new.internal.backends.neptune_backend_mock import NeptuneBackendMock from neptune.utils import IS_WINDOWS from tests.neptune.new.client.abstract_experiment_test_mixin import ( AbstractExperimentTestMixin, ) from tests.neptune.new.utils.api_experiments_factory import api_run AN_API_RUN = api_run() @patch("neptune.new.internal.backends.factory.HostedNeptuneBackend", NeptuneBackendMock) class TestClientRun(AbstractExperimentTestMixin, unittest.TestCase): @staticmethod def call_init(**kwargs): return init_run(**kwargs) @classmethod def setUpClass(cls) -> None: os.environ[PROJECT_ENV_NAME] = "organization/project" os.environ[API_TOKEN_ENV_NAME] = ANONYMOUS @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container", new=lambda _, container_id, expected_container_type: AN_API_RUN, ) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_attributes", new=lambda _, _uuid, _type: [Attribute("some/variable", AttributeType.INT)], ) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_int_attribute", new=lambda _, _uuid, _type, _path: IntAttribute(42), ) def test_read_only_mode(self): exp = init_run(mode="read-only", run="whatever") with self.assertLogs() as caplog: exp["some/variable"] = 13 exp["some/other_variable"] = 11 self.assertEqual( caplog.output, [ "WARNING:neptune.new.internal.operation_processors.read_only_operation_processor:" "Client in read-only mode, nothing will be saved to server." ], ) self.assertEqual(42, exp["some/variable"].fetch()) self.assertNotIn(str(exp._id), os.listdir(".neptune")) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container", new=lambda _, container_id, expected_container_type: AN_API_RUN, ) @patch( "neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_attributes", new=lambda _, _uuid, _type: [Attribute("test", AttributeType.STRING)], ) def test_resume(self): with init_run(flush_period=0.5, run="whatever") as exp: self.assertEqual(exp._id, AN_API_RUN.id) self.assertIsInstance(exp.get_structure()["test"], String) @patch("neptune.new.internal.utils.source_code.sys.argv", ["main.py"]) @patch("neptune.new.internal.init.run.os.path.isfile", new=lambda file: "." in file) @patch( "neptune.new.internal.utils.glob", new=lambda path, recursive=False: [path.replace("*", "file.txt")], ) @patch( "neptune.new.internal.utils.os.path.abspath", new=lambda path: os.path.normpath("/home/user/main_dir/" + path), ) @patch("neptune.new.internal.utils.os.getcwd", new=lambda: "/home/user/main_dir") @unittest.skipIf(IS_WINDOWS, "Linux/Mac test") def test_entrypoint(self): exp = init_run(mode="debug") self.assertEqual(exp["source_code/entrypoint"].fetch(), "main.py") exp = init_run(mode="debug", source_files=[]) self.assertEqual(exp["source_code/entrypoint"].fetch(), "main.py") exp = init_run(mode="debug", source_files=["../*"]) self.assertEqual(exp["source_code/entrypoint"].fetch(), "main_dir/main.py") exp = init_run(mode="debug", source_files=["internal/*"]) self.assertEqual(exp["source_code/entrypoint"].fetch(), "main.py") exp = init_run(mode="debug", source_files=["../other_dir/*"]) self.assertEqual(exp["source_code/entrypoint"].fetch(), "../main_dir/main.py") @patch("neptune.new.internal.utils.source_code.sys.argv", ["main.py"]) @patch("neptune.new.internal.utils.source_code.is_ipython", new=lambda: True) def test_entrypoint_in_interactive_python(self): exp = init_run(mode="debug") with self.assertRaises(MissingFieldException): exp["source_code/entrypoint"].fetch() exp = init_run(mode="debug", source_files=[]) with self.assertRaises(MissingFieldException): exp["source_code/entrypoint"].fetch() exp = init_run(mode="debug", source_files=["../*"]) with self.assertRaises(MissingFieldException): exp["source_code/entrypoint"].fetch() exp = init_run(mode="debug", source_files=["internal/*"]) with self.assertRaises(MissingFieldException): exp["source_code/entrypoint"].fetch() @patch("neptune.new.internal.utils.source_code.sys.argv", ["main.py"]) @patch("neptune.new.internal.utils.source_code.get_common_root", new=lambda _: None) @patch("neptune.new.internal.init.run.os.path.isfile", new=lambda file: "." in file) @patch( "neptune.new.internal.utils.glob", new=lambda path, recursive=False: [path.replace("*", "file.txt")], ) @patch( "neptune.new.internal.utils.os.path.abspath", new=lambda path: os.path.normpath("/home/user/main_dir/" + path), ) def test_entrypoint_without_common_root(self): exp = init_run(mode="debug", source_files=["../*"]) self.assertEqual( exp["source_code/entrypoint"].fetch(), "/home/user/main_dir/main.py" ) exp = init_run(mode="debug", source_files=["internal/*"]) self.assertEqual( exp["source_code/entrypoint"].fetch(), "/home/user/main_dir/main.py" ) def test_last_exp_is_raising_exception_when_non_initialized(self): # given uninitialized run Run.last_run = None # expect: raises NeptuneUninitializedException with self.assertRaises(NeptuneUninitializedException): get_last_run() def test_last_exp_is_the_latest_initialized(self): # given two initialized runs with init_run() as exp1, init_run() as exp2: # expect: `neptune.latest_run` to be the latest initialized one self.assertIsNot(exp1, get_last_run()) self.assertIs(exp2, get_last_run())
[ "neptune.new.internal.backends.api_model.IntAttribute", "neptune.new.get_last_run", "neptune.new.init_run", "neptune.new.internal.backends.api_model.Attribute" ]
[((1362, 1371), 'tests.neptune.new.utils.api_experiments_factory.api_run', 'api_run', ([], {}), '()\n', (1369, 1371), False, 'from tests.neptune.new.utils.api_experiments_factory import api_run\n'), ((1375, 1466), 'mock.patch', 'patch', (['"""neptune.new.internal.backends.factory.HostedNeptuneBackend"""', 'NeptuneBackendMock'], {}), "('neptune.new.internal.backends.factory.HostedNeptuneBackend',\n NeptuneBackendMock)\n", (1380, 1466), False, 'from mock import patch\n'), ((1783, 1959), 'mock.patch', 'patch', (['"""neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container"""'], {'new': '(lambda _, container_id, expected_container_type: AN_API_RUN)'}), "(\n 'neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container'\n , new=lambda _, container_id, expected_container_type: AN_API_RUN)\n", (1788, 1959), False, 'from mock import patch\n'), ((2992, 3168), 'mock.patch', 'patch', (['"""neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container"""'], {'new': '(lambda _, container_id, expected_container_type: AN_API_RUN)'}), "(\n 'neptune.new.internal.backends.neptune_backend_mock.NeptuneBackendMock.get_metadata_container'\n , new=lambda _, container_id, expected_container_type: AN_API_RUN)\n", (2997, 3168), False, 'from mock import patch\n'), ((3596, 3665), 'mock.patch', 'patch', (['"""neptune.new.internal.utils.source_code.sys.argv"""', "['main.py']"], {}), "('neptune.new.internal.utils.source_code.sys.argv', ['main.py'])\n", (3601, 3665), False, 'from mock import patch\n'), ((3671, 3758), 'mock.patch', 'patch', (['"""neptune.new.internal.init.run.os.path.isfile"""'], {'new': "(lambda file: '.' in file)"}), "('neptune.new.internal.init.run.os.path.isfile', new=lambda file: '.' in\n file)\n", (3676, 3758), False, 'from mock import patch\n'), ((4042, 4127), 'mock.patch', 'patch', (['"""neptune.new.internal.utils.os.getcwd"""'], {'new': "(lambda : '/home/user/main_dir')"}), "('neptune.new.internal.utils.os.getcwd', new=lambda :\n '/home/user/main_dir')\n", (4047, 4127), False, 'from mock import patch\n'), ((4128, 4173), 'unittest.skipIf', 'unittest.skipIf', (['IS_WINDOWS', '"""Linux/Mac test"""'], {}), "(IS_WINDOWS, 'Linux/Mac test')\n", (4143, 4173), False, 'import unittest\n'), ((4898, 4967), 'mock.patch', 'patch', (['"""neptune.new.internal.utils.source_code.sys.argv"""', "['main.py']"], {}), "('neptune.new.internal.utils.source_code.sys.argv', ['main.py'])\n", (4903, 4967), False, 'from mock import patch\n'), ((4973, 5050), 'mock.patch', 'patch', (['"""neptune.new.internal.utils.source_code.is_ipython"""'], {'new': '(lambda : True)'}), "('neptune.new.internal.utils.source_code.is_ipython', new=lambda : True)\n", (4978, 5050), False, 'from mock import patch\n'), ((5749, 5818), 'mock.patch', 'patch', (['"""neptune.new.internal.utils.source_code.sys.argv"""', "['main.py']"], {}), "('neptune.new.internal.utils.source_code.sys.argv', ['main.py'])\n", (5754, 5818), False, 'from mock import patch\n'), ((5824, 5911), 'mock.patch', 'patch', (['"""neptune.new.internal.utils.source_code.get_common_root"""'], {'new': '(lambda _: None)'}), "('neptune.new.internal.utils.source_code.get_common_root', new=lambda\n _: None)\n", (5829, 5911), False, 'from mock import patch\n'), ((5913, 6000), 'mock.patch', 'patch', (['"""neptune.new.internal.init.run.os.path.isfile"""'], {'new': "(lambda file: '.' in file)"}), "('neptune.new.internal.init.run.os.path.isfile', new=lambda file: '.' in\n file)\n", (5918, 6000), False, 'from mock import patch\n'), ((1594, 1612), 'neptune.new.init_run', 'init_run', ([], {}), '(**kwargs)\n', (1602, 1612), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((2399, 2441), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""read-only"""', 'run': '"""whatever"""'}), "(mode='read-only', run='whatever')\n", (2407, 2441), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((4219, 4241), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""'}), "(mode='debug')\n", (4227, 4241), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((4332, 4371), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': '[]'}), "(mode='debug', source_files=[])\n", (4340, 4371), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((4462, 4507), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': "['../*']"}), "(mode='debug', source_files=['../*'])\n", (4470, 4507), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((4607, 4658), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': "['internal/*']"}), "(mode='debug', source_files=['internal/*'])\n", (4615, 4658), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((4749, 4804), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': "['../other_dir/*']"}), "(mode='debug', source_files=['../other_dir/*'])\n", (4757, 4804), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((5117, 5139), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""'}), "(mode='debug')\n", (5125, 5139), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((5260, 5299), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': '[]'}), "(mode='debug', source_files=[])\n", (5268, 5299), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((5420, 5465), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': "['../*']"}), "(mode='debug', source_files=['../*'])\n", (5428, 5465), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((5586, 5637), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': "['internal/*']"}), "(mode='debug', source_files=['internal/*'])\n", (5594, 5637), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((6344, 6389), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': "['../*']"}), "(mode='debug', source_files=['../*'])\n", (6352, 6389), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((6522, 6573), 'neptune.new.init_run', 'init_run', ([], {'mode': '"""debug"""', 'source_files': "['internal/*']"}), "(mode='debug', source_files=['internal/*'])\n", (6530, 6573), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((2962, 2984), 'os.listdir', 'os.listdir', (['""".neptune"""'], {}), "('.neptune')\n", (2972, 2984), False, 'import os\n'), ((3415, 3457), 'neptune.new.init_run', 'init_run', ([], {'flush_period': '(0.5)', 'run': '"""whatever"""'}), "(flush_period=0.5, run='whatever')\n", (3423, 3457), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((6956, 6970), 'neptune.new.get_last_run', 'get_last_run', ([], {}), '()\n', (6968, 6970), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((7077, 7087), 'neptune.new.init_run', 'init_run', ([], {}), '()\n', (7085, 7087), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((7097, 7107), 'neptune.new.init_run', 'init_run', ([], {}), '()\n', (7105, 7107), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((2326, 2342), 'neptune.new.internal.backends.api_model.IntAttribute', 'IntAttribute', (['(42)'], {}), '(42)\n', (2338, 2342), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute\n'), ((3982, 4029), 'os.path.normpath', 'os.path.normpath', (["('/home/user/main_dir/' + path)"], {}), "('/home/user/main_dir/' + path)\n", (3998, 4029), False, 'import os\n'), ((6224, 6271), 'os.path.normpath', 'os.path.normpath', (["('/home/user/main_dir/' + path)"], {}), "('/home/user/main_dir/' + path)\n", (6240, 6271), False, 'import os\n'), ((7228, 7242), 'neptune.new.get_last_run', 'get_last_run', ([], {}), '()\n', (7240, 7242), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((7276, 7290), 'neptune.new.get_last_run', 'get_last_run', ([], {}), '()\n', (7288, 7290), False, 'from neptune.new import ANONYMOUS, Run, get_last_run, init_run\n'), ((2118, 2163), 'neptune.new.internal.backends.api_model.Attribute', 'Attribute', (['"""some/variable"""', 'AttributeType.INT'], {}), "('some/variable', AttributeType.INT)\n", (2127, 2163), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute\n'), ((3327, 3366), 'neptune.new.internal.backends.api_model.Attribute', 'Attribute', (['"""test"""', 'AttributeType.STRING'], {}), "('test', AttributeType.STRING)\n", (3336, 3366), False, 'from neptune.new.internal.backends.api_model import Attribute, AttributeType, IntAttribute\n')]
import neptune.new as neptune run = neptune.init(project="common/colab-test-run", api_token="<PASSWORD>") params = {"learning_rate": 0.1} # log params run["parameters"] = params # log name and append tags run["sys/name"] = "basic-colab-example" run["sys/tags"].add(["colab", "intro"]) # log loss during training for epoch in range(100): run["train/loss"].log(0.99 ** epoch) # log train and validation scores run["train/accuracy"] = 0.95 run["valid/accuracy"] = 0.93
[ "neptune.new.init" ]
[((37, 106), 'neptune.new.init', 'neptune.init', ([], {'project': '"""common/colab-test-run"""', 'api_token': '"""<PASSWORD>"""'}), "(project='common/colab-test-run', api_token='<PASSWORD>')\n", (49, 106), True, 'import neptune.new as neptune\n')]
""" Log using `neptune <https://www.neptune.ml>`_ Neptune logger can be used in the online mode or offline (silent) mode. To log experiment data in online mode, NeptuneLogger requries an API key: .. code-block:: python from pytorch_lightning.logging import NeptuneLogger # arguments made to NeptuneLogger are passed on to the neptune.experiments.Experiment class neptune_logger = NeptuneLogger( api_key=os.environ["NEPTUNE_API_TOKEN"], project_name="USER_NAME/PROJECT_NAME", experiment_name="default", # Optional, params={"max_epochs": 10}, # Optional, tags=["pytorch-lightning","mlp"] # Optional, ) trainer = Trainer(max_epochs=10, logger=neptune_logger) Use the logger anywhere in you LightningModule as follows: .. code-block:: python def train_step(...): # example self.logger.experiment.log_metric("acc_train", acc_train) # log metrics self.logger.experiment.log_image("worse_predictions", prediction_image) # log images self.logger.experiment.log_artifact("model_checkpoint.pt", prediction_image) # log model checkpoint self.logger.experiment.whatever_neptune_supports(...) def any_lightning_module_function_or_hook(...): self.logger.experiment.log_metric("acc_train", acc_train) # log metrics self.logger.experiment.log_image("worse_predictions", prediction_image) # log images self.logger.experiment.log_artifact("model_checkpoint.pt", prediction_image) # log model checkpoint self.logger.experiment.whatever_neptune_supports(...) """ from logging import getLogger try: import neptune except ImportError: raise ImportError('Missing neptune package. Run `pip install neptune-client`') from torch import is_tensor # from .base import LightningLoggerBase, rank_zero_only from pytorch_lightning.logging.base import LightningLoggerBase, rank_zero_only logger = getLogger(__name__) class NeptuneLogger(LightningLoggerBase): def __init__(self, api_key=None, project_name=None, offline_mode=False, experiment_name=None, upload_source_files=None, params=None, properties=None, tags=None, **kwargs): r""" Initialize a neptune.ml logger. .. note:: Requires either an API Key (online mode) or a local directory path (offline mode) .. code-block:: python # ONLINE MODE from pytorch_lightning.logging import NeptuneLogger # arguments made to NeptuneLogger are passed on to the neptune.experiments.Experiment class neptune_logger = NeptuneLogger( api_key=os.environ["NEPTUNE_API_TOKEN"], project_name="USER_NAME/PROJECT_NAME", experiment_name="default", # Optional, params={"max_epochs": 10}, # Optional, tags=["pytorch-lightning","mlp"] # Optional, ) trainer = Trainer(max_epochs=10, logger=neptune_logger) .. code-block:: python # OFFLINE MODE from pytorch_lightning.logging import NeptuneLogger # arguments made to NeptuneLogger are passed on to the neptune.experiments.Experiment class neptune_logger = NeptuneLogger( project_name="USER_NAME/PROJECT_NAME", experiment_name="default", # Optional, params={"max_epochs": 10}, # Optional, tags=["pytorch-lightning","mlp"] # Optional, ) trainer = Trainer(max_epochs=10, logger=neptune_logger) Args: api_key (str | None): Required in online mode. Neputne API token, found on https://neptune.ml. Read how to get your API key https://docs.neptune.ml/python-api/tutorials/get-started.html#copy-api-token. project_name (str): Required in online mode. Qualified name of a project in a form of "namespace/project_name" for example "tom/minst-classification". If None, the value of NEPTUNE_PROJECT environment variable will be taken. You need to create the project in https://neptune.ml first. offline_mode (bool): Optional default False. If offline_mode=True no logs will be send to neptune. Usually used for debug purposes. experiment_name (str|None): Optional. Editable name of the experiment. Name is displayed in the experiment’s Details (Metadata section) and in experiments view as a column. upload_source_files (list|None): Optional. List of source files to be uploaded. Must be list of str or single str. Uploaded sources are displayed in the experiment’s Source code tab. If None is passed, Python file from which experiment was created will be uploaded. Pass empty list ([]) to upload no files. Unix style pathname pattern expansion is supported. For example, you can pass '*.py' to upload all python source files from the current directory. For recursion lookup use '**/*.py' (for Python 3.5 and later). For more information see glob library. params (dict|None): Optional. Parameters of the experiment. After experiment creation params are read-only. Parameters are displayed in the experiment’s Parameters section and each key-value pair can be viewed in experiments view as a column. properties (dict|None): Optional default is {}. Properties of the experiment. They are editable after experiment is created. Properties are displayed in the experiment’s Details and each key-value pair can be viewed in experiments view as a column. tags (list|None): Optional default []. Must be list of str. Tags of the experiment. They are editable after experiment is created (see: append_tag() and remove_tag()). Tags are displayed in the experiment’s Details and can be viewed in experiments view as a column. """ super().__init__() self.api_key = api_key self.project_name = project_name self.offline_mode = offline_mode self.experiment_name = experiment_name self.upload_source_files = upload_source_files self.params = params self.properties = properties self.tags = tags self._experiment = None self._kwargs = kwargs if offline_mode: self.mode = "offline" neptune.init(project_qualified_name='dry-run/project', backend=neptune.OfflineBackend()) else: self.mode = "online" neptune.init(api_token=self.api_key, project_qualified_name=self.project_name) logger.info(f"NeptuneLogger was initialized in {self.mode} mode") @property def experiment(self): r""" Actual neptune object. To use neptune features do the following. Example:: self.logger.experiment.some_neptune_function() """ if self._experiment is not None: return self._experiment else: self._experiment = neptune.create_experiment(name=self.experiment_name, params=self.params, properties=self.properties, tags=self.tags, upload_source_files=self.upload_source_files, **self._kwargs) return self._experiment @rank_zero_only def log_hyperparams(self, params): for key, val in vars(params).items(): self.experiment.set_property(f"param__{key}", val) @rank_zero_only def log_metrics(self, metrics, step=None): """Log metrics (numeric values) in Neptune experiments :param float metric: Dictionary with metric names as keys and measured quanties as values :param int|None step: Step number at which the metrics should be recorded, must be strictly increasing """ for key, val in metrics.items(): if is_tensor(val): val = val.cpu().detach() if step is None: self.experiment.log_metric(key, val) else: self.experiment.log_metric(key, x=step, y=val) @rank_zero_only def finalize(self, status): self.experiment.stop() @property def name(self): if self.mode == "offline": return "offline-name" else: return self.experiment.name @property def version(self): if self.mode == "offline": return "offline-id-1234" else: return self.experiment.id @rank_zero_only def log_metric(self, metric_name, metric_value, step=None): """Log metrics (numeric values) in Neptune experiments :param str metric_name: The name of log, i.e. mse, loss, accuracy. :param str metric_value: The value of the log (data-point). :param int|None step: Step number at which the metrics should be recorded, must be strictly increasing """ if step is None: self.experiment.log_metric(metric_name, metric_value) else: self.experiment.log_metric(metric_name, x=step, y=metric_value) @rank_zero_only def log_text(self, log_name, text, step=None): """Log text data in Neptune experiment :param str log_name: The name of log, i.e. mse, my_text_data, timing_info. :param str text: The value of the log (data-point). :param int|None step: Step number at which the metrics should be recorded, must be strictly increasing """ if step is None: self.experiment.log_metric(log_name, text) else: self.experiment.log_metric(log_name, x=step, y=text) @rank_zero_only def log_image(self, log_name, image, step=None): """Log image data in Neptune experiment :param str log_name: The name of log, i.e. bboxes, visualisations, sample_images. :param str|PIL.Image|matplotlib.figure.Figure image: The value of the log (data-point). Can be one of the following types: PIL image, matplotlib.figure.Figure, path to image file (str) :param int|None step: Step number at which the metrics should be recorded, must be strictly increasing """ if step is None: self.experiment.log_image(log_name, image) else: self.experiment.log_image(log_name, x=step, y=image) @rank_zero_only def log_artifact(self, artifact, destination=None): """Save an artifact (file) in Neptune experiment storage. :param str artifact: A path to the file in local filesystem. :param str|None destination: Optional default None. A destination path. If None is passed, an artifact file name will be used. """ self.experiment.log_artifact(artifact, destination) @rank_zero_only def set_property(self, key, value): """Set key-value pair as Neptune experiment property. :param str key: Property key. :param obj value: New value of a property. """ self.experiment.set_property(key, value) @rank_zero_only def append_tags(self, tags): """appends tags to neptune experiment :param str|tuple|list(str) tags: Tags to add to the current experiment. If str is passed, singe tag is added. If multiple - comma separated - str are passed, all of them are added as tags. If list of str is passed, all elements of the list are added as tags. """ if not isinstance(tags, (list, set, tuple)): tags = [tags] # make it as an iterable is if it is not yet self.experiment.append_tags(*tags)
[ "neptune.OfflineBackend", "neptune.create_experiment", "neptune.init" ]
[((1927, 1946), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (1936, 1946), False, 'from logging import getLogger\n'), ((6715, 6793), 'neptune.init', 'neptune.init', ([], {'api_token': 'self.api_key', 'project_qualified_name': 'self.project_name'}), '(api_token=self.api_key, project_qualified_name=self.project_name)\n', (6727, 6793), False, 'import neptune\n'), ((7237, 7424), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': 'self.experiment_name', 'params': 'self.params', 'properties': 'self.properties', 'tags': 'self.tags', 'upload_source_files': 'self.upload_source_files'}), '(name=self.experiment_name, params=self.params,\n properties=self.properties, tags=self.tags, upload_source_files=self.\n upload_source_files, **self._kwargs)\n', (7262, 7424), False, 'import neptune\n'), ((8313, 8327), 'torch.is_tensor', 'is_tensor', (['val'], {}), '(val)\n', (8322, 8327), False, 'from torch import is_tensor\n'), ((6630, 6654), 'neptune.OfflineBackend', 'neptune.OfflineBackend', ([], {}), '()\n', (6652, 6654), False, 'import neptune\n')]
"""Implement a callback to log images.""" # ============================================================================= # Copyright 2021 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= from pathlib import Path from typing import Any, Dict, List, Sequence, Tuple, Union try: from neptune.new.types import File as NeptuneFile except ImportError: NeptuneFile = None import numpy as np from PIL import Image, ImageDraw, ImageFont from pytorch_lightning.callbacks import Callback from pytorch_lightning.loggers.base import LoggerCollection from pytorch_lightning.loggers.comet import CometLogger from pytorch_lightning.loggers.neptune import NeptuneLogger from pytorch_lightning.loggers.tensorboard import TensorBoardLogger from pytorch_lightning.loggers.wandb import WandbLogger from pytorch_lightning.trainer.trainer import Trainer import torch import torch.nn.functional as F from torchvision.utils import make_grid try: import wandb except ImportError: wandb = None from ptlflow.models.base_model.base_model import BaseModel from ptlflow.utils import flow_utils from ptlflow.utils.utils import config_logging config_logging() class LoggerCallback(Callback): """Callback to collect and log images during training and validation. For each dataloader, num_images samples will be collected. The samples are collected by trying to retrieve from both inputs and outputs tensors whose keys match the values provided in log_keys. num_images samples are uniformly sampled from the whole dataloader. """ def __init__( self, num_images: int = 5, image_size: Tuple[int, int] = (200, 400), log_keys: Sequence[str] = ('images', 'flows', 'occs', 'mbs', 'confs'), epe_clip: float = 5.0 ) -> None: """Initialize LoggerCallback. Parameters ---------- num_images : int, default 5 Number of images to log during one epoch. image_size : Tuple[int, int], default (200, 400) The size of the stored images. log_keys : Sequence[str], default ('images', 'flows', 'occs', 'mbs', 'confs') The keys to use to collect the images from the inputs and outputs of the model. If a key is not found, it is ignored. epe_clip : float, default 5.0 The maximum EPE value that is shown on EPE image. All EPE values above this will be clipped. """ super().__init__() self.num_images = num_images self.image_size = image_size self.log_keys = log_keys self.epe_clip = epe_clip self.train_collect_img_idx = [] self.train_images = {} self.val_dataloader_names = [] self.val_collect_image_idx = {} self.val_images = {} def log_image( self, title: str, image: torch.Tensor, pl_module: BaseModel ) -> None: """Log the image in all of the pl_module loggers. Note, however, that not all loggers may be able to log images. Parameters ---------- title : str A title for the image. image : torch.Tensor The image to log. It must be a 3D tensor CHW (typically C=3). pl_module : BaseModel An instance of the optical flow model to get the logger from. """ image_npy = image.permute(1, 2, 0).numpy() logger_collection = pl_module.logger if logger_collection is not None: if not isinstance(logger_collection, LoggerCollection): logger_collection = LoggerCollection([logger_collection]) for logger in logger_collection: if isinstance(logger, CometLogger): logger.experiment.log_image(image_npy, name=title) elif isinstance(logger, NeptuneLogger): logger.experiment[title].log(NeptuneFile.as_image(image)) elif isinstance(logger, TensorBoardLogger): logger.experiment.add_image(title, image, pl_module.global_step) elif isinstance(logger, WandbLogger) and wandb is not None: title_wb = title.replace('/', '-') image_wb = wandb.Image(image_npy) logger.experiment.log({title_wb: image_wb}) def on_train_batch_end( self, trainer: Trainer, pl_module: BaseModel, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor], batch_idx: int, dataloader_idx: int ) -> None: """Store one image to be logged, if the current batch_idx is in the log selection group. Parameters ---------- trainer : Trainer An instance of the PyTorch Lightning trainer. pl_module : BaseModel An instance of the optical flow model. outputs : Dict[str, torch.Tensor] The outputs of the current training batch. batch : Dict[str, torch.Tensor] The inputs of the current training batch. batch_idx : int The counter value of the current batch. dataloader_idx : int The index number of the current dataloader. """ if batch_idx in self.train_collect_img_idx: self._append_images(self.train_images, pl_module.last_inputs, pl_module.last_predictions) def on_train_epoch_start( self, trainer: Trainer, pl_module: BaseModel ) -> None: """Reset the training log params and accumulators. Parameters ---------- trainer : Trainer An instance of the PyTorch Lightning trainer. pl_module : BaseModel An instance of the optical flow model. """ self.train_images = {} collect_idx = np.unique(np.linspace( 0, self._compute_max_range(pl_module.train_dataloader_length, pl_module.args.limit_train_batches), self.num_images, dtype=np.int32)) self.train_collect_img_idx = collect_idx def on_train_epoch_end( self, trainer: Trainer, pl_module: BaseModel, outputs: Any = None # This arg does not exist anymore, but it is kept here for compatibility ) -> None: """Log the images accumulated during the training. Parameters ---------- trainer : Trainer An instance of the PyTorch Lightning trainer. pl_module : BaseModel An instance of the optical flow model. outputs : Any Outputs of the training epoch. """ img_grid = self._make_image_grid(self.train_images) self.log_image('train', img_grid, pl_module) def on_validation_batch_end( self, trainer: Trainer, pl_module: BaseModel, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor], batch_idx: int, dataloader_idx: int ) -> None: """Store one image to be logged, if the current batch_idx is in the log selection group. Parameters ---------- trainer : Trainer An instance of the PyTorch Lightning trainer. pl_module : BaseModel An instance of the optical flow model. outputs : Dict[str, torch.Tensor] The outputs of the current validation batch. batch : Dict[str, torch.Tensor] The inputs of the current validation batch. batch_idx : int The counter value of the current batch. dataloader_idx : int The index number of the current dataloader. """ dl_name = self.val_dataloader_names[dataloader_idx] if batch_idx in self.val_collect_image_idx[dl_name]: self._append_images(self.val_images[dl_name], pl_module.last_inputs, pl_module.last_predictions) def on_validation_epoch_start( self, trainer: Trainer, pl_module: BaseModel ) -> None: """Reset the validation log params and accumulators. Parameters ---------- trainer : Trainer An instance of the PyTorch Lightning trainer. pl_module : BaseModel An instance of the optical flow model. """ self.val_dataloader_names = pl_module.val_dataloader_names for dl_name in self.val_dataloader_names: self.val_images[dl_name] = {} for dname, dlen in zip(pl_module.val_dataloader_names, pl_module.val_dataloader_lengths): collect_idx = np.unique(np.linspace( 0, self._compute_max_range(dlen, pl_module.args.limit_val_batches), self.num_images, dtype=np.int32)) self.val_collect_image_idx[dname] = collect_idx def on_validation_epoch_end( self, trainer: Trainer, pl_module: BaseModel ) -> None: """Log the images accumulated during the validation. Parameters ---------- trainer : Trainer An instance of the PyTorch Lightning trainer. pl_module : BaseModel An instance of the optical flow model. """ for dl_name, dl_images in self.val_images.items(): img_grid = self._make_image_grid(dl_images) self.log_image(f'val/{dl_name}', img_grid, pl_module) def _add_title( self, image: torch.Tensor, img_title: str ) -> torch.Tensor: """Add a title to an image. Parameters ---------- image : torch.Tensor The image where the title will be added. img_title : str The title to be added. Returns ------- torch.Tensor The input image with the title superposed on it. """ size = min(image.shape[1:3]) image = (255*image.permute(1, 2, 0).numpy()).astype(np.uint8) image = Image.fromarray(image) this_dir = Path(__file__).resolve().parent title_font = ImageFont.truetype(str(this_dir / 'RobotoMono-Regular.ttf'), size//10) draw = ImageDraw.Draw(image) bb = (size//25, size//25, size//25+len(img_title)*size//15, size//25+size//8) draw.rectangle(bb, fill='black') draw.text((size//20, size//30), img_title, (237, 230, 211), font=title_font) image = np.array(image) image = torch.from_numpy(image.transpose(2, 0, 1)).float() / 255 return image def _append_images( # noqa: C901 self, images: Dict[str, List[torch.Tensor]], inputs: Dict[str, torch.Tensor], preds: Dict[str, torch.Tensor] ) -> None: """Append samples to the images accumulator. Parameters ---------- images : Dict[str, List[torch.Tensor]] The accumulator where the samples will be appended to. inputs : Dict[str, torch.Tensor] The inputs of the model. preds : Dict[str, torch.Tensor] The outrputs of the model. """ for k in self.log_keys: log_names = [] log_sources = [] if k in inputs or (k == 'confs' and k in preds): log_names.append(f'i_{k}') log_sources.append(inputs) if k in preds: log_names.append(f'o_{k}') log_sources.append(preds) if k == 'flows': log_names.append(f'epe<{self.epe_clip:.1f}') log_sources.append(None) for name, source in zip(log_names, log_sources): if images.get(name) is None: images[name] = [] if name == 'i_confs': img = self._compute_confidence_gt(preds['flows'], inputs['flows']) elif name.startswith('epe'): epe = torch.norm(preds[k] - inputs[k], p=2, dim=2, keepdim=True) img = torch.clamp(epe, 0, self.epe_clip) / self.epe_clip if inputs.get('valids') is not None: img[inputs['valids'] < 0.5] = 0 else: img = source[k] img = img[:1, 0].detach().cpu() img = F.interpolate(img, self.image_size) img = img[0] if 'images' in name: img = img.flip([0]) # BGR to RGB elif 'flows' in name: img = flow_utils.flow_to_rgb(img) images[name].append(img) def _compute_confidence_gt( self, pred_flows: torch.Tensor, target_flows: torch.Tensor ) -> torch.Tensor: """Compute a confidence score for the flow predictions. This score was proposed in https://arxiv.org/abs/2007.09319. Parameters ---------- pred_flows : torch.Tensor The predicted optical flow. target_flows : torch.Tensor The groundtruth optical flow. Returns ------- torch.Tensor The confidence score for each pixel of the input. """ conf_gt = torch.exp(-torch.pow(pred_flows - target_flows, 2).sum(dim=2, keepdim=True)) return conf_gt def _compute_max_range( self, dataloader_length: int, limit_batches: Union[float, int] ) -> int: """Find the maximum number of samples that will be drawn from a dataloader. Parameters ---------- dataloader_length : int Total size of the dataloader. limit_batches : Union[float, int] A value that may decrease the samples in the dataloader. See --limit_val_batches or --limit_train_batches from PyTorch Lightning for more information. Returns ------- int The maximum number of samples that will be drawn from the dataloader. """ if isinstance(limit_batches, int): max_range = limit_batches - 1 else: max_range = int(limit_batches * dataloader_length) - 1 return max_range def _make_image_grid( self, dl_images: Dict[str, List[torch.Tensor]] ) -> torch.Tensor: """Transform a bunch of images into a single one by adding them to a grid. Parameters ---------- dl_images : Dict[str, List[torch.Tensor]] Lists of images, each identified by a title name. Returns ------- torch.Tensor A single 3D tensor image 3HW. """ imgs = [] for img_label, img_list in dl_images.items(): for j, im in enumerate(img_list): if len(im.shape) == 2: im = im[None] if im.shape[0] == 1: im = im.repeat(3, 1, 1) if j == 0: im = self._add_title(im, img_label) imgs.append(im) grid = make_grid(imgs, len(imgs)//len(dl_images)) return grid
[ "neptune.new.types.File.as_image" ]
[((1712, 1728), 'ptlflow.utils.utils.config_logging', 'config_logging', ([], {}), '()\n', (1726, 1728), False, 'from ptlflow.utils.utils import config_logging\n'), ((10498, 10520), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (10513, 10520), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((10681, 10702), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['image'], {}), '(image)\n', (10695, 10702), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((10932, 10947), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (10940, 10947), True, 'import numpy as np\n'), ((4169, 4206), 'pytorch_lightning.loggers.base.LoggerCollection', 'LoggerCollection', (['[logger_collection]'], {}), '([logger_collection])\n', (4185, 4206), False, 'from pytorch_lightning.loggers.base import LoggerCollection\n'), ((12824, 12859), 'torch.nn.functional.interpolate', 'F.interpolate', (['img', 'self.image_size'], {}), '(img, self.image_size)\n', (12837, 12859), True, 'import torch.nn.functional as F\n'), ((10541, 10555), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (10545, 10555), False, 'from pathlib import Path\n'), ((12446, 12504), 'torch.norm', 'torch.norm', (['(preds[k] - inputs[k])'], {'p': '(2)', 'dim': '(2)', 'keepdim': '(True)'}), '(preds[k] - inputs[k], p=2, dim=2, keepdim=True)\n', (12456, 12504), False, 'import torch\n'), ((13045, 13072), 'ptlflow.utils.flow_utils.flow_to_rgb', 'flow_utils.flow_to_rgb', (['img'], {}), '(img)\n', (13067, 13072), False, 'from ptlflow.utils import flow_utils\n'), ((13736, 13775), 'torch.pow', 'torch.pow', (['(pred_flows - target_flows)', '(2)'], {}), '(pred_flows - target_flows, 2)\n', (13745, 13775), False, 'import torch\n'), ((4481, 4508), 'neptune.new.types.File.as_image', 'NeptuneFile.as_image', (['image'], {}), '(image)\n', (4501, 4508), True, 'from neptune.new.types import File as NeptuneFile\n'), ((12531, 12565), 'torch.clamp', 'torch.clamp', (['epe', '(0)', 'self.epe_clip'], {}), '(epe, 0, self.epe_clip)\n', (12542, 12565), False, 'import torch\n'), ((4817, 4839), 'wandb.Image', 'wandb.Image', (['image_npy'], {}), '(image_npy)\n', (4828, 4839), False, 'import wandb\n')]
from typing import Dict, List import neptune from catalyst.core.callback import ( Callback, CallbackNode, CallbackOrder, CallbackScope, ) from catalyst.core.runner import IRunner class NeptuneLogger(Callback): """Logger callback, translates ``runner.*_metrics`` to Neptune. Read about Neptune here https://neptune.ai Example: .. code-block:: python from catalyst.dl import SupervisedRunner from catalyst.contrib.dl.callbacks.neptune import NeptuneLogger runner = SupervisedRunner() runner.train( model=model, criterion=criterion, optimizer=optimizer, loaders=loaders, logdir=logdir, num_epochs=num_epochs, verbose=True, callbacks=[ NeptuneLogger( api_token="...", # your Neptune token project_name="your_project_name", offline_mode=False, # turn off neptune for debug name="your_experiment_name", params={...}, # your hyperparameters tags=["resnet", "no-augmentations"], # tags upload_source_files=["*.py"], # files to save ) ] ) You can see an example experiment here: https://ui.neptune.ai/o/shared/org/catalyst-integration/e/CAT-13/charts You can log your experiments without registering. Just use "ANONYMOUS" token:: runner.train( ... callbacks=[ "NepuneLogger( api_token="<PASSWORD>", project_name="shared/catalyst-integration", ... ) ] ) """ def __init__( self, metric_names: List[str] = None, log_on_batch_end: bool = True, log_on_epoch_end: bool = True, offline_mode: bool = False, **logging_params, ): """ Args: metric_names (List[str]): list of metric names to log, if none - logs everything log_on_batch_end (bool): logs per-batch metrics if set True log_on_epoch_end (bool): logs per-epoch metrics if set True offline_mode (bool): whether logging to Neptune server should be turned off. It is useful for debugging """ super().__init__( order=CallbackOrder.logging, node=CallbackNode.master, scope=CallbackScope.experiment, ) self.metrics_to_log = metric_names self.log_on_batch_end = log_on_batch_end self.log_on_epoch_end = log_on_epoch_end if not (self.log_on_batch_end or self.log_on_epoch_end): raise ValueError("You have to log something!") if (self.log_on_batch_end and not self.log_on_epoch_end) or ( not self.log_on_batch_end and self.log_on_epoch_end ): self.batch_log_suffix = "" self.epoch_log_suffix = "" else: self.batch_log_suffix = "_batch" self.epoch_log_suffix = "_epoch" if offline_mode: neptune.init( project_qualified_name="dry-run/project", backend=neptune.OfflineBackend(), ) else: neptune.init( api_token=logging_params["api_token"], project_qualified_name=logging_params["project_name"], ) logging_params.pop("api_token") logging_params.pop("project_name") self.experiment = neptune.create_experiment(**logging_params) def __del__(self): """@TODO: Docs. Contribution is welcome""" if hasattr(self, "experiment"): self.experiment.stop() def _log_metrics( self, metrics: Dict[str, float], step: int, mode: str, suffix="" ): if self.metrics_to_log is None: metrics_to_log = sorted(metrics.keys()) else: metrics_to_log = self.metrics_to_log for name in metrics_to_log: if name in metrics: metric_name = f"{name}/{mode}{suffix}" metric_value = metrics[name] self.experiment.log_metric(metric_name, y=metric_value, x=step) def on_batch_end(self, runner: IRunner): """Log batch metrics to Neptune.""" if self.log_on_batch_end: mode = runner.loader_name metrics = runner.batch_metrics self._log_metrics( metrics=metrics, step=runner.global_sample_step, mode=mode, suffix=self.batch_log_suffix, ) def on_loader_end(self, runner: IRunner): """Translate epoch metrics to Neptune.""" if self.log_on_epoch_end: mode = runner.loader_name metrics = runner.loader_metrics self._log_metrics( metrics=metrics, step=runner.global_epoch, mode=mode, suffix=self.epoch_log_suffix, ) __all__ = ["NeptuneLogger"]
[ "neptune.create_experiment", "neptune.init", "neptune.OfflineBackend" ]
[((3817, 3860), 'neptune.create_experiment', 'neptune.create_experiment', ([], {}), '(**logging_params)\n', (3842, 3860), False, 'import neptune\n'), ((3552, 3663), 'neptune.init', 'neptune.init', ([], {'api_token': "logging_params['api_token']", 'project_qualified_name': "logging_params['project_name']"}), "(api_token=logging_params['api_token'], project_qualified_name=\n logging_params['project_name'])\n", (3564, 3663), False, 'import neptune\n'), ((3486, 3510), 'neptune.OfflineBackend', 'neptune.OfflineBackend', ([], {}), '()\n', (3508, 3510), False, 'import neptune\n')]
# # Copyright (c) 2019, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=protected-access import contextlib import io import os import sys import unittest from typing import Optional from unittest import mock from uuid import uuid4 import altair as alt import matplotlib import numpy import pandas import plotly.express as px from bokeh.plotting import figure from matplotlib import pyplot from matplotlib.figure import Figure from PIL import Image from vega_datasets import data from neptune.new.internal.utils.images import get_html_content, get_image_content from neptune.utils import IS_MACOS, IS_WINDOWS matplotlib.use("agg") class TestImage(unittest.TestCase): TEST_DIR = "/tmp/neptune/{}".format(uuid4()) def setUp(self): if not os.path.exists(self.TEST_DIR): os.makedirs(self.TEST_DIR) def test_get_image_content_from_pil_image(self): # given image_array = self._random_image_array() expected_image = Image.fromarray(image_array.astype(numpy.uint8)) # expect self.assertEqual(get_image_content(expected_image), self._encode_pil_image(expected_image)) def test_get_image_content_from_2d_grayscale_array(self): # given image_array = self._random_image_array(d=None) scaled_array = image_array * 255 expected_image = Image.fromarray(scaled_array.astype(numpy.uint8)) # expect self.assertEqual(get_image_content(image_array), self._encode_pil_image(expected_image)) def test_get_image_content_from_3d_grayscale_array(self): # given image_array = numpy.array([[[1], [0]], [[-3], [4]], [[5], [6]]]) expected_array = numpy.array([[1, 0], [-3, 4], [5, 6]]) * 255 expected_image = Image.fromarray(expected_array.astype(numpy.uint8)) # expect stdout = io.StringIO() with contextlib.redirect_stdout(stdout): self.assertEqual(get_image_content(image_array), self._encode_pil_image(expected_image)) self.assertEqual( stdout.getvalue(), "The smallest value in the array is -3 and the largest value in the array is 6." " To be interpreted as colors correctly values in the array need to be in the [0, 1] range.\n", ) def test_get_image_content_from_rgb_array(self): # given image_array = self._random_image_array() scaled_array = image_array * 255 expected_image = Image.fromarray(scaled_array.astype(numpy.uint8)) # expect self.assertEqual(get_image_content(image_array), self._encode_pil_image(expected_image)) # and make sure that original image's size was preserved self.assertFalse((image_array * 255 - scaled_array).any()) def test_get_image_content_from_rgba_array(self): # given image_array = self._random_image_array(d=4) scaled_array = image_array * 255 expected_image = Image.fromarray(scaled_array.astype(numpy.uint8)) # expect self.assertEqual(get_image_content(image_array), self._encode_pil_image(expected_image)) # and make sure that original image's size was preserved self.assertFalse((image_array * 255 - scaled_array).any()) def test_get_image_content_from_figure(self): # given pyplot.plot([1, 2, 3, 4]) pyplot.ylabel("some interesting numbers") fig = pyplot.gcf() # expect self.assertEqual(get_image_content(fig), self._encode_figure(fig)) @unittest.skipIf(IS_WINDOWS, "Installing Torch on Windows takes too long") @unittest.skipIf( IS_MACOS and sys.version_info.major == 3 and sys.version_info.minor == 10, "No torch for 3.10 on Mac", ) def test_get_image_content_from_torch_tensor(self): import torch # pylint: disable=C0415 # given image_tensor = torch.rand(200, 300, 3) # pylint: disable=no-member expected_array = image_tensor.numpy() * 255 expected_image = Image.fromarray(expected_array.astype(numpy.uint8)) # expect self.assertEqual(get_image_content(image_tensor), self._encode_pil_image(expected_image)) # and make sure that original image's size was preserved self.assertFalse((image_tensor.numpy() * 255 - expected_array).any()) def test_get_image_content_from_tensorflow_tensor(self): import tensorflow as tf # pylint: disable=C0415 # given # pylint: disable=E1120 # false positive image_tensor = tf.random.uniform(shape=[200, 300, 3]) expected_array = image_tensor.numpy() * 255 expected_image = Image.fromarray(expected_array.astype(numpy.uint8)) # expect self.assertEqual(get_image_content(image_tensor), self._encode_pil_image(expected_image)) def test_get_html_from_matplotlib_figure(self): # given fig = pyplot.figure() x = [ 21, 22, 23, 4, 5, 6, 77, 8, 9, 10, 31, 32, 33, 34, 35, 36, 37, 18, 49, 50, 100, ] pyplot.hist(x, bins=5) # when result = get_html_content(fig) # then self.assertTrue(result.startswith('<html>\n<head><meta charset="utf-8" />')) def test_get_html_from_plotly(self): # given df = px.data.tips() fig = px.histogram( df, x="total_bill", y="tip", color="sex", marginal="rug", hover_data=df.columns, ) # when result = get_html_content(fig) # then self.assertTrue(result.startswith('<html>\n<head><meta charset="utf-8" />')) def test_get_html_from_altair(self): # given source = data.cars() chart = ( alt.Chart(source) .mark_circle(size=60) .encode( x="Horsepower", y="Miles_per_Gallon", color="Origin", tooltip=["Name", "Origin", "Horsepower", "Miles_per_Gallon"], ) .interactive() ) # when result = get_html_content(chart) # then self.assertTrue(result.startswith("<!DOCTYPE html>\n<html>\n<head>\n <style>")) def test_get_html_from_bokeh(self): # given p = figure(plot_width=400, plot_height=400) p.circle(size=20, color="navy", alpha=0.5) # when result = get_html_content(p) # then self.assertTrue(result.startswith('<!DOCTYPE html>\n<html lang="en">')) def test_get_html_from_pandas(self): # given table = pandas.DataFrame( numpy.random.randn(6, 4), index=pandas.date_range("20130101", periods=6), columns=list("ABCD"), ) # when result = get_html_content(table) # then self.assertTrue( result.startswith( '<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">' ) ) def test_get_oversize_html_from_pandas(self): # given table = mock.Mock(spec=pandas.DataFrame) table.to_html.return_value = 40_000_000 * "a" # when with self.assertLogs() as caplog: result = get_html_content(table) # then self.assertIsNone(result) self.assertEqual( caplog.output, [ "WARNING:neptune.new.internal.utils.limits:You are attempting to create an in-memory file that" " is 38.1MB large. Neptune supports logging in-memory file objects smaller than 32MB." " Resize or increase compression of this object" ], ) @staticmethod def _encode_pil_image(image: Image) -> bytes: with io.BytesIO() as image_buffer: image.save(image_buffer, format="PNG") return image_buffer.getvalue() @staticmethod def _encode_figure(fig: Figure) -> bytes: with io.BytesIO() as image_buffer: fig.savefig(image_buffer, format="PNG", bbox_inches="tight") return image_buffer.getvalue() @staticmethod def _random_image_array(w=20, h=30, d: Optional[int] = 3): if d: return numpy.random.rand(w, h, d) else: return numpy.random.rand(w, h)
[ "neptune.new.internal.utils.images.get_image_content", "neptune.new.internal.utils.images.get_html_content" ]
[((1154, 1175), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (1168, 1175), False, 'import matplotlib\n'), ((4060, 4133), 'unittest.skipIf', 'unittest.skipIf', (['IS_WINDOWS', '"""Installing Torch on Windows takes too long"""'], {}), "(IS_WINDOWS, 'Installing Torch on Windows takes too long')\n", (4075, 4133), False, 'import unittest\n'), ((4139, 4262), 'unittest.skipIf', 'unittest.skipIf', (['(IS_MACOS and sys.version_info.major == 3 and sys.version_info.minor == 10)', '"""No torch for 3.10 on Mac"""'], {}), "(IS_MACOS and sys.version_info.major == 3 and sys.\n version_info.minor == 10, 'No torch for 3.10 on Mac')\n", (4154, 4262), False, 'import unittest\n'), ((1255, 1262), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (1260, 1262), False, 'from uuid import uuid4\n'), ((2148, 2198), 'numpy.array', 'numpy.array', (['[[[1], [0]], [[-3], [4]], [[5], [6]]]'], {}), '([[[1], [0]], [[-3], [4]], [[5], [6]]])\n', (2159, 2198), False, 'import numpy\n'), ((2381, 2394), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (2392, 2394), False, 'import io\n'), ((3858, 3883), 'matplotlib.pyplot.plot', 'pyplot.plot', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (3869, 3883), False, 'from matplotlib import pyplot\n'), ((3892, 3933), 'matplotlib.pyplot.ylabel', 'pyplot.ylabel', (['"""some interesting numbers"""'], {}), "('some interesting numbers')\n", (3905, 3933), False, 'from matplotlib import pyplot\n'), ((3948, 3960), 'matplotlib.pyplot.gcf', 'pyplot.gcf', ([], {}), '()\n', (3958, 3960), False, 'from matplotlib import pyplot\n'), ((4423, 4446), 'torch.rand', 'torch.rand', (['(200)', '(300)', '(3)'], {}), '(200, 300, 3)\n', (4433, 4446), False, 'import torch\n'), ((5073, 5111), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '[200, 300, 3]'}), '(shape=[200, 300, 3])\n', (5090, 5111), True, 'import tensorflow as tf\n'), ((5440, 5455), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {}), '()\n', (5453, 5455), False, 'from matplotlib import pyplot\n'), ((5820, 5842), 'matplotlib.pyplot.hist', 'pyplot.hist', (['x'], {'bins': '(5)'}), '(x, bins=5)\n', (5831, 5842), False, 'from matplotlib import pyplot\n'), ((5876, 5897), 'neptune.new.internal.utils.images.get_html_content', 'get_html_content', (['fig'], {}), '(fig)\n', (5892, 5897), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((6070, 6084), 'plotly.express.data.tips', 'px.data.tips', ([], {}), '()\n', (6082, 6084), True, 'import plotly.express as px\n'), ((6099, 6196), 'plotly.express.histogram', 'px.histogram', (['df'], {'x': '"""total_bill"""', 'y': '"""tip"""', 'color': '"""sex"""', 'marginal': '"""rug"""', 'hover_data': 'df.columns'}), "(df, x='total_bill', y='tip', color='sex', marginal='rug',\n hover_data=df.columns)\n", (6111, 6196), True, 'import plotly.express as px\n'), ((6309, 6330), 'neptune.new.internal.utils.images.get_html_content', 'get_html_content', (['fig'], {}), '(fig)\n', (6325, 6330), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((6507, 6518), 'vega_datasets.data.cars', 'data.cars', ([], {}), '()\n', (6516, 6518), False, 'from vega_datasets import data\n'), ((6887, 6910), 'neptune.new.internal.utils.images.get_html_content', 'get_html_content', (['chart'], {}), '(chart)\n', (6903, 6910), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((7085, 7124), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(400)', 'plot_height': '(400)'}), '(plot_width=400, plot_height=400)\n', (7091, 7124), False, 'from bokeh.plotting import figure\n'), ((7209, 7228), 'neptune.new.internal.utils.images.get_html_content', 'get_html_content', (['p'], {}), '(p)\n', (7225, 7228), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((7592, 7615), 'neptune.new.internal.utils.images.get_html_content', 'get_html_content', (['table'], {}), '(table)\n', (7608, 7615), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((7898, 7930), 'unittest.mock.Mock', 'mock.Mock', ([], {'spec': 'pandas.DataFrame'}), '(spec=pandas.DataFrame)\n', (7907, 7930), False, 'from unittest import mock\n'), ((1301, 1330), 'os.path.exists', 'os.path.exists', (['self.TEST_DIR'], {}), '(self.TEST_DIR)\n', (1315, 1330), False, 'import os\n'), ((1344, 1370), 'os.makedirs', 'os.makedirs', (['self.TEST_DIR'], {}), '(self.TEST_DIR)\n', (1355, 1370), False, 'import os\n'), ((1607, 1640), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['expected_image'], {}), '(expected_image)\n', (1624, 1640), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((1975, 2005), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['image_array'], {}), '(image_array)\n', (1992, 2005), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((2224, 2262), 'numpy.array', 'numpy.array', (['[[1, 0], [-3, 4], [5, 6]]'], {}), '([[1, 0], [-3, 4], [5, 6]])\n', (2235, 2262), False, 'import numpy\n'), ((2408, 2442), 'contextlib.redirect_stdout', 'contextlib.redirect_stdout', (['stdout'], {}), '(stdout)\n', (2434, 2442), False, 'import contextlib\n'), ((3091, 3121), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['image_array'], {}), '(image_array)\n', (3108, 3121), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((3578, 3608), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['image_array'], {}), '(image_array)\n', (3595, 3608), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((4004, 4026), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['fig'], {}), '(fig)\n', (4021, 4026), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((4648, 4679), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['image_tensor'], {}), '(image_tensor)\n', (4665, 4679), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((5284, 5315), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['image_tensor'], {}), '(image_tensor)\n', (5301, 5315), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((7429, 7453), 'numpy.random.randn', 'numpy.random.randn', (['(6)', '(4)'], {}), '(6, 4)\n', (7447, 7453), False, 'import numpy\n'), ((8064, 8087), 'neptune.new.internal.utils.images.get_html_content', 'get_html_content', (['table'], {}), '(table)\n', (8080, 8087), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((8592, 8604), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (8602, 8604), False, 'import io\n'), ((8794, 8806), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (8804, 8806), False, 'import io\n'), ((9055, 9081), 'numpy.random.rand', 'numpy.random.rand', (['w', 'h', 'd'], {}), '(w, h, d)\n', (9072, 9081), False, 'import numpy\n'), ((9115, 9138), 'numpy.random.rand', 'numpy.random.rand', (['w', 'h'], {}), '(w, h)\n', (9132, 9138), False, 'import numpy\n'), ((2473, 2503), 'neptune.new.internal.utils.images.get_image_content', 'get_image_content', (['image_array'], {}), '(image_array)\n', (2490, 2503), False, 'from neptune.new.internal.utils.images import get_html_content, get_image_content\n'), ((7473, 7513), 'pandas.date_range', 'pandas.date_range', (['"""20130101"""'], {'periods': '(6)'}), "('20130101', periods=6)\n", (7490, 7513), False, 'import pandas\n'), ((6550, 6567), 'altair.Chart', 'alt.Chart', (['source'], {}), '(source)\n', (6559, 6567), True, 'import altair as alt\n')]
import os import neptune import pandas as pd from src.features.utils import md5_hash, get_filepaths APPLICATION_FEATURES_PATH = 'data/interim/application_features.csv' BUREAU_FEATURES_PATH = 'data/interim/bureau_features.csv' PROCESSED_FEATURES_FILEPATH = 'data/processed/features_joined_v1.csv' NROWS=None def main(): neptune.init(api_token=os.getenv('NEPTUNE_API_TOKEN'), project_qualified_name=os.getenv('NEPTUNE_PROJECT')) interim_feature_paths = [APPLICATION_FEATURES_PATH, BUREAU_FEATURES_PATH] with neptune.create_experiment(name='feature_extraction', tags=['processed', 'feature_extraction','joined_features'], upload_source_files=get_filepaths()): features = pd.read_csv(interim_feature_paths[0],usecols=['SK_ID_CURR'], nrows=NROWS) for path in interim_feature_paths: df = pd.read_csv(path, nrows=NROWS) features = features.merge(df, on='SK_ID_CURR') features.to_csv(PROCESSED_FEATURES_FILEPATH, index=None) neptune.set_property('features_version', md5_hash(PROCESSED_FEATURES_FILEPATH)) neptune.set_property('features_path', PROCESSED_FEATURES_FILEPATH) if __name__ == '__main__': main()
[ "neptune.set_property" ]
[((766, 840), 'pandas.read_csv', 'pd.read_csv', (['interim_feature_paths[0]'], {'usecols': "['SK_ID_CURR']", 'nrows': 'NROWS'}), "(interim_feature_paths[0], usecols=['SK_ID_CURR'], nrows=NROWS)\n", (777, 840), True, 'import pandas as pd\n'), ((1152, 1218), 'neptune.set_property', 'neptune.set_property', (['"""features_path"""', 'PROCESSED_FEATURES_FILEPATH'], {}), "('features_path', PROCESSED_FEATURES_FILEPATH)\n", (1172, 1218), False, 'import neptune\n'), ((351, 381), 'os.getenv', 'os.getenv', (['"""NEPTUNE_API_TOKEN"""'], {}), "('NEPTUNE_API_TOKEN')\n", (360, 381), False, 'import os\n'), ((406, 434), 'os.getenv', 'os.getenv', (['"""NEPTUNE_PROJECT"""'], {}), "('NEPTUNE_PROJECT')\n", (415, 434), False, 'import os\n'), ((900, 930), 'pandas.read_csv', 'pd.read_csv', (['path'], {'nrows': 'NROWS'}), '(path, nrows=NROWS)\n', (911, 930), True, 'import pandas as pd\n'), ((1105, 1142), 'src.features.utils.md5_hash', 'md5_hash', (['PROCESSED_FEATURES_FILEPATH'], {}), '(PROCESSED_FEATURES_FILEPATH)\n', (1113, 1142), False, 'from src.features.utils import md5_hash, get_filepaths\n'), ((728, 743), 'src.features.utils.get_filepaths', 'get_filepaths', ([], {}), '()\n', (741, 743), False, 'from src.features.utils import md5_hash, get_filepaths\n')]
import os import pandas as pd import models import data import generator as gen import json from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint import multiprocessing from _common import utils from _common import callbacks as cbs import argparse argparser = argparse.ArgumentParser(description='train and evaluate YOLOv3 model on any dataset') argparser.add_argument('-c', '--conf', help='path to configuration file') argparser.add_argument('-w', '--weights', help='path to trained model', default=None) args = argparser.parse_args() import neptune neptune.init('kail4ek/sandbox') def main(): config_path = args.conf initial_weights = args.weights with open(config_path) as config_buffer: config = json.loads(config_buffer.read()) train_set, valid_set, classes = data.create_training_instances(config['train']['train_folder'], None, config['train']['cache_name'], config['model']['labels']) num_classes = len(classes) print('Readed {} classes: {}'.format(num_classes, classes)) train_generator = gen.BatchGenerator( instances=train_set, labels=classes, batch_size=config['train']['batch_size'], input_sz=config['model']['infer_shape'], shuffle=True, norm=data.normalize ) valid_generator = gen.BatchGenerator( instances=valid_set, labels=classes, batch_size=config['train']['batch_size'], input_sz=config['model']['infer_shape'], norm=data.normalize, infer=True ) early_stop = EarlyStopping( monitor='val_loss', min_delta=0, patience=20, mode='min', verbose=1 ) reduce_on_plateau = ReduceLROnPlateau( monitor='val_loss', factor=0.5, patience=5, verbose=1, mode='min', min_delta=0.01, cooldown=0, min_lr=0 ) net_input_shape = (config['model']['infer_shape'][0], config['model']['infer_shape'][1], 3) train_model = models.create( base_name=config['model']['base'], num_classes=num_classes, input_shape=net_input_shape) if initial_weights: train_model.load_weights(initial_weights) print(train_model.summary()) # plot_model(train_model, to_file='images/MobileNetv2.png', show_shapes=True) optimizer = Adam(lr=config['train']['learning_rate'], clipnorm=0.001) train_model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) checkpoint_name = utils.get_checkpoint_name(config) utils.makedirs_4_file(checkpoint_name) static_chk_name = utils.get_static_checkpoint_name(config) utils.makedirs_4_file(static_chk_name) checkpoint_vloss = cbs.CustomModelCheckpoint( model_to_save=train_model, filepath=checkpoint_name, monitor='val_loss', verbose=1, save_best_only=True, mode='min', period=1 ) neptune_mon = cbs.NeptuneMonitor( monitoring=['loss', 'val_loss', 'accuracy', 'val_accuracy'], neptune=neptune ) chk_static = ModelCheckpoint( filepath=static_chk_name, monitor='val_loss', verbose=1, save_best_only=True, mode='min', period=1 ) callbacks = [early_stop, reduce_on_plateau, checkpoint_vloss, neptune_mon, chk_static] ### NEPTUNE ### sources_to_upload = [ 'models.py', 'config.json' ] params = { 'infer_size': "H{}xW{}".format(*config['model']['infer_shape']), 'classes': config['model']['labels'], } neptune.create_experiment( name=utils.get_neptune_name(config), upload_stdout=False, upload_source_files=sources_to_upload, params=params ) ### NEPTUNE ### hist = train_model.fit_generator( generator=train_generator, steps_per_epoch=len(train_generator) * config['train']['train_times'], validation_data=valid_generator, validation_steps=len(valid_generator) * config['valid']['valid_times'], epochs=config['train']['nb_epochs'], verbose=2 if config['train']['debug'] else 1, callbacks=callbacks, workers=multiprocessing.cpu_count(), max_queue_size=100 ) neptune.send_artifact(static_chk_name) neptune.send_artifact('config.json') # Hand-made history # if not os.path.exists('model'): # os.makedirs('model') # df = pd.DataFrame.from_dict(hist.history) # df.to_csv('model/hist.csv', encoding='utf-8', index=False) if __name__ == '__main__': main()
[ "neptune.send_artifact", "neptune.init" ]
[((345, 435), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""train and evaluate YOLOv3 model on any dataset"""'}), "(description=\n 'train and evaluate YOLOv3 model on any dataset')\n", (368, 435), False, 'import argparse\n'), ((638, 669), 'neptune.init', 'neptune.init', (['"""kail4ek/sandbox"""'], {}), "('kail4ek/sandbox')\n", (650, 669), False, 'import neptune\n'), ((879, 1010), 'data.create_training_instances', 'data.create_training_instances', (["config['train']['train_folder']", 'None', "config['train']['cache_name']", "config['model']['labels']"], {}), "(config['train']['train_folder'], None,\n config['train']['cache_name'], config['model']['labels'])\n", (909, 1010), False, 'import data\n'), ((1327, 1509), 'generator.BatchGenerator', 'gen.BatchGenerator', ([], {'instances': 'train_set', 'labels': 'classes', 'batch_size': "config['train']['batch_size']", 'input_sz': "config['model']['infer_shape']", 'shuffle': '(True)', 'norm': 'data.normalize'}), "(instances=train_set, labels=classes, batch_size=config[\n 'train']['batch_size'], input_sz=config['model']['infer_shape'],\n shuffle=True, norm=data.normalize)\n", (1345, 1509), True, 'import generator as gen\n'), ((1578, 1759), 'generator.BatchGenerator', 'gen.BatchGenerator', ([], {'instances': 'valid_set', 'labels': 'classes', 'batch_size': "config['train']['batch_size']", 'input_sz': "config['model']['infer_shape']", 'norm': 'data.normalize', 'infer': '(True)'}), "(instances=valid_set, labels=classes, batch_size=config[\n 'train']['batch_size'], input_sz=config['model']['infer_shape'], norm=\n data.normalize, infer=True)\n", (1596, 1759), True, 'import generator as gen\n'), ((1822, 1908), 'tensorflow.keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'min_delta': '(0)', 'patience': '(20)', 'mode': '"""min"""', 'verbose': '(1)'}), "(monitor='val_loss', min_delta=0, patience=20, mode='min',\n verbose=1)\n", (1835, 1908), False, 'from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\n'), ((1976, 2102), 'tensorflow.keras.callbacks.ReduceLROnPlateau', 'ReduceLROnPlateau', ([], {'monitor': '"""val_loss"""', 'factor': '(0.5)', 'patience': '(5)', 'verbose': '(1)', 'mode': '"""min"""', 'min_delta': '(0.01)', 'cooldown': '(0)', 'min_lr': '(0)'}), "(monitor='val_loss', factor=0.5, patience=5, verbose=1,\n mode='min', min_delta=0.01, cooldown=0, min_lr=0)\n", (1993, 2102), False, 'from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\n'), ((2331, 2437), 'models.create', 'models.create', ([], {'base_name': "config['model']['base']", 'num_classes': 'num_classes', 'input_shape': 'net_input_shape'}), "(base_name=config['model']['base'], num_classes=num_classes,\n input_shape=net_input_shape)\n", (2344, 2437), False, 'import models\n'), ((2667, 2724), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': "config['train']['learning_rate']", 'clipnorm': '(0.001)'}), "(lr=config['train']['learning_rate'], clipnorm=0.001)\n", (2671, 2724), False, 'from tensorflow.keras.optimizers import Adam\n'), ((2849, 2882), '_common.utils.get_checkpoint_name', 'utils.get_checkpoint_name', (['config'], {}), '(config)\n', (2874, 2882), False, 'from _common import utils\n'), ((2887, 2925), '_common.utils.makedirs_4_file', 'utils.makedirs_4_file', (['checkpoint_name'], {}), '(checkpoint_name)\n', (2908, 2925), False, 'from _common import utils\n'), ((2949, 2989), '_common.utils.get_static_checkpoint_name', 'utils.get_static_checkpoint_name', (['config'], {}), '(config)\n', (2981, 2989), False, 'from _common import utils\n'), ((2994, 3032), '_common.utils.makedirs_4_file', 'utils.makedirs_4_file', (['static_chk_name'], {}), '(static_chk_name)\n', (3015, 3032), False, 'from _common import utils\n'), ((3057, 3218), '_common.callbacks.CustomModelCheckpoint', 'cbs.CustomModelCheckpoint', ([], {'model_to_save': 'train_model', 'filepath': 'checkpoint_name', 'monitor': '"""val_loss"""', 'verbose': '(1)', 'save_best_only': '(True)', 'mode': '"""min"""', 'period': '(1)'}), "(model_to_save=train_model, filepath=\n checkpoint_name, monitor='val_loss', verbose=1, save_best_only=True,\n mode='min', period=1)\n", (3082, 3218), True, 'from _common import callbacks as cbs\n'), ((3295, 3395), '_common.callbacks.NeptuneMonitor', 'cbs.NeptuneMonitor', ([], {'monitoring': "['loss', 'val_loss', 'accuracy', 'val_accuracy']", 'neptune': 'neptune'}), "(monitoring=['loss', 'val_loss', 'accuracy',\n 'val_accuracy'], neptune=neptune)\n", (3313, 3395), True, 'from _common import callbacks as cbs\n'), ((3432, 3551), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': 'static_chk_name', 'monitor': '"""val_loss"""', 'verbose': '(1)', 'save_best_only': '(True)', 'mode': '"""min"""', 'period': '(1)'}), "(filepath=static_chk_name, monitor='val_loss', verbose=1,\n save_best_only=True, mode='min', period=1)\n", (3447, 3551), False, 'from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\n'), ((4627, 4665), 'neptune.send_artifact', 'neptune.send_artifact', (['static_chk_name'], {}), '(static_chk_name)\n', (4648, 4665), False, 'import neptune\n'), ((4670, 4706), 'neptune.send_artifact', 'neptune.send_artifact', (['"""config.json"""'], {}), "('config.json')\n", (4691, 4706), False, 'import neptune\n'), ((3976, 4006), '_common.utils.get_neptune_name', 'utils.get_neptune_name', (['config'], {}), '(config)\n', (3998, 4006), False, 'from _common import utils\n'), ((4556, 4583), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (4581, 4583), False, 'import multiprocessing\n')]
import torch.nn as nn import torch.utils import torch.nn.functional as F import torchvision.datasets as dset import torch.backends.cudnn as cudnn import numpy as np import pandas as pd from tqdm import tqdm import neptune import random import os import glob import torch import utils import logging from model_meta import MetaLearner from utils import timestr args = utils.read_yaml().parameters def main(): seed(args.seed) now = timestr() neptune.set_property('Time Str', now) mini_train_queque, mini_test_queque, cifar_train_queque, cifar_test_queque = parepare_dataset() learner = MetaLearner(args) learner.cuda() params = [utils.count_parameters_in_MB(m) for m in [learner.inet, learner.cnet]] print(f"Params: INet {params[0]}, CNet {params[1]}") for epoch in range(args.epochs): learner.scheduler_i.step() learner.scheduler_c.step() lr = learner.scheduler_i.get_lr()[0] print('epoch %d lr %e', epoch, lr) genotype = learner.cnet.module.genotype() print('CIFAR genotype = %s', genotype) genotype = learner.inet.module.genotype() print('MINI genotype = %s', genotype) print(F.softmax(learner.cnet.module.alphas_normal, dim=-1)) print(F.softmax(learner.cnet.module.alphas_reduce, dim=-1)) print(F.softmax(learner.inet.module.alphas_normal, dim=-1)) print(F.softmax(learner.inet.module.alphas_reduce, dim=-1)) print(learner.theta) # training train(cifar_train_queque, mini_train_queque, learner) # validation infer(cifar_test_queque, mini_test_queque, learner) torch.save( { 'cnet': learner.cnet.module.state_dict(), 'inet': learner.inet.module.state_dict(), 'alpha': learner.theta }, f'ckpt/model_{now}_{epoch}.pth' ) def train(cifar_train_queque, mini_train_queque, learner): learner.cnet.train() learner.inet.train() c_itr = iter(cifar_train_queque) i_itr = iter(mini_train_queque) steps = max(len(mini_train_queque), len(cifar_train_queque)) count_c = 0 losses_c = 0 correct_c = 0 count_i = 0 losses_i = 0 correct_i = 0 for step in tqdm(range(steps)): try: xc, yc = next(c_itr) except StopIteration: c_itr = iter(cifar_train_queque) xc, yc = next(c_itr) try: xi, yi = next(i_itr) except StopIteration: i_itr = iter(mini_train_queque) xi, yi = next(i_itr) loss_i, loss_c, logits_i, logits_c = learner.meta_step( xi.cuda(non_blocking=True), yi.cuda(non_blocking=True), xc.cuda(1, non_blocking=True), yc.cuda(1, non_blocking=True), args.meta_lr) prec1, prec5 = utils.accuracy(logits_i.cpu(), yi, topk=(1, 5)) neptune.send_metric('mini batch end loss', loss_i.item()) neptune.send_metric('mini batch end acc@1', prec1.item()) neptune.send_metric('mini batch end acc@5', prec5.item()) prec1, prec5 = utils.accuracy(logits_c.cpu(), yc, topk=(1, 5)) neptune.send_metric('cifar batch end loss', loss_c.item()) neptune.send_metric('cifar batch end acc@1', prec1.item()) neptune.send_metric('cifar batch end acc@5', prec5.item()) losses_c += loss_c.item() * xc.size(0) count_c += xc.size(0) correct_c += logits_c.argmax(dim=-1).cpu().eq(yc).sum().item() losses_i += loss_i.item() * xi.size(0) count_i += xi.size(0) correct_i += logits_i.argmax(dim=-1).cpu().eq(yi).sum().item() epoch_loss_c = losses_c / count_c epoch_acc_c = correct_c * 1.0 / count_c neptune.send_metric('cifar epoch end train loss', epoch_loss_c) neptune.send_metric('cifar epoch end train acc', epoch_acc_c) epoch_loss_i = losses_i / count_i epoch_acc_i = correct_i * 1.0 / count_i neptune.send_metric('mini epoch end train loss', epoch_loss_i) neptune.send_metric('mini epoch end train acc', epoch_acc_i) print(f"Training: MINI Acc {epoch_acc_i}, CIFAR Acc {epoch_acc_c}, " f"MINI Loss {epoch_loss_i}, CIFAR Loss {epoch_loss_c}") def infer(cifar_test_queque, mini_test_queque, learner): learner.cnet.eval() learner.inet.eval() c_itr = iter(cifar_test_queque) i_itr = iter(mini_test_queque) steps = max(len(cifar_test_queque), len(mini_test_queque)) count_c = 0 correct_c = 0 count_i = 0 correct_i = 0 with torch.no_grad(): for step in tqdm(range(steps)): try: xc, yc = next(c_itr) except StopIteration: c_itr = iter(cifar_test_queque) xc, yc = next(c_itr) try: xi, yi = next(i_itr) except StopIteration: i_itr = iter(mini_test_queque) xi, yi = next(i_itr) if xi is not None: logits_i = learner.inet(xi.cuda(non_blocking=True)) count_i += xi.size(0) correct_i += logits_i.argmax(dim=-1).cpu().eq(yi).sum().item() if xc is not None: logits_c = learner.cnet(xc.cuda(non_blocking=True)) count_c += xc.size(0) correct_c += logits_c.argmax(dim=-1).cpu().eq(yc).sum().item() epoch_acc_c = correct_c * 1.0 / count_c epoch_acc_i = correct_i * 1.0 / count_i neptune.send_metric('cifar epoch validation acc', epoch_acc_c) neptune.send_metric('mini epoch validation acc', epoch_acc_i) print(f"Validation: MINI Acc {epoch_acc_i}, CIFAR Acc {epoch_acc_c}") def parepare_dataset(): train_transform, valid_transform = utils._data_transforms_cifar100(args) cifar_train_data = dset.CIFAR100( root=args.data, train=True, download=True, transform=train_transform ) train_transform, valid_transform = utils._data_transforms_mini(args) mini_train_data = dset.ImageFolder( root=os.path.join(args.data, 'miniimagenet', 'train_'), transform=train_transform ) num_train = len(mini_train_data) indices = list(range(num_train)) split = int(np.floor(args.train_portion * num_train)) mini_train_queque = torch.utils.data.DataLoader( mini_train_data, batch_size=args.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[:split]), pin_memory=True, num_workers=2) mini_test_queque = torch.utils.data.DataLoader( mini_train_data, batch_size=args.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[split:]), pin_memory=True, num_workers=2) cifar_train_queque = torch.utils.data.DataLoader( cifar_train_data, batch_size=args.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[:split]), pin_memory=True, num_workers=2) cifar_test_queque = torch.utils.data.DataLoader( cifar_train_data, batch_size=args.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[split:]), pin_memory=True, num_workers=2) return mini_train_queque, mini_test_queque, cifar_train_queque, cifar_test_queque def seed(seed): random.seed(seed) torch.manual_seed(seed) cudnn.deterministic = True np.random.seed(args.seed) if __name__ == '__main__': neptune.init(project_qualified_name='zhoubinxyz/das') upload_files = glob.glob('*.py') + glob.glob('*.yaml') neptune.create_experiment(params=args, upload_source_files=upload_files) os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus main()
[ "neptune.init", "neptune.send_metric", "neptune.set_property", "neptune.create_experiment" ]
[((374, 391), 'utils.read_yaml', 'utils.read_yaml', ([], {}), '()\n', (389, 391), False, 'import utils\n'), ((451, 460), 'utils.timestr', 'timestr', ([], {}), '()\n', (458, 460), False, 'from utils import timestr\n'), ((465, 502), 'neptune.set_property', 'neptune.set_property', (['"""Time Str"""', 'now'], {}), "('Time Str', now)\n", (485, 502), False, 'import neptune\n'), ((619, 636), 'model_meta.MetaLearner', 'MetaLearner', (['args'], {}), '(args)\n', (630, 636), False, 'from model_meta import MetaLearner\n'), ((3772, 3835), 'neptune.send_metric', 'neptune.send_metric', (['"""cifar epoch end train loss"""', 'epoch_loss_c'], {}), "('cifar epoch end train loss', epoch_loss_c)\n", (3791, 3835), False, 'import neptune\n'), ((3840, 3901), 'neptune.send_metric', 'neptune.send_metric', (['"""cifar epoch end train acc"""', 'epoch_acc_c'], {}), "('cifar epoch end train acc', epoch_acc_c)\n", (3859, 3901), False, 'import neptune\n'), ((3989, 4051), 'neptune.send_metric', 'neptune.send_metric', (['"""mini epoch end train loss"""', 'epoch_loss_i'], {}), "('mini epoch end train loss', epoch_loss_i)\n", (4008, 4051), False, 'import neptune\n'), ((4056, 4116), 'neptune.send_metric', 'neptune.send_metric', (['"""mini epoch end train acc"""', 'epoch_acc_i'], {}), "('mini epoch end train acc', epoch_acc_i)\n", (4075, 4116), False, 'import neptune\n'), ((5516, 5578), 'neptune.send_metric', 'neptune.send_metric', (['"""cifar epoch validation acc"""', 'epoch_acc_c'], {}), "('cifar epoch validation acc', epoch_acc_c)\n", (5535, 5578), False, 'import neptune\n'), ((5583, 5644), 'neptune.send_metric', 'neptune.send_metric', (['"""mini epoch validation acc"""', 'epoch_acc_i'], {}), "('mini epoch validation acc', epoch_acc_i)\n", (5602, 5644), False, 'import neptune\n'), ((5785, 5822), 'utils._data_transforms_cifar100', 'utils._data_transforms_cifar100', (['args'], {}), '(args)\n', (5816, 5822), False, 'import utils\n'), ((5847, 5935), 'torchvision.datasets.CIFAR100', 'dset.CIFAR100', ([], {'root': 'args.data', 'train': '(True)', 'download': '(True)', 'transform': 'train_transform'}), '(root=args.data, train=True, download=True, transform=\n train_transform)\n', (5860, 5935), True, 'import torchvision.datasets as dset\n'), ((6009, 6042), 'utils._data_transforms_mini', 'utils._data_transforms_mini', (['args'], {}), '(args)\n', (6036, 6042), False, 'import utils\n'), ((7334, 7351), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (7345, 7351), False, 'import random\n'), ((7356, 7379), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (7373, 7379), False, 'import torch\n'), ((7415, 7440), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (7429, 7440), True, 'import numpy as np\n'), ((7473, 7526), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""zhoubinxyz/das"""'}), "(project_qualified_name='zhoubinxyz/das')\n", (7485, 7526), False, 'import neptune\n'), ((7590, 7662), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'params': 'args', 'upload_source_files': 'upload_files'}), '(params=args, upload_source_files=upload_files)\n', (7615, 7662), False, 'import neptune\n'), ((670, 701), 'utils.count_parameters_in_MB', 'utils.count_parameters_in_MB', (['m'], {}), '(m)\n', (698, 701), False, 'import utils\n'), ((4583, 4598), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4596, 4598), False, 'import torch\n'), ((6278, 6318), 'numpy.floor', 'np.floor', (['(args.train_portion * num_train)'], {}), '(args.train_portion * num_train)\n', (6286, 6318), True, 'import numpy as np\n'), ((7546, 7563), 'glob.glob', 'glob.glob', (['"""*.py"""'], {}), "('*.py')\n", (7555, 7563), False, 'import glob\n'), ((7566, 7585), 'glob.glob', 'glob.glob', (['"""*.yaml"""'], {}), "('*.yaml')\n", (7575, 7585), False, 'import glob\n'), ((1207, 1259), 'torch.nn.functional.softmax', 'F.softmax', (['learner.cnet.module.alphas_normal'], {'dim': '(-1)'}), '(learner.cnet.module.alphas_normal, dim=-1)\n', (1216, 1259), True, 'import torch.nn.functional as F\n'), ((1275, 1327), 'torch.nn.functional.softmax', 'F.softmax', (['learner.cnet.module.alphas_reduce'], {'dim': '(-1)'}), '(learner.cnet.module.alphas_reduce, dim=-1)\n', (1284, 1327), True, 'import torch.nn.functional as F\n'), ((1343, 1395), 'torch.nn.functional.softmax', 'F.softmax', (['learner.inet.module.alphas_normal'], {'dim': '(-1)'}), '(learner.inet.module.alphas_normal, dim=-1)\n', (1352, 1395), True, 'import torch.nn.functional as F\n'), ((1411, 1463), 'torch.nn.functional.softmax', 'F.softmax', (['learner.inet.module.alphas_reduce'], {'dim': '(-1)'}), '(learner.inet.module.alphas_reduce, dim=-1)\n', (1420, 1463), True, 'import torch.nn.functional as F\n'), ((6096, 6145), 'os.path.join', 'os.path.join', (['args.data', '"""miniimagenet"""', '"""train_"""'], {}), "(args.data, 'miniimagenet', 'train_')\n", (6108, 6145), False, 'import os\n'), ((6443, 6504), 'torch.utils.data.sampler.SubsetRandomSampler', 'torch.utils.data.sampler.SubsetRandomSampler', (['indices[:split]'], {}), '(indices[:split])\n', (6487, 6504), False, 'import torch\n'), ((6668, 6729), 'torch.utils.data.sampler.SubsetRandomSampler', 'torch.utils.data.sampler.SubsetRandomSampler', (['indices[split:]'], {}), '(indices[split:])\n', (6712, 6729), False, 'import torch\n'), ((6896, 6957), 'torch.utils.data.sampler.SubsetRandomSampler', 'torch.utils.data.sampler.SubsetRandomSampler', (['indices[:split]'], {}), '(indices[:split])\n', (6940, 6957), False, 'import torch\n'), ((7123, 7184), 'torch.utils.data.sampler.SubsetRandomSampler', 'torch.utils.data.sampler.SubsetRandomSampler', (['indices[split:]'], {}), '(indices[split:])\n', (7167, 7184), False, 'import torch\n')]
""" Train a model on miniImageNet. """ import random import neptune import tensorflow as tf from supervised_reptile.args import model_kwargs, train_kwargs, evaluate_kwargs, neptune_args from supervised_reptile.eval import evaluate from supervised_reptile.models import ProgressiveMiniImageNetModel from supervised_reptile.miniimagenet import read_dataset from supervised_reptile.train import train def main(): """ Load data and train a model on it. """ context = neptune.Context() context.integrate_with_tensorflow() final_train_channel = context.create_channel('final_train_accuracy', neptune.ChannelType.NUMERIC) final_val_channel = context.create_channel('final_val_accuracy', neptune.ChannelType.NUMERIC) final_test_channel = context.create_channel('final_test_accuracy', neptune.ChannelType.NUMERIC) args = neptune_args(context) print('args:', args) random.seed(args.seed) train_set, val_set, test_set = read_dataset(args.miniimagenet_src) model = ProgressiveMiniImageNetModel(args.classes, **model_kwargs(args)) config = tf.ConfigProto() config.gpu_options.allow_growth = args.allow_growth with tf.Session(config=config) as sess: if not args.pretrained: print('Training...') train(sess, model, train_set, test_set, args.checkpoint, **train_kwargs(args)) else: print('Restoring from checkpoint...') tf.train.Saver().restore(sess, tf.train.latest_checkpoint(args.checkpoint)) print('Evaluating...') eval_kwargs = evaluate_kwargs(args) final_train_accuracy = evaluate(sess, model, train_set, **eval_kwargs) print('final_train_accuracy:', final_train_accuracy) final_train_channel.send(final_train_accuracy) final_val_accuracy = evaluate(sess, model, val_set, **eval_kwargs) print('final_val_accuracy:', final_val_accuracy) final_val_channel.send(final_val_accuracy) final_test_accuracy = evaluate(sess, model, test_set, **eval_kwargs) print('final_test_accuracy:', final_test_accuracy) final_test_channel.send(final_test_accuracy) if __name__ == '__main__': main()
[ "neptune.Context" ]
[((484, 501), 'neptune.Context', 'neptune.Context', ([], {}), '()\n', (499, 501), False, 'import neptune\n'), ((853, 874), 'supervised_reptile.args.neptune_args', 'neptune_args', (['context'], {}), '(context)\n', (865, 874), False, 'from supervised_reptile.args import model_kwargs, train_kwargs, evaluate_kwargs, neptune_args\n'), ((904, 926), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (915, 926), False, 'import random\n'), ((963, 998), 'supervised_reptile.miniimagenet.read_dataset', 'read_dataset', (['args.miniimagenet_src'], {}), '(args.miniimagenet_src)\n', (975, 998), False, 'from supervised_reptile.miniimagenet import read_dataset\n'), ((1090, 1106), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (1104, 1106), True, 'import tensorflow as tf\n'), ((1172, 1197), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (1182, 1197), True, 'import tensorflow as tf\n'), ((1569, 1590), 'supervised_reptile.args.evaluate_kwargs', 'evaluate_kwargs', (['args'], {}), '(args)\n', (1584, 1590), False, 'from supervised_reptile.args import model_kwargs, train_kwargs, evaluate_kwargs, neptune_args\n'), ((1623, 1670), 'supervised_reptile.eval.evaluate', 'evaluate', (['sess', 'model', 'train_set'], {}), '(sess, model, train_set, **eval_kwargs)\n', (1631, 1670), False, 'from supervised_reptile.eval import evaluate\n'), ((1817, 1862), 'supervised_reptile.eval.evaluate', 'evaluate', (['sess', 'model', 'val_set'], {}), '(sess, model, val_set, **eval_kwargs)\n', (1825, 1862), False, 'from supervised_reptile.eval import evaluate\n'), ((2002, 2048), 'supervised_reptile.eval.evaluate', 'evaluate', (['sess', 'model', 'test_set'], {}), '(sess, model, test_set, **eval_kwargs)\n', (2010, 2048), False, 'from supervised_reptile.eval import evaluate\n'), ((1056, 1074), 'supervised_reptile.args.model_kwargs', 'model_kwargs', (['args'], {}), '(args)\n', (1068, 1074), False, 'from supervised_reptile.args import model_kwargs, train_kwargs, evaluate_kwargs, neptune_args\n'), ((1470, 1513), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['args.checkpoint'], {}), '(args.checkpoint)\n', (1496, 1513), True, 'import tensorflow as tf\n'), ((1343, 1361), 'supervised_reptile.args.train_kwargs', 'train_kwargs', (['args'], {}), '(args)\n', (1355, 1361), False, 'from supervised_reptile.args import model_kwargs, train_kwargs, evaluate_kwargs, neptune_args\n'), ((1439, 1455), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1453, 1455), True, 'import tensorflow as tf\n')]
import neptune.new as neptune import os import torch.nn as nn import torch import torch.nn.functional as F from torch.optim import SGD, Adam from torch.utils.data import DataLoader, random_split from torch.optim.lr_scheduler import CyclicLR import torch.multiprocessing as mp import numpy as np import random import sys sys.path.append("..") # adds higher directory to python modules path from LoaderPACK.Unet_leaky import Unet_leaky from LoaderPACK.Loader import shuffle_5min from LoaderPACK.Accuarcy_finder import Accuarcy_find from LoaderPACK.Accuarcy_upload import Accuarcy_upload from multiprocessing import Process try: mp.set_start_method('spawn') except RuntimeError: pass def net_SGD1(device, fl, it, train_path, val_path): token = os.getenv('Neptune_api') run = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, ) batch_size = 5 train_load_file = shuffle_5min(path = train_path, series_dict = 'train_series_length.pickle', size = (195, 22, 2060000), device = device) train_loader = torch.utils.data.DataLoader(train_load_file, batch_size=batch_size, shuffle=True, num_workers=0) val_load_file = shuffle_5min(path = val_path, series_dict = 'val_series_length.pickle', size = (28, 22, 549200), device = device) val_loader = torch.utils.data.DataLoader(val_load_file, batch_size=batch_size, shuffle=True, num_workers=0) valid_loss, train_loss = [], [] valid_acc = torch.tensor([]).to(device) train_acc = torch.tensor([]).to(device) avg_train_loss, avg_valid_loss = [], [] model = Unet_leaky(n_channels=1, n_classes=2).to(device) optimizer = SGD(model.parameters(), lr=0.001) lossFunc = nn.CrossEntropyLoss(weight = torch.tensor([1., 5.]).to(device), reduction = "mean") nEpoch = 100 scheduler = CyclicLR(optimizer, base_lr=0.001, max_lr=9, step_size_up=nEpoch-1, cycle_momentum=False) params = {"optimizer":"SGD", "batch_size":batch_size, "optimizer_learning_rate": 0.001, "loss_function":"CrossEntropyLoss", "loss_function_weights":[1, 5], "loss_function_reduction":"mean", "model":"Unet_leaky", "scheduler":"CyclicLR", "scheduler_base_lr":0.001, "scheduler_max_lr":9, "scheduler_cycle_momentum":False, "scheduler_step_size_up":nEpoch-1} run[f"network_SGD/parameters"] = params first_train = True first_val = True for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_SGD/learning_rate"].log(optimizer.param_groups[0]['lr']) t_mat = torch.zeros(2, 2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in train_loader: ind, tar, chan = series y_pred = model(ind) model.zero_grad() pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) if first_train: run[f"network_SGD/train_loss_pr_file"].log(loss) first_train = False loss.backward() optimizer.step() train_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) train_acc = torch.cat((train_acc, acc.view(1))) t_mat = t_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g run[f"network_SGD/train_loss_pr_file"].log( np.mean(np.array(train_loss))) train_loss = [] run[f"network_SGD/train_acc_pr_file"].log(torch.mean(train_acc)) train_acc = torch.tensor([]).to(device) run[f"network_SGD/matrix/train_confusion_matrix_pr_file"].log(t_mat) Accuarcy_upload(run, t_mat, total_pos, total_neg, "network_SGD", "train") v_mat = torch.zeros(2,2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in val_loader: ind, tar, chan = series y_pred = model(ind) pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) if first_val: run[f"network_SGD/validation_loss_pr_file"].log(loss) first_val = False valid_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) valid_acc = torch.cat((valid_acc, acc.view(1))) v_mat = v_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g run[f"network_SGD/validation_loss_pr_file"].log( np.mean(np.array(valid_loss))) valid_loss = [] run[f"network_SGD/val_acc_pr_file"].log(torch.mean(valid_acc)) valid_acc = torch.tensor([]).to(device) run[f"network_SGD/matrix/val_confusion_matrix_pr_file"].log(v_mat) Accuarcy_upload(run, v_mat, total_pos, total_neg, "network_SGD", "val") scheduler.step() run.stop() def net_ADAM1(device, fl, it, train_path, val_path): token = os.getenv('Neptune_api') run = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, ) batch_size = 5 train_load_file = shuffle_5min(path = train_path, series_dict = 'train_series_length.pickle', size = (195, 22, 2060000), device = device) train_loader = torch.utils.data.DataLoader(train_load_file, batch_size=batch_size, shuffle=True, num_workers=0) val_load_file = shuffle_5min(path = val_path, series_dict = 'val_series_length.pickle', size = (28, 22, 549200), device = device) val_loader = torch.utils.data.DataLoader(val_load_file, batch_size=batch_size, shuffle=True, num_workers=0) valid_loss, train_loss = [], [] valid_acc = torch.tensor([]).to(device) train_acc = torch.tensor([]).to(device) avg_train_loss, avg_valid_loss = [], [] model = Unet_leaky(n_channels=1, n_classes=2).to(device) optimizer = Adam(model.parameters(), lr=0.0001) lossFunc = nn.CrossEntropyLoss(weight = torch.tensor([1., 5.]).to(device), reduction = "mean") nEpoch = 100 scheduler = CyclicLR(optimizer, base_lr=0.0001, max_lr=0.5, step_size_up=nEpoch-1, cycle_momentum=False) params = {"optimizer":"Adam", "batch_size":batch_size, "optimizer_learning_rate": 0.0001, "loss_function":"CrossEntropyLoss", "loss_function_weights":[1, 5], "loss_function_reduction":"mean", "model":"Unet_leaky", "scheduler":"CyclicLR", "scheduler_cycle_momentum":False, "scheduler_base_lr":0.0001, "scheduler_max_lr":0.5, "scheduler_step_size_up":nEpoch-1} run[f"network_ADAM/parameters"] = params first_train = True first_val = True for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_ADAM/learning_rate"].log(optimizer.param_groups[0]['lr']) t_mat = torch.zeros(2, 2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in train_loader: ind, tar, chan = series y_pred = model(ind) model.zero_grad() pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) loss.backward() if first_train: run[f"network_ADAM/train_loss_pr_file"].log(loss) first_train = False optimizer.step() train_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) train_acc = torch.cat((train_acc, acc.view(1))) t_mat = t_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g #print(tot_n) #print(total_neg_train) run[f"network_ADAM/train_loss_pr_file"].log( np.mean(np.array(train_loss))) train_loss = [] run[f"network_ADAM/train_acc_pr_file"].log(torch.mean(train_acc)) train_acc = torch.tensor([]).to(device) run[f"network_ADAM/matrix/train_confusion_matrix_pr_file"].log(t_mat) Accuarcy_upload(run, t_mat, total_pos, total_neg, "network_ADAM", "train") v_mat = torch.zeros(2,2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in val_loader: ind, tar, chan = series y_pred = model(ind) pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) if first_val: run[f"network_ADAM/validation_loss_pr_file"].log(loss) first_val = False valid_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) valid_acc = torch.cat((valid_acc, acc.view(1))) v_mat = v_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g run[f"network_ADAM/validation_loss_pr_file"].log( np.mean(np.array(valid_loss))) valid_loss = [] run[f"network_ADAM/val_acc_pr_file"].log(torch.mean(valid_acc)) valid_acc = torch.tensor([]).to(device) run[f"network_ADAM/matrix/val_confusion_matrix_pr_file"].log(v_mat) Accuarcy_upload(run, v_mat, total_pos, total_neg, "network_ADAM", "val") scheduler.step() run.stop() def net_starter(nets, device, fl, it, train_path, val_path): for net in nets: pr1 = mp.Process(target=net, args = (device, fl, it, train_path, val_path,)) pr1.start() pr1.join() if __name__ == '__main__': device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) if device == "cpu": fl = torch.FloatTensor it = torch.LongTensor else: fl = torch.cuda.FloatTensor it = torch.cuda.LongTensor # Set up the datasets np.random.seed(42) core = torch.cuda.device_count() networks = [net_SGD1, net_ADAM1] cuda_dict = dict() for i in range(core): cuda_dict[i] = [] for i in range(len(networks)): cuda_dict[i % core].append(networks[i]) #"/home/tyson/model_data/train_model_data" train_path = "C:/Users/Marc/Desktop/model_data/train_model_data" val_path = "C:/Users/Marc/Desktop/model_data/val_model_data" pres = [] for i in range(core): pres.append(mp.Process(target=net_starter, args = (cuda_dict.get(i), f"cuda:{i}", fl, it, train_path, val_path,))) for process in pres: process.start() for process in pres: process.join() import neptune.new as neptune import os import torch.nn as nn import torch import torch.nn.functional as F from torch.optim import SGD, Adam from torch.utils.data import DataLoader, random_split from torch.optim.lr_scheduler import CyclicLR import torch.multiprocessing as mp import numpy as np import random import sys sys.path.append("..") # adds higher directory to python modules path from LoaderPACK.Unet_leaky import Unet_leaky from LoaderPACK.Loader import shuffle_5min from LoaderPACK.Accuarcy_finder import Accuarcy_find from LoaderPACK.Accuarcy_upload import Accuarcy_upload from multiprocessing import Process try: mp.set_start_method('spawn') except RuntimeError: pass def net_SGD1(device, fl, it, batch_size, train_loader, val_loader): token = os.getenv('Neptune_api') run = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, ) valid_loss, train_loss = [], [] valid_acc = torch.tensor([]).to(device) train_acc = torch.tensor([]).to(device) avg_train_loss, avg_valid_loss = [], [] model = Unet_leaky(n_channels=1, n_classes=2).to(device) optimizer = SGD(model.parameters(), lr=0.001) lossFunc = nn.CrossEntropyLoss(weight = torch.tensor([1., 5.]).to(device), reduction = "mean") nEpoch = 100 scheduler = CyclicLR(optimizer, base_lr=0.001, max_lr=9, step_size_up=nEpoch-1, cycle_momentum=False) params = {"optimizer":"SGD", "batch_size":batch_size, "optimizer_learning_rate": 0.001, "loss_function":"CrossEntropyLoss", "loss_function_weights":[1, 5], "loss_function_reduction":"mean", "model":"Unet_leaky", "scheduler":"CyclicLR", "scheduler_base_lr":0.001, "scheduler_max_lr":9, "scheduler_cycle_momentum":False, "scheduler_step_size_up":nEpoch-1} run[f"network_SGD/parameters"] = params first_train = True first_val = True for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_SGD/learning_rate"].log(optimizer.param_groups[0]['lr']) t_mat = torch.zeros(2, 2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in train_loader: ind, tar, chan = series y_pred = model(ind) model.zero_grad() pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) if first_train: run[f"network_SGD/train_loss_pr_file"].log(loss) first_train = False loss.backward() optimizer.step() train_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) train_acc = torch.cat((train_acc, acc.view(1))) t_mat = t_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g run[f"network_SGD/train_loss_pr_file"].log( np.mean(np.array(train_loss))) train_loss = [] run[f"network_SGD/train_acc_pr_file"].log(torch.mean(train_acc)) train_acc = torch.tensor([]).to(device) run[f"network_SGD/matrix/train_confusion_matrix_pr_file"].log(t_mat) Accuarcy_upload(run, t_mat, total_pos, total_neg, "network_SGD", "train") v_mat = torch.zeros(2,2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in val_loader: ind, tar, chan = series y_pred = model(ind) pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) if first_val: run[f"network_SGD/validation_loss_pr_file"].log(loss) first_val = False valid_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) valid_acc = torch.cat((valid_acc, acc.view(1))) v_mat = v_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g run[f"network_SGD/validation_loss_pr_file"].log( np.mean(np.array(valid_loss))) valid_loss = [] run[f"network_SGD/val_acc_pr_file"].log(torch.mean(valid_acc)) valid_acc = torch.tensor([]).to(device) run[f"network_SGD/matrix/val_confusion_matrix_pr_file"].log(v_mat) Accuarcy_upload(run, v_mat, total_pos, total_neg, "network_SGD", "val") scheduler.step() run.stop() def net_ADAM1(device, fl, it, batch_size, train_loader, val_loader): token = os.getenv('Neptune_api') run = neptune.init( project="NTLAB/artifact-rej-scalp", api_token=token, ) valid_loss, train_loss = [], [] valid_acc = torch.tensor([]).to(device) train_acc = torch.tensor([]).to(device) avg_train_loss, avg_valid_loss = [], [] model = Unet_leaky(n_channels=1, n_classes=2).to(device) optimizer = Adam(model.parameters(), lr=0.0001) lossFunc = nn.CrossEntropyLoss(weight = torch.tensor([1., 5.]).to(device), reduction = "mean") nEpoch = 100 scheduler = CyclicLR(optimizer, base_lr=0.0001, max_lr=0.5, step_size_up=nEpoch-1, cycle_momentum=False) params = {"optimizer":"Adam", "batch_size":batch_size, "optimizer_learning_rate": 0.0001, "loss_function":"CrossEntropyLoss", "loss_function_weights":[1, 5], "loss_function_reduction":"mean", "model":"Unet_leaky", "scheduler":"CyclicLR", "scheduler_cycle_momentum":False, "scheduler_base_lr":0.0001, "scheduler_max_lr":0.5, "scheduler_step_size_up":nEpoch-1} run[f"network_ADAM/parameters"] = params first_train = True first_val = True for iEpoch in range(nEpoch): print(f"Training epoch {iEpoch}") run[f"network_ADAM/learning_rate"].log(optimizer.param_groups[0]['lr']) t_mat = torch.zeros(2, 2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in train_loader: ind, tar, chan = series y_pred = model(ind) model.zero_grad() pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) loss.backward() if first_train: run[f"network_ADAM/train_loss_pr_file"].log(loss) first_train = False optimizer.step() train_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) train_acc = torch.cat((train_acc, acc.view(1))) t_mat = t_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g #print(tot_n) #print(total_neg_train) run[f"network_ADAM/train_loss_pr_file"].log( np.mean(np.array(train_loss))) train_loss = [] run[f"network_ADAM/train_acc_pr_file"].log(torch.mean(train_acc)) train_acc = torch.tensor([]).to(device) run[f"network_ADAM/matrix/train_confusion_matrix_pr_file"].log(t_mat) Accuarcy_upload(run, t_mat, total_pos, total_neg, "network_ADAM", "train") v_mat = torch.zeros(2,2) total_pos, total_neg = torch.tensor(0), torch.tensor(0) for series in val_loader: ind, tar, chan = series y_pred = model(ind) pred = y_pred.transpose(1, 2).reshape(-1, 2).type(fl) target = tar.view(-1).type(it) loss = lossFunc(pred, target) if first_val: run[f"network_ADAM/validation_loss_pr_file"].log(loss) first_val = False valid_loss.append(loss.item()) acc, mat, tot_p_g, tot_n_g = Accuarcy_find(y_pred, tar, device) valid_acc = torch.cat((valid_acc, acc.view(1))) v_mat = v_mat + mat total_pos = total_pos + tot_p_g total_neg = total_neg + tot_n_g run[f"network_ADAM/validation_loss_pr_file"].log( np.mean(np.array(valid_loss))) valid_loss = [] run[f"network_ADAM/val_acc_pr_file"].log(torch.mean(valid_acc)) valid_acc = torch.tensor([]).to(device) run[f"network_ADAM/matrix/val_confusion_matrix_pr_file"].log(v_mat) Accuarcy_upload(run, v_mat, total_pos, total_neg, "network_ADAM", "val") scheduler.step() run.stop() def net_starter(nets, device, fl, it, batch_size, train_loader, val_loader): for net in nets: pr1 = mp.Process(target=net, args = (device, fl, it, batch_size, train_loader, val_loader,)) pr1.start() pr1.join() if __name__ == '__main__': device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) if device == "cpu": fl = torch.FloatTensor it = torch.LongTensor else: fl = torch.cuda.FloatTensor it = torch.cuda.LongTensor # Set up the datasets np.random.seed(42) batch_size = 5 #"/home/tyson/model_data/train_model_data" train_load_file = shuffle_5min(path = "C:/Users/Marc/Desktop/model_data/train_model_data", series_dict = 'train_series_length.pickle', size = (195, 22, 2060000), device = device) train_loader = torch.utils.data.DataLoader(train_load_file, batch_size=batch_size, shuffle=True, num_workers=0) # "C:/Users/Marc/Desktop/model_data" val_load_file = shuffle_5min(path = "C:/Users/Marc/Desktop/model_data/val_model_data", series_dict = 'val_series_length.pickle', size = (28, 22, 549200), device = device) val_loader = torch.utils.data.DataLoader(val_load_file, batch_size=batch_size, shuffle=True, num_workers=0) #token = os.getenv('Neptune_api') #run = neptune.init( # project="NTLAB/artifact-rej-scalp", # api_token=token, #) core = torch.cuda.device_count() networks = [net_SGD1, net_ADAM1] cuda_dict = dict() for i in range(core): cuda_dict[i] = [] for i in range(len(networks)): cuda_dict[i % core].append(networks[i]) pres = [] for i in range(core): pres.append(mp.Process(target=net_starter, args = (cuda_dict.get(i), f"cuda:{i}", fl, it, batch_size, train_loader, val_loader,))) for process in pres: process.start() for process in pres: process.join()
[ "neptune.new.init" ]
[((321, 342), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (336, 342), False, 'import sys\n'), ((12959, 12980), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (12974, 12980), False, 'import sys\n'), ((633, 661), 'torch.multiprocessing.set_start_method', 'mp.set_start_method', (['"""spawn"""'], {}), "('spawn')\n", (652, 661), True, 'import torch.multiprocessing as mp\n'), ((759, 783), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (768, 783), False, 'import os\n'), ((794, 859), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token'}), "(project='NTLAB/artifact-rej-scalp', api_token=token)\n", (806, 859), True, 'import neptune.new as neptune\n'), ((927, 1042), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'train_path', 'series_dict': '"""train_series_length.pickle"""', 'size': '(195, 22, 2060000)', 'device': 'device'}), "(path=train_path, series_dict='train_series_length.pickle',\n size=(195, 22, 2060000), device=device)\n", (939, 1042), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((1191, 1292), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(train_load_file, batch_size=batch_size, shuffle\n =True, num_workers=0)\n', (1218, 1292), False, 'import torch\n'), ((1465, 1575), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'val_path', 'series_dict': '"""val_series_length.pickle"""', 'size': '(28, 22, 549200)', 'device': 'device'}), "(path=val_path, series_dict='val_series_length.pickle', size=(\n 28, 22, 549200), device=device)\n", (1477, 1575), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((1721, 1820), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(val_load_file, batch_size=batch_size, shuffle=\n True, num_workers=0)\n', (1748, 1820), False, 'import torch\n'), ((2423, 2518), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.001)', 'max_lr': '(9)', 'step_size_up': '(nEpoch - 1)', 'cycle_momentum': '(False)'}), '(optimizer, base_lr=0.001, max_lr=9, step_size_up=nEpoch - 1,\n cycle_momentum=False)\n', (2431, 2518), False, 'from torch.optim.lr_scheduler import CyclicLR\n'), ((5899, 5923), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (5908, 5923), False, 'import os\n'), ((5934, 5999), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token'}), "(project='NTLAB/artifact-rej-scalp', api_token=token)\n", (5946, 5999), True, 'import neptune.new as neptune\n'), ((6066, 6181), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'train_path', 'series_dict': '"""train_series_length.pickle"""', 'size': '(195, 22, 2060000)', 'device': 'device'}), "(path=train_path, series_dict='train_series_length.pickle',\n size=(195, 22, 2060000), device=device)\n", (6078, 6181), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((6330, 6431), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(train_load_file, batch_size=batch_size, shuffle\n =True, num_workers=0)\n', (6357, 6431), False, 'import torch\n'), ((6604, 6714), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': 'val_path', 'series_dict': '"""val_series_length.pickle"""', 'size': '(28, 22, 549200)', 'device': 'device'}), "(path=val_path, series_dict='val_series_length.pickle', size=(\n 28, 22, 549200), device=device)\n", (6616, 6714), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((6860, 6959), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(val_load_file, batch_size=batch_size, shuffle=\n True, num_workers=0)\n', (6887, 6959), False, 'import torch\n'), ((7564, 7662), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.0001)', 'max_lr': '(0.5)', 'step_size_up': '(nEpoch - 1)', 'cycle_momentum': '(False)'}), '(optimizer, base_lr=0.0001, max_lr=0.5, step_size_up=nEpoch - 1,\n cycle_momentum=False)\n', (7572, 7662), False, 'from torch.optim.lr_scheduler import CyclicLR\n'), ((11676, 11694), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (11690, 11694), True, 'import numpy as np\n'), ((11707, 11732), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (11730, 11732), False, 'import torch\n'), ((13271, 13299), 'torch.multiprocessing.set_start_method', 'mp.set_start_method', (['"""spawn"""'], {}), "('spawn')\n", (13290, 13299), True, 'import torch.multiprocessing as mp\n'), ((13413, 13437), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (13422, 13437), False, 'import os\n'), ((13448, 13513), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token'}), "(project='NTLAB/artifact-rej-scalp', api_token=token)\n", (13460, 13513), True, 'import neptune.new as neptune\n'), ((13987, 14082), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.001)', 'max_lr': '(9)', 'step_size_up': '(nEpoch - 1)', 'cycle_momentum': '(False)'}), '(optimizer, base_lr=0.001, max_lr=9, step_size_up=nEpoch - 1,\n cycle_momentum=False)\n', (13995, 14082), False, 'from torch.optim.lr_scheduler import CyclicLR\n'), ((17479, 17503), 'os.getenv', 'os.getenv', (['"""Neptune_api"""'], {}), "('Neptune_api')\n", (17488, 17503), False, 'import os\n'), ((17514, 17579), 'neptune.new.init', 'neptune.init', ([], {'project': '"""NTLAB/artifact-rej-scalp"""', 'api_token': 'token'}), "(project='NTLAB/artifact-rej-scalp', api_token=token)\n", (17526, 17579), True, 'import neptune.new as neptune\n'), ((18055, 18153), 'torch.optim.lr_scheduler.CyclicLR', 'CyclicLR', (['optimizer'], {'base_lr': '(0.0001)', 'max_lr': '(0.5)', 'step_size_up': '(nEpoch - 1)', 'cycle_momentum': '(False)'}), '(optimizer, base_lr=0.0001, max_lr=0.5, step_size_up=nEpoch - 1,\n cycle_momentum=False)\n', (18063, 18153), False, 'from torch.optim.lr_scheduler import CyclicLR\n'), ((22247, 22265), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (22261, 22265), True, 'import numpy as np\n'), ((22392, 22552), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': '"""C:/Users/Marc/Desktop/model_data/train_model_data"""', 'series_dict': '"""train_series_length.pickle"""', 'size': '(195, 22, 2060000)', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/model_data/train_model_data',\n series_dict='train_series_length.pickle', size=(195, 22, 2060000),\n device=device)\n", (22404, 22552), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((22697, 22798), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(train_load_file, batch_size=batch_size, shuffle\n =True, num_workers=0)\n', (22724, 22798), False, 'import torch\n'), ((23049, 23204), 'LoaderPACK.Loader.shuffle_5min', 'shuffle_5min', ([], {'path': '"""C:/Users/Marc/Desktop/model_data/val_model_data"""', 'series_dict': '"""val_series_length.pickle"""', 'size': '(28, 22, 549200)', 'device': 'device'}), "(path='C:/Users/Marc/Desktop/model_data/val_model_data',\n series_dict='val_series_length.pickle', size=(28, 22, 549200), device=\n device)\n", (23061, 23204), False, 'from LoaderPACK.Loader import shuffle_5min\n'), ((23346, 23445), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_load_file'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(val_load_file, batch_size=batch_size, shuffle=\n True, num_workers=0)\n', (23373, 23445), False, 'import torch\n'), ((23752, 23777), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (23775, 23777), False, 'import torch\n'), ((3273, 3290), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (3284, 3290), False, 'import torch\n'), ((4492, 4565), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 't_mat', 'total_pos', 'total_neg', '"""network_SGD"""', '"""train"""'], {}), "(run, t_mat, total_pos, total_neg, 'network_SGD', 'train')\n", (4507, 4565), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((4583, 4600), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (4594, 4600), False, 'import torch\n'), ((5716, 5787), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 'v_mat', 'total_pos', 'total_neg', '"""network_SGD"""', '"""val"""'], {}), "(run, v_mat, total_pos, total_neg, 'network_SGD', 'val')\n", (5731, 5787), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((8423, 8440), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (8434, 8440), False, 'import torch\n'), ((9708, 9782), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 't_mat', 'total_pos', 'total_neg', '"""network_ADAM"""', '"""train"""'], {}), "(run, t_mat, total_pos, total_neg, 'network_ADAM', 'train')\n", (9723, 9782), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((9800, 9817), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (9811, 9817), False, 'import torch\n'), ((10936, 11008), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 'v_mat', 'total_pos', 'total_neg', '"""network_ADAM"""', '"""val"""'], {}), "(run, v_mat, total_pos, total_neg, 'network_ADAM', 'val')\n", (10951, 11008), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((11150, 11217), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'net', 'args': '(device, fl, it, train_path, val_path)'}), '(target=net, args=(device, fl, it, train_path, val_path))\n', (11160, 11217), True, 'import torch.multiprocessing as mp\n'), ((14837, 14854), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (14848, 14854), False, 'import torch\n'), ((16056, 16129), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 't_mat', 'total_pos', 'total_neg', '"""network_SGD"""', '"""train"""'], {}), "(run, t_mat, total_pos, total_neg, 'network_SGD', 'train')\n", (16071, 16129), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((16147, 16164), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (16158, 16164), False, 'import torch\n'), ((17280, 17351), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 'v_mat', 'total_pos', 'total_neg', '"""network_SGD"""', '"""val"""'], {}), "(run, v_mat, total_pos, total_neg, 'network_SGD', 'val')\n", (17295, 17351), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((18914, 18931), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (18925, 18931), False, 'import torch\n'), ((20199, 20273), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 't_mat', 'total_pos', 'total_neg', '"""network_ADAM"""', '"""train"""'], {}), "(run, t_mat, total_pos, total_neg, 'network_ADAM', 'train')\n", (20214, 20273), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((20291, 20308), 'torch.zeros', 'torch.zeros', (['(2)', '(2)'], {}), '(2, 2)\n', (20302, 20308), False, 'import torch\n'), ((21427, 21499), 'LoaderPACK.Accuarcy_upload.Accuarcy_upload', 'Accuarcy_upload', (['run', 'v_mat', 'total_pos', 'total_neg', '"""network_ADAM"""', '"""val"""'], {}), "(run, v_mat, total_pos, total_neg, 'network_ADAM', 'val')\n", (21442, 21499), False, 'from LoaderPACK.Accuarcy_upload import Accuarcy_upload\n'), ((21657, 21744), 'torch.multiprocessing.Process', 'mp.Process', ([], {'target': 'net', 'args': '(device, fl, it, batch_size, train_loader, val_loader)'}), '(target=net, args=(device, fl, it, batch_size, train_loader,\n val_loader))\n', (21667, 21744), True, 'import torch.multiprocessing as mp\n'), ((2026, 2042), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (2038, 2042), False, 'import torch\n'), ((2070, 2086), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (2082, 2086), False, 'import torch\n'), ((2156, 2193), 'LoaderPACK.Unet_leaky.Unet_leaky', 'Unet_leaky', ([], {'n_channels': '(1)', 'n_classes': '(2)'}), '(n_channels=1, n_classes=2)\n', (2166, 2193), False, 'from LoaderPACK.Unet_leaky import Unet_leaky\n'), ((3322, 3337), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (3334, 3337), False, 'import torch\n'), ((3339, 3354), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (3351, 3354), False, 'import torch\n'), ((3913, 3947), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (3926, 3947), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((4335, 4356), 'torch.mean', 'torch.mean', (['train_acc'], {}), '(train_acc)\n', (4345, 4356), False, 'import torch\n'), ((4631, 4646), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (4643, 4646), False, 'import torch\n'), ((4648, 4663), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (4660, 4663), False, 'import torch\n'), ((5134, 5168), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (5147, 5168), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((5561, 5582), 'torch.mean', 'torch.mean', (['valid_acc'], {}), '(valid_acc)\n', (5571, 5582), False, 'import torch\n'), ((7165, 7181), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (7177, 7181), False, 'import torch\n'), ((7209, 7225), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (7221, 7225), False, 'import torch\n'), ((7295, 7332), 'LoaderPACK.Unet_leaky.Unet_leaky', 'Unet_leaky', ([], {'n_channels': '(1)', 'n_classes': '(2)'}), '(n_channels=1, n_classes=2)\n', (7305, 7332), False, 'from LoaderPACK.Unet_leaky import Unet_leaky\n'), ((8472, 8487), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (8484, 8487), False, 'import torch\n'), ((8489, 8504), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (8501, 8504), False, 'import torch\n'), ((9064, 9098), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (9077, 9098), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((9550, 9571), 'torch.mean', 'torch.mean', (['train_acc'], {}), '(train_acc)\n', (9560, 9571), False, 'import torch\n'), ((9848, 9863), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (9860, 9863), False, 'import torch\n'), ((9865, 9880), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (9877, 9880), False, 'import torch\n'), ((10351, 10385), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (10364, 10385), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((10780, 10801), 'torch.mean', 'torch.mean', (['valid_acc'], {}), '(valid_acc)\n', (10790, 10801), False, 'import torch\n'), ((11421, 11446), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (11444, 11446), False, 'import torch\n'), ((13590, 13606), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (13602, 13606), False, 'import torch\n'), ((13634, 13650), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (13646, 13650), False, 'import torch\n'), ((13720, 13757), 'LoaderPACK.Unet_leaky.Unet_leaky', 'Unet_leaky', ([], {'n_channels': '(1)', 'n_classes': '(2)'}), '(n_channels=1, n_classes=2)\n', (13730, 13757), False, 'from LoaderPACK.Unet_leaky import Unet_leaky\n'), ((14886, 14901), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (14898, 14901), False, 'import torch\n'), ((14903, 14918), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (14915, 14918), False, 'import torch\n'), ((15477, 15511), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (15490, 15511), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((15899, 15920), 'torch.mean', 'torch.mean', (['train_acc'], {}), '(train_acc)\n', (15909, 15920), False, 'import torch\n'), ((16195, 16210), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (16207, 16210), False, 'import torch\n'), ((16212, 16227), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (16224, 16227), False, 'import torch\n'), ((16698, 16732), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (16711, 16732), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((17125, 17146), 'torch.mean', 'torch.mean', (['valid_acc'], {}), '(valid_acc)\n', (17135, 17146), False, 'import torch\n'), ((17656, 17672), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (17668, 17672), False, 'import torch\n'), ((17700, 17716), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (17712, 17716), False, 'import torch\n'), ((17786, 17823), 'LoaderPACK.Unet_leaky.Unet_leaky', 'Unet_leaky', ([], {'n_channels': '(1)', 'n_classes': '(2)'}), '(n_channels=1, n_classes=2)\n', (17796, 17823), False, 'from LoaderPACK.Unet_leaky import Unet_leaky\n'), ((18963, 18978), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (18975, 18978), False, 'import torch\n'), ((18980, 18995), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (18992, 18995), False, 'import torch\n'), ((19555, 19589), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (19568, 19589), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((20041, 20062), 'torch.mean', 'torch.mean', (['train_acc'], {}), '(train_acc)\n', (20051, 20062), False, 'import torch\n'), ((20339, 20354), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (20351, 20354), False, 'import torch\n'), ((20356, 20371), 'torch.tensor', 'torch.tensor', (['(0)'], {}), '(0)\n', (20368, 20371), False, 'import torch\n'), ((20842, 20876), 'LoaderPACK.Accuarcy_finder.Accuarcy_find', 'Accuarcy_find', (['y_pred', 'tar', 'device'], {}), '(y_pred, tar, device)\n', (20855, 20876), False, 'from LoaderPACK.Accuarcy_finder import Accuarcy_find\n'), ((21271, 21292), 'torch.mean', 'torch.mean', (['valid_acc'], {}), '(valid_acc)\n', (21281, 21292), False, 'import torch\n'), ((21992, 22017), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (22015, 22017), False, 'import torch\n'), ((4237, 4257), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (4245, 4257), True, 'import numpy as np\n'), ((4378, 4394), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (4390, 4394), False, 'import torch\n'), ((5465, 5485), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (5473, 5485), True, 'import numpy as np\n'), ((5604, 5620), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (5616, 5620), False, 'import torch\n'), ((9451, 9471), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (9459, 9471), True, 'import numpy as np\n'), ((9593, 9609), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (9605, 9609), False, 'import torch\n'), ((10683, 10703), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (10691, 10703), True, 'import numpy as np\n'), ((10823, 10839), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (10835, 10839), False, 'import torch\n'), ((15801, 15821), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (15809, 15821), True, 'import numpy as np\n'), ((15942, 15958), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (15954, 15958), False, 'import torch\n'), ((17029, 17049), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (17037, 17049), True, 'import numpy as np\n'), ((17168, 17184), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (17180, 17184), False, 'import torch\n'), ((19942, 19962), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (19950, 19962), True, 'import numpy as np\n'), ((20084, 20100), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (20096, 20100), False, 'import torch\n'), ((21174, 21194), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (21182, 21194), True, 'import numpy as np\n'), ((21314, 21330), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (21326, 21330), False, 'import torch\n'), ((2299, 2323), 'torch.tensor', 'torch.tensor', (['[1.0, 5.0]'], {}), '([1.0, 5.0])\n', (2311, 2323), False, 'import torch\n'), ((7440, 7464), 'torch.tensor', 'torch.tensor', (['[1.0, 5.0]'], {}), '([1.0, 5.0])\n', (7452, 7464), False, 'import torch\n'), ((13863, 13887), 'torch.tensor', 'torch.tensor', (['[1.0, 5.0]'], {}), '([1.0, 5.0])\n', (13875, 13887), False, 'import torch\n'), ((17931, 17955), 'torch.tensor', 'torch.tensor', (['[1.0, 5.0]'], {}), '([1.0, 5.0])\n', (17943, 17955), False, 'import torch\n')]
import argparse import os import random import torch from torch.optim import Adam from runner.pretrain_trainer import PreTrainer from model.neural_apprentice import SmilesGenerator, SmilesGeneratorHandler from util.smiles.dataset import load_dataset from util.smiles.char_dict import SmilesCharDictionary import neptune if __name__ == "__main__": parser = argparse.ArgumentParser( description="pretrain", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("--dataset", type=str, default="zinc_daga") parser.add_argument("--dataset_path", type=str, default="./resource/data/zinc_daga/full.txt") parser.add_argument("--max_smiles_length", type=int, default=80) parser.add_argument("--hidden_size", type=int, default=1024) parser.add_argument("--n_layers", type=int, default=3) parser.add_argument("--lstm_dropout", type=float, default=0.2) # Training parameters parser.add_argument("--learning_rate", type=float, default=1e-3) parser.add_argument("--num_epochs", type=int, default=10) parser.add_argument("--batch_size", type=int, default=256) # Directory to save the pretrained model parser.add_argument("--save_dir", default="./resource/checkpoint/zinc_daga/") args = parser.parse_args() # Initialize random seed and prepare CUDA device device = torch.device(0) random.seed(0) # Initialize neptune neptune.init(project_qualified_name="sungsoo.ahn/deep-molecular-optimization") neptune.create_experiment(name="pretrain", params=vars(args)) neptune.append_tag(args.dataset) # Load character dict and dataset char_dict = SmilesCharDictionary(dataset=args.dataset, max_smi_len=args.max_smiles_length) dataset = load_dataset(char_dict=char_dict, smi_path=args.dataset_path) # Prepare neural apprentice. We set max_sampling_batch_size=0 since we do not use sampling. input_size = max(char_dict.char_idx.values()) + 1 generator = SmilesGenerator( input_size=input_size, hidden_size=args.hidden_size, output_size=input_size, n_layers=args.n_layers, lstm_dropout=args.lstm_dropout, ) generator = generator.to(device) optimizer = Adam(params=generator.parameters(), lr=args.learning_rate) generator_handler = SmilesGeneratorHandler( model=generator, optimizer=optimizer, char_dict=char_dict, max_sampling_batch_size=0 ) # Prepare trainer trainer = PreTrainer( char_dict=char_dict, dataset=dataset, generator_handler=generator_handler, num_epochs=args.num_epochs, batch_size=args.batch_size, save_dir=args.save_dir, device=device, ) trainer.train()
[ "neptune.append_tag", "neptune.init" ]
[((364, 472), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""pretrain"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='pretrain', formatter_class=argparse.\n ArgumentDefaultsHelpFormatter)\n", (387, 472), False, 'import argparse\n'), ((1356, 1371), 'torch.device', 'torch.device', (['(0)'], {}), '(0)\n', (1368, 1371), False, 'import torch\n'), ((1376, 1390), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (1387, 1390), False, 'import random\n'), ((1421, 1499), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""sungsoo.ahn/deep-molecular-optimization"""'}), "(project_qualified_name='sungsoo.ahn/deep-molecular-optimization')\n", (1433, 1499), False, 'import neptune\n'), ((1570, 1602), 'neptune.append_tag', 'neptune.append_tag', (['args.dataset'], {}), '(args.dataset)\n', (1588, 1602), False, 'import neptune\n'), ((1658, 1736), 'util.smiles.char_dict.SmilesCharDictionary', 'SmilesCharDictionary', ([], {'dataset': 'args.dataset', 'max_smi_len': 'args.max_smiles_length'}), '(dataset=args.dataset, max_smi_len=args.max_smiles_length)\n', (1678, 1736), False, 'from util.smiles.char_dict import SmilesCharDictionary\n'), ((1751, 1812), 'util.smiles.dataset.load_dataset', 'load_dataset', ([], {'char_dict': 'char_dict', 'smi_path': 'args.dataset_path'}), '(char_dict=char_dict, smi_path=args.dataset_path)\n', (1763, 1812), False, 'from util.smiles.dataset import load_dataset\n'), ((1980, 2137), 'model.neural_apprentice.SmilesGenerator', 'SmilesGenerator', ([], {'input_size': 'input_size', 'hidden_size': 'args.hidden_size', 'output_size': 'input_size', 'n_layers': 'args.n_layers', 'lstm_dropout': 'args.lstm_dropout'}), '(input_size=input_size, hidden_size=args.hidden_size,\n output_size=input_size, n_layers=args.n_layers, lstm_dropout=args.\n lstm_dropout)\n', (1995, 2137), False, 'from model.neural_apprentice import SmilesGenerator, SmilesGeneratorHandler\n'), ((2312, 2425), 'model.neural_apprentice.SmilesGeneratorHandler', 'SmilesGeneratorHandler', ([], {'model': 'generator', 'optimizer': 'optimizer', 'char_dict': 'char_dict', 'max_sampling_batch_size': '(0)'}), '(model=generator, optimizer=optimizer, char_dict=\n char_dict, max_sampling_batch_size=0)\n', (2334, 2425), False, 'from model.neural_apprentice import SmilesGenerator, SmilesGeneratorHandler\n'), ((2472, 2662), 'runner.pretrain_trainer.PreTrainer', 'PreTrainer', ([], {'char_dict': 'char_dict', 'dataset': 'dataset', 'generator_handler': 'generator_handler', 'num_epochs': 'args.num_epochs', 'batch_size': 'args.batch_size', 'save_dir': 'args.save_dir', 'device': 'device'}), '(char_dict=char_dict, dataset=dataset, generator_handler=\n generator_handler, num_epochs=args.num_epochs, batch_size=args.\n batch_size, save_dir=args.save_dir, device=device)\n', (2482, 2662), False, 'from runner.pretrain_trainer import PreTrainer\n')]
""" Script to train model for next sentence prediction """ import os, sys import logging import json import collections import itertools import argparse from typing import * import numpy as np from sklearn import metrics from scipy.special import softmax import torch import torch.nn as nn import skorch import skorch.helper import neptune import transformers from transformers import ( DataCollatorForLanguageModeling, BertForNextSentencePrediction, BertForSequenceClassification, BertForPreTraining, BertTokenizer, BertConfig, DataCollatorWithPadding, TrainingArguments, Trainer, TrainerCallback, EvalPrediction, ) import git SRC_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "tcr") sys.path.append(SRC_DIR) import data_loader as dl import featurization as ft import model_utils import utils MODEL_DIR = os.path.join(SRC_DIR, "models") assert os.path.isdir(MODEL_DIR) sys.path.append(MODEL_DIR) from transformer_custom import BertForThreewayNextSentencePrediction def compute_metrics(pred: EvalPrediction) -> Dict[str, float]: """Compute binary metrics to report""" # When doing pretraining (MLM + NSP) we have shapes: # predictions: (eval_examples, seq_len, 26) (eval_examples, 2) # labels: (seq_len,) (seq_len,) labels = pred.label_ids.squeeze() # These are indexes of the correct class preds = pred.predictions.argmax(-1) labels_expanded = np.zeros_like(pred.predictions) labels_expanded[np.arange(len(labels_expanded)), labels] = 1 assert np.all(np.sum(labels_expanded, axis=1) == 1) is_multiclass = pred.predictions.shape[1] > 2 if is_multiclass: preds_probs = softmax(pred.predictions, axis=1) else: preds_probs = softmax(pred.predictions, axis=1)[:, 1] # Macro calculates metrics for each label and finds the unweighted mean precision, recall, f1, _ = metrics.precision_recall_fscore_support( labels, preds, average="binary" if not is_multiclass else "macro", ) acc = metrics.accuracy_score(labels, preds) auroc = metrics.roc_auc_score(labels, preds_probs, multi_class="ovr") auprc = metrics.average_precision_score( labels if not is_multiclass else labels_expanded, preds_probs ) return { "accuracy": acc, "f1": f1, "precision": precision, "recall": recall, "auroc": auroc, "auprc": auprc, } def load_dataset(args): """Load in the dataset""" # Load the blacklist sequences: blacklist_antigens = None if args.blacklist: blacklist_antigens = [] for blacklist_fname in args.blacklist: seqs = utils.read_newline_file(blacklist_fname) blacklist_antigens.extend(seqs) blacklist_antigens = utils.dedup(blacklist_antigens) logging.info( f"Loaded in {len(args.blacklist)} blacklist files for {len(blacklist_antigens)} unique blacklisted seqs" ) # Build dataset according to given keyword arg if args.mode == "AB": logging.info("Loading 10x TRA/TRB pair dataset") tab = dl.load_10x() tra_max_len = max([len(s) for s in tab["TRA_aa"]]) trb_max_len = max([len(s) for s in tab["TRB_aa"]]) full_dataset = dl.TcrNextSentenceDataset( list(tab["TRA_aa"]), list(tab["TRB_aa"]), neg_ratio=args.negatives, tra_blacklist=blacklist_antigens, mlm=0.15 if args.mlm else 0, ) elif args.mode == "antigenB": # Antigen and TRB sequences (EXCLUDES TRA) logging.info("Loading VDJdb + PIRD antigen + TRB data") pird_tab = dl.load_pird(with_antigen_only=True) pird_antigens = pird_tab["Antigen.sequence"] pird_trbs = pird_tab["CDR3.beta.aa"] # Load only TRB sequences for VDJdb vdjdb_tab = dl.load_vdjdb(tra_trb_filter=["TRB"]) vdjdb_antigens = vdjdb_tab["antigen.epitope"] vdjdb_trbs = vdjdb_tab["cdr3"] full_dataset = dl.TcrNextSentenceDataset( list(pird_antigens) + list(vdjdb_antigens), list(pird_trbs) + list(vdjdb_trbs), neg_ratio=args.negatives, tra_blacklist=blacklist_antigens, mlm=0.15 if args.mlm else 0, ) elif args.mode == "antigenAB": logging.info("Loading VDJdb + PIRD antigen + TRA/TRB data") pird_tab = dl.load_pird(with_antigen_only=True) pird_antigens = pird_tab["Antigen.sequence"] pird_trbs = pird_tab["CDR3.beta.aa"] pird_tras = pird_tab["CDR3.alpha.aa"] vdjdb_tab = dl.load_vdjdb(tra_trb_filter=["TRA", "TRB"]) vdjdb_antigens = vdjdb_tab["antigen.epitope"] vdjdb_trs = vdjdb_tab["cdr3"] full_dataset = dl.TcrNextSentenceDataset( list(pird_antigens) + list(pird_antigens) + list(vdjdb_antigens), list(pird_trbs) + list(pird_tras) + list(vdjdb_trs), neg_ratio=args.negatives, tra_blacklist=blacklist_antigens, mlm=0.15 if args.mlm else 0, ) elif args.mode == "antigenLCMV": logging.info( "Loading LCMV dataset, primarily used for fine tuning, ignoring given negatives ratio" ) assert not args.dynamic, f"Cannot use dynamic sampling with LCMV dataset" lcmv_tab = dl.load_lcmv_table() lcmv_trbs = lcmv_tab["TRB"] lcmv_antigen = lcmv_tab["antigen.sequence"] lcmv_labels = np.array(lcmv_tab["tetramer"] == "TetPos") full_dataset = dl.TcrNextSentenceDataset( lcmv_antigen, lcmv_trbs, neg_ratio=0.0, tra_blacklist=blacklist_antigens, labels=lcmv_labels, mlm=0.15 if args.mlm else 0, shuffle=False, # Do not shuffle dataset since we will downsample ) elif args.mode.startswith("abLCMV"): assert args.mode in ["abLCMV", "abLCMVnoMid", "abLCMVmulticlass", "abLCMVold"] if args.mode == "abLCMVmulticlass": raise NotImplementedError logging.info("Loading LCMV dataset for TRA/TRB pairs, ignoring negatives ratio") lcmv_tab = dl.load_lcmv_table() if args.mode == "abLCMVnoMid": orig_count = len(lcmv_tab) lcmv_tab = lcmv_tab.loc[lcmv_tab["tetramer"] != "TetMid"] logging.info(f"Excluded {orig_count - len(lcmv_tab)} TetMid examples") if args.mode == "abLCMVold": # The old version where we don't dedup the data logging.warning( "Using legacy LCMV loading scheme where only TetPos is positive and we do NOT dedup" ) lcmv_tras = list(lcmv_tab["TRA"]) lcmv_trbs = list(lcmv_tab["TRB"]) lcmv_labels = [l == "TetPos" for l in lcmv_tab["tetramer"]] else: lcmv_dedup_ab, lcmv_dedup_labels = dl.dedup_lcmv_table(lcmv_tab) lcmv_tras, lcmv_trbs = zip(*lcmv_dedup_ab) # Pos and mid are both considered positive lcmv_labels = np.array( ["TetPos" in l or "TetMid" in l for l in lcmv_dedup_labels] ) logging.info( f"Created binary labels for LCMV dataset with {np.mean(lcmv_labels)} positive rate" ) assert lcmv_labels is not None, "Failed to generate labels for LCMV" full_dataset = dl.TcrNextSentenceDataset( lcmv_tras, lcmv_trbs, neg_ratio=0.0, tra_blacklist=blacklist_antigens, labels=lcmv_labels, mlm=0.15 if args.mlm else 0, shuffle=False, # Do not shuffle, train/valid/test split will shuffle ) else: raise ValueError(f"Unrecognized mode: {args.mode}") return full_dataset def get_model(path: str, mlm: bool = False, multiclass: bool = False): """Get a NSP model from the given pretrained path""" if mlm: if os.path.isdir(path): raise NotImplementedError("Cannot initialize MLM+NSP model from pretrained") elif os.path.isfile(path) and utils.is_json_file(path): logging.info(f"Loading BertForPretraining from scratch: {path}") params = utils.load_json_params(path) cfg = BertConfig( **params, vocab_size=len(ft.AMINO_ACIDS_WITH_ALL_ADDITIONAL), pad_token_id=ft.AMINO_ACIDS_WITH_ALL_ADDITIONAL_TO_IDX[ft.PAD], ) model = BertForPreTraining(cfg) else: raise ValueError(f"Cannot initialize model from: {path}") else: if os.path.isdir(path): logging.info( f"Loading BertForNextSentencePrediction from pretrained: {path}" ) if multiclass: model = BertForThreewayNextSentencePrediction.from_pretrained(path) else: model = BertForNextSentencePrediction.from_pretrained(path) elif os.path.isfile(path) and utils.is_json_file(path): params = utils.load_json_params(path) cfg = BertConfig( **params, vocab_size=len(ft.AMINO_ACIDS_WITH_ALL_ADDITIONAL), pad_token_id=ft.AMINO_ACIDS_WITH_ALL_ADDITIONAL_TO_IDX[ft.PAD], ) model = BertForNextSentencePrediction(cfg) else: raise ValueError(f"Cannot initialize model from: {path}") logging.info("Loading BertForNextSentencePrediction") return model def build_parser(): """Build argument parser""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "--model", type=str, required=True, help="Path to pretrained dir or config json" ) parser.add_argument( "-o", "--outdir", type=str, default=os.getcwd(), help="Output directory" ) parser.add_argument( "-m", "--mode", type=str, default="antigenB", choices=[ "AB", "antigenB", "antigenAB", "antigenLCMV", "abLCMV", "abLCMVnoMid", "abLCMVmulticlass", "abLCMVold", ], help="Pairing mode - TRA/TRB or Antigen/(TRA|TRB) or antigenLCMV (looks at TRB)", ) parser.add_argument( "-s", "--split", type=str, default="random", choices=["random", "antigen"], help="Method for determining data split", ) parser.add_argument( "--blacklist", type=str, nargs="*", required=False, help="File containing ANTIGEN sequences to ignore. Useful for excluding certain antigens from training.", ) parser.add_argument( "-n", "--negatives", type=float, default=1.0, help="Ratio of negatives to positives", ) parser.add_argument( "--downsample", type=float, default=1.0, help="Downsample training to given proportion", ) parser.add_argument( "-d", "--dynamic", action="store_true", help="Dynamically generate negative pairs in training", ) parser.add_argument("--mlm", action="store_true", help="MLM in addition to NSP") parser.add_argument("--bs", type=int, default=128, help="Batch size") parser.add_argument("--lr", type=float, default=2e-5, help="Learning rate") parser.add_argument("--wd", type=float, default=0.0, help="Weight decay") parser.add_argument("-e", "--epochs", type=int, default=5, help="Epochs to train") parser.add_argument( "-w", "--warmup", type=float, default=0.1, help="Proportion of steps to warmup" ) parser.add_argument("--progress", action="store_true", help="Show progress bar") parser.add_argument( "--noneptune", action="store_true", help="Disable neptune integration" ) return parser def main(): """Run training""" args = build_parser().parse_args() if not os.path.isdir(args.outdir): os.makedirs(args.outdir) # Setup logging logger = logging.getLogger() fh = logging.FileHandler(os.path.join(args.outdir, "nsp_training.log"), "w") fh.setLevel(logging.INFO) logger.addHandler(fh) # Log git status repo = git.Repo( path=os.path.dirname(os.path.abspath(__file__)), search_parent_directories=True ) sha = repo.head.object.hexsha logging.info(f"Git commit: {sha}") if torch.cuda.is_available(): logging.info(f"PyTorch CUDA version: {torch.version.cuda}") for arg in vars(args): logging.info(f"Parameter {arg}: {getattr(args, arg)}") with open(os.path.join(args.outdir, "params.json"), "w") as sink: json.dump(vars(args), sink, indent=4) full_dataset = load_dataset(args) if "LCMV" not in args.mode: # No validation dataset logging.info(f"Training NSP in full, using only train/test splits") if args.split == "random": train_dataset = dl.DatasetSplit( full_dataset, split="train", valid=0, test=0.1, dynamic_training=args.dynamic, ) eval_dataset = dl.DatasetSplit( full_dataset, split="test", valid=0, test=0.1 ) elif args.split == "antigen": # We split by antigen so that the evaluation and training sets are using # different antigens. This better captures whether or not we are learning # a general antigen-tcr interaction or not antigen_getter = lambda x: [pair[0] for pair in x.all_pairs] train_dataset = dl.DatasetSplitByAttribute( full_dataset, antigen_getter, split="train", dynamic_training=args.dynamic, valid=0, test=0.1, ) eval_dataset = dl.DatasetSplitByAttribute( full_dataset, antigen_getter, split="test", dynamic_training=args.dynamic, valid=0, test=0.1, ) else: raise ValueError(f"Unrecognized value for split method: {args.split}") else: logging.info( f"Got LCMV fine tuning dataset, using full train/valid/test split with no dynamic training" ) assert not args.dynamic assert ( args.split == "random" ), f"Only random split allowed for LCMV data with only one epitope" train_dataset = dl.DatasetSplit( full_dataset, split="train", dynamic_training=False ) eval_dataset = dl.DatasetSplit( full_dataset, split="valid", dynamic_training=False ) test_dataset = dl.DatasetSplit( full_dataset, split="test", dynamic_training=False ) assert ( 0.0 <= args.downsample <= 1.0 ), f"Invalid downsampling value {args.downsample}" if args.downsample < 1.0: logging.info(f"Downsampling training set to {args.downsample}") train_dataset = dl.DownsampledDataset(train_dataset, downsample=args.downsample) # Setting metric for best model auto sets greater_is_better as well training_args = TrainingArguments( output_dir=args.outdir, overwrite_output_dir=True, num_train_epochs=args.epochs, per_device_train_batch_size=args.bs, per_device_eval_batch_size=args.bs, learning_rate=args.lr, warmup_ratio=args.warmup, weight_decay=args.wd, evaluation_strategy="epoch", logging_strategy="epoch", save_strategy="epoch", save_total_limit=1, dataloader_num_workers=8, load_best_model_at_end=True, metric_for_best_model="eval_loss" if args.mlm else "eval_auprc", no_cuda=False, skip_memory_metrics=True, disable_tqdm=not args.progress, logging_dir=os.path.join(args.outdir, "logging"), ) model = get_model(args.model, mlm=args.mlm, multiclass="multiclass" in args.mode) # Set up neptune logging if specified neptune_logger = None neptune_tags = ["nsp", args.mode] if args.mlm: neptune_tags.append("mlm") if not utils.is_json_file(args.model): neptune_tags.append("pretrained") neptune_params = { "epochs": args.epochs, "batch_size": args.bs, "lr": args.lr, "warmup_ratio": args.warmup, "nsp_neg_ratio": args.negatives, "dynamic_training": args.dynamic, "data_split_method": args.split, "downsample": args.downsample, "blacklist": args.blacklist, "outdir": os.path.abspath(args.outdir), } if utils.is_json_file(args.model): neptune_params.update(utils.load_json_params(args.model)) else: # Is pretrained neptune_params["pretrained"] = os.path.abspath(args.model) if not args.noneptune: neptune.init(project_qualified_name="wukevin/tcr") experiment = neptune.create_experiment( name=f"nsp-{args.mode}" if not args.mlm else f"nsp-mlm-{args.mode}", params=neptune_params, tags=neptune_tags, ) neptune_logger = model_utils.NeptuneHuggingFaceCallback(experiment) # Train the model trainer = Trainer( model=model, args=training_args, # data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, compute_metrics=compute_metrics if not args.mlm else None, callbacks=[neptune_logger] if neptune_logger is not None else None, tokenizer=full_dataset.tok, ) trainer.train() trainer.save_model(args.outdir) # Evaluate test set performance test_ab = test_dataset.all_sequences() # Tuples of TRA/TRB test_labels = test_dataset.all_labels() test_nsp_preds = model_utils.get_transformer_nsp_preds( args.outdir, test_ab, inject_negatives=0, device=0, )[1][:, 1] test_auroc = metrics.roc_auc_score(test_labels, test_nsp_preds) test_auprc = metrics.average_precision_score(test_labels, test_nsp_preds) logging.info(f"Test set AUROC: {test_auroc:.4f}") logging.info(f"Test set AUPRC: {test_auprc:.4f}") with open(os.path.join(args.outdir, "test_perf.json"), "w") as sink: perf_dict = { "auroc": test_auroc, "auprc": test_auprc, "downsample": args.downsample, } logging.info(f"Writing test set performance metrics to {sink.name}") json.dump(perf_dict, sink, indent=4) if __name__ == "__main__": main()
[ "neptune.init", "neptune.create_experiment" ]
[((753, 777), 'sys.path.append', 'sys.path.append', (['SRC_DIR'], {}), '(SRC_DIR)\n', (768, 777), False, 'import os, sys\n'), ((875, 906), 'os.path.join', 'os.path.join', (['SRC_DIR', '"""models"""'], {}), "(SRC_DIR, 'models')\n", (887, 906), False, 'import os, sys\n'), ((914, 938), 'os.path.isdir', 'os.path.isdir', (['MODEL_DIR'], {}), '(MODEL_DIR)\n', (927, 938), False, 'import os, sys\n'), ((939, 965), 'sys.path.append', 'sys.path.append', (['MODEL_DIR'], {}), '(MODEL_DIR)\n', (954, 965), False, 'import os, sys\n'), ((1445, 1476), 'numpy.zeros_like', 'np.zeros_like', (['pred.predictions'], {}), '(pred.predictions)\n', (1458, 1476), True, 'import numpy as np\n'), ((1905, 2016), 'sklearn.metrics.precision_recall_fscore_support', 'metrics.precision_recall_fscore_support', (['labels', 'preds'], {'average': "('binary' if not is_multiclass else 'macro')"}), "(labels, preds, average='binary' if \n not is_multiclass else 'macro')\n", (1944, 2016), False, 'from sklearn import metrics\n'), ((2053, 2090), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['labels', 'preds'], {}), '(labels, preds)\n', (2075, 2090), False, 'from sklearn import metrics\n'), ((2103, 2164), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['labels', 'preds_probs'], {'multi_class': '"""ovr"""'}), "(labels, preds_probs, multi_class='ovr')\n", (2124, 2164), False, 'from sklearn import metrics\n'), ((2177, 2275), 'sklearn.metrics.average_precision_score', 'metrics.average_precision_score', (['(labels if not is_multiclass else labels_expanded)', 'preds_probs'], {}), '(labels if not is_multiclass else\n labels_expanded, preds_probs)\n', (2208, 2275), False, 'from sklearn import metrics\n'), ((9610, 9715), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(description=__doc__, formatter_class=argparse.\n ArgumentDefaultsHelpFormatter)\n', (9633, 9715), False, 'import argparse\n'), ((12198, 12217), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (12215, 12217), False, 'import logging\n'), ((12530, 12564), 'logging.info', 'logging.info', (['f"""Git commit: {sha}"""'], {}), "(f'Git commit: {sha}')\n", (12542, 12564), False, 'import logging\n'), ((12572, 12597), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (12595, 12597), False, 'import torch\n'), ((16901, 16931), 'utils.is_json_file', 'utils.is_json_file', (['args.model'], {}), '(args.model)\n', (16919, 16931), False, 'import utils\n'), ((17498, 17763), 'transformers.Trainer', 'Trainer', ([], {'model': 'model', 'args': 'training_args', 'train_dataset': 'train_dataset', 'eval_dataset': 'eval_dataset', 'compute_metrics': '(compute_metrics if not args.mlm else None)', 'callbacks': '([neptune_logger] if neptune_logger is not None else None)', 'tokenizer': 'full_dataset.tok'}), '(model=model, args=training_args, train_dataset=train_dataset,\n eval_dataset=eval_dataset, compute_metrics=compute_metrics if not args.\n mlm else None, callbacks=[neptune_logger] if neptune_logger is not None\n else None, tokenizer=full_dataset.tok)\n', (17505, 17763), False, 'from transformers import DataCollatorForLanguageModeling, BertForNextSentencePrediction, BertForSequenceClassification, BertForPreTraining, BertTokenizer, BertConfig, DataCollatorWithPadding, TrainingArguments, Trainer, TrainerCallback, EvalPrediction\n'), ((18229, 18279), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['test_labels', 'test_nsp_preds'], {}), '(test_labels, test_nsp_preds)\n', (18250, 18279), False, 'from sklearn import metrics\n'), ((18297, 18357), 'sklearn.metrics.average_precision_score', 'metrics.average_precision_score', (['test_labels', 'test_nsp_preds'], {}), '(test_labels, test_nsp_preds)\n', (18328, 18357), False, 'from sklearn import metrics\n'), ((18362, 18411), 'logging.info', 'logging.info', (['f"""Test set AUROC: {test_auroc:.4f}"""'], {}), "(f'Test set AUROC: {test_auroc:.4f}')\n", (18374, 18411), False, 'import logging\n'), ((18416, 18465), 'logging.info', 'logging.info', (['f"""Test set AUPRC: {test_auprc:.4f}"""'], {}), "(f'Test set AUPRC: {test_auprc:.4f}')\n", (18428, 18465), False, 'import logging\n'), ((718, 743), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (733, 743), False, 'import os, sys\n'), ((1692, 1725), 'scipy.special.softmax', 'softmax', (['pred.predictions'], {'axis': '(1)'}), '(pred.predictions, axis=1)\n', (1699, 1725), False, 'from scipy.special import softmax\n'), ((2811, 2842), 'utils.dedup', 'utils.dedup', (['blacklist_antigens'], {}), '(blacklist_antigens)\n', (2822, 2842), False, 'import utils\n'), ((3078, 3126), 'logging.info', 'logging.info', (['"""Loading 10x TRA/TRB pair dataset"""'], {}), "('Loading 10x TRA/TRB pair dataset')\n", (3090, 3126), False, 'import logging\n'), ((3141, 3154), 'data_loader.load_10x', 'dl.load_10x', ([], {}), '()\n', (3152, 3154), True, 'import data_loader as dl\n'), ((7978, 7997), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (7991, 7997), False, 'import os, sys\n'), ((8646, 8665), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (8659, 8665), False, 'import os, sys\n'), ((9472, 9525), 'logging.info', 'logging.info', (['"""Loading BertForNextSentencePrediction"""'], {}), "('Loading BertForNextSentencePrediction')\n", (9484, 9525), False, 'import logging\n'), ((12103, 12129), 'os.path.isdir', 'os.path.isdir', (['args.outdir'], {}), '(args.outdir)\n', (12116, 12129), False, 'import os, sys\n'), ((12139, 12163), 'os.makedirs', 'os.makedirs', (['args.outdir'], {}), '(args.outdir)\n', (12150, 12163), False, 'import os, sys\n'), ((12247, 12292), 'os.path.join', 'os.path.join', (['args.outdir', '"""nsp_training.log"""'], {}), "(args.outdir, 'nsp_training.log')\n", (12259, 12292), False, 'import os, sys\n'), ((12607, 12666), 'logging.info', 'logging.info', (['f"""PyTorch CUDA version: {torch.version.cuda}"""'], {}), "(f'PyTorch CUDA version: {torch.version.cuda}')\n", (12619, 12666), False, 'import logging\n'), ((12986, 13053), 'logging.info', 'logging.info', (['f"""Training NSP in full, using only train/test splits"""'], {}), "(f'Training NSP in full, using only train/test splits')\n", (12998, 13053), False, 'import logging\n'), ((14400, 14515), 'logging.info', 'logging.info', (['f"""Got LCMV fine tuning dataset, using full train/valid/test split with no dynamic training"""'], {}), "(\n f'Got LCMV fine tuning dataset, using full train/valid/test split with no dynamic training'\n )\n", (14412, 14515), False, 'import logging\n'), ((14712, 14780), 'data_loader.DatasetSplit', 'dl.DatasetSplit', (['full_dataset'], {'split': '"""train"""', 'dynamic_training': '(False)'}), "(full_dataset, split='train', dynamic_training=False)\n", (14727, 14780), True, 'import data_loader as dl\n'), ((14826, 14894), 'data_loader.DatasetSplit', 'dl.DatasetSplit', (['full_dataset'], {'split': '"""valid"""', 'dynamic_training': '(False)'}), "(full_dataset, split='valid', dynamic_training=False)\n", (14841, 14894), True, 'import data_loader as dl\n'), ((14940, 15007), 'data_loader.DatasetSplit', 'dl.DatasetSplit', (['full_dataset'], {'split': '"""test"""', 'dynamic_training': '(False)'}), "(full_dataset, split='test', dynamic_training=False)\n", (14955, 15007), True, 'import data_loader as dl\n'), ((15175, 15238), 'logging.info', 'logging.info', (['f"""Downsampling training set to {args.downsample}"""'], {}), "(f'Downsampling training set to {args.downsample}')\n", (15187, 15238), False, 'import logging\n'), ((15263, 15327), 'data_loader.DownsampledDataset', 'dl.DownsampledDataset', (['train_dataset'], {'downsample': 'args.downsample'}), '(train_dataset, downsample=args.downsample)\n', (15284, 15327), True, 'import data_loader as dl\n'), ((16421, 16451), 'utils.is_json_file', 'utils.is_json_file', (['args.model'], {}), '(args.model)\n', (16439, 16451), False, 'import utils\n'), ((16858, 16886), 'os.path.abspath', 'os.path.abspath', (['args.outdir'], {}), '(args.outdir)\n', (16873, 16886), False, 'import os, sys\n'), ((17065, 17092), 'os.path.abspath', 'os.path.abspath', (['args.model'], {}), '(args.model)\n', (17080, 17092), False, 'import os, sys\n'), ((17129, 17179), 'neptune.init', 'neptune.init', ([], {'project_qualified_name': '"""wukevin/tcr"""'}), "(project_qualified_name='wukevin/tcr')\n", (17141, 17179), False, 'import neptune\n'), ((17201, 17341), 'neptune.create_experiment', 'neptune.create_experiment', ([], {'name': "(f'nsp-{args.mode}' if not args.mlm else f'nsp-mlm-{args.mode}')", 'params': 'neptune_params', 'tags': 'neptune_tags'}), "(name=f'nsp-{args.mode}' if not args.mlm else\n f'nsp-mlm-{args.mode}', params=neptune_params, tags=neptune_tags)\n", (17226, 17341), False, 'import neptune\n'), ((17410, 17460), 'model_utils.NeptuneHuggingFaceCallback', 'model_utils.NeptuneHuggingFaceCallback', (['experiment'], {}), '(experiment)\n', (17448, 17460), False, 'import model_utils\n'), ((18689, 18757), 'logging.info', 'logging.info', (['f"""Writing test set performance metrics to {sink.name}"""'], {}), "(f'Writing test set performance metrics to {sink.name}')\n", (18701, 18757), False, 'import logging\n'), ((18766, 18802), 'json.dump', 'json.dump', (['perf_dict', 'sink'], {'indent': '(4)'}), '(perf_dict, sink, indent=4)\n', (18775, 18802), False, 'import json\n'), ((1560, 1591), 'numpy.sum', 'np.sum', (['labels_expanded'], {'axis': '(1)'}), '(labels_expanded, axis=1)\n', (1566, 1591), True, 'import numpy as np\n'), ((1758, 1791), 'scipy.special.softmax', 'softmax', (['pred.predictions'], {'axis': '(1)'}), '(pred.predictions, axis=1)\n', (1765, 1791), False, 'from scipy.special import softmax\n'), ((2697, 2737), 'utils.read_newline_file', 'utils.read_newline_file', (['blacklist_fname'], {}), '(blacklist_fname)\n', (2720, 2737), False, 'import utils\n'), ((3617, 3672), 'logging.info', 'logging.info', (['"""Loading VDJdb + PIRD antigen + TRB data"""'], {}), "('Loading VDJdb + PIRD antigen + TRB data')\n", (3629, 3672), False, 'import logging\n'), ((3692, 3728), 'data_loader.load_pird', 'dl.load_pird', ([], {'with_antigen_only': '(True)'}), '(with_antigen_only=True)\n', (3704, 3728), True, 'import data_loader as dl\n'), ((3891, 3928), 'data_loader.load_vdjdb', 'dl.load_vdjdb', ([], {'tra_trb_filter': "['TRB']"}), "(tra_trb_filter=['TRB'])\n", (3904, 3928), True, 'import data_loader as dl\n'), ((8679, 8757), 'logging.info', 'logging.info', (['f"""Loading BertForNextSentencePrediction from pretrained: {path}"""'], {}), "(f'Loading BertForNextSentencePrediction from pretrained: {path}')\n", (8691, 8757), False, 'import logging\n'), ((9914, 9925), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9923, 9925), False, 'import os, sys\n'), ((12772, 12812), 'os.path.join', 'os.path.join', (['args.outdir', '"""params.json"""'], {}), "(args.outdir, 'params.json')\n", (12784, 12812), False, 'import os, sys\n'), ((13117, 13215), 'data_loader.DatasetSplit', 'dl.DatasetSplit', (['full_dataset'], {'split': '"""train"""', 'valid': '(0)', 'test': '(0.1)', 'dynamic_training': 'args.dynamic'}), "(full_dataset, split='train', valid=0, test=0.1,\n dynamic_training=args.dynamic)\n", (13132, 13215), True, 'import data_loader as dl\n'), ((13334, 13396), 'data_loader.DatasetSplit', 'dl.DatasetSplit', (['full_dataset'], {'split': '"""test"""', 'valid': '(0)', 'test': '(0.1)'}), "(full_dataset, split='test', valid=0, test=0.1)\n", (13349, 13396), True, 'import data_loader as dl\n'), ((16120, 16156), 'os.path.join', 'os.path.join', (['args.outdir', '"""logging"""'], {}), "(args.outdir, 'logging')\n", (16132, 16156), False, 'import os, sys\n'), ((16963, 16997), 'utils.load_json_params', 'utils.load_json_params', (['args.model'], {}), '(args.model)\n', (16985, 16997), False, 'import utils\n'), ((18074, 18167), 'model_utils.get_transformer_nsp_preds', 'model_utils.get_transformer_nsp_preds', (['args.outdir', 'test_ab'], {'inject_negatives': '(0)', 'device': '(0)'}), '(args.outdir, test_ab,\n inject_negatives=0, device=0)\n', (18111, 18167), False, 'import model_utils\n'), ((18481, 18524), 'os.path.join', 'os.path.join', (['args.outdir', '"""test_perf.json"""'], {}), "(args.outdir, 'test_perf.json')\n", (18493, 18524), False, 'import os, sys\n'), ((4354, 4413), 'logging.info', 'logging.info', (['"""Loading VDJdb + PIRD antigen + TRA/TRB data"""'], {}), "('Loading VDJdb + PIRD antigen + TRA/TRB data')\n", (4366, 4413), False, 'import logging\n'), ((4433, 4469), 'data_loader.load_pird', 'dl.load_pird', ([], {'with_antigen_only': '(True)'}), '(with_antigen_only=True)\n', (4445, 4469), True, 'import data_loader as dl\n'), ((4634, 4678), 'data_loader.load_vdjdb', 'dl.load_vdjdb', ([], {'tra_trb_filter': "['TRA', 'TRB']"}), "(tra_trb_filter=['TRA', 'TRB'])\n", (4647, 4678), True, 'import data_loader as dl\n'), ((8101, 8121), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (8115, 8121), False, 'import os, sys\n'), ((8126, 8150), 'utils.is_json_file', 'utils.is_json_file', (['path'], {}), '(path)\n', (8144, 8150), False, 'import utils\n'), ((8164, 8228), 'logging.info', 'logging.info', (['f"""Loading BertForPretraining from scratch: {path}"""'], {}), "(f'Loading BertForPretraining from scratch: {path}')\n", (8176, 8228), False, 'import logging\n'), ((8250, 8278), 'utils.load_json_params', 'utils.load_json_params', (['path'], {}), '(path)\n', (8272, 8278), False, 'import utils\n'), ((8517, 8540), 'transformers.BertForPreTraining', 'BertForPreTraining', (['cfg'], {}), '(cfg)\n', (8535, 8540), False, 'from transformers import DataCollatorForLanguageModeling, BertForNextSentencePrediction, BertForSequenceClassification, BertForPreTraining, BertTokenizer, BertConfig, DataCollatorWithPadding, TrainingArguments, Trainer, TrainerCallback, EvalPrediction\n'), ((8839, 8898), 'transformer_custom.BertForThreewayNextSentencePrediction.from_pretrained', 'BertForThreewayNextSentencePrediction.from_pretrained', (['path'], {}), '(path)\n', (8892, 8898), False, 'from transformer_custom import BertForThreewayNextSentencePrediction\n'), ((8941, 8992), 'transformers.BertForNextSentencePrediction.from_pretrained', 'BertForNextSentencePrediction.from_pretrained', (['path'], {}), '(path)\n', (8986, 8992), False, 'from transformers import DataCollatorForLanguageModeling, BertForNextSentencePrediction, BertForSequenceClassification, BertForPreTraining, BertTokenizer, BertConfig, DataCollatorWithPadding, TrainingArguments, Trainer, TrainerCallback, EvalPrediction\n'), ((9006, 9026), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (9020, 9026), False, 'import os, sys\n'), ((9031, 9055), 'utils.is_json_file', 'utils.is_json_file', (['path'], {}), '(path)\n', (9049, 9055), False, 'import utils\n'), ((9078, 9106), 'utils.load_json_params', 'utils.load_json_params', (['path'], {}), '(path)\n', (9100, 9106), False, 'import utils\n'), ((9345, 9379), 'transformers.BertForNextSentencePrediction', 'BertForNextSentencePrediction', (['cfg'], {}), '(cfg)\n', (9374, 9379), False, 'from transformers import DataCollatorForLanguageModeling, BertForNextSentencePrediction, BertForSequenceClassification, BertForPreTraining, BertTokenizer, BertConfig, DataCollatorWithPadding, TrainingArguments, Trainer, TrainerCallback, EvalPrediction\n'), ((12427, 12452), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (12442, 12452), False, 'import os, sys\n'), ((13792, 13917), 'data_loader.DatasetSplitByAttribute', 'dl.DatasetSplitByAttribute', (['full_dataset', 'antigen_getter'], {'split': '"""train"""', 'dynamic_training': 'args.dynamic', 'valid': '(0)', 'test': '(0.1)'}), "(full_dataset, antigen_getter, split='train',\n dynamic_training=args.dynamic, valid=0, test=0.1)\n", (13818, 13917), True, 'import data_loader as dl\n'), ((14052, 14176), 'data_loader.DatasetSplitByAttribute', 'dl.DatasetSplitByAttribute', (['full_dataset', 'antigen_getter'], {'split': '"""test"""', 'dynamic_training': 'args.dynamic', 'valid': '(0)', 'test': '(0.1)'}), "(full_dataset, antigen_getter, split='test',\n dynamic_training=args.dynamic, valid=0, test=0.1)\n", (14078, 14176), True, 'import data_loader as dl\n'), ((5144, 5254), 'logging.info', 'logging.info', (['"""Loading LCMV dataset, primarily used for fine tuning, ignoring given negatives ratio"""'], {}), "(\n 'Loading LCMV dataset, primarily used for fine tuning, ignoring given negatives ratio'\n )\n", (5156, 5254), False, 'import logging\n'), ((5368, 5388), 'data_loader.load_lcmv_table', 'dl.load_lcmv_table', ([], {}), '()\n', (5386, 5388), True, 'import data_loader as dl\n'), ((5499, 5541), 'numpy.array', 'np.array', (["(lcmv_tab['tetramer'] == 'TetPos')"], {}), "(lcmv_tab['tetramer'] == 'TetPos')\n", (5507, 5541), True, 'import numpy as np\n'), ((5565, 5737), 'data_loader.TcrNextSentenceDataset', 'dl.TcrNextSentenceDataset', (['lcmv_antigen', 'lcmv_trbs'], {'neg_ratio': '(0.0)', 'tra_blacklist': 'blacklist_antigens', 'labels': 'lcmv_labels', 'mlm': '(0.15 if args.mlm else 0)', 'shuffle': '(False)'}), '(lcmv_antigen, lcmv_trbs, neg_ratio=0.0,\n tra_blacklist=blacklist_antigens, labels=lcmv_labels, mlm=0.15 if args.\n mlm else 0, shuffle=False)\n', (5590, 5737), True, 'import data_loader as dl\n'), ((6094, 6179), 'logging.info', 'logging.info', (['"""Loading LCMV dataset for TRA/TRB pairs, ignoring negatives ratio"""'], {}), "('Loading LCMV dataset for TRA/TRB pairs, ignoring negatives ratio'\n )\n", (6106, 6179), False, 'import logging\n'), ((6194, 6214), 'data_loader.load_lcmv_table', 'dl.load_lcmv_table', ([], {}), '()\n', (6212, 6214), True, 'import data_loader as dl\n'), ((7420, 7589), 'data_loader.TcrNextSentenceDataset', 'dl.TcrNextSentenceDataset', (['lcmv_tras', 'lcmv_trbs'], {'neg_ratio': '(0.0)', 'tra_blacklist': 'blacklist_antigens', 'labels': 'lcmv_labels', 'mlm': '(0.15 if args.mlm else 0)', 'shuffle': '(False)'}), '(lcmv_tras, lcmv_trbs, neg_ratio=0.0,\n tra_blacklist=blacklist_antigens, labels=lcmv_labels, mlm=0.15 if args.\n mlm else 0, shuffle=False)\n', (7445, 7589), True, 'import data_loader as dl\n'), ((6556, 6667), 'logging.warning', 'logging.warning', (['"""Using legacy LCMV loading scheme where only TetPos is positive and we do NOT dedup"""'], {}), "(\n 'Using legacy LCMV loading scheme where only TetPos is positive and we do NOT dedup'\n )\n", (6571, 6667), False, 'import logging\n'), ((6914, 6943), 'data_loader.dedup_lcmv_table', 'dl.dedup_lcmv_table', (['lcmv_tab'], {}), '(lcmv_tab)\n', (6933, 6943), True, 'import data_loader as dl\n'), ((7080, 7151), 'numpy.array', 'np.array', (["[('TetPos' in l or 'TetMid' in l) for l in lcmv_dedup_labels]"], {}), "([('TetPos' in l or 'TetMid' in l) for l in lcmv_dedup_labels])\n", (7088, 7151), True, 'import numpy as np\n'), ((7269, 7289), 'numpy.mean', 'np.mean', (['lcmv_labels'], {}), '(lcmv_labels)\n', (7276, 7289), True, 'import numpy as np\n')]
import copy import neptune import numpy as np import pommerman import torch from torch import nn from pommerman.dqn import utils, utility from pommerman.dqn.experience_replay import Memory, RecurrentMemory from pommerman.dqn.nets.vdn import VDNMixer class Arena: """Parent abstract Arena.""" def __init__(self, device, tau, epsilon, epsilon_decay, final_epsilon, dqn_agents, discount, reward_shaping=0, resumed_optimizers=None, time_step=0): self.device = device self.tau = tau self.discount = discount self.epsilon = epsilon self.epsilon_decay = epsilon_decay self.final_epsilon = final_epsilon self.reward_shaping = reward_shaping self.mixer = VDNMixer().to(self.device) self.target_mixer = copy.deepcopy(self.mixer) self.index_agent_dict = dict(zip([0, 2], dqn_agents)) if resumed_optimizers is not None: self.optimizer = resumed_optimizers[0] else: self.params = [] self.add_agent_model_params() self.optimizer = torch.optim.Adam(self.params) self.MSE_loss = nn.MSELoss() self.r_d_batch = None self.time_step = time_step def add_agent_model_params(self): for _, agent in self.index_agent_dict.items(): self.params += agent.get_model_params() def reset_agents(self): for _, agent in self.index_agent_dict.items(): agent.reset_game_state() def update(self, q_s_a_tot, q_n_s_a_tot, batch): # batch: [[(r, d), (r, d)], [(r, d), (r, d)]] reward_batches, done_batches = [], [] # episode: [(r, d), (r, d)] for episode in batch: reward_batch, done_batch = [], [] # experience: (r, d) for experience in episode: # sub_batch per: [r, r] reward_batch.append(experience[0]) done_batch.append(experience[1]) # batches: [[r, r], [r, r]] reward_batches.append(reward_batch) done_batches.append(done_batch) reward_batches = torch.FloatTensor(np.array(reward_batches)).to(self.device) done_batches = torch.LongTensor(np.array(done_batches)).to(self.device) # Add future reward only if state not terminal # Target target_values = reward_batches[:, self.time_step - 1] + ( 1 - done_batches[:, self.time_step - 1]) * self.discount * q_n_s_a_tot del reward_batches del done_batches del q_n_s_a_tot loss = self.MSE_loss(q_s_a_tot, target_values) neptune.send_metric('loss', loss) self.optimize(loss) def optimize(self, loss): self.optimizer.zero_grad() loss.backward() self.optimizer.step() del loss self.update_target() for _, agent in self.index_agent_dict.items(): agent.update_target() def update_epsilon(self): if self.epsilon > self.final_epsilon: self.epsilon -= self.epsilon_decay for _, agent in self.index_agent_dict.items(): agent.update_epsilon(self.epsilon) def run_episode(self, opponent): pass def update_target(self): # target network soft update for target_param, param in zip(self.target_mixer.parameters(), self.mixer.parameters()): target_param.data.copy_(self.tau * param + (1 - self.tau) * target_param) class ArenaNOXP(Arena): def __init__(self, buffer_size=10000, **kwargs): super().__init__(**kwargs) self.local_memory = Memory(max_size=buffer_size) def run_episode(self, opponent): # Create a set of agents (exactly four) agent_list = utility.create_agents(self.index_agent_dict, opponent) # Make the "Pommerman" environment using the agent list env = pommerman.make('PommeRadioCompetition-v2', agent_list) state = env.reset() episode_reward = [] done = False while not done: # env.render() actions = env.act(state) next_state, reward, done, info = env.step(actions) if self.reward_shaping: reward = utility.get_shaped_reward(reward) episode_reward = reward r_d_experience = utils.get_r_d_experience(reward, done, list(self.index_agent_dict.keys())) self.local_memory.push(r_d_experience) for index, agent in self.index_agent_dict.items(): s_a_n_s_experience = utils.get_s_a_n_s_experience(state, actions, next_state, index) agent.local_memory.push(s_a_n_s_experience) state = next_state self.r_d_batch = [self.local_memory.buffer] self.time_step = len(self.local_memory.buffer) # Store every agent's q-value of selected action in current state q_s_a_list = [] # Store every agent's q-value of taking best predicted action in next state q_n_s_a_list = [] q_s_a, q_n_s_a = None, None for _, agent in self.index_agent_dict.items(): q_s_a, q_n_s_a = agent.compute_q_values() # List of tensors with shape [1], num_tensors in list = num_dqn_agents q_s_a_list.append(q_s_a) q_n_s_a_list.append(q_n_s_a) del q_s_a del q_n_s_a # VDN # Stack list of tensors to get tensor of shape [num_dqn_agents, 1]: # Q-values of batch per agent # Sum over q-values of agents per batch: output [[1, 1]] q_s_a_tot = self.mixer.forward(torch.stack(q_s_a_list))[0] q_n_s_a_tot = self.target_mixer.forward(torch.stack(q_n_s_a_list))[0] del q_s_a_list del q_n_s_a_list self.update(q_s_a_tot=q_s_a_tot, q_n_s_a_tot=q_n_s_a_tot, batch=self.r_d_batch) del q_s_a_tot del q_n_s_a_tot for _, agent in self.index_agent_dict.items(): agent.local_memory.clear() self.local_memory.clear() self.update_epsilon() env.close() self.reset_agents() return episode_reward class ArenaXP(Arena): def __init__(self, batch_size, buffer_size=5000, **kwargs): super().__init__(**kwargs) self.batch_size = batch_size self.replay_buffer = RecurrentMemory(max_size=buffer_size) def sample(self): s_a_n_s_batch, r_d_batch = self.replay_buffer.sample_recurrent(self.batch_size, self.time_step) return s_a_n_s_batch, r_d_batch def run_episode(self, opponent): # Create a set of agents (exactly four) agent_list = utility.create_agents(self.index_agent_dict, opponent) # Make the "Pommerman" environment using the agent list env = pommerman.make('PommeRadioCompetition-v2', agent_list) state = env.reset() episode_reward = [] done = False buffer_can_sample = False while not done: # env.render() actions = env.act(state) next_state, reward, done, info = env.step(actions) if self.reward_shaping: reward = utility.get_shaped_reward(reward) episode_reward = reward # Store every agent's q-value of selected action in current state q_s_a_list = [] # Store every agent's q-value of taking best predicted action in next state q_n_s_a_list = [] experience = (state, actions, reward, next_state, done) self.replay_buffer.local_memory.push(experience) if len(self.replay_buffer) > self.batch_size: buffer_can_sample = True s_a_n_s_batch, r_d_batch = self.sample() self.r_d_batch = utils.get_arena_batch(r_d_batch, list(self.index_agent_dict.keys())) for index, agent in self.index_agent_dict.items(): q_s_a, q_n_s_a = agent.compute_q_values(utils.get_agent_batch(s_a_n_s_batch, index)) # List of tensors with shape [batch_size], num_tensors in list = num_dqn_agents q_s_a_list.append(q_s_a) q_n_s_a_list.append(q_n_s_a) del q_s_a del q_n_s_a # VDN if buffer_can_sample: # Stack list of tensors to get tensor of shape [num_dqn_agents, batch_size]: # Q-values of batches per agent # Sum over q-values of agents per batch: output [[1, batch_size]] q_s_a_tot = self.mixer.forward(torch.stack(q_s_a_list))[0] q_n_s_a_tot = self.target_mixer.forward(torch.stack(q_n_s_a_list))[0] del q_s_a_list del q_n_s_a_list self.update(q_s_a_tot=q_s_a_tot, q_n_s_a_tot=q_n_s_a_tot, batch=self.r_d_batch) del q_s_a_tot del q_n_s_a_tot state = next_state self.replay_buffer.add_mem_to_buffer() self.update_epsilon() env.close() self.reset_agents() return episode_reward, 0, 0, self.optimizer.state_dict(), None
[ "neptune.send_metric" ]
[((798, 823), 'copy.deepcopy', 'copy.deepcopy', (['self.mixer'], {}), '(self.mixer)\n', (811, 823), False, 'import copy\n'), ((1151, 1163), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (1161, 1163), False, 'from torch import nn\n'), ((2641, 2674), 'neptune.send_metric', 'neptune.send_metric', (['"""loss"""', 'loss'], {}), "('loss', loss)\n", (2660, 2674), False, 'import neptune\n'), ((3636, 3664), 'pommerman.dqn.experience_replay.Memory', 'Memory', ([], {'max_size': 'buffer_size'}), '(max_size=buffer_size)\n', (3642, 3664), False, 'from pommerman.dqn.experience_replay import Memory, RecurrentMemory\n'), ((3772, 3826), 'pommerman.dqn.utility.create_agents', 'utility.create_agents', (['self.index_agent_dict', 'opponent'], {}), '(self.index_agent_dict, opponent)\n', (3793, 3826), False, 'from pommerman.dqn import utils, utility\n'), ((3906, 3960), 'pommerman.make', 'pommerman.make', (['"""PommeRadioCompetition-v2"""', 'agent_list'], {}), "('PommeRadioCompetition-v2', agent_list)\n", (3920, 3960), False, 'import pommerman\n'), ((6346, 6383), 'pommerman.dqn.experience_replay.RecurrentMemory', 'RecurrentMemory', ([], {'max_size': 'buffer_size'}), '(max_size=buffer_size)\n', (6361, 6383), False, 'from pommerman.dqn.experience_replay import Memory, RecurrentMemory\n'), ((6658, 6712), 'pommerman.dqn.utility.create_agents', 'utility.create_agents', (['self.index_agent_dict', 'opponent'], {}), '(self.index_agent_dict, opponent)\n', (6679, 6712), False, 'from pommerman.dqn import utils, utility\n'), ((6792, 6846), 'pommerman.make', 'pommerman.make', (['"""PommeRadioCompetition-v2"""', 'agent_list'], {}), "('PommeRadioCompetition-v2', agent_list)\n", (6806, 6846), False, 'import pommerman\n'), ((1096, 1125), 'torch.optim.Adam', 'torch.optim.Adam', (['self.params'], {}), '(self.params)\n', (1112, 1125), False, 'import torch\n'), ((743, 753), 'pommerman.dqn.nets.vdn.VDNMixer', 'VDNMixer', ([], {}), '()\n', (751, 753), False, 'from pommerman.dqn.nets.vdn import VDNMixer\n'), ((4251, 4284), 'pommerman.dqn.utility.get_shaped_reward', 'utility.get_shaped_reward', (['reward'], {}), '(reward)\n', (4276, 4284), False, 'from pommerman.dqn import utils, utility\n'), ((4578, 4641), 'pommerman.dqn.utils.get_s_a_n_s_experience', 'utils.get_s_a_n_s_experience', (['state', 'actions', 'next_state', 'index'], {}), '(state, actions, next_state, index)\n', (4606, 4641), False, 'from pommerman.dqn import utils, utility\n'), ((5629, 5652), 'torch.stack', 'torch.stack', (['q_s_a_list'], {}), '(q_s_a_list)\n', (5640, 5652), False, 'import torch\n'), ((5705, 5730), 'torch.stack', 'torch.stack', (['q_n_s_a_list'], {}), '(q_n_s_a_list)\n', (5716, 5730), False, 'import torch\n'), ((7171, 7204), 'pommerman.dqn.utility.get_shaped_reward', 'utility.get_shaped_reward', (['reward'], {}), '(reward)\n', (7196, 7204), False, 'from pommerman.dqn import utils, utility\n'), ((2152, 2176), 'numpy.array', 'np.array', (['reward_batches'], {}), '(reward_batches)\n', (2160, 2176), True, 'import numpy as np\n'), ((2234, 2256), 'numpy.array', 'np.array', (['done_batches'], {}), '(done_batches)\n', (2242, 2256), True, 'import numpy as np\n'), ((7984, 8027), 'pommerman.dqn.utils.get_agent_batch', 'utils.get_agent_batch', (['s_a_n_s_batch', 'index'], {}), '(s_a_n_s_batch, index)\n', (8005, 8027), False, 'from pommerman.dqn import utils, utility\n'), ((8608, 8631), 'torch.stack', 'torch.stack', (['q_s_a_list'], {}), '(q_s_a_list)\n', (8619, 8631), False, 'import torch\n'), ((8692, 8717), 'torch.stack', 'torch.stack', (['q_n_s_a_list'], {}), '(q_n_s_a_list)\n', (8703, 8717), False, 'import torch\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from typing import TYPE_CHECKING, Optional from neptune.new.internal.background_job import BackgroundJob from neptune.new.internal.threading.daemon import Daemon if TYPE_CHECKING: from neptune.new.run import Run _logger = logging.getLogger(__name__) class PingBackgroundJob(BackgroundJob): def __init__(self, period: float = 10): self._period = period self._thread = None self._started = False def start(self, run: "Run"): self._thread = self.ReportingThread(self._period, run) self._thread.start() self._started = True def stop(self): if not self._started: return self._thread.interrupt() def join(self, seconds: Optional[float] = None): if not self._started: return self._thread.join(seconds) class ReportingThread(Daemon): def __init__(self, period: float, run: "Run"): super().__init__(sleep_time=period, name="NeptunePing") self._run = run @Daemon.ConnectionRetryWrapper( kill_message=( "Killing Neptune ping thread. Your run's status will not be updated and" " the run will be shown as inactive." ) ) def work(self) -> None: self._run.ping()
[ "neptune.new.internal.threading.daemon.Daemon.ConnectionRetryWrapper" ]
[((842, 869), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (859, 869), False, 'import logging\n'), ((1637, 1798), 'neptune.new.internal.threading.daemon.Daemon.ConnectionRetryWrapper', 'Daemon.ConnectionRetryWrapper', ([], {'kill_message': '"""Killing Neptune ping thread. Your run\'s status will not be updated and the run will be shown as inactive."""'}), '(kill_message=\n "Killing Neptune ping thread. Your run\'s status will not be updated and the run will be shown as inactive."\n )\n', (1666, 1798), False, 'from neptune.new.internal.threading.daemon import Daemon\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=protected-access from mock import patch, MagicMock from neptune.new.attributes.series.string_series import StringSeries from tests.neptune.new.attributes.test_attribute_base import TestAttributeBase @patch("time.time", new=TestAttributeBase._now) class TestStringSeries(TestAttributeBase): def test_assign_type_error(self): values = [55, "string", None] for value in values: with self.assertRaises(Exception): StringSeries(MagicMock(), MagicMock()).assign(value) def test_get(self): exp, path = self._create_run(), self._random_path() var = StringSeries(exp, path) var.log("asdfhadh") var.log("hej!") self.assertEqual("hej!", var.fetch_last()) def test_log(self): exp, path = self._create_run(), self._random_path() var = StringSeries(exp, path) var.log([str(val) for val in range(0, 5000)]) self.assertEqual("4999", var.fetch_last()) values = list(var.fetch_values()["value"].array) expected = list(range(0, 5000)) self.assertEqual(len(set(expected)), len(set(values)))
[ "neptune.new.attributes.series.string_series.StringSeries" ]
[((820, 866), 'mock.patch', 'patch', (['"""time.time"""'], {'new': 'TestAttributeBase._now'}), "('time.time', new=TestAttributeBase._now)\n", (825, 866), False, 'from mock import patch, MagicMock\n'), ((1230, 1253), 'neptune.new.attributes.series.string_series.StringSeries', 'StringSeries', (['exp', 'path'], {}), '(exp, path)\n', (1242, 1253), False, 'from neptune.new.attributes.series.string_series import StringSeries\n'), ((1456, 1479), 'neptune.new.attributes.series.string_series.StringSeries', 'StringSeries', (['exp', 'path'], {}), '(exp, path)\n', (1468, 1479), False, 'from neptune.new.attributes.series.string_series import StringSeries\n'), ((1091, 1102), 'mock.MagicMock', 'MagicMock', ([], {}), '()\n', (1100, 1102), False, 'from mock import patch, MagicMock\n'), ((1104, 1115), 'mock.MagicMock', 'MagicMock', ([], {}), '()\n', (1113, 1115), False, 'from mock import patch, MagicMock\n')]
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # pylint: disable=protected-access import pickle from io import StringIO, BytesIO import numpy from PIL import Image from neptune.new.internal.utils.images import _get_pil_image_data from neptune.new.types import File from tests.neptune.new.attributes.test_attribute_base import TestAttributeBase class TestFile(TestAttributeBase): def test_create_from_path(self): file = File("some/path.ext") self.assertEqual("some/path.ext", file.path) self.assertEqual(None, file.content) self.assertEqual("ext", file.extension) file = File("some/path.txt.ext") self.assertEqual("some/path.txt.ext", file.path) self.assertEqual(None, file.content) self.assertEqual("ext", file.extension) file = File("so.me/path") self.assertEqual("so.me/path", file.path) self.assertEqual(None, file.content) self.assertEqual("", file.extension) file = File("some/path.ext", extension="txt") self.assertEqual("some/path.ext", file.path) self.assertEqual(None, file.content) self.assertEqual("txt", file.extension) def test_create_from_string_content(self): file = File.from_content("some_content") self.assertEqual(None, file.path) self.assertEqual("some_content".encode("utf-8"), file.content) self.assertEqual("txt", file.extension) file = File.from_content("some_content", extension="png") self.assertEqual(None, file.path) self.assertEqual("some_content".encode("utf-8"), file.content) self.assertEqual("png", file.extension) def test_create_from_bytes_content(self): file = File.from_content(b"some_content") self.assertEqual(None, file.path) self.assertEqual(b"some_content", file.content) self.assertEqual("bin", file.extension) file = File.from_content(b"some_content", extension="png") self.assertEqual(None, file.path) self.assertEqual(b"some_content", file.content) self.assertEqual("png", file.extension) def test_create_from_string_io(self): file = File.from_stream(StringIO("aaabbbccc")) self.assertEqual(None, file.path) self.assertEqual(b"aaabbbccc", file.content) self.assertEqual("txt", file.extension) stream = StringIO("aaabbbccc") stream.seek(3) file = File.from_stream(stream) self.assertEqual(None, file.path) self.assertEqual(b"aaabbbccc", file.content) self.assertEqual("txt", file.extension) file = File.from_stream(StringIO("aaabbbccc"), extension="png") self.assertEqual(None, file.path) self.assertEqual(b"aaabbbccc", file.content) self.assertEqual("png", file.extension) file = File.from_stream(StringIO("aaabbbccc"), seek=5) self.assertEqual(None, file.path) self.assertEqual(b"bccc", file.content) self.assertEqual("txt", file.extension) def test_create_from_bytes_io(self): file = File.from_stream(BytesIO(b"aaabbbccc")) self.assertEqual(None, file.path) self.assertEqual(b"aaabbbccc", file.content) self.assertEqual("bin", file.extension) stream = BytesIO(b"aaabbbccc") stream.seek(3) file = File.from_stream(stream) self.assertEqual(None, file.path) self.assertEqual(b"aaabbbccc", file.content) self.assertEqual("bin", file.extension) file = File.from_stream(BytesIO(b"aaabbbccc"), extension="png") self.assertEqual(None, file.path) self.assertEqual(b"aaabbbccc", file.content) self.assertEqual("png", file.extension) file = File.from_stream(BytesIO(b"aaabbbccc"), seek=5) self.assertEqual(None, file.path) self.assertEqual(b"bccc", file.content) self.assertEqual("bin", file.extension) def test_as_image(self): # given image_array = numpy.random.rand(10, 10) * 255 expected_image = Image.fromarray(image_array.astype(numpy.uint8)) # when file = File.as_image(expected_image) # then self.assertEqual(file.extension, "png") self.assertEqual(file.content, _get_pil_image_data(expected_image)) def test_as_html(self): # given from bokeh.plotting import figure # given p = figure(plot_width=400, plot_height=400) p.circle(size=20, color="navy", alpha=0.5) # when file = File.as_html(p) # then self.assertEqual(file.extension, "html") self.assertTrue( file.content.startswith( '\n\n\n\n<!DOCTYPE html>\n<html lang="en">'.encode("utf-8") ) ) def test_as_pickle(self): # given obj = {"a": [b"xyz", 34], "b": 1246} # when file = File.as_pickle(obj) # then self.assertEqual(file.extension, "pkl") self.assertEqual(file.content, pickle.dumps(obj)) def test_raise_exception_in_constructor(self): with self.assertRaises(ValueError): File(path="path", content=b"some_content") with self.assertRaises(ValueError): File()
[ "neptune.new.types.File.as_html", "neptune.new.types.File.as_pickle", "neptune.new.internal.utils.images._get_pil_image_data", "neptune.new.types.File.from_stream", "neptune.new.types.File.from_content", "neptune.new.types.File.as_image", "neptune.new.types.File" ]
[((986, 1007), 'neptune.new.types.File', 'File', (['"""some/path.ext"""'], {}), "('some/path.ext')\n", (990, 1007), False, 'from neptune.new.types import File\n'), ((1170, 1195), 'neptune.new.types.File', 'File', (['"""some/path.txt.ext"""'], {}), "('some/path.txt.ext')\n", (1174, 1195), False, 'from neptune.new.types import File\n'), ((1362, 1380), 'neptune.new.types.File', 'File', (['"""so.me/path"""'], {}), "('so.me/path')\n", (1366, 1380), False, 'from neptune.new.types import File\n'), ((1537, 1575), 'neptune.new.types.File', 'File', (['"""some/path.ext"""'], {'extension': '"""txt"""'}), "('some/path.ext', extension='txt')\n", (1541, 1575), False, 'from neptune.new.types import File\n'), ((1785, 1818), 'neptune.new.types.File.from_content', 'File.from_content', (['"""some_content"""'], {}), "('some_content')\n", (1802, 1818), False, 'from neptune.new.types import File\n'), ((1996, 2046), 'neptune.new.types.File.from_content', 'File.from_content', (['"""some_content"""'], {'extension': '"""png"""'}), "('some_content', extension='png')\n", (2013, 2046), False, 'from neptune.new.types import File\n'), ((2270, 2304), 'neptune.new.types.File.from_content', 'File.from_content', (["b'some_content'"], {}), "(b'some_content')\n", (2287, 2304), False, 'from neptune.new.types import File\n'), ((2467, 2518), 'neptune.new.types.File.from_content', 'File.from_content', (["b'some_content'"], {'extension': '"""png"""'}), "(b'some_content', extension='png')\n", (2484, 2518), False, 'from neptune.new.types import File\n'), ((2924, 2945), 'io.StringIO', 'StringIO', (['"""aaabbbccc"""'], {}), "('aaabbbccc')\n", (2932, 2945), False, 'from io import StringIO, BytesIO\n'), ((2984, 3008), 'neptune.new.types.File.from_stream', 'File.from_stream', (['stream'], {}), '(stream)\n', (3000, 3008), False, 'from neptune.new.types import File\n'), ((3828, 3849), 'io.BytesIO', 'BytesIO', (["b'aaabbbccc'"], {}), "(b'aaabbbccc')\n", (3835, 3849), False, 'from io import StringIO, BytesIO\n'), ((3888, 3912), 'neptune.new.types.File.from_stream', 'File.from_stream', (['stream'], {}), '(stream)\n', (3904, 3912), False, 'from neptune.new.types import File\n'), ((4679, 4708), 'neptune.new.types.File.as_image', 'File.as_image', (['expected_image'], {}), '(expected_image)\n', (4692, 4708), False, 'from neptune.new.types import File\n'), ((4965, 5004), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(400)', 'plot_height': '(400)'}), '(plot_width=400, plot_height=400)\n', (4971, 5004), False, 'from bokeh.plotting import figure\n'), ((5087, 5102), 'neptune.new.types.File.as_html', 'File.as_html', (['p'], {}), '(p)\n', (5099, 5102), False, 'from neptune.new.types import File\n'), ((5453, 5472), 'neptune.new.types.File.as_pickle', 'File.as_pickle', (['obj'], {}), '(obj)\n', (5467, 5472), False, 'from neptune.new.types import File\n'), ((2740, 2761), 'io.StringIO', 'StringIO', (['"""aaabbbccc"""'], {}), "('aaabbbccc')\n", (2748, 2761), False, 'from io import StringIO, BytesIO\n'), ((3185, 3206), 'io.StringIO', 'StringIO', (['"""aaabbbccc"""'], {}), "('aaabbbccc')\n", (3193, 3206), False, 'from io import StringIO, BytesIO\n'), ((3401, 3422), 'io.StringIO', 'StringIO', (['"""aaabbbccc"""'], {}), "('aaabbbccc')\n", (3409, 3422), False, 'from io import StringIO, BytesIO\n'), ((3644, 3665), 'io.BytesIO', 'BytesIO', (["b'aaabbbccc'"], {}), "(b'aaabbbccc')\n", (3651, 3665), False, 'from io import StringIO, BytesIO\n'), ((4089, 4110), 'io.BytesIO', 'BytesIO', (["b'aaabbbccc'"], {}), "(b'aaabbbccc')\n", (4096, 4110), False, 'from io import StringIO, BytesIO\n'), ((4305, 4326), 'io.BytesIO', 'BytesIO', (["b'aaabbbccc'"], {}), "(b'aaabbbccc')\n", (4312, 4326), False, 'from io import StringIO, BytesIO\n'), ((4542, 4567), 'numpy.random.rand', 'numpy.random.rand', (['(10)', '(10)'], {}), '(10, 10)\n', (4559, 4567), False, 'import numpy\n'), ((4812, 4847), 'neptune.new.internal.utils.images._get_pil_image_data', '_get_pil_image_data', (['expected_image'], {}), '(expected_image)\n', (4831, 4847), False, 'from neptune.new.internal.utils.images import _get_pil_image_data\n'), ((5576, 5593), 'pickle.dumps', 'pickle.dumps', (['obj'], {}), '(obj)\n', (5588, 5593), False, 'import pickle\n'), ((5703, 5745), 'neptune.new.types.File', 'File', ([], {'path': '"""path"""', 'content': "b'some_content'"}), "(path='path', content=b'some_content')\n", (5707, 5745), False, 'from neptune.new.types import File\n'), ((5802, 5808), 'neptune.new.types.File', 'File', ([], {}), '()\n', (5806, 5808), False, 'from neptune.new.types import File\n')]
# -*- coding: utf-8 -*- import json import os import random import click import neptune import numpy as np import regex import torch from loguru import logger from neptune.exceptions import NoExperimentContext from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from bert.optimization import BertAdam from bert.tokenization import BertTokenizer from eval import evalb from label_encoder import LabelEncoder from model import ChartParser from trees import InternalParseNode, load_trees try: from apex import amp except ImportError: pass MODEL_FILENAME = "model.bin" BERT_TOKEN_MAPPING = { "-LRB-": "(", "-RRB-": ")", "-LCB-": "{", "-RCB-": "}", "-LSB-": "[", "-RSB-": "]", } def create_dataloader(sentences, batch_size, tag_encoder, tokenizer, is_eval): features = [] for sentence in sentences: tokens = [] tags = [] sections = [] for tag, phrase in sentence: subtokens = [] for token in regex.split( r"(?<=[^\W_])_(?=[^\W_])", phrase, flags=regex.FULLCASE ): for subtoken in tokenizer.tokenize( BERT_TOKEN_MAPPING.get(token, token) ): subtokens.append(subtoken) tokens.extend(subtokens) tags.append(tag_encoder.transform(tag, unknown_label="[UNK]")) sections.append(len(subtokens)) ids = tokenizer.convert_tokens_to_ids(["[CLS]"] + tokens + ["[SEP]"]) attention_mask = [1] * len(ids) features.append( { "ids": ids, "attention_mask": attention_mask, "tags": tags, "sections": sections, } ) dataset = TensorDataset(torch.arange(len(features), dtype=torch.long)) sampler = SequentialSampler(dataset) if is_eval else RandomSampler(dataset) dataloader = DataLoader(dataset, sampler=sampler, batch_size=batch_size) return dataloader, features def prepare_batch_input(indices, features, trees, sentences, tag_encoder, device): _ids = [] _attention_masks = [] _tags = [] _sections = [] _trees = [] _sentences = [] ids_padding_size = 0 tags_padding_size = 0 for _id in indices: _ids.append(features[_id]["ids"]) _attention_masks.append(features[_id]["attention_mask"]) _tags.append(features[_id]["tags"]) _sections.append(features[_id]["sections"]) _trees.append(trees[_id]) _sentences.append(sentences[_id]) ids_padding_size = max(ids_padding_size, len(features[_id]["ids"])) tags_padding_size = max(tags_padding_size, len(features[_id]["tags"])) # Zero-pad for _id, _attention_mask, _tag in zip(_ids, _attention_masks, _tags): padding_size = ids_padding_size - len(_id) _id += [0] * padding_size _attention_mask += [0] * padding_size _tag += [tag_encoder.transform("[PAD]")] * (tags_padding_size - len(_tag)) _ids = torch.tensor(_ids, dtype=torch.long, device=device) _attention_masks = torch.tensor(_attention_masks, dtype=torch.long, device=device) _tags = torch.tensor(_tags, dtype=torch.long, device=device) return _ids, _attention_masks, _tags, _sections, _trees, _sentences def eval( model, eval_dataloader, eval_features, eval_trees, eval_sentences, tag_encoder, device, ): # Evaluation phase model.eval() all_predicted_trees = [] for indices, *_ in tqdm(eval_dataloader, desc="Iteration"): ids, attention_masks, tags, sections, _, sentences = prepare_batch_input( indices=indices, features=eval_features, trees=eval_trees, sentences=eval_sentences, tag_encoder=tag_encoder, device=device, ) with torch.no_grad(): predicted_trees = model( ids=ids, attention_masks=attention_masks, tags=tags, sections=sections, sentences=sentences, gold_trees=None, ) for predicted_tree in predicted_trees: all_predicted_trees.append(predicted_tree.convert()) return evalb(eval_trees, all_predicted_trees) @click.command() @click.option("--train_file", required=True, type=click.Path()) @click.option("--dev_file", required=True, type=click.Path()) @click.option("--test_file", required=True, type=click.Path()) @click.option("--output_dir", required=True, type=click.Path()) @click.option("--bert_model", required=True, type=click.Path()) @click.option("--lstm_layers", default=2, show_default=True, type=click.INT) @click.option("--lstm_dim", default=250, show_default=True, type=click.INT) @click.option("--tag_embedding_dim", default=50, show_default=True, type=click.INT) @click.option("--label_hidden_dim", default=250, show_default=True, type=click.INT) @click.option("--dropout_prob", default=0.4, show_default=True, type=click.FLOAT) @click.option("--batch_size", default=32, show_default=True, type=click.INT) @click.option("--num_epochs", default=20, show_default=True, type=click.INT) @click.option("--learning_rate", default=5e-5, show_default=True, type=click.FLOAT) @click.option("--warmup_proportion", default=0.1, show_default=True, type=click.FLOAT) @click.option( "--gradient_accumulation_steps", default=1, show_default=True, type=click.INT ) @click.option("--seed", default=42, show_default=True, type=click.INT) @click.option("--device", default=0, show_default=True, type=click.INT) @click.option("--fp16", is_flag=True) @click.option("--do_eval", is_flag=True) @click.option("--resume", is_flag=True) @click.option("--preload", is_flag=True) @click.option("--freeze_bert", is_flag=True) def main(*_, **kwargs): use_cuda = torch.cuda.is_available() and kwargs["device"] >= 0 device = torch.device("cuda:" + str(kwargs["device"]) if use_cuda else "cpu") if use_cuda: torch.cuda.set_device(device) kwargs["use_cuda"] = use_cuda neptune.create_experiment( name="bert-span-parser", upload_source_files=[], params={k: str(v) if isinstance(v, bool) else v for k, v in kwargs.items()}, ) logger.info("Settings: {}", json.dumps(kwargs, indent=2, ensure_ascii=False)) # For reproducibility os.environ["PYTHONHASHSEED"] = str(kwargs["seed"]) random.seed(kwargs["seed"]) np.random.seed(kwargs["seed"]) torch.manual_seed(kwargs["seed"]) torch.cuda.manual_seed_all(kwargs["seed"]) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Prepare and load data tokenizer = BertTokenizer.from_pretrained(kwargs["bert_model"], do_lower_case=False) logger.info("Loading data...") train_treebank = load_trees(kwargs["train_file"]) dev_treebank = load_trees(kwargs["dev_file"]) test_treebank = load_trees(kwargs["test_file"]) logger.info( "Loaded {:,} train, {:,} dev, and {:,} test examples!", len(train_treebank), len(dev_treebank), len(test_treebank), ) logger.info("Preprocessing data...") train_parse = [tree.convert() for tree in train_treebank] train_sentences = [ [(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in train_parse ] dev_sentences = [ [(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in dev_treebank ] test_sentences = [ [(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in test_treebank ] logger.info("Data preprocessed!") logger.info("Preparing data for training...") tags = [] labels = [] for tree in train_parse: nodes = [tree] while nodes: node = nodes.pop() if isinstance(node, InternalParseNode): labels.append(node.label) nodes.extend(reversed(node.children)) else: tags.append(node.tag) tag_encoder = LabelEncoder() tag_encoder.fit(tags, reserved_labels=["[PAD]", "[UNK]"]) label_encoder = LabelEncoder() label_encoder.fit(labels, reserved_labels=[()]) logger.info("Data prepared!") # Settings num_train_optimization_steps = kwargs["num_epochs"] * ( (len(train_parse) - 1) // kwargs["batch_size"] + 1 ) kwargs["batch_size"] //= kwargs["gradient_accumulation_steps"] logger.info("Creating dataloaders for training...") train_dataloader, train_features = create_dataloader( sentences=train_sentences, batch_size=kwargs["batch_size"], tag_encoder=tag_encoder, tokenizer=tokenizer, is_eval=False, ) dev_dataloader, dev_features = create_dataloader( sentences=dev_sentences, batch_size=kwargs["batch_size"], tag_encoder=tag_encoder, tokenizer=tokenizer, is_eval=True, ) test_dataloader, test_features = create_dataloader( sentences=test_sentences, batch_size=kwargs["batch_size"], tag_encoder=tag_encoder, tokenizer=tokenizer, is_eval=True, ) logger.info("Dataloaders created!") # Initialize model model = ChartParser.from_pretrained( kwargs["bert_model"], tag_encoder=tag_encoder, label_encoder=label_encoder, lstm_layers=kwargs["lstm_layers"], lstm_dim=kwargs["lstm_dim"], tag_embedding_dim=kwargs["tag_embedding_dim"], label_hidden_dim=kwargs["label_hidden_dim"], dropout_prob=kwargs["dropout_prob"], ) model.to(device) # Prepare optimizer param_optimizers = list(model.named_parameters()) if kwargs["freeze_bert"]: for p in model.bert.parameters(): p.requires_grad = False param_optimizers = [(n, p) for n, p in param_optimizers if p.requires_grad] # Hack to remove pooler, which is not used thus it produce None grad that break apex param_optimizers = [n for n in param_optimizers if "pooler" not in n[0]] no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [ p for n, p in param_optimizers if not any(nd in n for nd in no_decay) ], "weight_decay": 0.01, }, { "params": [ p for n, p in param_optimizers if any(nd in n for nd in no_decay) ], "weight_decay": 0.0, }, ] optimizer = BertAdam( optimizer_grouped_parameters, lr=kwargs["learning_rate"], warmup=kwargs["warmup_proportion"], t_total=num_train_optimization_steps, ) if kwargs["fp16"]: model, optimizer = amp.initialize(model, optimizer, opt_level="O1") pretrained_model_file = os.path.join(kwargs["output_dir"], MODEL_FILENAME) if kwargs["do_eval"]: assert os.path.isfile( pretrained_model_file ), "Pretrained model file does not exist!" logger.info("Loading pretrained model from {}", pretrained_model_file) # Load model from file params = torch.load(pretrained_model_file, map_location=device) model.load_state_dict(params["model"]) logger.info( "Loaded pretrained model (Epoch: {:,}, Fscore: {:.2f})", params["epoch"], params["fscore"], ) eval_score = eval( model=model, eval_dataloader=test_dataloader, eval_features=test_features, eval_trees=test_treebank, eval_sentences=test_sentences, tag_encoder=tag_encoder, device=device, ) neptune.send_metric("test_eval_precision", eval_score.precision()) neptune.send_metric("test_eval_recall", eval_score.recall()) neptune.send_metric("test_eval_fscore", eval_score.fscore()) tqdm.write("Evaluation score: {}".format(str(eval_score))) else: # Training phase global_steps = 0 start_epoch = 0 best_dev_fscore = 0 if kwargs["preload"] or kwargs["resume"]: assert os.path.isfile( pretrained_model_file ), "Pretrained model file does not exist!" logger.info("Resuming model from {}", pretrained_model_file) # Load model from file params = torch.load(pretrained_model_file, map_location=device) model.load_state_dict(params["model"]) if kwargs["resume"]: optimizer.load_state_dict(params["optimizer"]) torch.cuda.set_rng_state_all( [state.cpu() for state in params["torch_cuda_random_state_all"]] ) torch.set_rng_state(params["torch_random_state"].cpu()) np.random.set_state(params["np_random_state"]) random.setstate(params["random_state"]) global_steps = params["global_steps"] start_epoch = params["epoch"] + 1 best_dev_fscore = params["fscore"] else: assert not os.path.isfile( pretrained_model_file ), "Please remove or move the pretrained model file to another place!" for epoch in trange(start_epoch, kwargs["num_epochs"], desc="Epoch"): model.train() train_loss = 0 num_train_steps = 0 for step, (indices, *_) in enumerate( tqdm(train_dataloader, desc="Iteration") ): ids, attention_masks, tags, sections, trees, sentences = prepare_batch_input( indices=indices, features=train_features, trees=train_parse, sentences=train_sentences, tag_encoder=tag_encoder, device=device, ) loss = model( ids=ids, attention_masks=attention_masks, tags=tags, sections=sections, sentences=sentences, gold_trees=trees, ) if kwargs["gradient_accumulation_steps"] > 1: loss /= kwargs["gradient_accumulation_steps"] if kwargs["fp16"]: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() train_loss += loss.item() num_train_steps += 1 if (step + 1) % kwargs["gradient_accumulation_steps"] == 0: optimizer.step() optimizer.zero_grad() global_steps += 1 # Write logs neptune.send_metric("train_loss", epoch, train_loss / num_train_steps) neptune.send_metric("global_steps", epoch, global_steps) tqdm.write( "Epoch: {:,} - Train loss: {:.4f} - Global steps: {:,}".format( epoch, train_loss / num_train_steps, global_steps ) ) # Evaluate eval_score = eval( model=model, eval_dataloader=dev_dataloader, eval_features=dev_features, eval_trees=dev_treebank, eval_sentences=dev_sentences, tag_encoder=tag_encoder, device=device, ) neptune.send_metric("eval_precision", epoch, eval_score.precision()) neptune.send_metric("eval_recall", epoch, eval_score.recall()) neptune.send_metric("eval_fscore", epoch, eval_score.fscore()) tqdm.write( "Epoch: {:,} - Evaluation score: {}".format(epoch, str(eval_score)) ) # Save best model if eval_score.fscore() > best_dev_fscore: best_dev_fscore = eval_score.fscore() tqdm.write("** Saving model...") os.makedirs(kwargs["output_dir"], exist_ok=True) torch.save( { "epoch": epoch, "global_steps": global_steps, "fscore": best_dev_fscore, "random_state": random.getstate(), "np_random_state": np.random.get_state(), "torch_random_state": torch.get_rng_state(), "torch_cuda_random_state_all": torch.cuda.get_rng_state_all(), "optimizer": optimizer.state_dict(), "model": ( model.module if hasattr(model, "module") else model ).state_dict(), }, pretrained_model_file, ) tqdm.write("** Best evaluation fscore: {:.2f}".format(best_dev_fscore)) if __name__ == "__main__": neptune.init(project_qualified_name=os.getenv("NEPTUNE_PROJECT_NAME")) try: # main( # [ # "--train_file=corpora/WSJ-PTB/02-21.10way.clean.train", # "--dev_file=corpora/WSJ-PTB/22.auto.clean.dev", # "--test_file=corpora/WSJ-PTB/23.auto.clean.test", # "--output_dir=outputs", # "--bert_model=models/bert-base-multilingual-cased", # "--batch_size=32", # "--num_epochs=20", # "--learning_rate=3e-5", # # "--fp16", # # "--do_eval", # ] # ) main() finally: try: neptune.stop() except NoExperimentContext: pass
[ "neptune.stop", "neptune.send_metric" ]
[((4406, 4421), 'click.command', 'click.command', ([], {}), '()\n', (4419, 4421), False, 'import click\n'), ((4740, 4815), 'click.option', 'click.option', (['"""--lstm_layers"""'], {'default': '(2)', 'show_default': '(True)', 'type': 'click.INT'}), "('--lstm_layers', default=2, show_default=True, type=click.INT)\n", (4752, 4815), False, 'import click\n'), ((4817, 4891), 'click.option', 'click.option', (['"""--lstm_dim"""'], {'default': '(250)', 'show_default': '(True)', 'type': 'click.INT'}), "('--lstm_dim', default=250, show_default=True, type=click.INT)\n", (4829, 4891), False, 'import click\n'), ((4893, 4980), 'click.option', 'click.option', (['"""--tag_embedding_dim"""'], {'default': '(50)', 'show_default': '(True)', 'type': 'click.INT'}), "('--tag_embedding_dim', default=50, show_default=True, type=\n click.INT)\n", (4905, 4980), False, 'import click\n'), ((4977, 5064), 'click.option', 'click.option', (['"""--label_hidden_dim"""'], {'default': '(250)', 'show_default': '(True)', 'type': 'click.INT'}), "('--label_hidden_dim', default=250, show_default=True, type=\n click.INT)\n", (4989, 5064), False, 'import click\n'), ((5061, 5146), 'click.option', 'click.option', (['"""--dropout_prob"""'], {'default': '(0.4)', 'show_default': '(True)', 'type': 'click.FLOAT'}), "('--dropout_prob', default=0.4, show_default=True, type=click.FLOAT\n )\n", (5073, 5146), False, 'import click\n'), ((5143, 5218), 'click.option', 'click.option', (['"""--batch_size"""'], {'default': '(32)', 'show_default': '(True)', 'type': 'click.INT'}), "('--batch_size', default=32, show_default=True, type=click.INT)\n", (5155, 5218), False, 'import click\n'), ((5220, 5295), 'click.option', 'click.option', (['"""--num_epochs"""'], {'default': '(20)', 'show_default': '(True)', 'type': 'click.INT'}), "('--num_epochs', default=20, show_default=True, type=click.INT)\n", (5232, 5295), False, 'import click\n'), ((5297, 5385), 'click.option', 'click.option', (['"""--learning_rate"""'], {'default': '(5e-05)', 'show_default': '(True)', 'type': 'click.FLOAT'}), "('--learning_rate', default=5e-05, show_default=True, type=\n click.FLOAT)\n", (5309, 5385), False, 'import click\n'), ((5381, 5471), 'click.option', 'click.option', (['"""--warmup_proportion"""'], {'default': '(0.1)', 'show_default': '(True)', 'type': 'click.FLOAT'}), "('--warmup_proportion', default=0.1, show_default=True, type=\n click.FLOAT)\n", (5393, 5471), False, 'import click\n'), ((5468, 5563), 'click.option', 'click.option', (['"""--gradient_accumulation_steps"""'], {'default': '(1)', 'show_default': '(True)', 'type': 'click.INT'}), "('--gradient_accumulation_steps', default=1, show_default=True,\n type=click.INT)\n", (5480, 5563), False, 'import click\n'), ((5567, 5636), 'click.option', 'click.option', (['"""--seed"""'], {'default': '(42)', 'show_default': '(True)', 'type': 'click.INT'}), "('--seed', default=42, show_default=True, type=click.INT)\n", (5579, 5636), False, 'import click\n'), ((5638, 5708), 'click.option', 'click.option', (['"""--device"""'], {'default': '(0)', 'show_default': '(True)', 'type': 'click.INT'}), "('--device', default=0, show_default=True, type=click.INT)\n", (5650, 5708), False, 'import click\n'), ((5710, 5746), 'click.option', 'click.option', (['"""--fp16"""'], {'is_flag': '(True)'}), "('--fp16', is_flag=True)\n", (5722, 5746), False, 'import click\n'), ((5748, 5787), 'click.option', 'click.option', (['"""--do_eval"""'], {'is_flag': '(True)'}), "('--do_eval', is_flag=True)\n", (5760, 5787), False, 'import click\n'), ((5789, 5827), 'click.option', 'click.option', (['"""--resume"""'], {'is_flag': '(True)'}), "('--resume', is_flag=True)\n", (5801, 5827), False, 'import click\n'), ((5829, 5868), 'click.option', 'click.option', (['"""--preload"""'], {'is_flag': '(True)'}), "('--preload', is_flag=True)\n", (5841, 5868), False, 'import click\n'), ((5870, 5913), 'click.option', 'click.option', (['"""--freeze_bert"""'], {'is_flag': '(True)'}), "('--freeze_bert', is_flag=True)\n", (5882, 5913), False, 'import click\n'), ((1993, 2052), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'sampler': 'sampler', 'batch_size': 'batch_size'}), '(dataset, sampler=sampler, batch_size=batch_size)\n', (2003, 2052), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n'), ((3111, 3162), 'torch.tensor', 'torch.tensor', (['_ids'], {'dtype': 'torch.long', 'device': 'device'}), '(_ids, dtype=torch.long, device=device)\n', (3123, 3162), False, 'import torch\n'), ((3186, 3249), 'torch.tensor', 'torch.tensor', (['_attention_masks'], {'dtype': 'torch.long', 'device': 'device'}), '(_attention_masks, dtype=torch.long, device=device)\n', (3198, 3249), False, 'import torch\n'), ((3262, 3314), 'torch.tensor', 'torch.tensor', (['_tags'], {'dtype': 'torch.long', 'device': 'device'}), '(_tags, dtype=torch.long, device=device)\n', (3274, 3314), False, 'import torch\n'), ((3613, 3652), 'tqdm.tqdm', 'tqdm', (['eval_dataloader'], {'desc': '"""Iteration"""'}), "(eval_dataloader, desc='Iteration')\n", (3617, 3652), False, 'from tqdm import tqdm, trange\n'), ((4364, 4402), 'eval.evalb', 'evalb', (['eval_trees', 'all_predicted_trees'], {}), '(eval_trees, all_predicted_trees)\n', (4369, 4402), False, 'from eval import evalb\n'), ((6535, 6562), 'random.seed', 'random.seed', (["kwargs['seed']"], {}), "(kwargs['seed'])\n", (6546, 6562), False, 'import random\n'), ((6567, 6597), 'numpy.random.seed', 'np.random.seed', (["kwargs['seed']"], {}), "(kwargs['seed'])\n", (6581, 6597), True, 'import numpy as np\n'), ((6602, 6635), 'torch.manual_seed', 'torch.manual_seed', (["kwargs['seed']"], {}), "(kwargs['seed'])\n", (6619, 6635), False, 'import torch\n'), ((6640, 6682), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (["kwargs['seed']"], {}), "(kwargs['seed'])\n", (6666, 6682), False, 'import torch\n'), ((6817, 6889), 'bert.tokenization.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (["kwargs['bert_model']"], {'do_lower_case': '(False)'}), "(kwargs['bert_model'], do_lower_case=False)\n", (6846, 6889), False, 'from bert.tokenization import BertTokenizer\n'), ((6895, 6925), 'loguru.logger.info', 'logger.info', (['"""Loading data..."""'], {}), "('Loading data...')\n", (6906, 6925), False, 'from loguru import logger\n'), ((6948, 6980), 'trees.load_trees', 'load_trees', (["kwargs['train_file']"], {}), "(kwargs['train_file'])\n", (6958, 6980), False, 'from trees import InternalParseNode, load_trees\n'), ((7000, 7030), 'trees.load_trees', 'load_trees', (["kwargs['dev_file']"], {}), "(kwargs['dev_file'])\n", (7010, 7030), False, 'from trees import InternalParseNode, load_trees\n'), ((7051, 7082), 'trees.load_trees', 'load_trees', (["kwargs['test_file']"], {}), "(kwargs['test_file'])\n", (7061, 7082), False, 'from trees import InternalParseNode, load_trees\n'), ((7260, 7296), 'loguru.logger.info', 'logger.info', (['"""Preprocessing data..."""'], {}), "('Preprocessing data...')\n", (7271, 7296), False, 'from loguru import logger\n'), ((7701, 7734), 'loguru.logger.info', 'logger.info', (['"""Data preprocessed!"""'], {}), "('Data preprocessed!')\n", (7712, 7734), False, 'from loguru import logger\n'), ((7740, 7785), 'loguru.logger.info', 'logger.info', (['"""Preparing data for training..."""'], {}), "('Preparing data for training...')\n", (7751, 7785), False, 'from loguru import logger\n'), ((8145, 8159), 'label_encoder.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (8157, 8159), False, 'from label_encoder import LabelEncoder\n'), ((8243, 8257), 'label_encoder.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (8255, 8257), False, 'from label_encoder import LabelEncoder\n'), ((8315, 8344), 'loguru.logger.info', 'logger.info', (['"""Data prepared!"""'], {}), "('Data prepared!')\n", (8326, 8344), False, 'from loguru import logger\n'), ((8558, 8609), 'loguru.logger.info', 'logger.info', (['"""Creating dataloaders for training..."""'], {}), "('Creating dataloaders for training...')\n", (8569, 8609), False, 'from loguru import logger\n'), ((9280, 9315), 'loguru.logger.info', 'logger.info', (['"""Dataloaders created!"""'], {}), "('Dataloaders created!')\n", (9291, 9315), False, 'from loguru import logger\n'), ((9352, 9665), 'model.ChartParser.from_pretrained', 'ChartParser.from_pretrained', (["kwargs['bert_model']"], {'tag_encoder': 'tag_encoder', 'label_encoder': 'label_encoder', 'lstm_layers': "kwargs['lstm_layers']", 'lstm_dim': "kwargs['lstm_dim']", 'tag_embedding_dim': "kwargs['tag_embedding_dim']", 'label_hidden_dim': "kwargs['label_hidden_dim']", 'dropout_prob': "kwargs['dropout_prob']"}), "(kwargs['bert_model'], tag_encoder=tag_encoder,\n label_encoder=label_encoder, lstm_layers=kwargs['lstm_layers'],\n lstm_dim=kwargs['lstm_dim'], tag_embedding_dim=kwargs[\n 'tag_embedding_dim'], label_hidden_dim=kwargs['label_hidden_dim'],\n dropout_prob=kwargs['dropout_prob'])\n", (9379, 9665), False, 'from model import ChartParser\n'), ((10659, 10804), 'bert.optimization.BertAdam', 'BertAdam', (['optimizer_grouped_parameters'], {'lr': "kwargs['learning_rate']", 'warmup': "kwargs['warmup_proportion']", 't_total': 'num_train_optimization_steps'}), "(optimizer_grouped_parameters, lr=kwargs['learning_rate'], warmup=\n kwargs['warmup_proportion'], t_total=num_train_optimization_steps)\n", (10667, 10804), False, 'from bert.optimization import BertAdam\n'), ((10968, 11018), 'os.path.join', 'os.path.join', (["kwargs['output_dir']", 'MODEL_FILENAME'], {}), "(kwargs['output_dir'], MODEL_FILENAME)\n", (10980, 11018), False, 'import os\n'), ((1909, 1935), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['dataset'], {}), '(dataset)\n', (1926, 1935), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n'), ((1952, 1974), 'torch.utils.data.RandomSampler', 'RandomSampler', (['dataset'], {}), '(dataset)\n', (1965, 1974), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n'), ((5953, 5978), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5976, 5978), False, 'import torch\n'), ((6113, 6142), 'torch.cuda.set_device', 'torch.cuda.set_device', (['device'], {}), '(device)\n', (6134, 6142), False, 'import torch\n'), ((6399, 6447), 'json.dumps', 'json.dumps', (['kwargs'], {'indent': '(2)', 'ensure_ascii': '(False)'}), '(kwargs, indent=2, ensure_ascii=False)\n', (6409, 6447), False, 'import json\n'), ((10890, 10938), 'apex.amp.initialize', 'amp.initialize', (['model', 'optimizer'], {'opt_level': '"""O1"""'}), "(model, optimizer, opt_level='O1')\n", (10904, 10938), False, 'from apex import amp\n'), ((11061, 11098), 'os.path.isfile', 'os.path.isfile', (['pretrained_model_file'], {}), '(pretrained_model_file)\n', (11075, 11098), False, 'import os\n'), ((11171, 11241), 'loguru.logger.info', 'logger.info', (['"""Loading pretrained model from {}"""', 'pretrained_model_file'], {}), "('Loading pretrained model from {}', pretrained_model_file)\n", (11182, 11241), False, 'from loguru import logger\n'), ((11291, 11345), 'torch.load', 'torch.load', (['pretrained_model_file'], {'map_location': 'device'}), '(pretrained_model_file, map_location=device)\n', (11301, 11345), False, 'import torch\n'), ((11403, 11511), 'loguru.logger.info', 'logger.info', (['"""Loaded pretrained model (Epoch: {:,}, Fscore: {:.2f})"""', "params['epoch']", "params['fscore']"], {}), "('Loaded pretrained model (Epoch: {:,}, Fscore: {:.2f})', params\n ['epoch'], params['fscore'])\n", (11414, 11511), False, 'from loguru import logger\n'), ((13449, 13504), 'tqdm.trange', 'trange', (['start_epoch', "kwargs['num_epochs']"], {'desc': '"""Epoch"""'}), "(start_epoch, kwargs['num_epochs'], desc='Epoch')\n", (13455, 13504), False, 'from tqdm import tqdm, trange\n'), ((4472, 4484), 'click.Path', 'click.Path', ([], {}), '()\n', (4482, 4484), False, 'import click\n'), ((4534, 4546), 'click.Path', 'click.Path', ([], {}), '()\n', (4544, 4546), False, 'import click\n'), ((4597, 4609), 'click.Path', 'click.Path', ([], {}), '()\n', (4607, 4609), False, 'import click\n'), ((4661, 4673), 'click.Path', 'click.Path', ([], {}), '()\n', (4671, 4673), False, 'import click\n'), ((4725, 4737), 'click.Path', 'click.Path', ([], {}), '()\n', (4735, 4737), False, 'import click\n'), ((1057, 1126), 'regex.split', 'regex.split', (['"""(?<=[^\\\\W_])_(?=[^\\\\W_])"""', 'phrase'], {'flags': 'regex.FULLCASE'}), "('(?<=[^\\\\W_])_(?=[^\\\\W_])', phrase, flags=regex.FULLCASE)\n", (1068, 1126), False, 'import regex\n'), ((3957, 3972), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3970, 3972), False, 'import torch\n'), ((12312, 12349), 'os.path.isfile', 'os.path.isfile', (['pretrained_model_file'], {}), '(pretrained_model_file)\n', (12326, 12349), False, 'import os\n'), ((12434, 12494), 'loguru.logger.info', 'logger.info', (['"""Resuming model from {}"""', 'pretrained_model_file'], {}), "('Resuming model from {}', pretrained_model_file)\n", (12445, 12494), False, 'from loguru import logger\n'), ((12552, 12606), 'torch.load', 'torch.load', (['pretrained_model_file'], {'map_location': 'device'}), '(pretrained_model_file, map_location=device)\n', (12562, 12606), False, 'import torch\n'), ((15011, 15081), 'neptune.send_metric', 'neptune.send_metric', (['"""train_loss"""', 'epoch', '(train_loss / num_train_steps)'], {}), "('train_loss', epoch, train_loss / num_train_steps)\n", (15030, 15081), False, 'import neptune\n'), ((15094, 15150), 'neptune.send_metric', 'neptune.send_metric', (['"""global_steps"""', 'epoch', 'global_steps'], {}), "('global_steps', epoch, global_steps)\n", (15113, 15150), False, 'import neptune\n'), ((17248, 17281), 'os.getenv', 'os.getenv', (['"""NEPTUNE_PROJECT_NAME"""'], {}), "('NEPTUNE_PROJECT_NAME')\n", (17257, 17281), False, 'import os\n'), ((17905, 17919), 'neptune.stop', 'neptune.stop', ([], {}), '()\n', (17917, 17919), False, 'import neptune\n'), ((12994, 13040), 'numpy.random.set_state', 'np.random.set_state', (["params['np_random_state']"], {}), "(params['np_random_state'])\n", (13013, 13040), True, 'import numpy as np\n'), ((13057, 13096), 'random.setstate', 'random.setstate', (["params['random_state']"], {}), "(params['random_state'])\n", (13072, 13096), False, 'import random\n'), ((13290, 13327), 'os.path.isfile', 'os.path.isfile', (['pretrained_model_file'], {}), '(pretrained_model_file)\n', (13304, 13327), False, 'import os\n'), ((13659, 13699), 'tqdm.tqdm', 'tqdm', (['train_dataloader'], {'desc': '"""Iteration"""'}), "(train_dataloader, desc='Iteration')\n", (13663, 13699), False, 'from tqdm import tqdm, trange\n'), ((16218, 16250), 'tqdm.tqdm.write', 'tqdm.write', (['"""** Saving model..."""'], {}), "('** Saving model...')\n", (16228, 16250), False, 'from tqdm import tqdm, trange\n'), ((16268, 16316), 'os.makedirs', 'os.makedirs', (["kwargs['output_dir']"], {'exist_ok': '(True)'}), "(kwargs['output_dir'], exist_ok=True)\n", (16279, 16316), False, 'import os\n'), ((14545, 14576), 'apex.amp.scale_loss', 'amp.scale_loss', (['loss', 'optimizer'], {}), '(loss, optimizer)\n', (14559, 14576), False, 'from apex import amp\n'), ((16553, 16570), 'random.getstate', 'random.getstate', ([], {}), '()\n', (16568, 16570), False, 'import random\n'), ((16615, 16636), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (16634, 16636), True, 'import numpy as np\n'), ((16684, 16705), 'torch.get_rng_state', 'torch.get_rng_state', ([], {}), '()\n', (16703, 16705), False, 'import torch\n'), ((16762, 16792), 'torch.cuda.get_rng_state_all', 'torch.cuda.get_rng_state_all', ([], {}), '()\n', (16790, 16792), False, 'import torch\n')]