code
stringlengths
17
6.64M
class SpatialTransformer(nn.Module): '\n Transformer block for image-like data.\n First, project the input (aka embedding)\n and reshape to b, t, d.\n Then apply standard transformer action.\n Finally, reshape to image\n ' def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0....
class AbstractDistribution(): def sample(self): raise NotImplementedError() def mode(self): raise NotImplementedError()
class DiracDistribution(AbstractDistribution): def __init__(self, value): self.value = value def sample(self): return self.value def mode(self): return self.value
class DiagonalGaussianDistribution(object): def __init__(self, parameters, deterministic=False): self.parameters = parameters (self.mean, self.logvar) = torch.chunk(parameters, 2, dim=1) self.logvar = torch.clamp(self.logvar, (- 30.0), 20.0) self.deterministic = deterministic ...
def normal_kl(mean1, logvar1, mean2, logvar2): '\n source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12\n Compute the KL divergence between two gaussians.\n Shapes are automatically broadcasted, so batches can be compared to\n ...
class LitEma(nn.Module): def __init__(self, model, decay=0.9999, use_num_upates=True): super().__init__() if ((decay < 0.0) or (decay > 1.0)): raise ValueError('Decay must be between 0 and 1') self.m_name2s_name = {} self.register_buffer('decay', torch.tensor(decay, dt...
class LPIPSWithDiscriminator(nn.Module): def __init__(self, disc_start, logvar_init=0.0, kl_weight=1.0, pixelloss_weight=1.0, disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0, perceptual_weight=1.0, use_actnorm=False, disc_conditional=False, disc_loss='hinge'): super().__init__() ...
def hinge_d_loss_with_exemplar_weights(logits_real, logits_fake, weights): assert (weights.shape[0] == logits_real.shape[0] == logits_fake.shape[0]) loss_real = torch.mean(F.relu((1.0 - logits_real)), dim=[1, 2, 3]) loss_fake = torch.mean(F.relu((1.0 + logits_fake)), dim=[1, 2, 3]) loss_real = ((weigh...
def adopt_weight(weight, global_step, threshold=0, value=0.0): if (global_step < threshold): weight = value return weight
def measure_perplexity(predicted_indices, n_embed): encodings = F.one_hot(predicted_indices, n_embed).float().reshape((- 1), n_embed) avg_probs = encodings.mean(0) perplexity = (- (avg_probs * torch.log((avg_probs + 1e-10))).sum()).exp() cluster_use = torch.sum((avg_probs > 0)) return (perplexity,...
def l1(x, y): return torch.abs((x - y))
def l2(x, y): return torch.pow((x - y), 2)
class VQLPIPSWithDiscriminator(nn.Module): def __init__(self, disc_start, codebook_weight=1.0, pixelloss_weight=1.0, disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0, perceptual_weight=1.0, use_actnorm=False, disc_conditional=False, disc_ndf=64, disc_loss='hinge', n_classes=None, perceptua...
def log_txt_as_img(wh, xc, size=10): b = len(xc) txts = list() for bi in range(b): txt = Image.new('RGB', wh, color='white') draw = ImageDraw.Draw(txt) font = ImageFont.truetype('data/DejaVuSans.ttf', size=size) nc = int((40 * (wh[0] / 256))) lines = '\n'.join((xc[b...
def ismap(x): if (not isinstance(x, torch.Tensor)): return False return ((len(x.shape) == 4) and (x.shape[1] > 3))
def isimage(x): if (not isinstance(x, torch.Tensor)): return False return ((len(x.shape) == 4) and ((x.shape[1] == 3) or (x.shape[1] == 1)))
def exists(x): return (x is not None)
def default(val, d): if exists(val): return val return (d() if isfunction(d) else d)
def mean_flat(tensor): '\n https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86\n Take the mean over all non-batch dimensions.\n ' return tensor.mean(dim=list(range(1, len(tensor.shape))))
def count_params(model, verbose=False): total_params = sum((p.numel() for p in model.parameters())) if verbose: print(f'{model.__class__.__name__} has {(total_params * 1e-06):.2f} M params.') return total_params
def instantiate_from_config(config): if (not ('target' in config)): if (config == '__is_first_stage__'): return None elif (config == '__is_unconditional__'): return None raise KeyError('Expected key `target` to instantiate.') return get_obj_from_str(config['targ...
def get_obj_from_str(string, reload=False): (module, cls) = string.rsplit('.', 1) if reload: module_imp = importlib.import_module(module) importlib.reload(module_imp) return getattr(importlib.import_module(module, package=None), cls)
def _do_parallel_data_prefetch(func, Q, data, idx, idx_to_fn=False): if idx_to_fn: res = func(data, worker_id=idx) else: res = func(data) Q.put([idx, res]) Q.put('Done')
def parallel_data_prefetch(func: callable, data, n_proc, target_data_type='ndarray', cpu_intensive=True, use_worker_id=False): if (isinstance(data, np.ndarray) and (target_data_type == 'list')): raise ValueError('list expected but function got ndarray.') elif isinstance(data, abc.Iterable): if...
def get_parser(**parser_kwargs): def str2bool(v): if isinstance(v, bool): return v if (v.lower() in ('yes', 'true', 't', 'y', '1')): return True elif (v.lower() in ('no', 'false', 'f', 'n', '0')): return False else: raise argparse.Ar...
def nondefault_trainer_args(opt): parser = argparse.ArgumentParser() parser = Trainer.add_argparse_args(parser) args = parser.parse_args([]) return sorted((k for k in vars(args) if (getattr(opt, k) != getattr(args, k))))
class WrappedDataset(Dataset): 'Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset' def __init__(self, dataset): self.data = dataset def __len__(self): return len(self.data) def __getitem__(self, idx): return self.data[idx]
def worker_init_fn(_): worker_info = torch.utils.data.get_worker_info() dataset = worker_info.dataset worker_id = worker_info.id if isinstance(dataset, Txt2ImgIterableBaseDataset): split_size = (dataset.num_records // worker_info.num_workers) dataset.sample_ids = dataset.valid_ids[(wor...
class DataModuleFromConfig(pl.LightningDataModule): def __init__(self, batch_size, train=None, validation=None, test=None, predict=None, wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False, shuffle_val_dataloader=False): super().__init__() self.batch_size = batch_siz...
class SetupCallback(Callback): def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config): super().__init__() self.resume = resume self.now = now self.logdir = logdir self.ckptdir = ckptdir self.cfgdir = cfgdir self.config = config ...
class ImageLogger(Callback): def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True, rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False, log_images_kwargs=None): super().__init__() self.rescale = rescale self.batch_freq = batch_frequenc...
class CUDACallback(Callback): def on_train_epoch_start(self, trainer, pl_module): torch.cuda.reset_peak_memory_stats(trainer.root_gpu) torch.cuda.synchronize(trainer.root_gpu) self.start_time = time.time() def on_train_epoch_end(self, trainer, pl_module, outputs): torch.cuda....
def download_models(mode): if (mode == 'superresolution'): url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1' url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1' path_conf = 'logs/diffusion/superresolution_bsr/configs/project.yaml' pat...
def load_model_from_config(config, ckpt): print(f'Loading model from {ckpt}') pl_sd = torch.load(ckpt, map_location='cpu') global_step = pl_sd['global_step'] sd = pl_sd['state_dict'] model = instantiate_from_config(config.model) (m, u) = model.load_state_dict(sd, strict=False) model.cuda()...
def get_model(mode): (path_conf, path_ckpt) = download_models(mode) config = OmegaConf.load(path_conf) (model, step) = load_model_from_config(config, path_ckpt) return model
def get_custom_cond(mode): dest = 'data/example_conditioning' if (mode == 'superresolution'): uploaded_img = files.upload() filename = next(iter(uploaded_img)) (name, filetype) = filename.split('.') os.rename(f'{filename}', f'{dest}/{mode}/custom_{name}.{filetype}') elif (m...
def get_cond_options(mode): path = 'data/example_conditioning' path = os.path.join(path, mode) onlyfiles = [f for f in sorted(os.listdir(path))] return (path, onlyfiles)
def select_cond_path(mode): path = 'data/example_conditioning' path = os.path.join(path, mode) onlyfiles = [f for f in sorted(os.listdir(path))] selected = widgets.RadioButtons(options=onlyfiles, description='Select conditioning:', disabled=False) display(selected) selected_path = os.path.join...
def get_cond(mode, selected_path): example = dict() if (mode == 'superresolution'): up_f = 4 visualize_cond_img(selected_path) c = Image.open(selected_path) c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0) c_up = torchvision.transforms.functional.resize(c, s...
def visualize_cond_img(path): display(ipyimg(filename=path))
def run(model, selected_path, task, custom_steps, resize_enabled=False, classifier_ckpt=None, global_step=None): example = get_cond(task, selected_path) save_intermediate_vid = False n_runs = 1 masked = False guider = None ckwargs = None mode = 'ddim' ddim_use_x0_pred = False tempe...
@torch.no_grad() def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None, mask=None, x0=None, quantize_x0=False, img_callback=None, temperature=1.0, noise_dropout=0.0, score_corrector=None, corrector_kwargs=None, x_T=None, log_every_t=None): ddim = DDIMSampler(model) bs = ...
@torch.no_grad() def make_convolutional_sample(batch, model, mode='vanilla', custom_steps=None, eta=1.0, swap_mode=False, masked=False, invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000, resize_enabled=False, custom_shape=None, temperature=1.0, noise_dropout=0.0, corrector=None, correcto...
def chunk(it, size): it = iter(it) return iter((lambda : tuple(islice(it, size))), ())
def load_model_from_config(config, ckpt, verbose=False): print(f'Loading model from {ckpt}') pl_sd = torch.load(ckpt, map_location='cpu') if ('global_step' in pl_sd): print(f"Global Step: {pl_sd['global_step']}") sd = pl_sd['state_dict'] model = instantiate_from_config(config.model) (m...
def load_img(path): image = Image.open(path).convert('RGB') (w, h) = image.size print(f'loaded input image of size ({w}, {h}) from {path}') (w, h) = map((lambda x: (x - (x % 64))), (w, h)) image = image.resize((w, h), resample=PIL.Image.LANCZOS) image = (np.array(image).astype(np.float32) / 25...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--prompt', type=str, nargs='?', default='a painting of a virus monster playing guitar', help='the prompt to render') parser.add_argument('--init-img', type=str, nargs='?', help='path to the input image') parser.add_argument('--outdir'...
def make_batch(image, mask, device): image = np.array(Image.open(image).convert('RGB')) image = (image.astype(np.float32) / 255.0) image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image) mask = np.array(Image.open(mask).convert('L')) mask = (mask.astype(np.float32) / 255.0) ...
def load_model_from_config(config, ckpt): print(f'Loading model from {ckpt}') pl_sd = torch.load(ckpt) sd = pl_sd['state_dict'] model = instantiate_from_config(config.model) (m, u) = model.load_state_dict(sd, strict=False) model.cuda() model.eval() return model
def get_model(): config = OmegaConf.load('configs/latent-diffusion/cin256-v2.yaml') model = load_model_from_config(config, 'models/ldm/cin256-v2/model.ckpt') return model
def custom_to_pil(x): x = x.detach().cpu() x = torch.clamp(x, (- 1.0), 1.0) x = ((x + 1.0) / 2.0) x = x.permute(1, 2, 0).numpy() x = (255 * x).astype(np.uint8) x = Image.fromarray(x) if (not (x.mode == 'RGB')): x = x.convert('RGB') return x
def custom_to_np(x): sample = x.detach().cpu() sample = ((sample + 1) * 127.5).clamp(0, 255).to(torch.uint8) sample = sample.permute(0, 2, 3, 1) sample = sample.contiguous() return sample
def logs2pil(logs, keys=['sample']): imgs = dict() for k in logs: try: if (len(logs[k].shape) == 4): img = custom_to_pil(logs[k][(0, ...)]) elif (len(logs[k].shape) == 3): img = custom_to_pil(logs[k]) else: print(f'Unk...
@torch.no_grad() def convsample(model, shape, return_intermediates=True, verbose=True, make_prog_row=False): if (not make_prog_row): return model.p_sample_loop(None, shape, return_intermediates=return_intermediates, verbose=verbose) else: return model.progressive_denoising(None, shape, verbose...
@torch.no_grad() def convsample_ddim(model, steps, shape, eta=1.0): ddim = DDIMSampler(model) bs = shape[0] shape = shape[1:] (samples, intermediates) = ddim.sample(steps, batch_size=bs, shape=shape, eta=eta, verbose=False) return (samples, intermediates)
@torch.no_grad() def make_convolutional_sample(model, batch_size, vanilla=False, custom_steps=None, eta=1.0): log = dict() shape = [batch_size, model.model.diffusion_model.in_channels, model.model.diffusion_model.image_size, model.model.diffusion_model.image_size] with model.ema_scope('Plotting'): ...
def run(model, logdir, batch_size=50, vanilla=False, custom_steps=None, eta=None, n_samples=50000, nplog=None): if vanilla: print(f'Using Vanilla DDPM sampling with {model.num_timesteps} sampling steps.') else: print(f'Using DDIM sampling with {custom_steps} sampling steps and eta={eta}') ...
def save_logs(logs, path, n_saved=0, key='sample', np_path=None): for k in logs: if (k == key): batch = logs[key] if (np_path is None): for x in batch: img = custom_to_pil(x) imgpath = os.path.join(path, f'{key}_{n_saved:06}.p...
def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('-r', '--resume', type=str, nargs='?', help='load from logdir or checkpoint in logdir') parser.add_argument('-n', '--n_samples', type=int, nargs='?', help='number of samples to draw', default=50000) parser.add_argument('-e', '--e...
def load_model_from_config(config, sd): model = instantiate_from_config(config) model.load_state_dict(sd, strict=False) model.cuda() model.eval() return model
def load_model(config, ckpt, gpu, eval_mode): if ckpt: print(f'Loading model from {ckpt}') pl_sd = torch.load(ckpt, map_location='cpu') global_step = pl_sd['global_step'] else: pl_sd = {'state_dict': None} global_step = None model = load_model_from_config(config.mod...
def testit(img_path): bgr = cv2.imread(img_path) decoder = WatermarkDecoder('bytes', 136) watermark = decoder.decode(bgr, 'dwtDct') try: dec = watermark.decode('utf-8') except: dec = 'null' print(dec)
def complex_flatten(real, imag): real = tf.keras.layers.Flatten()(real) imag = tf.keras.layers.Flatten()(imag) return (real, imag)
def CReLU(real, imag): real = tf.keras.layers.ReLU()(real) imag = tf.keras.layers.ReLU()(imag) return (real, imag)
def CLeaky_ReLU(real, imag): real = tf.nn.leaky_relu(real) imag = tf.nn.leaky_relu(imag) return (real, imag)
def zReLU(real, imag): real = tf.keras.layers.ReLU()(real) imag = tf.keras.layers.ReLU()(imag) ' \n parts์— ๊ฐ’์ด ์žˆ์œผ๋ฉด True == 1๋กœ ๋งŒ๋“ค๊ณ , ๊ฐ’์ด 0์ด๋ฉด False == 0์„ ๋ฐ˜ํ™˜\n part๊ฐ€ True == 1์ด๋ฉด 1 ๋ฐ˜ํ™˜, ํ•˜๋‚˜๋ผ๋„ False == 0์ด๋ฉด 0 ๋ฐ˜ํ™˜\n ๊ทธ๋ž˜์„œ real, imag ์ค‘ ํ•˜๋‚˜๋ผ๋„ ์ถ• ์œ„์— ๊ฐ’์ด ์žˆ์œผ๋ฉด flag๋Š” (0, ...) ์ด๋‹ค.\n ' real_flag = tf.cast(tf.cast...
def modReLU(real, imag): norm = tf.abs(tf.complex(real, imag)) bias = tf.Variable(np.zeros([norm.get_shape()[(- 1)]]), trainable=True, dtype=tf.float32) relu = tf.nn.relu((norm + bias)) real = tf.math.multiply(((relu / norm) + 100000.0), real) imag = tf.math.multiply(((relu / norm) + 100000.0), im...
def complex_tanh(real, imag): real = tf.nn.tanh(real) imag = tf.nn.tanh(imag) return (real, imag)
def complex_softmax(real, imag): magnitude = tf.abs(tf.complex(real, imag)) magnitude = tf.keras.layers.Softmax()(magnitude) return magnitude
class Naive_DCUnet16(): def __init__(self, input_size=16384, length=1023, over_lapping=256, padding='same', norm_trainig=True): self.input_size = input_size self.length = length self.over_lapping = over_lapping self.padding = padding self.norm_trainig = norm_trainig ...
class Naive_DCUnet20(): def __init__(self, input_size=16384, length=1023, over_lapping=256, padding='same', norm_trainig=True): self.input_size = input_size self.length = length self.over_lapping = over_lapping self.padding = padding self.norm_trainig = norm_trainig ...
class DCUnet16(): def __init__(self, input_size=16384, length=1023, over_lapping=256, padding='same', norm_trainig=True): self.input_size = input_size self.length = length self.over_lapping = over_lapping self.padding = padding self.norm_trainig = norm_trainig self...
class DCUnet20(): def __init__(self, input_size=16384, length=1023, over_lapping=256, padding='same', norm_trainig=True): self.input_size = input_size self.length = length self.over_lapping = over_lapping self.padding = padding self.norm_trainig = norm_trainig self...
class datagenerator(tf.keras.utils.Sequence): def __init__(self, inputs_ids, outputs_ids, inputs_dir, outputs_dir, batch_size=16, shuffle=True): '\n inputs_ids : ์ž…๋ ฅํ•  noisy speech์˜ ๋ฐ์ดํ„ฐ ๋„ค์ž„\n outputs_ids : ํƒ€๊ฒŸ์œผ๋กœ ์‚ผ์„ clean speech์˜ ๋ฐ์ดํ„ฐ ๋„ค์ž„\n inputs_dir : ์ž…๋ ฅํ•  noisy speech์˜ ํŒŒ์ผ ๊ฒฝ๋กœ\n ou...
def modified_SDR_loss(pred, true, eps=1e-08): num = K.sum((true * pred)) den = (K.sqrt(K.sum((true * true))) * K.sqrt(K.sum((pred * pred)))) return (- (num / (den + eps)))
def weighted_SDR_loss(noisy_speech, pred_speech, true_speech): def SDR_loss(pred, true, eps=1e-08): num = K.sum((pred * true)) den = (K.sqrt(K.sum((true * true))) * K.sqrt(K.sum((pred * pred)))) return (- (num / (den + eps))) pred_noise = (noisy_speech - pred_speech) true_noise = ...
def get_file_list(file_path): file_list = [] for (root, dirs, files) in os.walk(file_path): for fname in files: if ((fname == 'desktop.ini') or (fname == '.DS_Store')): continue full_fname = os.path.join(root, fname) file_list.append(full_fname) ...
def inference(path_list, save_path): for (index1, speech_file_path) in tqdm(enumerate(path_list)): (_, unseen_noisy_speech) = scipy.io.wavfile.read(speech_file_path) restore = [] for index2 in range(int((len(unseen_noisy_speech) / speech_length))): split_speech = unseen_noisy_s...
def data_generator(train_arguments, test_arguments): train_generator = datagenerator(**train_arguments) test_generator = datagenerator(**test_arguments) return (train_generator, test_generator)
@tf.function def loop_train(model, optimizer, train_noisy_speech, train_clean_speech): with tf.GradientTape() as tape: train_predict_speech = model(train_noisy_speech) if (loss_function == 'SDR'): train_loss = modified_SDR_loss(train_predict_speech, train_clean_speech) elif (lo...
@tf.function def loop_test(model, test_noisy_speech, test_clean_speech): 'Test loop do not caclultae gradient and backpropagation' test_predict_speech = model(test_noisy_speech) if (loss_function == 'SDR'): test_loss = modified_SDR_loss(test_predict_speech, test_clean_speech) elif (loss_functi...
def learning_rate_scheduler(epoch, learning_rate): if ((epoch + 1) <= int((0.5 * epoch))): return (1.0 * learning_rate) elif (((epoch + 1) > int((0.5 * epoch))) and ((epoch + 1) <= int((0.75 * epoch)))): return (0.2 * learning_rate) else: return (0.05 * learning_rate)
def model_flow(model, total_epochs, train_generator, test_generator): train_step = (len(os.listdir(train_noisy_path)) // batch_size) test_step = (len(os.listdir(test_noisy_path)) // batch_size) print('TRAIN STEPS, TEST STEPS ', train_step, test_step) for epoch in tqdm(range(total_epochs)): t...
class GIN(torch.nn.Module): def __init__(self, in_channels, out_channels, num_layers, batch_norm=False, cat=True, lin=True): super(GIN, self).__init__() self.in_channels = in_channels self.num_layers = num_layers self.batch_norm = batch_norm self.cat = cat self.lin...
class MLP(torch.nn.Module): def __init__(self, in_channels, out_channels, num_layers, batch_norm=False, dropout=0.0): super(MLP, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.num_layers = num_layers self.batch_norm = batch_norm ...
class RelConv(MessagePassing): def __init__(self, in_channels, out_channels): super(RelConv, self).__init__(aggr='mean') self.in_channels = in_channels self.out_channels = out_channels self.lin1 = Lin(in_channels, out_channels, bias=False) self.lin2 = Lin(in_channels, out_...
class RelCNN(torch.nn.Module): def __init__(self, in_channels, out_channels, num_layers, batch_norm=False, cat=True, lin=True, dropout=0.0): super(RelCNN, self).__init__() self.in_channels = in_channels self.num_layers = num_layers self.batch_norm = batch_norm self.cat = c...
class SplineCNN(torch.nn.Module): def __init__(self, in_channels, out_channels, dim, num_layers, cat=True, lin=True, dropout=0.0): super(SplineCNN, self).__init__() self.in_channels = in_channels self.dim = dim self.num_layers = num_layers self.cat = cat self.lin =...
class SumEmbedding(object): def __call__(self, data): (data.x1, data.x2) = (data.x1.sum(dim=1), data.x2.sum(dim=1)) return data
def train(): model.train() optimizer.zero_grad() (_, S_L) = model(data.x1, data.edge_index1, None, None, data.x2, data.edge_index2, None, None, data.train_y) loss = model.loss(S_L, data.train_y) loss.backward() optimizer.step() return loss
@torch.no_grad() def test(): model.eval() (_, S_L) = model(data.x1, data.edge_index1, None, None, data.x2, data.edge_index2, None, None) hits1 = model.acc(S_L, data.test_y) hits10 = model.hits_at_k(10, S_L, data.test_y) return (hits1, hits10)
def generate_y(y_col): y_row = torch.arange(y_col.size(0), device=device) return torch.stack([y_row, y_col], dim=0)
def train(): model.train() total_loss = 0 for data in train_loader: optimizer.zero_grad() data = data.to(device) (S_0, S_L) = model(data.x_s, data.edge_index_s, data.edge_attr_s, data.x_s_batch, data.x_t, data.edge_index_t, data.edge_attr_t, data.x_t_batch) y = generate_y(d...
@torch.no_grad() def test(dataset): model.eval() loader = DataLoader(dataset, args.batch_size, shuffle=False, follow_batch=['x_s', 'x_t']) correct = num_examples = 0 while (num_examples < args.test_samples): for data in loader: data = data.to(device) (S_0, S_L) = model(...
class RandomGraphDataset(torch.utils.data.Dataset): def __init__(self, min_inliers, max_inliers, min_outliers, max_outliers, min_scale=0.9, max_scale=1.2, noise=0.05, transform=None): self.min_inliers = min_inliers self.max_inliers = max_inliers self.min_outliers = min_outliers se...
def train(): model.train() total_loss = total_examples = total_correct = 0 for (i, data) in enumerate(train_loader): optimizer.zero_grad() data = data.to(device) (S_0, S_L) = model(data.x_s, data.edge_index_s, data.edge_attr_s, data.x_s_batch, data.x_t, data.edge_index_t, data.edge...
@torch.no_grad() def test(dataset): model.eval() correct = num_examples = 0 for pair in dataset.pairs: (data_s, data_t) = (dataset[pair[0]], dataset[pair[1]]) (data_s, data_t) = (data_s.to(device), data_t.to(device)) (S_0, S_L) = model(data_s.x, data_s.edge_index, data_s.edge_attr,...
def generate_voc_y(y_col): y_row = torch.arange(y_col.size(0), device=device) return torch.stack([y_row, y_col], dim=0)
def pretrain(): model.train() total_loss = 0 for data in pretrain_loader: optimizer.zero_grad() data = data.to(device) (S_0, S_L) = model(data.x_s, data.edge_index_s, data.edge_attr_s, data.x_s_batch, data.x_t, data.edge_index_t, data.edge_attr_t, data.x_t_batch) y = genera...
def generate_y(num_nodes, batch_size): row = torch.arange((num_nodes * batch_size), device=device) col = row[:num_nodes].view(1, (- 1)).repeat(batch_size, 1).view((- 1)) return torch.stack([row, col], dim=0)