diff --git a/docs/examples b/docs/examples deleted file mode 120000 index a6573af9..00000000 --- a/docs/examples +++ /dev/null @@ -1 +0,0 @@ -../examples \ No newline at end of file diff --git a/docs/examples b/docs/examples new file mode 100644 index 00000000..a6573af9 --- /dev/null +++ b/docs/examples @@ -0,0 +1 @@ +../examples \ No newline at end of file diff --git a/normflows/core.py b/normflows/core.py index 03f9566b..12b8d3d2 100644 --- a/normflows/core.py +++ b/normflows/core.py @@ -48,7 +48,7 @@ def forward_and_log_det(self, z): Batch in the space of the target distribution, log determinant of the Jacobian """ - log_det = torch.zeros(len(z), device=z.device) + log_det = torch.zeros(z.shape[0], device=z.device) for flow in self.flows: z, log_d = flow(z) log_det += log_d @@ -78,7 +78,7 @@ def inverse_and_log_det(self, x): Batch in the latent space, log determinant of the Jacobian """ - log_det = torch.zeros(len(x), device=x.device) + log_det = torch.zeros(x.shape[0], device=x.device) for i in range(len(self.flows) - 1, -1, -1): x, log_d = self.flows[i].inverse(x) log_det += log_d @@ -93,7 +93,7 @@ def forward_kld(self, x): Returns: Estimate of forward KL divergence averaged over batch """ - log_q = torch.zeros(len(x), device=x.device) + log_q = torch.zeros(x.shape[0], device=x.device) z = x for i in range(len(self.flows) - 1, -1, -1): z, log_det = self.flows[i].inverse(z) @@ -188,7 +188,7 @@ def log_prob(self, x): Returns: log probability """ - log_q = torch.zeros(len(x), dtype=x.dtype, device=x.device) + log_q = torch.zeros(x.shape[0], dtype=x.dtype, device=x.device) z = x for i in range(len(self.flows) - 1, -1, -1): z, log_det = self.flows[i].inverse(z) @@ -245,7 +245,7 @@ def forward_and_log_det(self, z, context=None): Batch in the space of the target distribution, log determinant of the Jacobian """ - log_det = torch.zeros(len(z), device=z.device) + log_det = torch.zeros(z.shape[0], device=z.device) for flow in self.flows: z, log_d = flow(z, context=context) log_det += log_d @@ -277,7 +277,7 @@ def inverse_and_log_det(self, x, context=None): Batch in the latent space, log determinant of the Jacobian """ - log_det = torch.zeros(len(x), device=x.device) + log_det = torch.zeros(x.shape[0], device=x.device) for i in range(len(self.flows) - 1, -1, -1): x, log_d = self.flows[i].inverse(x, context=context) log_det += log_d @@ -309,7 +309,7 @@ def log_prob(self, x, context=None): Returns: log probability """ - log_q = torch.zeros(len(x), dtype=x.dtype, device=x.device) + log_q = torch.zeros(x.shape[0], dtype=x.dtype, device=x.device) z = x for i in range(len(self.flows) - 1, -1, -1): z, log_det = self.flows[i].inverse(z, context=context) @@ -327,7 +327,7 @@ def forward_kld(self, x, context=None): Returns: Estimate of forward KL divergence averaged over batch """ - log_q = torch.zeros(len(x), device=x.device) + log_q = torch.zeros(x.shape[0], device=x.device) z = x for i in range(len(self.flows) - 1, -1, -1): z, log_det = self.flows[i].inverse(z, context=context) @@ -393,7 +393,7 @@ def forward_kld(self, x, y): Returns: Estimate of forward KL divergence averaged over batch """ - log_q = torch.zeros(len(x), dtype=x.dtype, device=x.device) + log_q = torch.zeros(x.shape[0], dtype=x.dtype, device=x.device) z = x for i in range(len(self.flows) - 1, -1, -1): z, log_det = self.flows[i].inverse(z) @@ -427,7 +427,7 @@ def log_prob(self, x, y): Returns: log probability """ - log_q = torch.zeros(len(x), dtype=x.dtype, device=x.device) + log_q = torch.zeros(x.shape[0], dtype=x.dtype, device=x.device) z = x for i in range(len(self.flows) - 1, -1, -1): z, log_det = self.flows[i].inverse(z) @@ -534,7 +534,7 @@ def inverse_and_log_det(self, x): Returns: List of latent variables z, log determinant of Jacobian """ - log_det = torch.zeros(len(x), dtype=x.dtype, device=x.device) + log_det = torch.zeros(x.shape[0], dtype=x.dtype, device=x.device) if self.transform is not None: x, log_det_ = self.transform.inverse(x) log_det += log_det_ diff --git a/normflows/distributions/base.py b/normflows/distributions/base.py index 1adb781e..2084d562 100644 --- a/normflows/distributions/base.py +++ b/normflows/distributions/base.py @@ -175,8 +175,8 @@ def __init__(self, shape, low=-1.0, high=1.0): shape = tuple(shape) self.shape = shape self.d = np.prod(shape) - self.low = torch.tensor(low) - self.high = torch.tensor(high) + self.register_buffer("low", torch.tensor(low), persistent=False) + self.register_buffer("high", torch.tensor(high), persistent=False) self.log_prob_val = -self.d * np.log(self.high - self.low) def forward(self, num_samples=1, context=None): @@ -261,7 +261,7 @@ def sample(self, num_samples=1, context=None): return self.scale * z def log_prob(self, z, context=None): - log_p_u = torch.broadcast_to(-torch.log(self.scale[self.ind]), (len(z), -1)) + log_p_u = torch.broadcast_to(-torch.log(self.scale[self.ind]), (z.shape[0], -1)) log_p_g = ( -0.5 * np.log(2 * np.pi) - torch.log(self.scale[self.ind_]) diff --git a/normflows/flows/mixing.py b/normflows/flows/mixing.py index 58228363..08bec3b3 100644 --- a/normflows/flows/mixing.py +++ b/normflows/flows/mixing.py @@ -449,27 +449,9 @@ def inverse_no_cache(self, inputs): N = num of inputs ``` """ - lower, upper = self._create_lower_upper() - outputs = inputs - self.bias - try: - outputs = torch.linalg.solve_triangular( - lower, outputs.t(), upper=False, unitriangular=True - ) - outputs = torch.linalg.solve_triangular( - upper, outputs, upper=True, unitriangular=False - ) - except: - outputs, _ = torch.triangular_solve( - outputs.t(), lower, upper=False, unitriangular=True - ) - outputs, _ = torch.triangular_solve( - outputs, upper, upper=True, unitriangular=False - ) - outputs = outputs.t() - - logabsdet = -self.logabsdet() - logabsdet = logabsdet * inputs.new_ones(outputs.shape[0]) - + W_inv = self.weight_inverse() + outputs = torch.matmul(inputs - self.bias, W_inv.t()) + logabsdet = -self.logabsdet() * inputs.new_ones(outputs.shape[0]) return outputs, logabsdet def weight(self): @@ -503,13 +485,7 @@ def weight_inverse(self): D = num of features ``` """ - lower, upper = self._create_lower_upper() - identity = torch.eye(self.features, self.features) - lower_inverse = torch.linalg.solve_triangular(lower, identity, upper=False, unitriangular=True) - weight_inverse = torch.linalg.solve_triangular( - upper, lower_inverse, upper=True, unitriangular=False - ) - return weight_inverse + return torch.inverse(self.weight()) @property def upper_diag(self): @@ -560,4 +536,4 @@ def forward(self, z, context=None): def inverse(self, z, context=None): z, _ = self.permutation(z, context=context) z, log_det = self.linear(z, context=context) - return z, log_det.view(-1) + return z, log_det.view(-1) \ No newline at end of file diff --git a/normflows/utils/splines.py b/normflows/utils/splines.py index ac59867b..1ef56bfe 100644 --- a/normflows/utils/splines.py +++ b/normflows/utils/splines.py @@ -26,58 +26,88 @@ def unconstrained_rational_quadratic_spline( min_derivative=DEFAULT_MIN_DERIVATIVE, ): inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound) - outside_interval_mask = ~inside_interval_mask - outputs = torch.zeros_like(inputs) - logabsdet = torch.zeros_like(inputs) + outputs_outside = inputs + logabsdet_outside = torch.zeros_like(inputs) if tails == "linear": - unnormalized_derivatives_ = F.pad(unnormalized_derivatives, pad=(1, 1)) + unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1)) constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives_[..., 0] = constant - unnormalized_derivatives_[..., -1] = constant - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 + first = torch.full_like(unnormalized_derivatives[..., :1], constant) + last = torch.full_like(unnormalized_derivatives[..., -1:], constant) + middle = unnormalized_derivatives[..., 1:-1] + unnormalized_derivatives = torch.cat([first, middle, last], dim=-1) + elif tails == "circular": - unnormalized_derivatives_ = F.pad(unnormalized_derivatives, pad=(0, 1)) - unnormalized_derivatives_[..., -1] = unnormalized_derivatives_[..., 0] + unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(0, 1)) + + first = unnormalized_derivatives[..., :1] + middle = unnormalized_derivatives[..., 1:-1] + last = first + unnormalized_derivatives = torch.cat([first, middle, last], dim=-1) - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 elif isinstance(tails, list) or isinstance(tails, tuple): - unnormalized_derivatives_ = unnormalized_derivatives.clone() - ind_lin = [t == "linear" for t in tails] - ind_circ = [t == "circular" for t in tails] constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives_[..., ind_lin, 0] = constant - unnormalized_derivatives_[..., ind_lin, -1] = constant - unnormalized_derivatives_[..., ind_circ, -1] = unnormalized_derivatives_[ - ..., ind_circ, 0 - ] + + first = unnormalized_derivatives[..., :1] + middle = unnormalized_derivatives[..., 1:-1] + last = unnormalized_derivatives[..., -1:] + + feature_dim = unnormalized_derivatives.shape[-2] + view_shape = [1] * unnormalized_derivatives.ndim + view_shape[-2] = feature_dim + view_shape[-1] = 1 + + lin_mask = torch.tensor( + [t == "linear" for t in tails], + dtype=torch.bool, + device=unnormalized_derivatives.device, + ).view(*view_shape) + + circ_mask = torch.tensor( + [t == "circular" for t in tails], + dtype=torch.bool, + device=unnormalized_derivatives.device, + ).view(*view_shape) + + constant_first = torch.full_like(first, constant) + constant_last = torch.full_like(last, constant) + + new_first = torch.where(lin_mask, constant_first, first) + new_last = torch.where(lin_mask, constant_last, last) + new_last = torch.where(circ_mask, new_first, new_last) + + unnormalized_derivatives = torch.cat([new_first, middle, new_last], dim=-1) + else: raise RuntimeError("{} tails are not implemented.".format(tails)) if torch.is_tensor(tail_bound): tail_bound_ = torch.broadcast_to(tail_bound, inputs.shape) - left = -tail_bound_[inside_interval_mask] - right = tail_bound_[inside_interval_mask] - bottom = -tail_bound_[inside_interval_mask] - top = tail_bound_[inside_interval_mask] + left = -tail_bound_ + right = tail_bound_ + bottom = -tail_bound_ + top = tail_bound_ + + clamp_min = -tail_bound_ + clamp_max = tail_bound_ else: left = -tail_bound right = tail_bound bottom = -tail_bound top = tail_bound - ( - outputs_masked, - logabsdet_masked - ) = rational_quadratic_spline( - inputs=inputs[inside_interval_mask], - unnormalized_widths=unnormalized_widths[inside_interval_mask, :], - unnormalized_heights=unnormalized_heights[inside_interval_mask, :], - unnormalized_derivatives=unnormalized_derivatives_[inside_interval_mask, :], + clamp_min = -tail_bound + clamp_max = tail_bound + + inputs_clamped = torch.clamp(inputs, min=clamp_min, max=clamp_max) + + outputs_spline, logabsdet_spline = rational_quadratic_spline( + inputs=inputs_clamped, + unnormalized_widths=unnormalized_widths, + unnormalized_heights=unnormalized_heights, + unnormalized_derivatives=unnormalized_derivatives, inverse=inverse, left=left, right=right, @@ -87,12 +117,9 @@ def unconstrained_rational_quadratic_spline( min_bin_height=min_bin_height, min_derivative=min_derivative, ) - if outputs.dtype == outputs_masked.dtype and logabsdet.dtype == logabsdet_masked.dtype: - outputs[inside_interval_mask] = outputs_masked - logabsdet[inside_interval_mask] = logabsdet_masked - else: - outputs[inside_interval_mask] = outputs_masked.to(outputs.dtype) - logabsdet[inside_interval_mask] = logabsdet_masked.to(logabsdet.dtype) + + outputs = torch.where(inside_interval_mask, outputs_spline, outputs_outside) + logabsdet = torch.where(inside_interval_mask, logabsdet_spline, logabsdet_outside) return outputs, logabsdet @@ -178,6 +205,7 @@ def rational_quadratic_spline( c = -input_delta * (inputs - input_cumheights) discriminant = b.pow(2) - 4 * a * c + discriminant = discriminant.clamp(min=0) assert (discriminant >= 0).all() root = (2 * c) / (-b - torch.sqrt(discriminant))