Skip to content

fix(infer): preserve PRNG implementations in Predictive - #2442

Open
rpinho wants to merge 2 commits into
pyro-ppl:masterfrom
rpinho:fix-predictive-prng
Open

rpinho wants to merge 2 commits into
pyro-ppl:masterfrom
rpinho:fix-predictive-prng

Conversation

@rpinho

@rpinho rpinho commented Nov 18, 2026 •

Copy link
Copy Markdown

Predictive raises a TypeError when a key uses the rbg implementation. Call Predictive(model, num_samples=4)(jax.random.key(0, impl="rbg")) for a model that samples a Normal. The patch passes keys through the prediction map with their PRNG type.

Context from review: key_data was added in #2073 to work around #2071, which came from soft_vmap always padding the keys. Since #2318 the pad is skipped when its width is zero, and _predictive uses a chunk size of num_samples or 1, so it never pads and typed keys can pass straight through. The same line also fixes infer_discrete=True with rbg keys, which on master fails with expected key_data.shape to end with (2,); got shape=(4,).

The test adds an rbg case to the existing rng_key fixture: test_predictive[rbg-True] and test_predictive[rbg-False] fail on master with the original TypeError and pass with the patch. The fixture's "old" case uses random.PRNGKey(0) again, as #2073 intended.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LKxc9GKLwnyeV2jaZBxH9N

@github-actions github-actions Bot added the awaiting review Awaiting review from maintainers label Nov 18, 2026

@juanitorduz juanitorduz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @rpinho! The fix in util.py looks right. I'm requesting changes for the tests: the new test has 8 cases that all catch the same bug, and it compares exact values against a copy of numpyro's internals, so unrelated changes would break it. Details and a smaller alternative are inline.

Comment thread numpyro/infer/util.py
return soft_vmap(
single_prediction,
(jax.random.key_data(rng_key), posterior_samples),
(rng_key, posterior_samples),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This change looks right to me. Some context for the PR description: key_data was added in #2073 to work around #2071 (Cannot convert_element_type from int32 to key<fry>), which happened because soft_vmap always called jnp.pad on the keys. #2318 now skips the pad when the width is zero, and here chunk_size is either num_samples or 1, so _predictive never pads. That's why typed keys can pass straight through now.

That dependency is already covered: if I put the unconditional pad back in soft_vmap, test_predictive[new-True], test_predictive_with_deterministic[True] and test_predictive_with_batched_model_params[True] fail with the #2071 error.

This line also fixes infer_discrete=True with rbg keys. On master that fails with expected key_data.shape to end with (2,); got shape=(4,), and on this branch it passes. Worth mentioning in the description.

rng_type = request.param
if rng_type == "old":
return random.key(0)
return random.PRNGKey(0)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Good catch, please keep this. #2073 added the fixture with random.PRNGKey(0) for "old", and the bulk rename in #2134 changed it to random.key(0), so both params have been testing typed keys since then.

Comment thread test/infer/test_infer_util.py Outdated
Comment on lines +52 to +54
@pytest.mark.parametrize("impl", ["rbg", "unsafe_rbg"])
@pytest.mark.parametrize("parallel", [False, True])
@pytest.mark.parametrize("num_samples", [1, 4])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

All 8 cases fail on master with the same TypeError: Incorrect type for rng_seed, so they catch one bug 8 times. Most of the grid can go:

  • unsafe_rbg repeats rbg: both have key data of shape (4,), and numpyro has no impl-specific code.
  • With num_samples=1, soft_vmap gets chunk_size=1 whether parallel is True or False, so those two cases run the same code.
  • num_samples=1 vs 4 doesn't reach the bug, which isn't in the split/reshape step.
  • parallel is worth keeping. Parallel Predictive with new-style prng keys #2071 broke only the parallel=True path, so a typed-key regression in one branch has happened before.

Comment thread test/infer/test_infer_util.py Outdated
Comment on lines +59 to +70
def sample(key):
_, subkey = random.split(key)
return dist.Normal(1.0, 2.0).sample(subkey)

key = random.key(0, impl=impl)
if num_samples == 1:
expected = sample(key)[None]
else:
keys = random.split(key, num_samples)
expected = jax.vmap(sample)(keys) if parallel else jax.lax.map(sample, keys)
actual = Predictive(model, num_samples=num_samples, parallel=parallel)(key)["y"]
np.testing.assert_array_equal(actual, expected)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'd drop the exact-value comparison. expected copies three internals: seed's split convention (_, subkey = random.split(key)), _predictive skipping the split when num_samples == 1, and soft_vmap choosing vmap or lax.map.

The last one matters more than it looks. Locally (CPU, jax 0.10.2), jax.vmap(sample)(keys) and jax.lax.map(sample, keys) differ by up to 4.9 for rbg and 3.3 for unsafe_rbg, because rbg random bits change under vmap. That's why expected has to branch on parallel. For threefry the bits match, but the floats still differ by 1 ULP (1.19e-7) between the two compiled paths. So assert_array_equal would fail if Predictive ever chunked differently or XLA compiled the sampling differently, with nothing wrong for users.

The bug users hit is the TypeError, so checking the shape (and maybe that the draws are distinct) is enough. The import jax at the top can go too, since only this test uses it.

Comment thread test/infer/test_infer_util.py Outdated
@pytest.mark.parametrize("impl", ["rbg", "unsafe_rbg"])
@pytest.mark.parametrize("parallel", [False, True])
@pytest.mark.parametrize("num_samples", [1, 4])
def test_predictive_with_nondefault_prng(impl, parallel, num_samples):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Instead of this test, I'd add an rbg case to the existing rng_key fixture above:

@pytest.fixture(params=["old", "new", "rbg"])
def rng_key(request):
    rng_type = request.param
    if rng_type == "old":
        return random.PRNGKey(0)
    elif rng_type == "rbg":
        return random.key(0, impl="rbg")
    else:
        return random.key(0)

I tried this locally. On master, test_predictive[rbg-True] and test_predictive[rbg-False] fail with the original TypeError. On this branch all 6 test_predictive cases pass in about 5s. That covers both parallel branches with 2 cases instead of 8 and only checks shapes.

One drawback: test_predictive also runs MCMC with the rbg key, so an MCMC bug with rbg keys would show up there too. If you'd rather keep MCMC out of it, a small prior-predictive test parametrized only on parallel that checks the shape and that the draws are distinct works as well.

Replace the exact-value test with an rbg case in the existing rng_key
fixture, as suggested in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LKxc9GKLwnyeV2jaZBxH9N
@rpinho

rpinho commented Nov 19, 2026

Copy link
Copy Markdown
Author

Thanks, that's helpful. I changed those.

@github-actions

Copy link
Copy Markdown

Benchmark report

this PR fix-predictive-prng at ff9c7507 vs baseline master at fc7691c7

  run time:     unchanged across 32 benchmarks
  compile time: unchanged across 32 benchmarks

No significant changes

Every benchmark stayed within ±5% run time and ±25% compile time.

Red is slower, green is faster; a row is coloured by the worse of its two columns. A delta in parentheses cleared the threshold on a measurement below the resolution floor, so it is shown without being called a change. † marks a benchmark that could not be compared — see below.

Full results

distributions

                                 ──────── run time ────────     ────── compile time ──────
  benchmark                      baseline  this PR        Δ     baseline   this PR       Δ
──────────────────────────────────────────────────────────────────────────────────────────
  biject_to_constraints            2.7 ms   2.7 ms    +0.9%     140.6 ms  143.4 ms   +2.0%
  categorical_log_prob             1.5 ms   1.4 ms    -4.4%      50.9 ms   44.3 ms  -12.9%
  dirichlet_log_prob               459 µs   487 µs  (+6.2%)     796.2 ms  761.3 ms   -4.4%
  dirichlet_sample                86.7 ms  86.9 ms    +0.2%       1.72 s    1.67 s   -3.2%
  gamma_log_prob                   1.2 ms   1.2 ms    -0.6%       4.02 s    4.04 s   +0.5%
  gamma_sample                    26.2 ms  25.6 ms    -2.5%       1.67 s    1.60 s   -3.8%
  lkj_cholesky_sample              2.5 ms   2.5 ms    +1.8%       1.88 s    1.77 s   -5.9%
  mixture_same_family_log_prob     679 µs   723 µs  (+6.6%)      53.8 ms   54.5 ms   +1.3%
  multivariate_normal_log_prob     437 µs   470 µs  (+7.8%)     317.9 ms  298.4 ms   -6.1%
  normal_log_prob                  938 µs   928 µs    -1.1%      47.8 ms   46.6 ms   -2.5%
  normal_sample                   43.5 ms  43.0 ms    -1.0%     498.0 ms  492.2 ms   -1.2%
  stick_breaking_transform         4.3 ms   4.2 ms    -2.0%     132.9 ms  123.4 ms   -7.2%
  student_t_log_prob               1.4 ms   1.4 ms    +0.1%      51.3 ms   55.5 ms   +8.2%
  truncated_normal_log_prob        948 µs   929 µs    -2.0%      56.1 ms   50.4 ms  -10.1%

handlers

                                  ───────── run time ─────────     ─────── compile time ───────
  benchmark                       baseline   this PR         Δ     baseline   this PR         Δ
───────────────────────────────────────────────────────────────────────────────────────────────
  initialize_model_hierarchical    31.5 ms   30.7 ms     -2.3%       2.39 s    2.30 s     -3.5%
  log_density_hierarchical          2.5 ms    2.5 ms     +0.2%     688.6 ms  690.5 ms     +0.3%
  nested_handler_stack              1.1 ms    1.1 ms     -2.9%       711 µs    514 µs  (-27.8%)
  potential_energy_and_grad          18 µs     16 µs  (-11.2%)      58.9 ms   55.4 ms     -6.0%
  predictive_forward_sampling     590.4 ms  598.1 ms     +1.3%     204.8 ms  195.7 ms     -4.5%
  trace_seeded_model                480 µs    536 µs  (+11.7%)     472.1 ms  447.9 ms     -5.1%

mcmc

                             ──────── run time ───────     ───── compile time ─────
  benchmark                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────
  hmc_logistic_regression    934.7 ms  938.1 ms  +0.4%       1.98 s   1.93 s  -2.6%
  nuts_dense_mass_funnel       1.11 s    1.14 s  +2.2%       1.74 s   1.79 s  +3.4%
  nuts_eight_schools           1.53 s    1.54 s  +0.8%       1.83 s   1.82 s  -0.9%
  nuts_hierarchical_glm        2.10 s    2.09 s  -0.6%       2.88 s   2.99 s  +3.9%
  nuts_logistic_regression     1.44 s    1.45 s  +1.2%       2.08 s   2.02 s  -3.0%
  nuts_vectorized_chains       3.08 s    3.06 s  -0.5%       2.26 s   2.27 s  +0.0%

svi

                                             ──────── run time ───────     ───── compile time ─────
  benchmark                                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────────────
  svi_autodelta_map_logistic                 300.6 ms  295.3 ms  -1.8%       2.06 s   2.10 s  +1.9%
  svi_autodiagonalnormal_hierarchical        623.7 ms  626.2 ms  +0.4%       3.21 s   3.07 s  -4.3%
  svi_automultivariatenormal_eight_schools   554.2 ms  534.0 ms  -3.7%       3.21 s   3.14 s  -2.1%
  svi_autonormal_logistic                    963.1 ms  947.6 ms  -1.6%       2.22 s   2.19 s  -1.5%
  svi_multi_particle_elbo                      1.11 s    1.13 s  +1.8%       2.27 s   2.44 s  +7.5%
  svi_trace_mean_field_elbo                  881.1 ms  888.7 ms  +0.9%       3.57 s   3.50 s  -1.9%
Methodology and environment

Each benchmark is set up untimed, then called once with the JAX caches cleared and several more times warm. Run is the fastest warm call; compile is the first call minus that, i.e. the tracing, lowering and XLA compilation the warm calls did not have to pay for.

Both refs were measured on the same runner over 2 interleaved round(s), taking the best observation per benchmark. A result is called neutral when it moves less than ±5% (run) or ±25% (compile), or when the measurement itself is under 1 ms (run) / 50 ms (compile) — a shared CI runner cannot resolve changes below that. Compile time gets the looser band because it is measured once per round rather than best-of-N, and swings by roughly 20% even between two runs of identical code. A delta shown in parentheses did clear its threshold, but on a measurement below the resolution floor, so it is reported without being called a change.

baseline this PR
ref master fix-predictive-prng
commit fc7691c7 ff9c7507
numpyro 0.22.0 0.22.0
jax 0.12.1 0.12.1
backend cpu cpu
python 3.14.4 3.14.4

Runner: Linux-7.0.0-1016-aws-x86_64-with-glibc2.43, 4 CPUs.

Produced by this benchmark run.

@juanitorduz

Copy link
Copy Markdown
Collaborator

@rpinho I think you also need to fix some tests because of the precison and change in rng 🙏

@juanitorduz juanitorduz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

please look into the tests

@rpinho

rpinho commented Nov 19, 2026

Copy link
Copy Markdown
Author

Thanks! We would be glad to help in any way we can. What would be helpful for you? What's a hard problem?

@rpinho

rpinho commented Nov 22, 2026

Copy link
Copy Markdown
Author

I looked but I don't see it. The 11 failures in test-modeling and test-inference (3.14) also fail on master (fc7691c) with jax 0.12.1, with the same values, and the same jobs fail on #2443 and #2447. None of it calls Predictive. CI passed on 11-17 with jax 0.12.0.1, and test_infer_util.py passes with the rbg case (64/64). So I don't think this PR broke them. Let me know if you disagree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review Awaiting review from maintainers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants