code
stringlengths
17
6.64M
def remove_chumpy_dep(dico): output_dict = {} for (key, val) in dico.items(): if ('chumpy' in str(type(val))): output_dict[key] = np.array(val) else: output_dict[key] = val return output_dict
def load_and_remove_chumpy_dep(path): with open(path, 'rb') as pkl_file: import warnings warnings.filterwarnings('ignore', category=DeprecationWarning) data = pickle.load(pkl_file, encoding='latin1') data = remove_chumpy_dep(data) return data
def load_npz_into_dict(path): data = {key: val for (key, val) in np.load(smplh_fn).items()} data = remove_chumpy_dep(data) return data
def load_and_clean_data(path): ext = os.path.splitext(path)[(- 1)] if (ext == '.npz'): data = load_npz_into_dict(path) elif (ext == '.pkl'): data = load_and_remove_chumpy_dep(path) else: raise TypeError('The format should be pkl or npz') return data
def merge_models(smplh_fn, mano_left_fn, mano_right_fn, output_folder='output'): body_data = load_and_clean_data(smplh_fn) lhand_data = load_and_clean_data(mano_left_fn) rhand_data = load_and_clean_data(mano_right_fn) modelname = osp.split(smplh_fn)[1] parent_folder = osp.split(osp.split(smplh_fn)...
def save_json(save_path, data): with open(save_path, 'w') as file: json.dump(data, file)
def load_json(file_path): with open(file_path, 'r') as file: data = json.load(file) return data
def process(graph): (V, entities, relations) = ({}, {}, []) for i in graph['verbs']: description = i['description'] pos = 0 flag = 0 (_words, _spans) = ([], []) (tags, verb) = ({}, 0) for i in description.split(): if ('[' in i): _role...
def extend_paths(path, keyids, *, onesample=True, number_of_samples=1): if (not onesample): template_path = str((path / 'KEYID_INDEX.npy')) paths = [template_path.replace('INDEX', str(index)) for i in range(number_of_samples)] else: paths = [str((path / 'KEYID.npy'))] all_paths = [...
def render_cli() -> None: cfg = parse_args(phase='render') cfg.FOLDER = cfg.RENDER.FOLDER if (cfg.RENDER.INPUT_MODE.lower() == 'npy'): output_dir = Path(os.path.dirname(cfg.RENDER.NPY)) paths = [cfg.RENDER.NPY] elif (cfg.RENDER.INPUT_MODE.lower() == 'dir'): output_dir = Path(cf...
def Rodrigues(rotvec): theta = np.linalg.norm(rotvec) r = ((rotvec / theta).reshape(3, 1) if (theta > 0.0) else rotvec) cost = np.cos(theta) mat = np.asarray([[0, (- r[2]), r[1]], [r[2], 0, (- r[0])], [(- r[1]), r[0], 0]]) return (((cost * np.eye(3)) + ((1 - cost) * r.dot(r.T))) + (np.sin(theta) *...
def setup_scene(model_path, fps_target): scene = bpy.data.scenes['Scene'] scene.render.fps = fps_target if ('Cube' in bpy.data.objects): bpy.data.objects['Cube'].select_set(True) bpy.ops.object.delete() bpy.ops.import_scene.fbx(filepath=model_path)
def process_pose(current_frame, pose, trans, pelvis_position): if (pose.shape[0] == 72): rod_rots = pose.reshape(24, 3) else: rod_rots = pose.reshape(26, 3) mat_rots = [Rodrigues(rod_rot) for rod_rot in rod_rots] armature = bpy.data.objects['Armature'] bones = armature.pose.bones ...
def process_poses(input_path, gender, fps_source, fps_target, start_origin, person_id=1): print(('Processing: ' + input_path)) data = joblib.load(input_path) person_id = list(data.keys())[0] poses = data[person_id]['pose'] if ('trans' not in data[person_id].keys()): trans = np.zeros((poses...
def export_animated_mesh(output_path): output_dir = os.path.dirname(output_path) if (not os.path.isdir(output_dir)): os.makedirs(output_dir, exist_ok=True) bpy.ops.object.select_all(action='DESELECT') bpy.data.objects['Armature'].select_set(True) bpy.data.objects['Armature'].children[0].se...
def Rodrigues(rotvec): theta = np.linalg.norm(rotvec) r = ((rotvec / theta).reshape(3, 1) if (theta > 0.0) else rotvec) cost = np.cos(theta) mat = np.asarray([[0, (- r[2]), r[1]], [r[2], 0, (- r[0])], [(- r[1]), r[0], 0]]) return (((cost * np.eye(3)) + ((1 - cost) * r.dot(r.T))) + (np.sin(theta) *...
def setup_scene(model_path, fps_target): scene = bpy.data.scenes['Scene'] scene.render.fps = fps_target if ('Cube' in bpy.data.objects): bpy.data.objects['Cube'].select_set(True) bpy.ops.object.delete() bpy.ops.import_scene.fbx(filepath=model_path)
def process_pose(current_frame, pose, lhandpose, rhandpose, trans, pelvis_position): rod_rots = pose.reshape(24, 4) lhrod_rots = lhandpose.reshape(15, 4) rhrod_rots = rhandpose.reshape(15, 4) armature = bpy.data.objects[ROOT_NAME] bones = armature.pose.bones bones[BODY_JOINT_NAMES[0]].location...
def process_poses(input_path, gender, fps_source, fps_target, start_origin, person_id=1): print(('Processing: ' + input_path)) smpl_params = joblib.load(input_path) (poses, lhposes, rhposes) = ([], [], []) for iframe in smpl_params.keys(): poses.append(smpl_params[iframe]['rot']) lhpos...
def export_animated_mesh(output_path): output_dir = os.path.dirname(output_path) if (not os.path.isdir(output_dir)): os.makedirs(output_dir, exist_ok=True) bpy.ops.object.select_all(action='DESELECT') bpy.data.objects[ROOT_NAME].select_set(True) bpy.data.objects[ROOT_NAME].children[0].sele...
def print_table(title, metrics): table = Table(title=title) table.add_column('Metrics', style='cyan', no_wrap=True) table.add_column('Value', style='magenta') for (key, value) in metrics.items(): table.add_row(key, str(value)) console = get_console() console.print(table, justify='cente...
def get_metric_statistics(values, replication_times): mean = np.mean(values, axis=0) std = np.std(values, axis=0) conf_interval = ((1.96 * std) / np.sqrt(replication_times)) return (mean, conf_interval)
def main(): cfg = parse_args(phase='test') cfg.FOLDER = cfg.TEST.FOLDER logger = create_logger(cfg, phase='test') output_dir = Path(os.path.join(cfg.FOLDER, str(cfg.model.model_type), str(cfg.NAME), ('samples_' + cfg.TIME))) output_dir.mkdir(parents=True, exist_ok=True) logger.info(OmegaConf.t...
def main(): parser = ArgumentParser() group = parser.add_argument_group('Params') group.add_argument('--ply_dir', type=str, required=True, help='ply set') group.add_argument('--out_dir', type=str, required=True, help='output folder') params = parser.parse_args() plys2npy(params.ply_dir, params...
def plys2npy(ply_dir, out_dir): ply_dir = Path(ply_dir) paths = [] file_list = natsort.natsorted(os.listdir(ply_dir)) for item in file_list: if (item.endswith('.ply') and (not item.endswith('_gt.ply'))): paths.append(os.path.join(ply_dir, item)) meshs = np.zeros((len(paths), 68...
def print_table(title, metrics): table = Table(title=title) table.add_column('Metrics', style='cyan', no_wrap=True) table.add_column('Value', style='magenta') for (key, value) in metrics.items(): table.add_row(key, str(value)) console = get_console() console.print(table, justify='cente...
def get_metric_statistics(values, replication_times): mean = np.mean(values, axis=0) std = np.std(values, axis=0) conf_interval = ((1.96 * std) / np.sqrt(replication_times)) return (mean, conf_interval)
def main(): cfg = parse_args(phase='test') cfg.FOLDER = cfg.TEST.FOLDER logger = create_logger(cfg, phase='test') output_dir = Path(os.path.join(cfg.FOLDER, str(cfg.model.model_type), str(cfg.NAME), ('samples_' + cfg.TIME))) output_dir.mkdir(parents=True, exist_ok=True) logger.info(OmegaConf.t...
def main(): cfg = parse_args() logger = create_logger(cfg, phase='train') if cfg.TRAIN.RESUME: resume = cfg.TRAIN.RESUME backcfg = cfg.TRAIN.copy() if os.path.exists(resume): file_list = sorted(os.listdir(resume), reverse=True) for item in file_list: ...
def get_gaussian_dataset(role, size, dim, std): x = (std * torch.randn(size, dim)) y = torch.zeros(size).long() return SupervisedDataset(f'gaussian-dim{dim}-std{std}', role, x, y)
def get_well_conditioned_gaussian_datasets(dim, std, oos_std): train_dset = get_gaussian_dataset(role='train', size=50000, dim=dim, std=std) valid_dset = get_gaussian_dataset(role='valid', size=5000, dim=dim, std=std) test_dsets = [get_gaussian_dataset(role='test', size=10000, dim=dim, std=std), get_gauss...
def get_linear_gaussian_dataset(role, size): A = torch.tensor([[(- 4.0)], [1.0]]) b = torch.tensor([1.0, (- 3.0)]) sigma = 0.1 z = torch.randn(size, A.shape[1], 1) Az = torch.matmul(A, z).view(size, A.shape[0]) x = ((Az + b) + (sigma * torch.randn_like(Az))) return SupervisedDataset(name='...
def get_linear_gaussian_datasets(): train_dset = get_linear_gaussian_dataset(role='train', size=100000) valid_dset = get_linear_gaussian_dataset(role='valid', size=10000) test_dset = get_linear_gaussian_dataset(role='test', size=10000) return (train_dset, valid_dset, test_dset)
class NotMNIST(Dataset): def __init__(self, root, train=False, download=False): assert (not train), 'Only test set available for NotMNIST' (self.data, self.targets) = self._load_tensors(root) def _load_tensors(self, root): data_path = os.path.join(root, 'data.pt') targets_pat...
def get_raw_image_tensors(dataset_name, train, data_root): data_dir = os.path.join(data_root, dataset_name) if (dataset_name == 'cifar10'): dataset = torchvision.datasets.CIFAR10(root=data_dir, train=train, download=True) images = torch.tensor(dataset.data).permute((0, 3, 1, 2)) labels...
def image_tensors_to_supervised_dataset(dataset_name, dataset_role, images, labels): images = images.to(dtype=torch.get_default_dtype()) labels = labels.long() return SupervisedDataset(dataset_name, dataset_role, images, labels)
def get_train_valid_image_datasets(dataset_name, data_root, valid_fraction, add_train_hflips): (images, labels) = get_raw_image_tensors(dataset_name, train=True, data_root=data_root) perm = torch.randperm(images.shape[0]) shuffled_images = images[perm] shuffled_labels = labels[perm] valid_size = i...
def get_test_image_dataset(dataset_name, data_root): (images, labels) = get_raw_image_tensors(dataset_name, train=False, data_root=data_root) return image_tensors_to_supervised_dataset(dataset_name, 'test', images, labels)
def get_image_datasets(dataset_name, data_root, make_valid_dset): valid_fraction = (0.1 if make_valid_dset else 0) add_train_hflips = False (train_dset, valid_dset) = get_train_valid_image_datasets(dataset_name, data_root, valid_fraction, add_train_hflips) test_dset = get_test_image_dataset(dataset_na...
def get_loader(dset, device, batch_size, drop_last): return torch.utils.data.DataLoader(dset.to(device), batch_size=batch_size, shuffle=True, drop_last=drop_last, num_workers=0, pin_memory=False)
def get_loaders(dataset, device, data_root, make_valid_loader, train_batch_size, valid_batch_size, test_batch_size): print('Loading data...', end='', flush=True, file=sys.stderr) if (dataset in ['cifar10', 'svhn', 'mnist', 'fashion-mnist']): (train_dset, valid_dset, test_dset) = get_image_datasets(dat...
class SupervisedDataset(torch.utils.data.Dataset): def __init__(self, name, role, x, y=None): if (y is None): y = torch.zeros(x.shape[0]).long() assert (x.shape[0] == y.shape[0]) assert (role in ['train', 'valid', 'test']) self.name = name self.role = role ...
def train(config, load_dir): (density, trainer, writer) = setup_experiment(config=config, load_dir=load_dir, checkpoint_to_load='latest') writer.write_json('config', config) writer.write_json('model', {'num_params': num_params(density), 'schema': get_schema(config)}) writer.write_textfile('git-head', ...
def print_test_metrics(config, load_dir): (_, trainer, _) = setup_experiment(config={**config, 'write_to_disk': False}, load_dir=load_dir, checkpoint_to_load='best_valid') with torch.no_grad(): test_metrics = trainer.test() test_metrics = {k: v.item() for (k, v) in test_metrics.items()} print(...
def print_model(config): (density, _, _, _) = setup_density_and_loaders(config={**config, 'write_to_disk': False}, device=torch.device('cpu')) print(density)
def print_num_params(config): (density, _, _, _) = setup_density_and_loaders(config={**config, 'write_to_disk': False}, device=torch.device('cpu')) print(f'Number of parameters: {num_params(density):,}')
def setup_density_and_loaders(config, device): (train_loader, valid_loader, test_loader) = get_loaders(dataset=config['dataset'], device=device, data_root=config['data_root'], make_valid_loader=config['early_stopping'], train_batch_size=config['train_batch_size'], valid_batch_size=config['valid_batch_size'], test...
def load_run(run_dir, device): run_dir = Path(run_dir) with open((run_dir / 'config.json'), 'r') as f: config = json.load(f) (density, train_loader, valid_loader, test_loader) = setup_density_and_loaders(config=config, device=device) try: checkpoint = torch.load(((run_dir / 'checkpoint...
def setup_experiment(config, load_dir, checkpoint_to_load): torch.manual_seed(config['seed']) np.random.seed((config['seed'] + 1)) random.seed((config['seed'] + 2)) device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu')) (density, train_loader, valid_loader, test_loader) = setup_de...
def get_lr_scheduler(opt, num_train_batches, config): if (config['lr_schedule'] == 'cosine'): return torch.optim.lr_scheduler.CosineAnnealingLR(optimizer=opt, T_max=(config['max_epochs'] * num_train_batches), eta_min=0.0) elif (config['lr_schedule'] == 'none'): return torch.optim.lr_scheduler....
def get_train_metrics(density, config): if (config['train_objective'] == 'iwae'): train_metric = (lambda density, x: {'losses': {'pq-loss': iwae(density, x, config['num_train_importance_samples'], detach_q=False)}}) opt = get_opt(density.parameters(), config) return (train_metric, {'pq-los...
def get_q_loss(config): train_objective = config['train_objective'] if (train_objective == 'rws'): return (lambda density, x: rws(density, x, config['num_train_importance_samples'])) elif (train_objective == 'rws-dreg'): return (lambda density, x: rws_dreg(density, x, config['num_train_imp...
def get_opt(parameters, config): if (config['opt'] == 'sgd'): opt_class = optim.SGD elif (config['opt'] == 'adam'): opt_class = optim.Adam elif (config['opt'] == 'adamax'): opt_class = optim.Adamax else: assert False, f"Invalid optimiser type {config['opt']}" return...
def num_params(module): return sum((p.view((- 1)).shape[0] for p in module.parameters()))
def metrics(density, x, num_importance_samples): result = density.elbo(x, num_importance_samples, detach_q_params=False, detach_q_samples=False) elbo_samples = result['log-w'] elbo = elbo_samples.mean(dim=1) iwae = (elbo_samples.logsumexp(dim=1) - np.log(num_importance_samples)) dim = int(np.prod(...
def iwae(density, x, num_importance_samples, detach_q): log_w = density.elbo(x=x, num_importance_samples=num_importance_samples, detach_q_params=detach_q, detach_q_samples=detach_q)['log-w'] return (- log_w.logsumexp(dim=1).mean())
def iwae_alt(density, x, num_importance_samples, grad_weight_pow): log_w = density.elbo(x=x, num_importance_samples=num_importance_samples, detach_q_params=True, detach_q_samples=False)['log-w'] log_Z = log_w.logsumexp(dim=1).view(x.shape[0], 1, 1) grad_weight = ((log_w - log_Z).exp() ** grad_weight_pow) ...
def rws(density, x, num_importance_samples): log_w = density.elbo(x=x, num_importance_samples=num_importance_samples, detach_q_params=False, detach_q_samples=True)['log-w'] log_Z = log_w.logsumexp(dim=1).view(x.shape[0], 1, 1) grad_weight = (log_w - log_Z).exp() return (grad_weight.detach() * log_w).s...
def rws_dreg(density, x, num_importance_samples): log_w = density.elbo(x=x, num_importance_samples=num_importance_samples, detach_q_params=True, detach_q_samples=False)['log-w'] log_Z = log_w.logsumexp(dim=1).view(x.shape[0], 1, 1) grad_weight = (log_w - log_Z).exp().detach() return (- ((grad_weight -...
class ActNormBijection(Bijection): def __init__(self, x_shape): super().__init__(x_shape=x_shape, z_shape=x_shape) self.actnorm = ActNormNd(num_features=x_shape[0]) self.actnorm.shape = ((1, (- 1)) + ((1,) * len(x_shape[1:]))) def _x_to_z(self, x, **kwargs): (z, neg_log_jac) ...
class AffineBijection(Bijection): def __init__(self, x_shape, per_channel): super().__init__(x_shape=x_shape, z_shape=x_shape) if per_channel: param_shape = (x_shape[0], *[1 for _ in x_shape[1:]]) self.log_jac_factor = np.prod(x_shape[1:]) else: param_s...
class ConditionalAffineBijection(Bijection): def __init__(self, x_shape, coupler): super().__init__(x_shape, x_shape) self.coupler = coupler def _x_to_z(self, x, **kwargs): (shift, log_scale) = self._shift_log_scale(kwargs['u']) z = ((x + shift) * torch.exp(log_scale)) ...
class BatchNormBijection(Bijection): def __init__(self, x_shape, per_channel, apply_affine, momentum, eps=1e-05): super().__init__(x_shape=x_shape, z_shape=x_shape) assert (0 <= momentum <= 1) self.momentum = momentum assert (eps > 0) self.eps = eps if per_channel:...
class Bijection(nn.Module): def __init__(self, x_shape, z_shape): super().__init__() self.x_shape = x_shape self.z_shape = z_shape def forward(self, inputs, direction, **kwargs): if (direction == 'x-to-z'): assert (inputs.shape[1:] == self.x_shape), f'Expected sha...
class ConditionedBijection(Bijection): def __init__(self, bijection, u): super().__init__(x_shape=bijection.x_shape, z_shape=bijection.z_shape) self.bijection = bijection self.register_buffer('u', u) def _x_to_z(self, x, **kwargs): return self.bijection.x_to_z(x, u=self._expa...
class InverseBijection(Bijection): def __init__(self, bijection): super().__init__(x_shape=bijection.z_shape, z_shape=bijection.x_shape) self.bijection = bijection def _x_to_z(self, x, **kwargs): result = self.bijection.z_to_x(x, **kwargs) z = result.pop('x') return {...
class IdentityBijection(Bijection): def __init__(self, x_shape): super().__init__(x_shape=x_shape, z_shape=x_shape) def _x_to_z(self, x, **kwargs): return {'z': x, 'log-jac': self._log_jac_like(x)} def _z_to_x(self, z, **kwargs): return {'x': z, 'log-jac': self._log_jac_like(z)}...
class CompositeBijection(Bijection): def __init__(self, layers, direction): if (direction == 'z-to-x'): x_shape = layers[(- 1)].x_shape z_shape = layers[0].z_shape elif (direction == 'x-to-z'): x_shape = layers[0].x_shape z_shape = layers[(- 1)].z_s...
class BlockNeuralAutoregressiveBijection(Bijection): def __init__(self, num_input_channels, num_hidden_layers, hidden_channels_factor, activation, residual): shape = (num_input_channels,) super().__init__(x_shape=shape, z_shape=shape) if (activation == 'tanh'): warnings.warn('...
class Nonlinearity(nn.Module): def forward(self, inputs, grad=None): (outputs, log_jac) = self._do_forward(inputs) if (grad is None): grad = log_jac else: grad = (log_jac.view(grad.shape) + grad) return (outputs, grad)
class LeakyReLU(Nonlinearity): def _do_forward(self, inputs): outputs = F.leaky_relu(inputs, negative_slope=self.negative_slope) log_jac = torch.zeros_like(inputs) log_jac[(inputs < 0)] = np.log(self.negative_slope) return (outputs, log_jac)
class SoftLeakyReLU(Nonlinearity): def __init__(self, negative_slope=0.01): super().__init__() self.negative_slope = negative_slope def _do_forward(self, inputs): eps = self.negative_slope outputs = ((eps * inputs) + ((1 - eps) * F.softplus(inputs))) log_jac = torch.l...
class Invertible1x1ConvBijection(Bijection): def __init__(self, x_shape, num_u_channels=0): assert ((len(x_shape) == 1) or (len(x_shape) == 3)) super().__init__(x_shape, x_shape) num_channels = x_shape[0] self.weight_shape = [num_channels, num_channels] self.conv_weights_s...
class BruteForceInvertible1x1ConvBijection(Invertible1x1ConvBijection): def __init__(self, x_shape, num_u_channels=0): super().__init__(x_shape, num_u_channels) self.weights = nn.Parameter(self.weights_init) def _get_weights(self): return self.weights def _log_jac_single(self): ...
class LUInvertible1x1ConvBijection(Invertible1x1ConvBijection): def __init__(self, x_shape, num_u_channels=0): super().__init__(x_shape, num_u_channels) (P, lower, upper) = torch.lu_unpack(*torch.lu(self.weights_init)) s = torch.diag(upper) log_s = torch.log(torch.abs(s)) ...
class LULinearBijection(Bijection): def __init__(self, num_input_channels): shape = (num_input_channels,) super().__init__(x_shape=shape, z_shape=shape) self.linear = LULinear(features=num_input_channels, identity_init=True) def _x_to_z(self, x, **kwargs): (z, log_jac) = self...
class ElementwiseBijection(Bijection): def __init__(self, x_shape): super().__init__(x_shape=x_shape, z_shape=x_shape) def _x_to_z(self, x, **kwargs): return {'z': self._F(x), 'log-jac': self._log_jac_x_to_z(x)} def _z_to_x(self, z, **kwargs): return {'x': self._F_inv(z), 'log-j...
class LogitBijection(ElementwiseBijection): _EPS = 1e-07 def _F(self, x): return (torch.log(x) - torch.log((1 - x))) def _F_inv(self, z): return torch.sigmoid(z) def _log_dF(self, x): x_clamped = x.clamp(self._EPS, (1 - self._EPS)) return ((- torch.log(x_clamped)) - ...
class TanhBijection(ElementwiseBijection): _EPS = 1e-07 def _F(self, x): return torch.tanh(x) def _F_inv(self, z): z_clamped = z.clamp(((- 1) + self._EPS), (1 - self._EPS)) return (0.5 * (torch.log((1 + z_clamped)) - torch.log((1 - z_clamped)))) def _log_dF(self, x): ...
class ScalarMultiplicationBijection(ElementwiseBijection): def __init__(self, x_shape, value): assert np.isscalar(value) assert (value != 0.0), 'Scalar multiplication by zero is not a bijection' super().__init__(x_shape=x_shape) self.value = value def _F(self, x): ret...
class ScalarAdditionBijection(ElementwiseBijection): def __init__(self, x_shape, value): assert np.isscalar(value) super().__init__(x_shape=x_shape) self.value = value def _F(self, x): return (x + self.value) def _F_inv(self, z): return (z - self.value) def ...
class RationalQuadraticSplineBijection(Bijection): def __init__(self, num_input_channels, flow): shape = (num_input_channels,) super().__init__(x_shape=shape, z_shape=shape) self.flow = flow def _x_to_z(self, x): (z, log_jac) = self.flow(x) return {'z': z, 'log-jac': ...
class CoupledRationalQuadraticSplineBijection(RationalQuadraticSplineBijection): def __init__(self, num_input_channels, num_hidden_layers, num_hidden_channels, num_bins, tail_bound, activation, dropout_probability, reverse_mask): def transform_net_create_fn(in_features, out_features): return...
class AutoregressiveRationalQuadraticSplineBijection(RationalQuadraticSplineBijection): def __init__(self, num_input_channels, num_hidden_layers, num_hidden_channels, num_bins, tail_bound, activation, dropout_probability): super().__init__(num_input_channels=num_input_channels, flow=MaskedPiecewiseRation...
class ODEVelocityFunction(ODEnet): def __init__(self, hidden_dims, x_input_shape, nonlinearity, num_u_channels=0, strides=None, conv=False, layer_type='concatsquash'): super().__init__(hidden_dims=hidden_dims, input_shape=x_input_shape, strides=strides, conv=conv, layer_type=layer_type, nonlinearity=nonl...
class FFJORDBijection(Bijection): _VELOCITY_NONLINEARITY = 'tanh' _DIVERGENCE_METHOD = 'brute_force' _SOLVER = 'dopri5' _INTEGRATION_TIME = 0.5 def __init__(self, x_shape, velocity_hidden_channels, num_u_channels, relative_tolerance, absolute_tolerance): super().__init__(x_shape=x_shape, ...
class ResidualFlowBijection(Bijection): def __init__(self, x_shape, lipschitz_net, reduce_memory): super().__init__(x_shape=x_shape, z_shape=x_shape) self.block = self._get_iresblock(net=lipschitz_net, reduce_memory=reduce_memory) def _x_to_z(self, x, **kwargs): (z, neg_log_jac) = se...
class SumOfSquaresPolynomialBijection(Bijection): def __init__(self, num_input_channels, hidden_channels, activation, num_polynomials, polynomial_degree): super().__init__(x_shape=(num_input_channels,), z_shape=(num_input_channels,)) arn = AutoRegressiveNN(input_dim=int(num_input_channels), hidde...
class BernoulliConditionalDensity(ConditionalDensity): def __init__(self, logit_net): super().__init__() self.logit_net = logit_net def _log_prob(self, inputs, cond_inputs): logits = self.logit_net(cond_inputs) log_probs = dist.bernoulli.Bernoulli(logits=logits).log_prob(inpu...
def concrete_log_prob(u, alphas, lam): assert (alphas.shape == u.shape) flat_u = u.flatten(start_dim=1) flat_alphas = alphas.flatten(start_dim=1) (_, dim) = flat_u.shape const_term = (np.sum(np.log(np.arange(1, dim))) + ((dim - 1) * np.log(lam))) log_denominator = torch.logsumexp((torch.log(fl...
def concrete_sample(alphas, lam): standard_gumbel = torch.distributions.gumbel.Gumbel(torch.zeros_like(alphas), torch.ones_like(alphas)) gumbels = standard_gumbel.sample() log_numerator = ((torch.log(alphas) + gumbels) / lam) log_denominator = torch.logsumexp(log_numerator, dim=1, keepdim=True) re...
class ConcreteConditionalDensity(ConditionalDensity): def __init__(self, log_alpha_map, lam): super().__init__() self.log_alpha_map = log_alpha_map self.lam = lam def _log_prob(self, inputs, cond_inputs): return {'log-prob': concrete_log_prob(inputs, self._alphas(cond_inputs)...
class ConditionalDensity(nn.Module): def forward(self, mode, *args, **kwargs): if (mode == 'log-prob'): return self._log_prob(*args, **kwargs) elif (mode == 'sample'): return self._sample(*args, **kwargs) else: assert False, f'Invalid mode {mode}' ...
class DiagonalGaussianConditionalDensity(ConditionalDensity): def __init__(self, coupler): super().__init__() self.coupler = coupler def _log_prob(self, inputs, cond_inputs): (means, stddevs) = self._means_and_stddevs(cond_inputs) return {'log-prob': diagonal_gaussian_log_pro...
class CIFDensity(Density): def __init__(self, prior, p_u_density, bijection, q_u_density): super().__init__() self.bijection = bijection self.prior = prior self.p_u_density = p_u_density self.q_u_density = q_u_density def p_parameters(self): return [*self.bije...
class Density(nn.Module): def forward(self, mode, *args, **kwargs): if (mode == 'elbo'): return self._elbo(*args, **kwargs) elif (mode == 'sample'): return self._sample(*args, **kwargs) elif (mode == 'fixed-sample'): return self._fixed_sample(*args, **k...
class FlowDensity(Density): def __init__(self, prior, bijection): super().__init__() self.bijection = bijection self.prior = prior def p_parameters(self): return [*self.bijection.parameters(), *self.prior.p_parameters()] def q_parameters(self): return self.prior....
def diagonal_gaussian_log_prob(w, means, stddevs): assert (means.shape == stddevs.shape == w.shape) flat_w = w.flatten(start_dim=1) flat_means = means.flatten(start_dim=1) flat_vars = (stddevs.flatten(start_dim=1) ** 2) (_, dim) = flat_w.shape const_term = (((- 0.5) * dim) * np.log((2 * np.pi)...
def diagonal_gaussian_sample(means, stddevs): return ((stddevs * torch.randn_like(means)) + means)
def diagonal_gaussian_entropy(stddevs): flat_stddevs = stddevs.flatten(start_dim=1) (_, dim) = flat_stddevs.shape return (torch.sum(torch.log(flat_stddevs), dim=1, keepdim=True) + ((0.5 * dim) * (1 + np.log((2 * np.pi)))))