Skip to content
Closed
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
60 changes: 60 additions & 0 deletions tests/test_distributions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
r"""Tests for the zuko.distributions module."""

import pytest
import torch

from torch.distributions import *
Expand Down Expand Up @@ -59,3 +60,62 @@ def test_distributions() -> None:
log_p = d.log_prob(x)

assert log_p.shape == d.batch_shape, d


@pytest.mark.parametrize(
"base_shape,lower_shape,upper_shape,batch_shape",
[
((), (), (), ()),
((), (3,), (), (3,)),
((), (), (3,), (3,)),
((), (2, 1), (3,), (2, 3)),
((2, 1), (), (3,), (2, 3)),
((2, 3), (), (), (2, 3)),
((2, 1), (1, 3), (), (2, 3)),
],
)
def test_truncated_batch_shape(
base_shape: tuple[int, ...],
lower_shape: tuple[int, ...],
upper_shape: tuple[int, ...],
batch_shape: tuple[int, ...],
) -> None:
base = Normal(torch.zeros(base_shape), torch.ones(base_shape))
d = Truncated(base, -torch.ones(lower_shape), torch.ones(upper_shape))

assert d.batch_shape == batch_shape

for distribution in (d, d.expand((4,) + batch_shape)):
x = distribution.rsample((5,))

assert x.shape == (5,) + distribution.batch_shape
assert distribution.log_prob(x).shape == x.shape
assert distribution.cdf(x).shape == x.shape
assert torch.all((-1 <= x) & (x < 1))


def test_truncated_joint() -> None:
base = Normal(0.0, 1.0)
truncated = Truncated(base, torch.tensor([-1.0, 0.0]), torch.tensor([1.0, 2.0]))
joint = Joint(truncated, base)
x = joint.rsample((5,))

assert joint.batch_shape == (2,)
assert x.shape == (5, 2, 2)
assert torch.allclose(
joint.log_prob(x), truncated.log_prob(x[..., 0]) + base.log_prob(x[..., 1])
)


def test_truncated_mixture() -> None:
base = Normal(0.0, 1.0)
truncated = Truncated(base, torch.tensor([-1.0, 0.0]), torch.tensor([1.0, 2.0]))
mixture = Mixture(truncated, torch.zeros(2))
x = mixture.sample((5,))
expected = torch.logsumexp(truncated.log_prob(x.unsqueeze(-1)), dim=-1) - torch.log(
torch.tensor(2.0)
)

assert mixture.batch_shape == ()
assert x.shape == (5,)
assert torch.allclose(mixture.log_prob(x), expected)
2 changes: 1 addition & 1 deletion zuko/distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def __repr__(self) -> str:

@property
def batch_shape(self) -> Size:
return self.base.batch_shape
return self.uniform.batch_shape

def expand(self, batch_shape: Size, new: Distribution | None = None) -> Distribution:
new = self._get_checked_instance(Truncated, new)
Expand Down
Loading