Skip to content
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

Memoize Transform.inv #885

Merged
merged 1 commit into from
Jan 21, 2021
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
10 changes: 9 additions & 1 deletion numpyro/distributions/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import math
import warnings
import weakref

import numpy as np

Expand Down Expand Up @@ -52,6 +53,7 @@ def _clipped_expit(x):
class Transform(object):
domain = constraints.real
codomain = constraints.real
_inv = None

@property
def event_dim(self):
Expand All @@ -62,7 +64,13 @@ def event_dim(self):

@property
def inv(self):
return _InverseTransform(self)
inv = None
if self._inv is not None:
inv = self._inv()
if inv is None:
inv = _InverseTransform(self)
self._inv = weakref.ref(inv)
return inv

def __call__(self, x):
return NotImplementedError
Expand Down
1 change: 1 addition & 0 deletions test/test_distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1038,6 +1038,7 @@ def test_bijective_transforms(transform, event_shape, batch_shape):
z = transform.inv(y)
assert_allclose(x, z, atol=1e-6, rtol=1e-6)
assert transform.inv.inv is transform
assert transform.inv is transform.inv
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix, @fritzo!

assert transform.domain is transform.inv.codomain
assert transform.codomain is transform.inv.domain

Expand Down