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

Add JAX implementation for InvGammaRV #1480

Merged
merged 1 commit into from
Mar 23, 2023
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
21 changes: 21 additions & 0 deletions aesara/link/jax/dispatch/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,3 +453,24 @@ def sample_fn(rng, size, dtype, *parameters):
return (rng, samples)

return sample_fn


@jax_sample_fn.register(aer.InvGammaRV)
def jax_sample_fn_invgamma(op):
"""JAX implementation of `InvGammaRV`."""

def sample_fn(rng, size, dtype, *parameters):
rng_key = rng["jax_state"]
rng_key, sampling_key = jax.random.split(rng_key, 2)

(
shape,
scale,
) = parameters
# InvGamma[shape, scale] <-> 1 / Gamma[shape, 1 / scale]
samples = 1 / (jax.random.gamma(sampling_key, shape, size, dtype) / scale)

rng["jax_state"] = rng_key
return (rng, samples)

return sample_fn
13 changes: 13 additions & 0 deletions tests/link/jax/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,19 @@ def test_random_dirichlet(parameter, size):
np.testing.assert_allclose(samples.mean(axis=0), 0.5, 1)


@pytest.mark.parametrize(
"shape, scale",
[(3, 3), (2, 1), (2, 5)],
)
def test_random_invgamma(shape, scale):
rng = shared(np.random.RandomState(123))
g = at.random.invgamma(shape, scale, size=(100000,), rng=rng)
g_fn = function([], g, mode=jax_mode)
samples = g_fn()
# mean = scale / (shape - 1) only exists for shape > 1
np.testing.assert_allclose(samples.mean(), scale / (shape - 1), rtol=1e-01)


def test_random_choice():
# Elements are picked at equal frequency
num_samples = 10000
Expand Down