Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docs/examples

This file was deleted.

1 change: 1 addition & 0 deletions docs/examples
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
../examples
22 changes: 11 additions & 11 deletions normflows/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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_
Expand Down
6 changes: 3 additions & 3 deletions normflows/distributions/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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_])
Expand Down
34 changes: 5 additions & 29 deletions normflows/flows/mixing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
104 changes: 66 additions & 38 deletions normflows/utils/splines.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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

Expand Down Expand Up @@ -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))
Expand Down