Skip to content

Support broadcasting batch shapes in MTMVN.from_independent_mvns #2621

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 16, 2025
Merged
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
3 changes: 2 additions & 1 deletion gpytorch/distributions/multitask_multivariate_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,8 @@ def from_independent_mvns(cls, mvns):
if any(isinstance(mvn, MultitaskMultivariateNormal) for mvn in mvns):
raise ValueError("Cannot accept MultitaskMultivariateNormals")
if not all(m.batch_shape == mvns[0].batch_shape for m in mvns[1:]):
raise ValueError("All MultivariateNormals must have the same batch shape")
batch_shape = torch.broadcast_shapes(*(m.batch_shape for m in mvns))
mvns = [mvn.expand(batch_shape) for mvn in mvns]
if not all(m.event_shape == mvns[0].event_shape for m in mvns[1:]):
raise ValueError("All MultivariateNormals must have the same event shape")
mean = torch.stack([mvn.mean for mvn in mvns], -1)
Expand Down
8 changes: 8 additions & 0 deletions test/distributions/test_multitask_multivariate_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,14 @@ def test_from_independent_mvns(self, cuda=False):
self.assertEqual(list(mvn.mean.shape), expected_mean_shape)
self.assertEqual(list(mvn.covariance_matrix.shape), expected_covar_shape)

# Test mixed batch mode mvns
# Second MVN is batched, so the first one will be expanded to match.
mvns[1] = mvns[1].expand(torch.Size([3]))
expected_mvn = mvn.expand(torch.Size([3]))
mvn = MultitaskMultivariateNormal.from_independent_mvns(mvns=mvns)
self.assertTrue(torch.equal(mvn.mean, expected_mvn.mean))
self.assertTrue(torch.equal(mvn.covariance_matrix, expected_mvn.covariance_matrix))

# Test batch mode mvns
b = 3
mvns = [
Expand Down
Loading