-
Notifications
You must be signed in to change notification settings - Fork 578
reduce linear operator overhead in exact marginal log likelihood computation #2682
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
Open
kayween
wants to merge
3
commits into
cornellius-gp:main
Choose a base branch
from
kayween:linop-overhead-exact-mll
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| import torch | ||
|
|
||
| from torch import Tensor | ||
|
|
||
|
|
||
| class TensorInvQuadLogdet(torch.autograd.Function): | ||
| r"""This function computes the inverse quadratic form and the log determinant of a positive semi-definite matrix. | ||
| This is a light weight implementation of `LinearOperator.inv_quad_logdet`. The main motivation is to avoid the | ||
| overhead of linear operators for dense kernel matrices by doing linear algebra operations directly on torch tensors. | ||
| """ | ||
|
|
||
| @staticmethod | ||
| def forward( | ||
| ctx, | ||
| matrix: Tensor, | ||
| inv_quad_rhs: Tensor, | ||
| ) -> tuple[Tensor, Tensor]: | ||
| r"""Compute the inverse quadratic form and the log determinant. | ||
|
|
||
| :param matrix: A positive semi-definite matrix of size `(..., N, N)`. | ||
| :param inv_quad_rhs: The right-hand side vector of size `(..., N, 1)`. | ||
| :return: The inverse quadratic form and the log determinant, both of size `(...)`. | ||
| """ | ||
| chol = torch.linalg.cholesky(matrix) | ||
|
|
||
| # The inverse quadratic term | ||
| inv_quad_solves = torch.cholesky_solve(inv_quad_rhs, chol) | ||
| inv_quad_term = (inv_quad_solves * inv_quad_rhs).sum(-2) | ||
| inv_quad_term = inv_quad_term.squeeze(-1) | ||
|
|
||
| # The log determinant term | ||
| logdet_term = 2.0 * chol.diagonal(dim1=-1, dim2=-2).log().sum(-1) | ||
|
|
||
| ctx.save_for_backward(chol, inv_quad_solves) | ||
|
|
||
| return inv_quad_term, logdet_term | ||
|
|
||
| @staticmethod | ||
| def backward(ctx, d_inv_quad: Tensor, d_logdet: Tensor) -> tuple[Tensor, Tensor]: | ||
| r"""Compute the backward pass for the inverse quadratic form and the log determinant. | ||
|
|
||
| :param d_inv_quad: The gradient of the inverse quadratic form of size `(...)`. | ||
| :param d_logdet: The gradient of the log determinant of size `(...)`. | ||
| :return: The gradients with respect to the input matrix and the right-hand side vector. | ||
| """ | ||
| chol, inv_quad_solves = ctx.saved_tensors | ||
|
|
||
| d_matrix_one = ( | ||
| -1.0 * inv_quad_solves @ inv_quad_solves.transpose(-2, -1) * d_inv_quad.unsqueeze(-1).unsqueeze(-1) | ||
| ) | ||
| d_matrix_two = torch.cholesky_inverse(chol) * d_logdet.unsqueeze(-1).unsqueeze(-1) | ||
| d_matrix = d_matrix_one + d_matrix_two | ||
|
|
||
| d_inv_quad_rhs = 2.0 * inv_quad_solves * d_inv_quad.unsqueeze(-1).unsqueeze(-1) | ||
|
|
||
| return d_matrix, d_inv_quad_rhs |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| import unittest | ||
|
|
||
| import torch | ||
|
|
||
| from gpytorch.functions import TensorInvQuadLogdet | ||
| from gpytorch.kernels import RBFKernel | ||
|
|
||
|
|
||
| class TestInvQuadLogdet(unittest.TestCase): | ||
| def test_inv_quad_logdet(self): | ||
| # NOTE: Use small matrics here to avoid flakiness since we are testing in `float32`. | ||
| num_data = 3 | ||
| jitter = 1e-4 | ||
|
|
||
| train_x = torch.linspace(0, 1, num_data).view(num_data, 1) | ||
|
|
||
| # Foward and backward using `InvQuadLogdet` | ||
| covar_module = RBFKernel() | ||
| covar_matrix = covar_module(train_x).evaluate_kernel().add_jitter(jitter).to_dense() | ||
|
|
||
| inv_quad_rhs = torch.linspace(0, 1, num_data).requires_grad_(True) | ||
|
|
||
| inv_quad, logdet = TensorInvQuadLogdet.apply(covar_matrix, inv_quad_rhs.unsqueeze(-1)) | ||
| inv_quad_logdet = inv_quad + logdet | ||
| inv_quad_logdet.backward() | ||
|
|
||
| # Forward and backward using linear operators | ||
| covar_module_linop = RBFKernel() | ||
| covar_matrix_linop = covar_module_linop(train_x).evaluate_kernel().add_jitter(jitter) | ||
|
|
||
| inv_quad_rhs_linop = inv_quad_rhs.detach().clone().requires_grad_(True) | ||
|
|
||
| inv_quad_linop, logdet_linop = covar_matrix_linop.inv_quad_logdet(inv_quad_rhs_linop.unsqueeze(-1), logdet=True) | ||
| inv_quad_logdet_linop = inv_quad_linop + logdet_linop | ||
| inv_quad_logdet_linop.backward() | ||
|
|
||
| self.assertTrue(torch.allclose(inv_quad, inv_quad_linop)) | ||
| self.assertTrue(torch.allclose(logdet, logdet_linop)) | ||
| self.assertTrue(torch.allclose(inv_quad_logdet, inv_quad_logdet_linop)) | ||
| self.assertTrue(torch.allclose(covar_module.raw_lengthscale.grad, covar_module_linop.raw_lengthscale.grad)) | ||
| self.assertTrue(torch.allclose(inv_quad_rhs.grad, inv_quad_rhs_linop.grad)) | ||
|
|
||
| def test_batch_inv_quad_logdet(self): | ||
| num_data = 3 | ||
| jitter = 1e-4 | ||
|
|
||
| train_x = torch.linspace(0, 1, 2 * num_data).view(2, num_data, 1) | ||
|
|
||
| # Foward and backward using `InvQuadLogdet` | ||
| covar_module = RBFKernel(batch_shape=torch.Size([2])) | ||
| covar_matrix = covar_module(train_x).evaluate_kernel().add_jitter(jitter).to_dense() | ||
|
|
||
| inv_quad_rhs = torch.linspace(0, 1, 2 * num_data).view(2, num_data).requires_grad_(True) | ||
|
|
||
| inv_quad, logdet = TensorInvQuadLogdet.apply(covar_matrix, inv_quad_rhs.unsqueeze(-1)) | ||
| inv_quad_logdet = torch.sum(inv_quad + logdet) | ||
| inv_quad_logdet.backward() | ||
|
|
||
| # Forward and backward using linear operators | ||
| covar_module_linop = RBFKernel(batch_shape=torch.Size([2])) | ||
| covar_matrix_linop = covar_module_linop(train_x).evaluate_kernel().add_jitter(jitter) | ||
|
|
||
| inv_quad_rhs_linop = inv_quad_rhs.detach().clone().requires_grad_(True) | ||
|
|
||
| inv_quad_linop, logdet_linop = covar_matrix_linop.inv_quad_logdet(inv_quad_rhs_linop.unsqueeze(-1), logdet=True) | ||
| inv_quad_logdet_linop = torch.sum(inv_quad_linop + logdet_linop) | ||
| inv_quad_logdet_linop.backward() | ||
|
|
||
| self.assertTrue(torch.allclose(inv_quad, inv_quad_linop)) | ||
| self.assertTrue(torch.allclose(logdet, logdet_linop)) | ||
| self.assertTrue(torch.allclose(inv_quad_logdet, inv_quad_logdet_linop)) | ||
| self.assertTrue(torch.allclose(covar_module.raw_lengthscale.grad, covar_module_linop.raw_lengthscale.grad)) | ||
| self.assertTrue(torch.allclose(inv_quad_rhs.grad, inv_quad_rhs_linop.grad)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do we think about making this on by default up to some N?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Indeed, the first version of this PR turns on this flag up to some N as you suggested. But the benchmark shows speed up even for N=1000 (whereas the default threshold for Cholesky decomposition is N=800). So I decided to turns this on as long as Cholesky decomposition is used for training and inference.
I think the design here is intertwined with your comments below---what would happen for larger N. I'll circle back on this once we have benchmark results for larger N.